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;
168 /// Worklist - All of the instructions that need to be simplified.
169 InstCombineWorklist Worklist;
171 /// Builder - This is an IRBuilder that automatically inserts new
172 /// instructions into the worklist when they are created.
173 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
176 static char ID; // Pass identification, replacement for typeid
177 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
179 LLVMContext *Context;
180 LLVMContext *getContext() const { return Context; }
183 virtual bool runOnFunction(Function &F);
185 bool DoOneIteration(Function &F, unsigned ItNum);
187 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
188 AU.addPreservedID(LCSSAID);
189 AU.setPreservesCFG();
192 TargetData *getTargetData() const { return TD; }
194 // Visitation implementation - Implement instruction combining for different
195 // instruction types. The semantics are as follows:
197 // null - No change was made
198 // I - Change was made, I is still valid, I may be dead though
199 // otherwise - Change was made, replace I with returned instruction
201 Instruction *visitAdd(BinaryOperator &I);
202 Instruction *visitFAdd(BinaryOperator &I);
203 Instruction *visitSub(BinaryOperator &I);
204 Instruction *visitFSub(BinaryOperator &I);
205 Instruction *visitMul(BinaryOperator &I);
206 Instruction *visitFMul(BinaryOperator &I);
207 Instruction *visitURem(BinaryOperator &I);
208 Instruction *visitSRem(BinaryOperator &I);
209 Instruction *visitFRem(BinaryOperator &I);
210 bool SimplifyDivRemOfSelect(BinaryOperator &I);
211 Instruction *commonRemTransforms(BinaryOperator &I);
212 Instruction *commonIRemTransforms(BinaryOperator &I);
213 Instruction *commonDivTransforms(BinaryOperator &I);
214 Instruction *commonIDivTransforms(BinaryOperator &I);
215 Instruction *visitUDiv(BinaryOperator &I);
216 Instruction *visitSDiv(BinaryOperator &I);
217 Instruction *visitFDiv(BinaryOperator &I);
218 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
219 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
220 Instruction *visitAnd(BinaryOperator &I);
221 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
222 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
223 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
224 Value *A, Value *B, Value *C);
225 Instruction *visitOr (BinaryOperator &I);
226 Instruction *visitXor(BinaryOperator &I);
227 Instruction *visitShl(BinaryOperator &I);
228 Instruction *visitAShr(BinaryOperator &I);
229 Instruction *visitLShr(BinaryOperator &I);
230 Instruction *commonShiftTransforms(BinaryOperator &I);
231 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
233 Instruction *visitFCmpInst(FCmpInst &I);
234 Instruction *visitICmpInst(ICmpInst &I);
235 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
236 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
239 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
240 ConstantInt *DivRHS);
242 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
243 ICmpInst::Predicate Cond, Instruction &I);
244 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
246 Instruction *commonCastTransforms(CastInst &CI);
247 Instruction *commonIntCastTransforms(CastInst &CI);
248 Instruction *commonPointerCastTransforms(CastInst &CI);
249 Instruction *visitTrunc(TruncInst &CI);
250 Instruction *visitZExt(ZExtInst &CI);
251 Instruction *visitSExt(SExtInst &CI);
252 Instruction *visitFPTrunc(FPTruncInst &CI);
253 Instruction *visitFPExt(CastInst &CI);
254 Instruction *visitFPToUI(FPToUIInst &FI);
255 Instruction *visitFPToSI(FPToSIInst &FI);
256 Instruction *visitUIToFP(CastInst &CI);
257 Instruction *visitSIToFP(CastInst &CI);
258 Instruction *visitPtrToInt(PtrToIntInst &CI);
259 Instruction *visitIntToPtr(IntToPtrInst &CI);
260 Instruction *visitBitCast(BitCastInst &CI);
261 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
263 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
264 Instruction *visitSelectInst(SelectInst &SI);
265 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
266 Instruction *visitCallInst(CallInst &CI);
267 Instruction *visitInvokeInst(InvokeInst &II);
268 Instruction *visitPHINode(PHINode &PN);
269 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
270 Instruction *visitAllocationInst(AllocationInst &AI);
271 Instruction *visitFreeInst(FreeInst &FI);
272 Instruction *visitLoadInst(LoadInst &LI);
273 Instruction *visitStoreInst(StoreInst &SI);
274 Instruction *visitBranchInst(BranchInst &BI);
275 Instruction *visitSwitchInst(SwitchInst &SI);
276 Instruction *visitInsertElementInst(InsertElementInst &IE);
277 Instruction *visitExtractElementInst(ExtractElementInst &EI);
278 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
279 Instruction *visitExtractValueInst(ExtractValueInst &EV);
281 // visitInstruction - Specify what to return for unhandled instructions...
282 Instruction *visitInstruction(Instruction &I) { return 0; }
285 Instruction *visitCallSite(CallSite CS);
286 bool transformConstExprCastCall(CallSite CS);
287 Instruction *transformCallThroughTrampoline(CallSite CS);
288 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
289 bool DoXform = true);
290 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
291 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
295 // InsertNewInstBefore - insert an instruction New before instruction Old
296 // in the program. Add the new instruction to the worklist.
298 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
299 assert(New && New->getParent() == 0 &&
300 "New instruction already inserted into a basic block!");
301 BasicBlock *BB = Old.getParent();
302 BB->getInstList().insert(&Old, New); // Insert inst
307 // ReplaceInstUsesWith - This method is to be used when an instruction is
308 // found to be dead, replacable with another preexisting expression. Here
309 // we add all uses of I to the worklist, replace all uses of I with the new
310 // value, then return I, so that the inst combiner will know that I was
313 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
314 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
316 // If we are replacing the instruction with itself, this must be in a
317 // segment of unreachable code, so just clobber the instruction.
319 V = UndefValue::get(I.getType());
321 I.replaceAllUsesWith(V);
325 // EraseInstFromFunction - When dealing with an instruction that has side
326 // effects or produces a void value, we can't rely on DCE to delete the
327 // instruction. Instead, visit methods should return the value returned by
329 Instruction *EraseInstFromFunction(Instruction &I) {
330 assert(I.use_empty() && "Cannot erase instruction that is used!");
331 // Make sure that we reprocess all operands now that we reduced their
333 if (I.getNumOperands() < 8) {
334 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
335 if (Instruction *Op = dyn_cast<Instruction>(*i))
340 return 0; // Don't do anything with FI
343 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
344 APInt &KnownOne, unsigned Depth = 0) const {
345 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
348 bool MaskedValueIsZero(Value *V, const APInt &Mask,
349 unsigned Depth = 0) const {
350 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
352 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
353 return llvm::ComputeNumSignBits(Op, TD, Depth);
358 /// SimplifyCommutative - This performs a few simplifications for
359 /// commutative operators.
360 bool SimplifyCommutative(BinaryOperator &I);
362 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
363 /// most-complex to least-complex order.
364 bool SimplifyCompare(CmpInst &I);
366 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
367 /// based on the demanded bits.
368 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
369 APInt& KnownZero, APInt& KnownOne,
371 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
372 APInt& KnownZero, APInt& KnownOne,
375 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
376 /// SimplifyDemandedBits knows about. See if the instruction has any
377 /// properties that allow us to simplify its operands.
378 bool SimplifyDemandedInstructionBits(Instruction &Inst);
380 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
381 APInt& UndefElts, unsigned Depth = 0);
383 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
384 // PHI node as operand #0, see if we can fold the instruction into the PHI
385 // (which is only possible if all operands to the PHI are constants).
386 Instruction *FoldOpIntoPhi(Instruction &I);
388 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
389 // operator and they all are only used by the PHI, PHI together their
390 // inputs, and do the operation once, to the result of the PHI.
391 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
392 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
393 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
396 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
397 ConstantInt *AndRHS, BinaryOperator &TheAnd);
399 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
400 bool isSub, Instruction &I);
401 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
402 bool isSigned, bool Inside, Instruction &IB);
403 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
404 Instruction *MatchBSwap(BinaryOperator &I);
405 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
406 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
407 Instruction *SimplifyMemSet(MemSetInst *MI);
410 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
412 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
413 unsigned CastOpc, int &NumCastsRemoved);
414 unsigned GetOrEnforceKnownAlignment(Value *V,
415 unsigned PrefAlign = 0);
418 } // end anonymous namespace
420 char InstCombiner::ID = 0;
421 static RegisterPass<InstCombiner>
422 X("instcombine", "Combine redundant instructions");
424 // getComplexity: Assign a complexity or rank value to LLVM Values...
425 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
426 static unsigned getComplexity(Value *V) {
427 if (isa<Instruction>(V)) {
428 if (BinaryOperator::isNeg(V) ||
429 BinaryOperator::isFNeg(V) ||
430 BinaryOperator::isNot(V))
434 if (isa<Argument>(V)) return 3;
435 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
438 // isOnlyUse - Return true if this instruction will be deleted if we stop using
440 static bool isOnlyUse(Value *V) {
441 return V->hasOneUse() || isa<Constant>(V);
444 // getPromotedType - Return the specified type promoted as it would be to pass
445 // though a va_arg area...
446 static const Type *getPromotedType(const Type *Ty) {
447 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
448 if (ITy->getBitWidth() < 32)
449 return Type::getInt32Ty(Ty->getContext());
454 /// getBitCastOperand - If the specified operand is a CastInst, a constant
455 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
456 /// operand value, otherwise return null.
457 static Value *getBitCastOperand(Value *V) {
458 if (Operator *O = dyn_cast<Operator>(V)) {
459 if (O->getOpcode() == Instruction::BitCast)
460 return O->getOperand(0);
461 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
462 if (GEP->hasAllZeroIndices())
463 return GEP->getPointerOperand();
468 /// This function is a wrapper around CastInst::isEliminableCastPair. It
469 /// simply extracts arguments and returns what that function returns.
470 static Instruction::CastOps
471 isEliminableCastPair(
472 const CastInst *CI, ///< The first cast instruction
473 unsigned opcode, ///< The opcode of the second cast instruction
474 const Type *DstTy, ///< The target type for the second cast instruction
475 TargetData *TD ///< The target data for pointer size
478 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
479 const Type *MidTy = CI->getType(); // B from above
481 // Get the opcodes of the two Cast instructions
482 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
483 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
485 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
487 TD ? TD->getIntPtrType(CI->getContext()) : 0);
489 // We don't want to form an inttoptr or ptrtoint that converts to an integer
490 // type that differs from the pointer size.
491 if ((Res == Instruction::IntToPtr &&
492 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
493 (Res == Instruction::PtrToInt &&
494 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
497 return Instruction::CastOps(Res);
500 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
501 /// in any code being generated. It does not require codegen if V is simple
502 /// enough or if the cast can be folded into other casts.
503 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
504 const Type *Ty, TargetData *TD) {
505 if (V->getType() == Ty || isa<Constant>(V)) return false;
507 // If this is another cast that can be eliminated, it isn't codegen either.
508 if (const CastInst *CI = dyn_cast<CastInst>(V))
509 if (isEliminableCastPair(CI, opcode, Ty, TD))
514 // SimplifyCommutative - This performs a few simplifications for commutative
517 // 1. Order operands such that they are listed from right (least complex) to
518 // left (most complex). This puts constants before unary operators before
521 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
522 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
524 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
525 bool Changed = false;
526 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
527 Changed = !I.swapOperands();
529 if (!I.isAssociative()) return Changed;
530 Instruction::BinaryOps Opcode = I.getOpcode();
531 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
532 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
533 if (isa<Constant>(I.getOperand(1))) {
534 Constant *Folded = ConstantExpr::get(I.getOpcode(),
535 cast<Constant>(I.getOperand(1)),
536 cast<Constant>(Op->getOperand(1)));
537 I.setOperand(0, Op->getOperand(0));
538 I.setOperand(1, Folded);
540 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
541 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
542 isOnlyUse(Op) && isOnlyUse(Op1)) {
543 Constant *C1 = cast<Constant>(Op->getOperand(1));
544 Constant *C2 = cast<Constant>(Op1->getOperand(1));
546 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
547 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
548 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
552 I.setOperand(0, New);
553 I.setOperand(1, Folded);
560 /// SimplifyCompare - For a CmpInst this function just orders the operands
561 /// so that theyare listed from right (least complex) to left (most complex).
562 /// This puts constants before unary operators before binary operators.
563 bool InstCombiner::SimplifyCompare(CmpInst &I) {
564 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
567 // Compare instructions are not associative so there's nothing else we can do.
571 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
572 // if the LHS is a constant zero (which is the 'negate' form).
574 static inline Value *dyn_castNegVal(Value *V) {
575 if (BinaryOperator::isNeg(V))
576 return BinaryOperator::getNegArgument(V);
578 // Constants can be considered to be negated values if they can be folded.
579 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
580 return ConstantExpr::getNeg(C);
582 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
583 if (C->getType()->getElementType()->isInteger())
584 return ConstantExpr::getNeg(C);
589 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
590 // instruction if the LHS is a constant negative zero (which is the 'negate'
593 static inline Value *dyn_castFNegVal(Value *V) {
594 if (BinaryOperator::isFNeg(V))
595 return BinaryOperator::getFNegArgument(V);
597 // Constants can be considered to be negated values if they can be folded.
598 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
599 return ConstantExpr::getFNeg(C);
601 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
602 if (C->getType()->getElementType()->isFloatingPoint())
603 return ConstantExpr::getFNeg(C);
608 static inline Value *dyn_castNotVal(Value *V) {
609 if (BinaryOperator::isNot(V))
610 return BinaryOperator::getNotArgument(V);
612 // Constants can be considered to be not'ed values...
613 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
614 return ConstantInt::get(C->getType(), ~C->getValue());
618 // dyn_castFoldableMul - If this value is a multiply that can be folded into
619 // other computations (because it has a constant operand), return the
620 // non-constant operand of the multiply, and set CST to point to the multiplier.
621 // Otherwise, return null.
623 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
624 if (V->hasOneUse() && V->getType()->isInteger())
625 if (Instruction *I = dyn_cast<Instruction>(V)) {
626 if (I->getOpcode() == Instruction::Mul)
627 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
628 return I->getOperand(0);
629 if (I->getOpcode() == Instruction::Shl)
630 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
631 // The multiplier is really 1 << CST.
632 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
633 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
634 CST = ConstantInt::get(V->getType()->getContext(),
635 APInt(BitWidth, 1).shl(CSTVal));
636 return I->getOperand(0);
642 /// AddOne - Add one to a ConstantInt
643 static Constant *AddOne(Constant *C) {
644 return ConstantExpr::getAdd(C,
645 ConstantInt::get(C->getType(), 1));
647 /// SubOne - Subtract one from a ConstantInt
648 static Constant *SubOne(ConstantInt *C) {
649 return ConstantExpr::getSub(C,
650 ConstantInt::get(C->getType(), 1));
652 /// MultiplyOverflows - True if the multiply can not be expressed in an int
654 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
655 uint32_t W = C1->getBitWidth();
656 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
665 APInt MulExt = LHSExt * RHSExt;
668 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
669 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
670 return MulExt.slt(Min) || MulExt.sgt(Max);
672 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
676 /// ShrinkDemandedConstant - Check to see if the specified operand of the
677 /// specified instruction is a constant integer. If so, check to see if there
678 /// are any bits set in the constant that are not demanded. If so, shrink the
679 /// constant and return true.
680 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
682 assert(I && "No instruction?");
683 assert(OpNo < I->getNumOperands() && "Operand index too large");
685 // If the operand is not a constant integer, nothing to do.
686 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
687 if (!OpC) return false;
689 // If there are no bits set that aren't demanded, nothing to do.
690 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
691 if ((~Demanded & OpC->getValue()) == 0)
694 // This instruction is producing bits that are not demanded. Shrink the RHS.
695 Demanded &= OpC->getValue();
696 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
700 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
701 // set of known zero and one bits, compute the maximum and minimum values that
702 // could have the specified known zero and known one bits, returning them in
704 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
705 const APInt& KnownOne,
706 APInt& Min, APInt& Max) {
707 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
708 KnownZero.getBitWidth() == Min.getBitWidth() &&
709 KnownZero.getBitWidth() == Max.getBitWidth() &&
710 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
711 APInt UnknownBits = ~(KnownZero|KnownOne);
713 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
714 // bit if it is unknown.
716 Max = KnownOne|UnknownBits;
718 if (UnknownBits.isNegative()) { // Sign bit is unknown
719 Min.set(Min.getBitWidth()-1);
720 Max.clear(Max.getBitWidth()-1);
724 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
725 // a set of known zero and one bits, compute the maximum and minimum values that
726 // could have the specified known zero and known one bits, returning them in
728 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
729 const APInt &KnownOne,
730 APInt &Min, APInt &Max) {
731 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
732 KnownZero.getBitWidth() == Min.getBitWidth() &&
733 KnownZero.getBitWidth() == Max.getBitWidth() &&
734 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
735 APInt UnknownBits = ~(KnownZero|KnownOne);
737 // The minimum value is when the unknown bits are all zeros.
739 // The maximum value is when the unknown bits are all ones.
740 Max = KnownOne|UnknownBits;
743 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
744 /// SimplifyDemandedBits knows about. See if the instruction has any
745 /// properties that allow us to simplify its operands.
746 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
747 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
748 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
749 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
751 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
752 KnownZero, KnownOne, 0);
753 if (V == 0) return false;
754 if (V == &Inst) return true;
755 ReplaceInstUsesWith(Inst, V);
759 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
760 /// specified instruction operand if possible, updating it in place. It returns
761 /// true if it made any change and false otherwise.
762 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
763 APInt &KnownZero, APInt &KnownOne,
765 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
766 KnownZero, KnownOne, Depth);
767 if (NewVal == 0) return false;
773 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
774 /// value based on the demanded bits. When this function is called, it is known
775 /// that only the bits set in DemandedMask of the result of V are ever used
776 /// downstream. Consequently, depending on the mask and V, it may be possible
777 /// to replace V with a constant or one of its operands. In such cases, this
778 /// function does the replacement and returns true. In all other cases, it
779 /// returns false after analyzing the expression and setting KnownOne and known
780 /// to be one in the expression. KnownZero contains all the bits that are known
781 /// to be zero in the expression. These are provided to potentially allow the
782 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
783 /// the expression. KnownOne and KnownZero always follow the invariant that
784 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
785 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
786 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
787 /// and KnownOne must all be the same.
789 /// This returns null if it did not change anything and it permits no
790 /// simplification. This returns V itself if it did some simplification of V's
791 /// operands based on the information about what bits are demanded. This returns
792 /// some other non-null value if it found out that V is equal to another value
793 /// in the context where the specified bits are demanded, but not for all users.
794 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
795 APInt &KnownZero, APInt &KnownOne,
797 assert(V != 0 && "Null pointer of Value???");
798 assert(Depth <= 6 && "Limit Search Depth");
799 uint32_t BitWidth = DemandedMask.getBitWidth();
800 const Type *VTy = V->getType();
801 assert((TD || !isa<PointerType>(VTy)) &&
802 "SimplifyDemandedBits needs to know bit widths!");
803 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
804 (!VTy->isIntOrIntVector() ||
805 VTy->getScalarSizeInBits() == BitWidth) &&
806 KnownZero.getBitWidth() == BitWidth &&
807 KnownOne.getBitWidth() == BitWidth &&
808 "Value *V, DemandedMask, KnownZero and KnownOne "
809 "must have same BitWidth");
810 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
811 // We know all of the bits for a constant!
812 KnownOne = CI->getValue() & DemandedMask;
813 KnownZero = ~KnownOne & DemandedMask;
816 if (isa<ConstantPointerNull>(V)) {
817 // We know all of the bits for a constant!
819 KnownZero = DemandedMask;
825 if (DemandedMask == 0) { // Not demanding any bits from V.
826 if (isa<UndefValue>(V))
828 return UndefValue::get(VTy);
831 if (Depth == 6) // Limit search depth.
834 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
835 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
837 Instruction *I = dyn_cast<Instruction>(V);
839 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
840 return 0; // Only analyze instructions.
843 // If there are multiple uses of this value and we aren't at the root, then
844 // we can't do any simplifications of the operands, because DemandedMask
845 // only reflects the bits demanded by *one* of the users.
846 if (Depth != 0 && !I->hasOneUse()) {
847 // Despite the fact that we can't simplify this instruction in all User's
848 // context, we can at least compute the knownzero/knownone bits, and we can
849 // do simplifications that apply to *just* the one user if we know that
850 // this instruction has a simpler value in that context.
851 if (I->getOpcode() == Instruction::And) {
852 // If either the LHS or the RHS are Zero, the result is zero.
853 ComputeMaskedBits(I->getOperand(1), DemandedMask,
854 RHSKnownZero, RHSKnownOne, Depth+1);
855 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
856 LHSKnownZero, LHSKnownOne, Depth+1);
858 // If all of the demanded bits are known 1 on one side, return the other.
859 // These bits cannot contribute to the result of the 'and' in this
861 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
862 (DemandedMask & ~LHSKnownZero))
863 return I->getOperand(0);
864 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
865 (DemandedMask & ~RHSKnownZero))
866 return I->getOperand(1);
868 // If all of the demanded bits in the inputs are known zeros, return zero.
869 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
870 return Constant::getNullValue(VTy);
872 } else if (I->getOpcode() == Instruction::Or) {
873 // We can simplify (X|Y) -> X or Y in the user's context if we know that
874 // only bits from X or Y are demanded.
876 // If either the LHS or the RHS are One, the result is One.
877 ComputeMaskedBits(I->getOperand(1), DemandedMask,
878 RHSKnownZero, RHSKnownOne, Depth+1);
879 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
880 LHSKnownZero, LHSKnownOne, Depth+1);
882 // If all of the demanded bits are known zero on one side, return the
883 // other. These bits cannot contribute to the result of the 'or' in this
885 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
886 (DemandedMask & ~LHSKnownOne))
887 return I->getOperand(0);
888 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
889 (DemandedMask & ~RHSKnownOne))
890 return I->getOperand(1);
892 // If all of the potentially set bits on one side are known to be set on
893 // the other side, just use the 'other' side.
894 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
895 (DemandedMask & (~RHSKnownZero)))
896 return I->getOperand(0);
897 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
898 (DemandedMask & (~LHSKnownZero)))
899 return I->getOperand(1);
902 // Compute the KnownZero/KnownOne bits to simplify things downstream.
903 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
907 // If this is the root being simplified, allow it to have multiple uses,
908 // just set the DemandedMask to all bits so that we can try to simplify the
909 // operands. This allows visitTruncInst (for example) to simplify the
910 // operand of a trunc without duplicating all the logic below.
911 if (Depth == 0 && !V->hasOneUse())
912 DemandedMask = APInt::getAllOnesValue(BitWidth);
914 switch (I->getOpcode()) {
916 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
918 case Instruction::And:
919 // If either the LHS or the RHS are Zero, the result is zero.
920 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
921 RHSKnownZero, RHSKnownOne, Depth+1) ||
922 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
923 LHSKnownZero, LHSKnownOne, Depth+1))
925 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
926 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
928 // If all of the demanded bits are known 1 on one side, return the other.
929 // These bits cannot contribute to the result of the 'and'.
930 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
931 (DemandedMask & ~LHSKnownZero))
932 return I->getOperand(0);
933 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
934 (DemandedMask & ~RHSKnownZero))
935 return I->getOperand(1);
937 // If all of the demanded bits in the inputs are known zeros, return zero.
938 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
939 return Constant::getNullValue(VTy);
941 // If the RHS is a constant, see if we can simplify it.
942 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
945 // Output known-1 bits are only known if set in both the LHS & RHS.
946 RHSKnownOne &= LHSKnownOne;
947 // Output known-0 are known to be clear if zero in either the LHS | RHS.
948 RHSKnownZero |= LHSKnownZero;
950 case Instruction::Or:
951 // If either the LHS or the RHS are One, the result is One.
952 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
953 RHSKnownZero, RHSKnownOne, Depth+1) ||
954 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
955 LHSKnownZero, LHSKnownOne, Depth+1))
957 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
958 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
960 // If all of the demanded bits are known zero on one side, return the other.
961 // These bits cannot contribute to the result of the 'or'.
962 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
963 (DemandedMask & ~LHSKnownOne))
964 return I->getOperand(0);
965 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
966 (DemandedMask & ~RHSKnownOne))
967 return I->getOperand(1);
969 // If all of the potentially set bits on one side are known to be set on
970 // the other side, just use the 'other' side.
971 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
972 (DemandedMask & (~RHSKnownZero)))
973 return I->getOperand(0);
974 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
975 (DemandedMask & (~LHSKnownZero)))
976 return I->getOperand(1);
978 // If the RHS is a constant, see if we can simplify it.
979 if (ShrinkDemandedConstant(I, 1, DemandedMask))
982 // Output known-0 bits are only known if clear in both the LHS & RHS.
983 RHSKnownZero &= LHSKnownZero;
984 // Output known-1 are known to be set if set in either the LHS | RHS.
985 RHSKnownOne |= LHSKnownOne;
987 case Instruction::Xor: {
988 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1) ||
990 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
991 LHSKnownZero, LHSKnownOne, Depth+1))
993 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
994 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
996 // If all of the demanded bits are known zero on one side, return the other.
997 // These bits cannot contribute to the result of the 'xor'.
998 if ((DemandedMask & RHSKnownZero) == DemandedMask)
999 return I->getOperand(0);
1000 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1001 return I->getOperand(1);
1003 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1004 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1005 (RHSKnownOne & LHSKnownOne);
1006 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1007 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1008 (RHSKnownOne & LHSKnownZero);
1010 // If all of the demanded bits are known to be zero on one side or the
1011 // other, turn this into an *inclusive* or.
1012 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1013 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0)
1014 return Builder->CreateOr(I->getOperand(0), I->getOperand(1),I->getName());
1016 // If all of the demanded bits on one side are known, and all of the set
1017 // bits on that side are also known to be set on the other side, turn this
1018 // into an AND, as we know the bits will be cleared.
1019 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1020 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1022 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1023 Constant *AndC = Constant::getIntegerValue(VTy,
1024 ~RHSKnownOne & DemandedMask);
1026 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1027 return InsertNewInstBefore(And, *I);
1031 // If the RHS is a constant, see if we can simplify it.
1032 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1033 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1036 RHSKnownZero = KnownZeroOut;
1037 RHSKnownOne = KnownOneOut;
1040 case Instruction::Select:
1041 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1042 RHSKnownZero, RHSKnownOne, Depth+1) ||
1043 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1044 LHSKnownZero, LHSKnownOne, Depth+1))
1046 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1047 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1049 // If the operands are constants, see if we can simplify them.
1050 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1051 ShrinkDemandedConstant(I, 2, DemandedMask))
1054 // Only known if known in both the LHS and RHS.
1055 RHSKnownOne &= LHSKnownOne;
1056 RHSKnownZero &= LHSKnownZero;
1058 case Instruction::Trunc: {
1059 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1060 DemandedMask.zext(truncBf);
1061 RHSKnownZero.zext(truncBf);
1062 RHSKnownOne.zext(truncBf);
1063 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1064 RHSKnownZero, RHSKnownOne, Depth+1))
1066 DemandedMask.trunc(BitWidth);
1067 RHSKnownZero.trunc(BitWidth);
1068 RHSKnownOne.trunc(BitWidth);
1069 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1072 case Instruction::BitCast:
1073 if (!I->getOperand(0)->getType()->isIntOrIntVector())
1074 return false; // vector->int or fp->int?
1076 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1077 if (const VectorType *SrcVTy =
1078 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1079 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1080 // Don't touch a bitcast between vectors of different element counts.
1083 // Don't touch a scalar-to-vector bitcast.
1085 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1086 // Don't touch a vector-to-scalar bitcast.
1089 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1090 RHSKnownZero, RHSKnownOne, Depth+1))
1092 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1094 case Instruction::ZExt: {
1095 // Compute the bits in the result that are not present in the input.
1096 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1098 DemandedMask.trunc(SrcBitWidth);
1099 RHSKnownZero.trunc(SrcBitWidth);
1100 RHSKnownOne.trunc(SrcBitWidth);
1101 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1102 RHSKnownZero, RHSKnownOne, Depth+1))
1104 DemandedMask.zext(BitWidth);
1105 RHSKnownZero.zext(BitWidth);
1106 RHSKnownOne.zext(BitWidth);
1107 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1108 // The top bits are known to be zero.
1109 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1112 case Instruction::SExt: {
1113 // Compute the bits in the result that are not present in the input.
1114 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1116 APInt InputDemandedBits = DemandedMask &
1117 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1119 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1120 // If any of the sign extended bits are demanded, we know that the sign
1122 if ((NewBits & DemandedMask) != 0)
1123 InputDemandedBits.set(SrcBitWidth-1);
1125 InputDemandedBits.trunc(SrcBitWidth);
1126 RHSKnownZero.trunc(SrcBitWidth);
1127 RHSKnownOne.trunc(SrcBitWidth);
1128 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1129 RHSKnownZero, RHSKnownOne, Depth+1))
1131 InputDemandedBits.zext(BitWidth);
1132 RHSKnownZero.zext(BitWidth);
1133 RHSKnownOne.zext(BitWidth);
1134 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1136 // If the sign bit of the input is known set or clear, then we know the
1137 // top bits of the result.
1139 // If the input sign bit is known zero, or if the NewBits are not demanded
1140 // convert this into a zero extension.
1141 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1142 // Convert to ZExt cast
1143 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1144 return InsertNewInstBefore(NewCast, *I);
1145 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1146 RHSKnownOne |= NewBits;
1150 case Instruction::Add: {
1151 // Figure out what the input bits are. If the top bits of the and result
1152 // are not demanded, then the add doesn't demand them from its input
1154 unsigned NLZ = DemandedMask.countLeadingZeros();
1156 // If there is a constant on the RHS, there are a variety of xformations
1158 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159 // If null, this should be simplified elsewhere. Some of the xforms here
1160 // won't work if the RHS is zero.
1164 // If the top bit of the output is demanded, demand everything from the
1165 // input. Otherwise, we demand all the input bits except NLZ top bits.
1166 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1168 // Find information about known zero/one bits in the input.
1169 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1170 LHSKnownZero, LHSKnownOne, Depth+1))
1173 // If the RHS of the add has bits set that can't affect the input, reduce
1175 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1178 // Avoid excess work.
1179 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1182 // Turn it into OR if input bits are zero.
1183 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1185 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1187 return InsertNewInstBefore(Or, *I);
1190 // We can say something about the output known-zero and known-one bits,
1191 // depending on potential carries from the input constant and the
1192 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1193 // bits set and the RHS constant is 0x01001, then we know we have a known
1194 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1196 // To compute this, we first compute the potential carry bits. These are
1197 // the bits which may be modified. I'm not aware of a better way to do
1199 const APInt &RHSVal = RHS->getValue();
1200 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1202 // Now that we know which bits have carries, compute the known-1/0 sets.
1204 // Bits are known one if they are known zero in one operand and one in the
1205 // other, and there is no input carry.
1206 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1207 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1209 // Bits are known zero if they are known zero in both operands and there
1210 // is no input carry.
1211 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1213 // If the high-bits of this ADD are not demanded, then it does not demand
1214 // the high bits of its LHS or RHS.
1215 if (DemandedMask[BitWidth-1] == 0) {
1216 // Right fill the mask of bits for this ADD to demand the most
1217 // significant bit and all those below it.
1218 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1219 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1220 LHSKnownZero, LHSKnownOne, Depth+1) ||
1221 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1222 LHSKnownZero, LHSKnownOne, Depth+1))
1228 case Instruction::Sub:
1229 // If the high-bits of this SUB are not demanded, then it does not demand
1230 // the high bits of its LHS or RHS.
1231 if (DemandedMask[BitWidth-1] == 0) {
1232 // Right fill the mask of bits for this SUB to demand the most
1233 // significant bit and all those below it.
1234 uint32_t NLZ = DemandedMask.countLeadingZeros();
1235 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1236 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1237 LHSKnownZero, LHSKnownOne, Depth+1) ||
1238 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1239 LHSKnownZero, LHSKnownOne, Depth+1))
1242 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1243 // the known zeros and ones.
1244 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1246 case Instruction::Shl:
1247 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1248 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1249 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1250 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1251 RHSKnownZero, RHSKnownOne, Depth+1))
1253 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1254 RHSKnownZero <<= ShiftAmt;
1255 RHSKnownOne <<= ShiftAmt;
1256 // low bits known zero.
1258 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1261 case Instruction::LShr:
1262 // For a logical shift right
1263 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1264 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1266 // Unsigned shift right.
1267 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1268 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1269 RHSKnownZero, RHSKnownOne, Depth+1))
1271 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1272 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1273 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1275 // Compute the new bits that are at the top now.
1276 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1277 RHSKnownZero |= HighBits; // high bits known zero.
1281 case Instruction::AShr:
1282 // If this is an arithmetic shift right and only the low-bit is set, we can
1283 // always convert this into a logical shr, even if the shift amount is
1284 // variable. The low bit of the shift cannot be an input sign bit unless
1285 // the shift amount is >= the size of the datatype, which is undefined.
1286 if (DemandedMask == 1) {
1287 // Perform the logical shift right.
1288 Instruction *NewVal = BinaryOperator::CreateLShr(
1289 I->getOperand(0), I->getOperand(1), I->getName());
1290 return InsertNewInstBefore(NewVal, *I);
1293 // If the sign bit is the only bit demanded by this ashr, then there is no
1294 // need to do it, the shift doesn't change the high bit.
1295 if (DemandedMask.isSignBit())
1296 return I->getOperand(0);
1298 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1299 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1301 // Signed shift right.
1302 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1303 // If any of the "high bits" are demanded, we should set the sign bit as
1305 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1306 DemandedMaskIn.set(BitWidth-1);
1307 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1308 RHSKnownZero, RHSKnownOne, Depth+1))
1310 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1311 // Compute the new bits that are at the top now.
1312 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1313 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1314 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1316 // Handle the sign bits.
1317 APInt SignBit(APInt::getSignBit(BitWidth));
1318 // Adjust to where it is now in the mask.
1319 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1321 // If the input sign bit is known to be zero, or if none of the top bits
1322 // are demanded, turn this into an unsigned shift right.
1323 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1324 (HighBits & ~DemandedMask) == HighBits) {
1325 // Perform the logical shift right.
1326 Instruction *NewVal = BinaryOperator::CreateLShr(
1327 I->getOperand(0), SA, I->getName());
1328 return InsertNewInstBefore(NewVal, *I);
1329 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1330 RHSKnownOne |= HighBits;
1334 case Instruction::SRem:
1335 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1336 APInt RA = Rem->getValue().abs();
1337 if (RA.isPowerOf2()) {
1338 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
1339 return I->getOperand(0);
1341 APInt LowBits = RA - 1;
1342 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1343 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1344 LHSKnownZero, LHSKnownOne, Depth+1))
1347 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1348 LHSKnownZero |= ~LowBits;
1350 KnownZero |= LHSKnownZero & DemandedMask;
1352 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
1356 case Instruction::URem: {
1357 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1358 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1359 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1360 KnownZero2, KnownOne2, Depth+1) ||
1361 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1362 KnownZero2, KnownOne2, Depth+1))
1365 unsigned Leaders = KnownZero2.countLeadingOnes();
1366 Leaders = std::max(Leaders,
1367 KnownZero2.countLeadingOnes());
1368 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1371 case Instruction::Call:
1372 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1373 switch (II->getIntrinsicID()) {
1375 case Intrinsic::bswap: {
1376 // If the only bits demanded come from one byte of the bswap result,
1377 // just shift the input byte into position to eliminate the bswap.
1378 unsigned NLZ = DemandedMask.countLeadingZeros();
1379 unsigned NTZ = DemandedMask.countTrailingZeros();
1381 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1382 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1383 // have 14 leading zeros, round to 8.
1386 // If we need exactly one byte, we can do this transformation.
1387 if (BitWidth-NLZ-NTZ == 8) {
1388 unsigned ResultBit = NTZ;
1389 unsigned InputBit = BitWidth-NTZ-8;
1391 // Replace this with either a left or right shift to get the byte into
1393 Instruction *NewVal;
1394 if (InputBit > ResultBit)
1395 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1396 ConstantInt::get(I->getType(), InputBit-ResultBit));
1398 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1399 ConstantInt::get(I->getType(), ResultBit-InputBit));
1400 NewVal->takeName(I);
1401 return InsertNewInstBefore(NewVal, *I);
1404 // TODO: Could compute known zero/one bits based on the input.
1409 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1413 // If the client is only demanding bits that we know, return the known
1415 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1416 return Constant::getIntegerValue(VTy, RHSKnownOne);
1421 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1422 /// any number of elements. DemandedElts contains the set of elements that are
1423 /// actually used by the caller. This method analyzes which elements of the
1424 /// operand are undef and returns that information in UndefElts.
1426 /// If the information about demanded elements can be used to simplify the
1427 /// operation, the operation is simplified, then the resultant value is
1428 /// returned. This returns null if no change was made.
1429 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1432 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1433 APInt EltMask(APInt::getAllOnesValue(VWidth));
1434 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1436 if (isa<UndefValue>(V)) {
1437 // If the entire vector is undefined, just return this info.
1438 UndefElts = EltMask;
1440 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1441 UndefElts = EltMask;
1442 return UndefValue::get(V->getType());
1446 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1447 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1448 Constant *Undef = UndefValue::get(EltTy);
1450 std::vector<Constant*> Elts;
1451 for (unsigned i = 0; i != VWidth; ++i)
1452 if (!DemandedElts[i]) { // If not demanded, set to undef.
1453 Elts.push_back(Undef);
1455 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1456 Elts.push_back(Undef);
1458 } else { // Otherwise, defined.
1459 Elts.push_back(CP->getOperand(i));
1462 // If we changed the constant, return it.
1463 Constant *NewCP = ConstantVector::get(Elts);
1464 return NewCP != CP ? NewCP : 0;
1465 } else if (isa<ConstantAggregateZero>(V)) {
1466 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1469 // Check if this is identity. If so, return 0 since we are not simplifying
1471 if (DemandedElts == ((1ULL << VWidth) -1))
1474 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1475 Constant *Zero = Constant::getNullValue(EltTy);
1476 Constant *Undef = UndefValue::get(EltTy);
1477 std::vector<Constant*> Elts;
1478 for (unsigned i = 0; i != VWidth; ++i) {
1479 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1480 Elts.push_back(Elt);
1482 UndefElts = DemandedElts ^ EltMask;
1483 return ConstantVector::get(Elts);
1486 // Limit search depth.
1490 // If multiple users are using the root value, procede with
1491 // simplification conservatively assuming that all elements
1493 if (!V->hasOneUse()) {
1494 // Quit if we find multiple users of a non-root value though.
1495 // They'll be handled when it's their turn to be visited by
1496 // the main instcombine process.
1498 // TODO: Just compute the UndefElts information recursively.
1501 // Conservatively assume that all elements are needed.
1502 DemandedElts = EltMask;
1505 Instruction *I = dyn_cast<Instruction>(V);
1506 if (!I) return 0; // Only analyze instructions.
1508 bool MadeChange = false;
1509 APInt UndefElts2(VWidth, 0);
1511 switch (I->getOpcode()) {
1514 case Instruction::InsertElement: {
1515 // If this is a variable index, we don't know which element it overwrites.
1516 // demand exactly the same input as we produce.
1517 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1519 // Note that we can't propagate undef elt info, because we don't know
1520 // which elt is getting updated.
1521 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1522 UndefElts2, Depth+1);
1523 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1527 // If this is inserting an element that isn't demanded, remove this
1529 unsigned IdxNo = Idx->getZExtValue();
1530 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1532 return I->getOperand(0);
1535 // Otherwise, the element inserted overwrites whatever was there, so the
1536 // input demanded set is simpler than the output set.
1537 APInt DemandedElts2 = DemandedElts;
1538 DemandedElts2.clear(IdxNo);
1539 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1540 UndefElts, Depth+1);
1541 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543 // The inserted element is defined.
1544 UndefElts.clear(IdxNo);
1547 case Instruction::ShuffleVector: {
1548 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1549 uint64_t LHSVWidth =
1550 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1551 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1552 for (unsigned i = 0; i < VWidth; i++) {
1553 if (DemandedElts[i]) {
1554 unsigned MaskVal = Shuffle->getMaskValue(i);
1555 if (MaskVal != -1u) {
1556 assert(MaskVal < LHSVWidth * 2 &&
1557 "shufflevector mask index out of range!");
1558 if (MaskVal < LHSVWidth)
1559 LeftDemanded.set(MaskVal);
1561 RightDemanded.set(MaskVal - LHSVWidth);
1566 APInt UndefElts4(LHSVWidth, 0);
1567 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1568 UndefElts4, Depth+1);
1569 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1571 APInt UndefElts3(LHSVWidth, 0);
1572 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1573 UndefElts3, Depth+1);
1574 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1576 bool NewUndefElts = false;
1577 for (unsigned i = 0; i < VWidth; i++) {
1578 unsigned MaskVal = Shuffle->getMaskValue(i);
1579 if (MaskVal == -1u) {
1581 } else if (MaskVal < LHSVWidth) {
1582 if (UndefElts4[MaskVal]) {
1583 NewUndefElts = true;
1587 if (UndefElts3[MaskVal - LHSVWidth]) {
1588 NewUndefElts = true;
1595 // Add additional discovered undefs.
1596 std::vector<Constant*> Elts;
1597 for (unsigned i = 0; i < VWidth; ++i) {
1599 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1601 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1602 Shuffle->getMaskValue(i)));
1604 I->setOperand(2, ConstantVector::get(Elts));
1609 case Instruction::BitCast: {
1610 // Vector->vector casts only.
1611 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1613 unsigned InVWidth = VTy->getNumElements();
1614 APInt InputDemandedElts(InVWidth, 0);
1617 if (VWidth == InVWidth) {
1618 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1619 // elements as are demanded of us.
1621 InputDemandedElts = DemandedElts;
1622 } else if (VWidth > InVWidth) {
1626 // If there are more elements in the result than there are in the source,
1627 // then an input element is live if any of the corresponding output
1628 // elements are live.
1629 Ratio = VWidth/InVWidth;
1630 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1631 if (DemandedElts[OutIdx])
1632 InputDemandedElts.set(OutIdx/Ratio);
1638 // If there are more elements in the source than there are in the result,
1639 // then an input element is live if the corresponding output element is
1641 Ratio = InVWidth/VWidth;
1642 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1643 if (DemandedElts[InIdx/Ratio])
1644 InputDemandedElts.set(InIdx);
1647 // div/rem demand all inputs, because they don't want divide by zero.
1648 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1649 UndefElts2, Depth+1);
1651 I->setOperand(0, TmpV);
1655 UndefElts = UndefElts2;
1656 if (VWidth > InVWidth) {
1657 llvm_unreachable("Unimp");
1658 // If there are more elements in the result than there are in the source,
1659 // then an output element is undef if the corresponding input element is
1661 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1662 if (UndefElts2[OutIdx/Ratio])
1663 UndefElts.set(OutIdx);
1664 } else if (VWidth < InVWidth) {
1665 llvm_unreachable("Unimp");
1666 // If there are more elements in the source than there are in the result,
1667 // then a result element is undef if all of the corresponding input
1668 // elements are undef.
1669 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1670 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1671 if (!UndefElts2[InIdx]) // Not undef?
1672 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
1676 case Instruction::And:
1677 case Instruction::Or:
1678 case Instruction::Xor:
1679 case Instruction::Add:
1680 case Instruction::Sub:
1681 case Instruction::Mul:
1682 // div/rem demand all inputs, because they don't want divide by zero.
1683 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1684 UndefElts, Depth+1);
1685 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1686 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1687 UndefElts2, Depth+1);
1688 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1690 // Output elements are undefined if both are undefined. Consider things
1691 // like undef&0. The result is known zero, not undef.
1692 UndefElts &= UndefElts2;
1695 case Instruction::Call: {
1696 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1698 switch (II->getIntrinsicID()) {
1701 // Binary vector operations that work column-wise. A dest element is a
1702 // function of the corresponding input elements from the two inputs.
1703 case Intrinsic::x86_sse_sub_ss:
1704 case Intrinsic::x86_sse_mul_ss:
1705 case Intrinsic::x86_sse_min_ss:
1706 case Intrinsic::x86_sse_max_ss:
1707 case Intrinsic::x86_sse2_sub_sd:
1708 case Intrinsic::x86_sse2_mul_sd:
1709 case Intrinsic::x86_sse2_min_sd:
1710 case Intrinsic::x86_sse2_max_sd:
1711 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1712 UndefElts, Depth+1);
1713 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1714 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1715 UndefElts2, Depth+1);
1716 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1718 // If only the low elt is demanded and this is a scalarizable intrinsic,
1719 // scalarize it now.
1720 if (DemandedElts == 1) {
1721 switch (II->getIntrinsicID()) {
1723 case Intrinsic::x86_sse_sub_ss:
1724 case Intrinsic::x86_sse_mul_ss:
1725 case Intrinsic::x86_sse2_sub_sd:
1726 case Intrinsic::x86_sse2_mul_sd:
1727 // TODO: Lower MIN/MAX/ABS/etc
1728 Value *LHS = II->getOperand(1);
1729 Value *RHS = II->getOperand(2);
1730 // Extract the element as scalars.
1731 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
1732 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1733 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1734 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1736 switch (II->getIntrinsicID()) {
1737 default: llvm_unreachable("Case stmts out of sync!");
1738 case Intrinsic::x86_sse_sub_ss:
1739 case Intrinsic::x86_sse2_sub_sd:
1740 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1741 II->getName()), *II);
1743 case Intrinsic::x86_sse_mul_ss:
1744 case Intrinsic::x86_sse2_mul_sd:
1745 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1746 II->getName()), *II);
1751 InsertElementInst::Create(
1752 UndefValue::get(II->getType()), TmpV,
1753 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1754 InsertNewInstBefore(New, *II);
1759 // Output elements are undefined if both are undefined. Consider things
1760 // like undef&0. The result is known zero, not undef.
1761 UndefElts &= UndefElts2;
1767 return MadeChange ? I : 0;
1771 /// AssociativeOpt - Perform an optimization on an associative operator. This
1772 /// function is designed to check a chain of associative operators for a
1773 /// potential to apply a certain optimization. Since the optimization may be
1774 /// applicable if the expression was reassociated, this checks the chain, then
1775 /// reassociates the expression as necessary to expose the optimization
1776 /// opportunity. This makes use of a special Functor, which must define
1777 /// 'shouldApply' and 'apply' methods.
1779 template<typename Functor>
1780 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1781 unsigned Opcode = Root.getOpcode();
1782 Value *LHS = Root.getOperand(0);
1784 // Quick check, see if the immediate LHS matches...
1785 if (F.shouldApply(LHS))
1786 return F.apply(Root);
1788 // Otherwise, if the LHS is not of the same opcode as the root, return.
1789 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1790 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1791 // Should we apply this transform to the RHS?
1792 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1794 // If not to the RHS, check to see if we should apply to the LHS...
1795 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1796 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1800 // If the functor wants to apply the optimization to the RHS of LHSI,
1801 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1803 // Now all of the instructions are in the current basic block, go ahead
1804 // and perform the reassociation.
1805 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1807 // First move the selected RHS to the LHS of the root...
1808 Root.setOperand(0, LHSI->getOperand(1));
1810 // Make what used to be the LHS of the root be the user of the root...
1811 Value *ExtraOperand = TmpLHSI->getOperand(1);
1812 if (&Root == TmpLHSI) {
1813 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1816 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1817 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1818 BasicBlock::iterator ARI = &Root; ++ARI;
1819 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1822 // Now propagate the ExtraOperand down the chain of instructions until we
1824 while (TmpLHSI != LHSI) {
1825 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1826 // Move the instruction to immediately before the chain we are
1827 // constructing to avoid breaking dominance properties.
1828 NextLHSI->moveBefore(ARI);
1831 Value *NextOp = NextLHSI->getOperand(1);
1832 NextLHSI->setOperand(1, ExtraOperand);
1834 ExtraOperand = NextOp;
1837 // Now that the instructions are reassociated, have the functor perform
1838 // the transformation...
1839 return F.apply(Root);
1842 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1849 // AddRHS - Implements: X + X --> X << 1
1852 explicit AddRHS(Value *rhs) : RHS(rhs) {}
1853 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1854 Instruction *apply(BinaryOperator &Add) const {
1855 return BinaryOperator::CreateShl(Add.getOperand(0),
1856 ConstantInt::get(Add.getType(), 1));
1860 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1862 struct AddMaskingAnd {
1864 explicit AddMaskingAnd(Constant *c) : C2(c) {}
1865 bool shouldApply(Value *LHS) const {
1867 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1868 ConstantExpr::getAnd(C1, C2)->isNullValue();
1870 Instruction *apply(BinaryOperator &Add) const {
1871 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1877 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1879 if (CastInst *CI = dyn_cast<CastInst>(&I))
1880 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1882 // Figure out if the constant is the left or the right argument.
1883 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1884 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1886 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1888 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1889 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1892 Value *Op0 = SO, *Op1 = ConstOperand;
1894 std::swap(Op0, Op1);
1896 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1897 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1898 SO->getName()+".op");
1899 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1900 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1901 SO->getName()+".cmp");
1902 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1903 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1904 SO->getName()+".cmp");
1905 llvm_unreachable("Unknown binary instruction type!");
1908 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1909 // constant as the other operand, try to fold the binary operator into the
1910 // select arguments. This also works for Cast instructions, which obviously do
1911 // not have a second operand.
1912 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1914 // Don't modify shared select instructions
1915 if (!SI->hasOneUse()) return 0;
1916 Value *TV = SI->getOperand(1);
1917 Value *FV = SI->getOperand(2);
1919 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1920 // Bool selects with constant operands can be folded to logical ops.
1921 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1923 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1924 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1926 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1933 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1934 /// node as operand #0, see if we can fold the instruction into the PHI (which
1935 /// is only possible if all operands to the PHI are constants).
1936 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1937 PHINode *PN = cast<PHINode>(I.getOperand(0));
1938 unsigned NumPHIValues = PN->getNumIncomingValues();
1939 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1941 // Check to see if all of the operands of the PHI are constants. If there is
1942 // one non-constant value, remember the BB it is. If there is more than one
1943 // or if *it* is a PHI, bail out.
1944 BasicBlock *NonConstBB = 0;
1945 for (unsigned i = 0; i != NumPHIValues; ++i)
1946 if (!isa<Constant>(PN->getIncomingValue(i))) {
1947 if (NonConstBB) return 0; // More than one non-const value.
1948 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1949 NonConstBB = PN->getIncomingBlock(i);
1951 // If the incoming non-constant value is in I's block, we have an infinite
1953 if (NonConstBB == I.getParent())
1957 // If there is exactly one non-constant value, we can insert a copy of the
1958 // operation in that block. However, if this is a critical edge, we would be
1959 // inserting the computation one some other paths (e.g. inside a loop). Only
1960 // do this if the pred block is unconditionally branching into the phi block.
1962 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1963 if (!BI || !BI->isUnconditional()) return 0;
1966 // Okay, we can do the transformation: create the new PHI node.
1967 PHINode *NewPN = PHINode::Create(I.getType(), "");
1968 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1969 InsertNewInstBefore(NewPN, *PN);
1970 NewPN->takeName(PN);
1972 // Next, add all of the operands to the PHI.
1973 if (I.getNumOperands() == 2) {
1974 Constant *C = cast<Constant>(I.getOperand(1));
1975 for (unsigned i = 0; i != NumPHIValues; ++i) {
1977 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1978 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1979 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1981 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1983 assert(PN->getIncomingBlock(i) == NonConstBB);
1984 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1985 InV = BinaryOperator::Create(BO->getOpcode(),
1986 PN->getIncomingValue(i), C, "phitmp",
1987 NonConstBB->getTerminator());
1988 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1989 InV = CmpInst::Create(CI->getOpcode(),
1991 PN->getIncomingValue(i), C, "phitmp",
1992 NonConstBB->getTerminator());
1994 llvm_unreachable("Unknown binop!");
1996 Worklist.Add(cast<Instruction>(InV));
1998 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2001 CastInst *CI = cast<CastInst>(&I);
2002 const Type *RetTy = CI->getType();
2003 for (unsigned i = 0; i != NumPHIValues; ++i) {
2005 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2006 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2008 assert(PN->getIncomingBlock(i) == NonConstBB);
2009 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2010 I.getType(), "phitmp",
2011 NonConstBB->getTerminator());
2012 Worklist.Add(cast<Instruction>(InV));
2014 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2017 return ReplaceInstUsesWith(I, NewPN);
2021 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2022 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2023 /// This basically requires proving that the add in the original type would not
2024 /// overflow to change the sign bit or have a carry out.
2025 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2026 // There are different heuristics we can use for this. Here are some simple
2029 // Add has the property that adding any two 2's complement numbers can only
2030 // have one carry bit which can change a sign. As such, if LHS and RHS each
2031 // have at least two sign bits, we know that the addition of the two values will
2032 // sign extend fine.
2033 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2037 // If one of the operands only has one non-zero bit, and if the other operand
2038 // has a known-zero bit in a more significant place than it (not including the
2039 // sign bit) the ripple may go up to and fill the zero, but won't change the
2040 // sign. For example, (X & ~4) + 1.
2048 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2049 bool Changed = SimplifyCommutative(I);
2050 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2052 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2053 // X + undef -> undef
2054 if (isa<UndefValue>(RHS))
2055 return ReplaceInstUsesWith(I, RHS);
2058 if (RHSC->isNullValue())
2059 return ReplaceInstUsesWith(I, LHS);
2061 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2062 // X + (signbit) --> X ^ signbit
2063 const APInt& Val = CI->getValue();
2064 uint32_t BitWidth = Val.getBitWidth();
2065 if (Val == APInt::getSignBit(BitWidth))
2066 return BinaryOperator::CreateXor(LHS, RHS);
2068 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2069 // (X & 254)+1 -> (X&254)|1
2070 if (SimplifyDemandedInstructionBits(I))
2073 // zext(bool) + C -> bool ? C + 1 : C
2074 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2075 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2076 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2079 if (isa<PHINode>(LHS))
2080 if (Instruction *NV = FoldOpIntoPhi(I))
2083 ConstantInt *XorRHS = 0;
2085 if (isa<ConstantInt>(RHSC) &&
2086 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2087 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2088 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2090 uint32_t Size = TySizeBits / 2;
2091 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2092 APInt CFF80Val(-C0080Val);
2094 if (TySizeBits > Size) {
2095 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2096 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2097 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2098 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2099 // This is a sign extend if the top bits are known zero.
2100 if (!MaskedValueIsZero(XorLHS,
2101 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2102 Size = 0; // Not a sign ext, but can't be any others either.
2107 C0080Val = APIntOps::lshr(C0080Val, Size);
2108 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2109 } while (Size >= 1);
2111 // FIXME: This shouldn't be necessary. When the backends can handle types
2112 // with funny bit widths then this switch statement should be removed. It
2113 // is just here to get the size of the "middle" type back up to something
2114 // that the back ends can handle.
2115 const Type *MiddleType = 0;
2118 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2119 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2120 case 8: MiddleType = Type::getInt8Ty(*Context); break;
2123 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2124 return new SExtInst(NewTrunc, I.getType(), I.getName());
2129 if (I.getType() == Type::getInt1Ty(*Context))
2130 return BinaryOperator::CreateXor(LHS, RHS);
2133 if (I.getType()->isInteger()) {
2134 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2137 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2138 if (RHSI->getOpcode() == Instruction::Sub)
2139 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2140 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2142 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2143 if (LHSI->getOpcode() == Instruction::Sub)
2144 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2145 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2150 // -A + -B --> -(A + B)
2151 if (Value *LHSV = dyn_castNegVal(LHS)) {
2152 if (LHS->getType()->isIntOrIntVector()) {
2153 if (Value *RHSV = dyn_castNegVal(RHS)) {
2154 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2155 return BinaryOperator::CreateNeg(NewAdd);
2159 return BinaryOperator::CreateSub(RHS, LHSV);
2163 if (!isa<Constant>(RHS))
2164 if (Value *V = dyn_castNegVal(RHS))
2165 return BinaryOperator::CreateSub(LHS, V);
2169 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2170 if (X == RHS) // X*C + X --> X * (C+1)
2171 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2173 // X*C1 + X*C2 --> X * (C1+C2)
2175 if (X == dyn_castFoldableMul(RHS, C1))
2176 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2179 // X + X*C --> X * (C+1)
2180 if (dyn_castFoldableMul(RHS, C2) == LHS)
2181 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2183 // X + ~X --> -1 since ~X = -X-1
2184 if (dyn_castNotVal(LHS) == RHS ||
2185 dyn_castNotVal(RHS) == LHS)
2186 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2189 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2190 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2191 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2194 // A+B --> A|B iff A and B have no bits set in common.
2195 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2196 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2197 APInt LHSKnownOne(IT->getBitWidth(), 0);
2198 APInt LHSKnownZero(IT->getBitWidth(), 0);
2199 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2200 if (LHSKnownZero != 0) {
2201 APInt RHSKnownOne(IT->getBitWidth(), 0);
2202 APInt RHSKnownZero(IT->getBitWidth(), 0);
2203 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2205 // No bits in common -> bitwise or.
2206 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2207 return BinaryOperator::CreateOr(LHS, RHS);
2211 // W*X + Y*Z --> W * (X+Z) iff W == Y
2212 if (I.getType()->isIntOrIntVector()) {
2213 Value *W, *X, *Y, *Z;
2214 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2215 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2219 } else if (Y == X) {
2221 } else if (X == Z) {
2228 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2229 return BinaryOperator::CreateMul(W, NewAdd);
2234 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2236 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2237 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2239 // (X & FF00) + xx00 -> (X+xx00) & FF00
2240 if (LHS->hasOneUse() &&
2241 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2242 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2243 if (Anded == CRHS) {
2244 // See if all bits from the first bit set in the Add RHS up are included
2245 // in the mask. First, get the rightmost bit.
2246 const APInt& AddRHSV = CRHS->getValue();
2248 // Form a mask of all bits from the lowest bit added through the top.
2249 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2251 // See if the and mask includes all of these bits.
2252 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2254 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2255 // Okay, the xform is safe. Insert the new add pronto.
2256 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2257 return BinaryOperator::CreateAnd(NewAdd, C2);
2262 // Try to fold constant add into select arguments.
2263 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2264 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2268 // add (select X 0 (sub n A)) A --> select X A n
2270 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2273 SI = dyn_cast<SelectInst>(RHS);
2276 if (SI && SI->hasOneUse()) {
2277 Value *TV = SI->getTrueValue();
2278 Value *FV = SI->getFalseValue();
2281 // Can we fold the add into the argument of the select?
2282 // We check both true and false select arguments for a matching subtract.
2283 if (match(FV, m_Zero()) &&
2284 match(TV, m_Sub(m_Value(N), m_Specific(A))))
2285 // Fold the add into the true select value.
2286 return SelectInst::Create(SI->getCondition(), N, A);
2287 if (match(TV, m_Zero()) &&
2288 match(FV, m_Sub(m_Value(N), m_Specific(A))))
2289 // Fold the add into the false select value.
2290 return SelectInst::Create(SI->getCondition(), A, N);
2294 // Check for (add (sext x), y), see if we can merge this into an
2295 // integer add followed by a sext.
2296 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2297 // (add (sext x), cst) --> (sext (add x, cst'))
2298 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2300 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2301 if (LHSConv->hasOneUse() &&
2302 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2303 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2304 // Insert the new, smaller add.
2305 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2307 return new SExtInst(NewAdd, I.getType());
2311 // (add (sext x), (sext y)) --> (sext (add int x, y))
2312 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2313 // Only do this if x/y have the same type, if at last one of them has a
2314 // single use (so we don't increase the number of sexts), and if the
2315 // integer add will not overflow.
2316 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2317 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2318 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2319 RHSConv->getOperand(0))) {
2320 // Insert the new integer add.
2321 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2322 RHSConv->getOperand(0), "addconv");
2323 return new SExtInst(NewAdd, I.getType());
2328 return Changed ? &I : 0;
2331 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2332 bool Changed = SimplifyCommutative(I);
2333 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2335 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2337 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2338 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2339 (I.getType())->getValueAPF()))
2340 return ReplaceInstUsesWith(I, LHS);
2343 if (isa<PHINode>(LHS))
2344 if (Instruction *NV = FoldOpIntoPhi(I))
2349 // -A + -B --> -(A + B)
2350 if (Value *LHSV = dyn_castFNegVal(LHS))
2351 return BinaryOperator::CreateFSub(RHS, LHSV);
2354 if (!isa<Constant>(RHS))
2355 if (Value *V = dyn_castFNegVal(RHS))
2356 return BinaryOperator::CreateFSub(LHS, V);
2358 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2359 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2360 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2361 return ReplaceInstUsesWith(I, LHS);
2363 // Check for (add double (sitofp x), y), see if we can merge this into an
2364 // integer add followed by a promotion.
2365 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2366 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2367 // ... if the constant fits in the integer value. This is useful for things
2368 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2369 // requires a constant pool load, and generally allows the add to be better
2371 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2373 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2374 if (LHSConv->hasOneUse() &&
2375 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2376 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2377 // Insert the new integer add.
2378 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2380 return new SIToFPInst(NewAdd, I.getType());
2384 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2385 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2386 // Only do this if x/y have the same type, if at last one of them has a
2387 // single use (so we don't increase the number of int->fp conversions),
2388 // and if the integer add will not overflow.
2389 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2390 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2391 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2392 RHSConv->getOperand(0))) {
2393 // Insert the new integer add.
2394 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2395 RHSConv->getOperand(0), "addconv");
2396 return new SIToFPInst(NewAdd, I.getType());
2401 return Changed ? &I : 0;
2404 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2405 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2407 if (Op0 == Op1) // sub X, X -> 0
2408 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2410 // If this is a 'B = x-(-A)', change to B = x+A...
2411 if (Value *V = dyn_castNegVal(Op1))
2412 return BinaryOperator::CreateAdd(Op0, V);
2414 if (isa<UndefValue>(Op0))
2415 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2416 if (isa<UndefValue>(Op1))
2417 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2419 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2420 // Replace (-1 - A) with (~A)...
2421 if (C->isAllOnesValue())
2422 return BinaryOperator::CreateNot(Op1);
2424 // C - ~X == X + (1+C)
2426 if (match(Op1, m_Not(m_Value(X))))
2427 return BinaryOperator::CreateAdd(X, AddOne(C));
2429 // -(X >>u 31) -> (X >>s 31)
2430 // -(X >>s 31) -> (X >>u 31)
2432 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2433 if (SI->getOpcode() == Instruction::LShr) {
2434 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2435 // Check to see if we are shifting out everything but the sign bit.
2436 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2437 SI->getType()->getPrimitiveSizeInBits()-1) {
2438 // Ok, the transformation is safe. Insert AShr.
2439 return BinaryOperator::Create(Instruction::AShr,
2440 SI->getOperand(0), CU, SI->getName());
2444 else if (SI->getOpcode() == Instruction::AShr) {
2445 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2446 // Check to see if we are shifting out everything but the sign bit.
2447 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2448 SI->getType()->getPrimitiveSizeInBits()-1) {
2449 // Ok, the transformation is safe. Insert LShr.
2450 return BinaryOperator::CreateLShr(
2451 SI->getOperand(0), CU, SI->getName());
2458 // Try to fold constant sub into select arguments.
2459 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2460 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2463 // C - zext(bool) -> bool ? C - 1 : C
2464 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2465 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2466 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2469 if (I.getType() == Type::getInt1Ty(*Context))
2470 return BinaryOperator::CreateXor(Op0, Op1);
2472 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2473 if (Op1I->getOpcode() == Instruction::Add) {
2474 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2475 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2477 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2478 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2480 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2481 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2482 // C1-(X+C2) --> (C1-C2)-X
2483 return BinaryOperator::CreateSub(
2484 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2488 if (Op1I->hasOneUse()) {
2489 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2490 // is not used by anyone else...
2492 if (Op1I->getOpcode() == Instruction::Sub) {
2493 // Swap the two operands of the subexpr...
2494 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2495 Op1I->setOperand(0, IIOp1);
2496 Op1I->setOperand(1, IIOp0);
2498 // Create the new top level add instruction...
2499 return BinaryOperator::CreateAdd(Op0, Op1);
2502 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2504 if (Op1I->getOpcode() == Instruction::And &&
2505 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2506 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2508 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2509 return BinaryOperator::CreateAnd(Op0, NewNot);
2512 // 0 - (X sdiv C) -> (X sdiv -C)
2513 if (Op1I->getOpcode() == Instruction::SDiv)
2514 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2516 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2517 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2518 ConstantExpr::getNeg(DivRHS));
2520 // X - X*C --> X * (1-C)
2521 ConstantInt *C2 = 0;
2522 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2524 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2526 return BinaryOperator::CreateMul(Op0, CP1);
2531 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2532 if (Op0I->getOpcode() == Instruction::Add) {
2533 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2534 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2535 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2536 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2537 } else if (Op0I->getOpcode() == Instruction::Sub) {
2538 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2539 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2545 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2546 if (X == Op1) // X*C - X --> X * (C-1)
2547 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2549 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2550 if (X == dyn_castFoldableMul(Op1, C2))
2551 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2556 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2557 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2559 // If this is a 'B = x-(-A)', change to B = x+A...
2560 if (Value *V = dyn_castFNegVal(Op1))
2561 return BinaryOperator::CreateFAdd(Op0, V);
2563 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2564 if (Op1I->getOpcode() == Instruction::FAdd) {
2565 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2566 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2568 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2569 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2577 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2578 /// comparison only checks the sign bit. If it only checks the sign bit, set
2579 /// TrueIfSigned if the result of the comparison is true when the input value is
2581 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2582 bool &TrueIfSigned) {
2584 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2585 TrueIfSigned = true;
2586 return RHS->isZero();
2587 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2588 TrueIfSigned = true;
2589 return RHS->isAllOnesValue();
2590 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2591 TrueIfSigned = false;
2592 return RHS->isAllOnesValue();
2593 case ICmpInst::ICMP_UGT:
2594 // True if LHS u> RHS and RHS == high-bit-mask - 1
2595 TrueIfSigned = true;
2596 return RHS->getValue() ==
2597 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2598 case ICmpInst::ICMP_UGE:
2599 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2600 TrueIfSigned = true;
2601 return RHS->getValue().isSignBit();
2607 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2608 bool Changed = SimplifyCommutative(I);
2609 Value *Op0 = I.getOperand(0);
2611 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2612 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2614 // Simplify mul instructions with a constant RHS...
2615 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2616 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2618 // ((X << C1)*C2) == (X * (C2 << C1))
2619 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2620 if (SI->getOpcode() == Instruction::Shl)
2621 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2622 return BinaryOperator::CreateMul(SI->getOperand(0),
2623 ConstantExpr::getShl(CI, ShOp));
2626 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2627 if (CI->equalsInt(1)) // X * 1 == X
2628 return ReplaceInstUsesWith(I, Op0);
2629 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2630 return BinaryOperator::CreateNeg(Op0, I.getName());
2632 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2633 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2634 return BinaryOperator::CreateShl(Op0,
2635 ConstantInt::get(Op0->getType(), Val.logBase2()));
2637 } else if (isa<VectorType>(Op1->getType())) {
2638 if (Op1->isNullValue())
2639 return ReplaceInstUsesWith(I, Op1);
2641 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2642 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2643 return BinaryOperator::CreateNeg(Op0, I.getName());
2645 // As above, vector X*splat(1.0) -> X in all defined cases.
2646 if (Constant *Splat = Op1V->getSplatValue()) {
2647 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2648 if (CI->equalsInt(1))
2649 return ReplaceInstUsesWith(I, Op0);
2654 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2655 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2656 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2657 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2658 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2659 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
2660 return BinaryOperator::CreateAdd(Add, C1C2);
2664 // Try to fold constant mul into select arguments.
2665 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2666 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2669 if (isa<PHINode>(Op0))
2670 if (Instruction *NV = FoldOpIntoPhi(I))
2674 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2675 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2676 return BinaryOperator::CreateMul(Op0v, Op1v);
2678 // (X / Y) * Y = X - (X % Y)
2679 // (X / Y) * -Y = (X % Y) - X
2681 Value *Op1 = I.getOperand(1);
2682 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2684 (BO->getOpcode() != Instruction::UDiv &&
2685 BO->getOpcode() != Instruction::SDiv)) {
2687 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2689 Value *Neg = dyn_castNegVal(Op1);
2690 if (BO && BO->hasOneUse() &&
2691 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2692 (BO->getOpcode() == Instruction::UDiv ||
2693 BO->getOpcode() == Instruction::SDiv)) {
2694 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2696 // If the division is exact, X % Y is zero.
2697 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2698 if (SDiv->isExact()) {
2700 return ReplaceInstUsesWith(I, Op0BO);
2702 return BinaryOperator::CreateNeg(Op0BO);
2706 if (BO->getOpcode() == Instruction::UDiv)
2707 Rem = Builder->CreateURem(Op0BO, Op1BO);
2709 Rem = Builder->CreateSRem(Op0BO, Op1BO);
2713 return BinaryOperator::CreateSub(Op0BO, Rem);
2714 return BinaryOperator::CreateSub(Rem, Op0BO);
2718 if (I.getType() == Type::getInt1Ty(*Context))
2719 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2721 // If one of the operands of the multiply is a cast from a boolean value, then
2722 // we know the bool is either zero or one, so this is a 'masking' multiply.
2723 // See if we can simplify things based on how the boolean was originally
2725 CastInst *BoolCast = 0;
2726 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2727 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2730 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2731 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2734 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2735 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2736 const Type *SCOpTy = SCIOp0->getType();
2739 // If the icmp is true iff the sign bit of X is set, then convert this
2740 // multiply into a shift/and combination.
2741 if (isa<ConstantInt>(SCIOp1) &&
2742 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2744 // Shift the X value right to turn it into "all signbits".
2745 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2746 SCOpTy->getPrimitiveSizeInBits()-1);
2747 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2748 BoolCast->getOperand(0)->getName()+".mask");
2750 // If the multiply type is not the same as the source type, sign extend
2751 // or truncate to the multiply type.
2752 if (I.getType() != V->getType())
2753 V = Builder->CreateIntCast(V, I.getType(), true);
2755 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2756 return BinaryOperator::CreateAnd(V, OtherOp);
2761 return Changed ? &I : 0;
2764 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2765 bool Changed = SimplifyCommutative(I);
2766 Value *Op0 = I.getOperand(0);
2768 // Simplify mul instructions with a constant RHS...
2769 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2770 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2771 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2772 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2773 if (Op1F->isExactlyValue(1.0))
2774 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2775 } else if (isa<VectorType>(Op1->getType())) {
2776 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2777 // As above, vector X*splat(1.0) -> X in all defined cases.
2778 if (Constant *Splat = Op1V->getSplatValue()) {
2779 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2780 if (F->isExactlyValue(1.0))
2781 return ReplaceInstUsesWith(I, Op0);
2786 // Try to fold constant mul into select arguments.
2787 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2788 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2791 if (isa<PHINode>(Op0))
2792 if (Instruction *NV = FoldOpIntoPhi(I))
2796 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2797 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2798 return BinaryOperator::CreateFMul(Op0v, Op1v);
2800 return Changed ? &I : 0;
2803 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2805 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2806 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2808 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2809 int NonNullOperand = -1;
2810 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2811 if (ST->isNullValue())
2813 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2814 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2815 if (ST->isNullValue())
2818 if (NonNullOperand == -1)
2821 Value *SelectCond = SI->getOperand(0);
2823 // Change the div/rem to use 'Y' instead of the select.
2824 I.setOperand(1, SI->getOperand(NonNullOperand));
2826 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2827 // problem. However, the select, or the condition of the select may have
2828 // multiple uses. Based on our knowledge that the operand must be non-zero,
2829 // propagate the known value for the select into other uses of it, and
2830 // propagate a known value of the condition into its other users.
2832 // If the select and condition only have a single use, don't bother with this,
2834 if (SI->use_empty() && SelectCond->hasOneUse())
2837 // Scan the current block backward, looking for other uses of SI.
2838 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2840 while (BBI != BBFront) {
2842 // If we found a call to a function, we can't assume it will return, so
2843 // information from below it cannot be propagated above it.
2844 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2847 // Replace uses of the select or its condition with the known values.
2848 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2851 *I = SI->getOperand(NonNullOperand);
2853 } else if (*I == SelectCond) {
2854 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2855 ConstantInt::getFalse(*Context);
2860 // If we past the instruction, quit looking for it.
2863 if (&*BBI == SelectCond)
2866 // If we ran out of things to eliminate, break out of the loop.
2867 if (SelectCond == 0 && SI == 0)
2875 /// This function implements the transforms on div instructions that work
2876 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2877 /// used by the visitors to those instructions.
2878 /// @brief Transforms common to all three div instructions
2879 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2880 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2882 // undef / X -> 0 for integer.
2883 // undef / X -> undef for FP (the undef could be a snan).
2884 if (isa<UndefValue>(Op0)) {
2885 if (Op0->getType()->isFPOrFPVector())
2886 return ReplaceInstUsesWith(I, Op0);
2887 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2890 // X / undef -> undef
2891 if (isa<UndefValue>(Op1))
2892 return ReplaceInstUsesWith(I, Op1);
2897 /// This function implements the transforms common to both integer division
2898 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2899 /// division instructions.
2900 /// @brief Common integer divide transforms
2901 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2902 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2904 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2906 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2907 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2908 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2909 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2912 Constant *CI = ConstantInt::get(I.getType(), 1);
2913 return ReplaceInstUsesWith(I, CI);
2916 if (Instruction *Common = commonDivTransforms(I))
2919 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2920 // This does not apply for fdiv.
2921 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2924 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2926 if (RHS->equalsInt(1))
2927 return ReplaceInstUsesWith(I, Op0);
2929 // (X / C1) / C2 -> X / (C1*C2)
2930 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2931 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2932 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2933 if (MultiplyOverflows(RHS, LHSRHS,
2934 I.getOpcode()==Instruction::SDiv))
2935 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2937 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2938 ConstantExpr::getMul(RHS, LHSRHS));
2941 if (!RHS->isZero()) { // avoid X udiv 0
2942 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2943 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2945 if (isa<PHINode>(Op0))
2946 if (Instruction *NV = FoldOpIntoPhi(I))
2951 // 0 / X == 0, we don't need to preserve faults!
2952 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2953 if (LHS->equalsInt(0))
2954 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2956 // It can't be division by zero, hence it must be division by one.
2957 if (I.getType() == Type::getInt1Ty(*Context))
2958 return ReplaceInstUsesWith(I, Op0);
2960 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2961 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2964 return ReplaceInstUsesWith(I, Op0);
2970 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2973 // Handle the integer div common cases
2974 if (Instruction *Common = commonIDivTransforms(I))
2977 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2978 // X udiv C^2 -> X >> C
2979 // Check to see if this is an unsigned division with an exact power of 2,
2980 // if so, convert to a right shift.
2981 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2982 return BinaryOperator::CreateLShr(Op0,
2983 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2985 // X udiv C, where C >= signbit
2986 if (C->getValue().isNegative()) {
2987 Value *IC = Builder->CreateICmpULT( Op0, C);
2988 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2989 ConstantInt::get(I.getType(), 1));
2993 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2994 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2995 if (RHSI->getOpcode() == Instruction::Shl &&
2996 isa<ConstantInt>(RHSI->getOperand(0))) {
2997 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2998 if (C1.isPowerOf2()) {
2999 Value *N = RHSI->getOperand(1);
3000 const Type *NTy = N->getType();
3001 if (uint32_t C2 = C1.logBase2())
3002 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3003 return BinaryOperator::CreateLShr(Op0, N);
3008 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3009 // where C1&C2 are powers of two.
3010 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3011 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3012 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3013 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3014 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3015 // Compute the shift amounts
3016 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3017 // Construct the "on true" case of the select
3018 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3019 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3021 // Construct the "on false" case of the select
3022 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3023 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3025 // construct the select instruction and return it.
3026 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3032 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3033 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3035 // Handle the integer div common cases
3036 if (Instruction *Common = commonIDivTransforms(I))
3039 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3041 if (RHS->isAllOnesValue())
3042 return BinaryOperator::CreateNeg(Op0);
3044 // sdiv X, C --> ashr X, log2(C)
3045 if (cast<SDivOperator>(&I)->isExact() &&
3046 RHS->getValue().isNonNegative() &&
3047 RHS->getValue().isPowerOf2()) {
3048 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3049 RHS->getValue().exactLogBase2());
3050 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3053 // -X/C --> X/-C provided the negation doesn't overflow.
3054 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3055 if (isa<Constant>(Sub->getOperand(0)) &&
3056 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3057 Sub->hasNoSignedWrap())
3058 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3059 ConstantExpr::getNeg(RHS));
3062 // If the sign bits of both operands are zero (i.e. we can prove they are
3063 // unsigned inputs), turn this into a udiv.
3064 if (I.getType()->isInteger()) {
3065 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3066 if (MaskedValueIsZero(Op0, Mask)) {
3067 if (MaskedValueIsZero(Op1, Mask)) {
3068 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3069 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3071 ConstantInt *ShiftedInt;
3072 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3073 ShiftedInt->getValue().isPowerOf2()) {
3074 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3075 // Safe because the only negative value (1 << Y) can take on is
3076 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3077 // the sign bit set.
3078 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3086 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3087 return commonDivTransforms(I);
3090 /// This function implements the transforms on rem instructions that work
3091 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3092 /// is used by the visitors to those instructions.
3093 /// @brief Transforms common to all three rem instructions
3094 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3095 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3097 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3098 if (I.getType()->isFPOrFPVector())
3099 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3100 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3102 if (isa<UndefValue>(Op1))
3103 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3105 // Handle cases involving: rem X, (select Cond, Y, Z)
3106 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3112 /// This function implements the transforms common to both integer remainder
3113 /// instructions (urem and srem). It is called by the visitors to those integer
3114 /// remainder instructions.
3115 /// @brief Common integer remainder transforms
3116 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3117 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3119 if (Instruction *common = commonRemTransforms(I))
3122 // 0 % X == 0 for integer, we don't need to preserve faults!
3123 if (Constant *LHS = dyn_cast<Constant>(Op0))
3124 if (LHS->isNullValue())
3125 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3127 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3128 // X % 0 == undef, we don't need to preserve faults!
3129 if (RHS->equalsInt(0))
3130 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3132 if (RHS->equalsInt(1)) // X % 1 == 0
3133 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3135 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3136 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3137 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3139 } else if (isa<PHINode>(Op0I)) {
3140 if (Instruction *NV = FoldOpIntoPhi(I))
3144 // See if we can fold away this rem instruction.
3145 if (SimplifyDemandedInstructionBits(I))
3153 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3154 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3156 if (Instruction *common = commonIRemTransforms(I))
3159 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3160 // X urem C^2 -> X and C
3161 // Check to see if this is an unsigned remainder with an exact power of 2,
3162 // if so, convert to a bitwise and.
3163 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3164 if (C->getValue().isPowerOf2())
3165 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3168 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3169 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3170 if (RHSI->getOpcode() == Instruction::Shl &&
3171 isa<ConstantInt>(RHSI->getOperand(0))) {
3172 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3173 Constant *N1 = Constant::getAllOnesValue(I.getType());
3174 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3175 return BinaryOperator::CreateAnd(Op0, Add);
3180 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3181 // where C1&C2 are powers of two.
3182 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3183 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3184 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3185 // STO == 0 and SFO == 0 handled above.
3186 if ((STO->getValue().isPowerOf2()) &&
3187 (SFO->getValue().isPowerOf2())) {
3188 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3189 SI->getName()+".t");
3190 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3191 SI->getName()+".f");
3192 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3200 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3201 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3203 // Handle the integer rem common cases
3204 if (Instruction *Common = commonIRemTransforms(I))
3207 if (Value *RHSNeg = dyn_castNegVal(Op1))
3208 if (!isa<Constant>(RHSNeg) ||
3209 (isa<ConstantInt>(RHSNeg) &&
3210 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3212 Worklist.AddValue(I.getOperand(1));
3213 I.setOperand(1, RHSNeg);
3217 // If the sign bits of both operands are zero (i.e. we can prove they are
3218 // unsigned inputs), turn this into a urem.
3219 if (I.getType()->isInteger()) {
3220 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3221 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3222 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3223 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3227 // If it's a constant vector, flip any negative values positive.
3228 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3229 unsigned VWidth = RHSV->getNumOperands();
3231 bool hasNegative = false;
3232 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3233 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3234 if (RHS->getValue().isNegative())
3238 std::vector<Constant *> Elts(VWidth);
3239 for (unsigned i = 0; i != VWidth; ++i) {
3240 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3241 if (RHS->getValue().isNegative())
3242 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3248 Constant *NewRHSV = ConstantVector::get(Elts);
3249 if (NewRHSV != RHSV) {
3250 Worklist.AddValue(I.getOperand(1));
3251 I.setOperand(1, NewRHSV);
3260 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3261 return commonRemTransforms(I);
3264 // isOneBitSet - Return true if there is exactly one bit set in the specified
3266 static bool isOneBitSet(const ConstantInt *CI) {
3267 return CI->getValue().isPowerOf2();
3270 // isHighOnes - Return true if the constant is of the form 1+0+.
3271 // This is the same as lowones(~X).
3272 static bool isHighOnes(const ConstantInt *CI) {
3273 return (~CI->getValue() + 1).isPowerOf2();
3276 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3277 /// are carefully arranged to allow folding of expressions such as:
3279 /// (A < B) | (A > B) --> (A != B)
3281 /// Note that this is only valid if the first and second predicates have the
3282 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3284 /// Three bits are used to represent the condition, as follows:
3289 /// <=> Value Definition
3290 /// 000 0 Always false
3297 /// 111 7 Always true
3299 static unsigned getICmpCode(const ICmpInst *ICI) {
3300 switch (ICI->getPredicate()) {
3302 case ICmpInst::ICMP_UGT: return 1; // 001
3303 case ICmpInst::ICMP_SGT: return 1; // 001
3304 case ICmpInst::ICMP_EQ: return 2; // 010
3305 case ICmpInst::ICMP_UGE: return 3; // 011
3306 case ICmpInst::ICMP_SGE: return 3; // 011
3307 case ICmpInst::ICMP_ULT: return 4; // 100
3308 case ICmpInst::ICMP_SLT: return 4; // 100
3309 case ICmpInst::ICMP_NE: return 5; // 101
3310 case ICmpInst::ICMP_ULE: return 6; // 110
3311 case ICmpInst::ICMP_SLE: return 6; // 110
3314 llvm_unreachable("Invalid ICmp predicate!");
3319 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3320 /// predicate into a three bit mask. It also returns whether it is an ordered
3321 /// predicate by reference.
3322 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3325 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3326 case FCmpInst::FCMP_UNO: return 0; // 000
3327 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3328 case FCmpInst::FCMP_UGT: return 1; // 001
3329 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3330 case FCmpInst::FCMP_UEQ: return 2; // 010
3331 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3332 case FCmpInst::FCMP_UGE: return 3; // 011
3333 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3334 case FCmpInst::FCMP_ULT: return 4; // 100
3335 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3336 case FCmpInst::FCMP_UNE: return 5; // 101
3337 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3338 case FCmpInst::FCMP_ULE: return 6; // 110
3341 // Not expecting FCMP_FALSE and FCMP_TRUE;
3342 llvm_unreachable("Unexpected FCmp predicate!");
3347 /// getICmpValue - This is the complement of getICmpCode, which turns an
3348 /// opcode and two operands into either a constant true or false, or a brand
3349 /// new ICmp instruction. The sign is passed in to determine which kind
3350 /// of predicate to use in the new icmp instruction.
3351 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3352 LLVMContext *Context) {
3354 default: llvm_unreachable("Illegal ICmp code!");
3355 case 0: return ConstantInt::getFalse(*Context);
3358 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3360 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3361 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3364 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3366 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3369 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3371 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3372 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3375 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3377 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3378 case 7: return ConstantInt::getTrue(*Context);
3382 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3383 /// opcode and two operands into either a FCmp instruction. isordered is passed
3384 /// in to determine which kind of predicate to use in the new fcmp instruction.
3385 static Value *getFCmpValue(bool isordered, unsigned code,
3386 Value *LHS, Value *RHS, LLVMContext *Context) {
3388 default: llvm_unreachable("Illegal FCmp code!");
3391 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3393 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3396 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3398 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3401 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3403 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3406 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3408 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3411 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3413 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3416 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3418 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3421 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3423 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3424 case 7: return ConstantInt::getTrue(*Context);
3428 /// PredicatesFoldable - Return true if both predicates match sign or if at
3429 /// least one of them is an equality comparison (which is signless).
3430 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3431 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3432 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3433 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3437 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3438 struct FoldICmpLogical {
3441 ICmpInst::Predicate pred;
3442 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3443 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3444 pred(ICI->getPredicate()) {}
3445 bool shouldApply(Value *V) const {
3446 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3447 if (PredicatesFoldable(pred, ICI->getPredicate()))
3448 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3449 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3452 Instruction *apply(Instruction &Log) const {
3453 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3454 if (ICI->getOperand(0) != LHS) {
3455 assert(ICI->getOperand(1) == LHS);
3456 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3459 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3460 unsigned LHSCode = getICmpCode(ICI);
3461 unsigned RHSCode = getICmpCode(RHSICI);
3463 switch (Log.getOpcode()) {
3464 case Instruction::And: Code = LHSCode & RHSCode; break;
3465 case Instruction::Or: Code = LHSCode | RHSCode; break;
3466 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3467 default: llvm_unreachable("Illegal logical opcode!"); return 0;
3470 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3471 ICmpInst::isSignedPredicate(ICI->getPredicate());
3473 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3474 if (Instruction *I = dyn_cast<Instruction>(RV))
3476 // Otherwise, it's a constant boolean value...
3477 return IC.ReplaceInstUsesWith(Log, RV);
3480 } // end anonymous namespace
3482 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3483 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3484 // guaranteed to be a binary operator.
3485 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3487 ConstantInt *AndRHS,
3488 BinaryOperator &TheAnd) {
3489 Value *X = Op->getOperand(0);
3490 Constant *Together = 0;
3492 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3494 switch (Op->getOpcode()) {
3495 case Instruction::Xor:
3496 if (Op->hasOneUse()) {
3497 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3498 Value *And = Builder->CreateAnd(X, AndRHS);
3500 return BinaryOperator::CreateXor(And, Together);
3503 case Instruction::Or:
3504 if (Together == AndRHS) // (X | C) & C --> C
3505 return ReplaceInstUsesWith(TheAnd, AndRHS);
3507 if (Op->hasOneUse() && Together != OpRHS) {
3508 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3509 Value *Or = Builder->CreateOr(X, Together);
3511 return BinaryOperator::CreateAnd(Or, AndRHS);
3514 case Instruction::Add:
3515 if (Op->hasOneUse()) {
3516 // Adding a one to a single bit bit-field should be turned into an XOR
3517 // of the bit. First thing to check is to see if this AND is with a
3518 // single bit constant.
3519 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3521 // If there is only one bit set...
3522 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3523 // Ok, at this point, we know that we are masking the result of the
3524 // ADD down to exactly one bit. If the constant we are adding has
3525 // no bits set below this bit, then we can eliminate the ADD.
3526 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3528 // Check to see if any bits below the one bit set in AndRHSV are set.
3529 if ((AddRHS & (AndRHSV-1)) == 0) {
3530 // If not, the only thing that can effect the output of the AND is
3531 // the bit specified by AndRHSV. If that bit is set, the effect of
3532 // the XOR is to toggle the bit. If it is clear, then the ADD has
3534 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3535 TheAnd.setOperand(0, X);
3538 // Pull the XOR out of the AND.
3539 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3540 NewAnd->takeName(Op);
3541 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3548 case Instruction::Shl: {
3549 // We know that the AND will not produce any of the bits shifted in, so if
3550 // the anded constant includes them, clear them now!
3552 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3553 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3554 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3555 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3557 if (CI->getValue() == ShlMask) {
3558 // Masking out bits that the shift already masks
3559 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3560 } else if (CI != AndRHS) { // Reducing bits set in and.
3561 TheAnd.setOperand(1, CI);
3566 case Instruction::LShr:
3568 // We know that the AND will not produce any of the bits shifted in, so if
3569 // the anded constant includes them, clear them now! This only applies to
3570 // unsigned shifts, because a signed shr may bring in set bits!
3572 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3573 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3574 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3575 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3577 if (CI->getValue() == ShrMask) {
3578 // Masking out bits that the shift already masks.
3579 return ReplaceInstUsesWith(TheAnd, Op);
3580 } else if (CI != AndRHS) {
3581 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3586 case Instruction::AShr:
3588 // See if this is shifting in some sign extension, then masking it out
3590 if (Op->hasOneUse()) {
3591 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3592 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3593 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3594 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3595 if (C == AndRHS) { // Masking out bits shifted in.
3596 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3597 // Make the argument unsigned.
3598 Value *ShVal = Op->getOperand(0);
3599 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3600 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3609 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3610 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3611 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3612 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3613 /// insert new instructions.
3614 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3615 bool isSigned, bool Inside,
3617 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3618 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3619 "Lo is not <= Hi in range emission code!");
3622 if (Lo == Hi) // Trivially false.
3623 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3625 // V >= Min && V < Hi --> V < Hi
3626 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3627 ICmpInst::Predicate pred = (isSigned ?
3628 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3629 return new ICmpInst(pred, V, Hi);
3632 // Emit V-Lo <u Hi-Lo
3633 Constant *NegLo = ConstantExpr::getNeg(Lo);
3634 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3635 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3636 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3639 if (Lo == Hi) // Trivially true.
3640 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3642 // V < Min || V >= Hi -> V > Hi-1
3643 Hi = SubOne(cast<ConstantInt>(Hi));
3644 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3645 ICmpInst::Predicate pred = (isSigned ?
3646 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3647 return new ICmpInst(pred, V, Hi);
3650 // Emit V-Lo >u Hi-1-Lo
3651 // Note that Hi has already had one subtracted from it, above.
3652 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3653 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3654 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3655 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3658 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3659 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3660 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3661 // not, since all 1s are not contiguous.
3662 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3663 const APInt& V = Val->getValue();
3664 uint32_t BitWidth = Val->getType()->getBitWidth();
3665 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3667 // look for the first zero bit after the run of ones
3668 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3669 // look for the first non-zero bit
3670 ME = V.getActiveBits();
3674 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3675 /// where isSub determines whether the operator is a sub. If we can fold one of
3676 /// the following xforms:
3678 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3679 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3680 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3682 /// return (A +/- B).
3684 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3685 ConstantInt *Mask, bool isSub,
3687 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3688 if (!LHSI || LHSI->getNumOperands() != 2 ||
3689 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3691 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3693 switch (LHSI->getOpcode()) {
3695 case Instruction::And:
3696 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3697 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3698 if ((Mask->getValue().countLeadingZeros() +
3699 Mask->getValue().countPopulation()) ==
3700 Mask->getValue().getBitWidth())
3703 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3704 // part, we don't need any explicit masks to take them out of A. If that
3705 // is all N is, ignore it.
3706 uint32_t MB = 0, ME = 0;
3707 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3708 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3709 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3710 if (MaskedValueIsZero(RHS, Mask))
3715 case Instruction::Or:
3716 case Instruction::Xor:
3717 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3718 if ((Mask->getValue().countLeadingZeros() +
3719 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3720 && ConstantExpr::getAnd(N, Mask)->isNullValue())
3726 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3727 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3730 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3731 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3732 ICmpInst *LHS, ICmpInst *RHS) {
3734 ConstantInt *LHSCst, *RHSCst;
3735 ICmpInst::Predicate LHSCC, RHSCC;
3737 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3738 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3739 m_ConstantInt(LHSCst))) ||
3740 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3741 m_ConstantInt(RHSCst))))
3744 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3745 // where C is a power of 2
3746 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3747 LHSCst->getValue().isPowerOf2()) {
3748 Value *NewOr = Builder->CreateOr(Val, Val2);
3749 return new ICmpInst(LHSCC, NewOr, LHSCst);
3752 // From here on, we only handle:
3753 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3754 if (Val != Val2) return 0;
3756 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3757 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3758 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3759 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3760 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3763 // We can't fold (ugt x, C) & (sgt x, C2).
3764 if (!PredicatesFoldable(LHSCC, RHSCC))
3767 // Ensure that the larger constant is on the RHS.
3769 if (ICmpInst::isSignedPredicate(LHSCC) ||
3770 (ICmpInst::isEquality(LHSCC) &&
3771 ICmpInst::isSignedPredicate(RHSCC)))
3772 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3774 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3777 std::swap(LHS, RHS);
3778 std::swap(LHSCst, RHSCst);
3779 std::swap(LHSCC, RHSCC);
3782 // At this point, we know we have have two icmp instructions
3783 // comparing a value against two constants and and'ing the result
3784 // together. Because of the above check, we know that we only have
3785 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3786 // (from the FoldICmpLogical check above), that the two constants
3787 // are not equal and that the larger constant is on the RHS
3788 assert(LHSCst != RHSCst && "Compares not folded above?");
3791 default: llvm_unreachable("Unknown integer condition code!");
3792 case ICmpInst::ICMP_EQ:
3794 default: llvm_unreachable("Unknown integer condition code!");
3795 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3796 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3797 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3798 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3799 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3800 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3801 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3802 return ReplaceInstUsesWith(I, LHS);
3804 case ICmpInst::ICMP_NE:
3806 default: llvm_unreachable("Unknown integer condition code!");
3807 case ICmpInst::ICMP_ULT:
3808 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3809 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3810 break; // (X != 13 & X u< 15) -> no change
3811 case ICmpInst::ICMP_SLT:
3812 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3813 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3814 break; // (X != 13 & X s< 15) -> no change
3815 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3816 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3817 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3818 return ReplaceInstUsesWith(I, RHS);
3819 case ICmpInst::ICMP_NE:
3820 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3821 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3822 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3823 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3824 ConstantInt::get(Add->getType(), 1));
3826 break; // (X != 13 & X != 15) -> no change
3829 case ICmpInst::ICMP_ULT:
3831 default: llvm_unreachable("Unknown integer condition code!");
3832 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3833 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3834 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3835 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3837 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3838 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3839 return ReplaceInstUsesWith(I, LHS);
3840 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3844 case ICmpInst::ICMP_SLT:
3846 default: llvm_unreachable("Unknown integer condition code!");
3847 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3848 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3849 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3850 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3852 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3853 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3854 return ReplaceInstUsesWith(I, LHS);
3855 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3859 case ICmpInst::ICMP_UGT:
3861 default: llvm_unreachable("Unknown integer condition code!");
3862 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3863 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3864 return ReplaceInstUsesWith(I, RHS);
3865 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3867 case ICmpInst::ICMP_NE:
3868 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3869 return new ICmpInst(LHSCC, Val, RHSCst);
3870 break; // (X u> 13 & X != 15) -> no change
3871 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3872 return InsertRangeTest(Val, AddOne(LHSCst),
3873 RHSCst, false, true, I);
3874 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3878 case ICmpInst::ICMP_SGT:
3880 default: llvm_unreachable("Unknown integer condition code!");
3881 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3882 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3883 return ReplaceInstUsesWith(I, RHS);
3884 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3886 case ICmpInst::ICMP_NE:
3887 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3888 return new ICmpInst(LHSCC, Val, RHSCst);
3889 break; // (X s> 13 & X != 15) -> no change
3890 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3891 return InsertRangeTest(Val, AddOne(LHSCst),
3892 RHSCst, true, true, I);
3893 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3902 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3905 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3906 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3907 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3908 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3909 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3910 // If either of the constants are nans, then the whole thing returns
3912 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3913 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3914 return new FCmpInst(FCmpInst::FCMP_ORD,
3915 LHS->getOperand(0), RHS->getOperand(0));
3918 // Handle vector zeros. This occurs because the canonical form of
3919 // "fcmp ord x,x" is "fcmp ord x, 0".
3920 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3921 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3922 return new FCmpInst(FCmpInst::FCMP_ORD,
3923 LHS->getOperand(0), RHS->getOperand(0));
3927 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3928 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3929 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3932 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3933 // Swap RHS operands to match LHS.
3934 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3935 std::swap(Op1LHS, Op1RHS);
3938 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3939 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3941 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3943 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3944 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3945 if (Op0CC == FCmpInst::FCMP_TRUE)
3946 return ReplaceInstUsesWith(I, RHS);
3947 if (Op1CC == FCmpInst::FCMP_TRUE)
3948 return ReplaceInstUsesWith(I, LHS);
3952 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3953 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3955 std::swap(LHS, RHS);
3956 std::swap(Op0Pred, Op1Pred);
3957 std::swap(Op0Ordered, Op1Ordered);
3960 // uno && ueq -> uno && (uno || eq) -> ueq
3961 // ord && olt -> ord && (ord && lt) -> olt
3962 if (Op0Ordered == Op1Ordered)
3963 return ReplaceInstUsesWith(I, RHS);
3965 // uno && oeq -> uno && (ord && eq) -> false
3966 // uno && ord -> false
3968 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3969 // ord && ueq -> ord && (uno || eq) -> oeq
3970 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3971 Op0LHS, Op0RHS, Context));
3979 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3980 bool Changed = SimplifyCommutative(I);
3981 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3983 if (isa<UndefValue>(Op1)) // X & undef -> 0
3984 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3988 return ReplaceInstUsesWith(I, Op1);
3990 // See if we can simplify any instructions used by the instruction whose sole
3991 // purpose is to compute bits we don't care about.
3992 if (SimplifyDemandedInstructionBits(I))
3994 if (isa<VectorType>(I.getType())) {
3995 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3996 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3997 return ReplaceInstUsesWith(I, I.getOperand(0));
3998 } else if (isa<ConstantAggregateZero>(Op1)) {
3999 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4003 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4004 const APInt& AndRHSMask = AndRHS->getValue();
4005 APInt NotAndRHS(~AndRHSMask);
4007 // Optimize a variety of ((val OP C1) & C2) combinations...
4008 if (isa<BinaryOperator>(Op0)) {
4009 Instruction *Op0I = cast<Instruction>(Op0);
4010 Value *Op0LHS = Op0I->getOperand(0);
4011 Value *Op0RHS = Op0I->getOperand(1);
4012 switch (Op0I->getOpcode()) {
4013 case Instruction::Xor:
4014 case Instruction::Or:
4015 // If the mask is only needed on one incoming arm, push it up.
4016 if (Op0I->hasOneUse()) {
4017 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4018 // Not masking anything out for the LHS, move to RHS.
4019 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4020 Op0RHS->getName()+".masked");
4021 return BinaryOperator::Create(
4022 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4024 if (!isa<Constant>(Op0RHS) &&
4025 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4026 // Not masking anything out for the RHS, move to LHS.
4027 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4028 Op0LHS->getName()+".masked");
4029 return BinaryOperator::Create(
4030 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4035 case Instruction::Add:
4036 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4037 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4038 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4039 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4040 return BinaryOperator::CreateAnd(V, AndRHS);
4041 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4042 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4045 case Instruction::Sub:
4046 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4047 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4048 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4049 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4050 return BinaryOperator::CreateAnd(V, AndRHS);
4052 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4053 // has 1's for all bits that the subtraction with A might affect.
4054 if (Op0I->hasOneUse()) {
4055 uint32_t BitWidth = AndRHSMask.getBitWidth();
4056 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4057 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4059 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4060 if (!(A && A->isZero()) && // avoid infinite recursion.
4061 MaskedValueIsZero(Op0LHS, Mask)) {
4062 Value *NewNeg = Builder->CreateNeg(Op0RHS);
4063 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4068 case Instruction::Shl:
4069 case Instruction::LShr:
4070 // (1 << x) & 1 --> zext(x == 0)
4071 // (1 >> x) & 1 --> zext(x == 0)
4072 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4074 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4075 return new ZExtInst(NewICmp, I.getType());
4080 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4081 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4083 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4084 // If this is an integer truncation or change from signed-to-unsigned, and
4085 // if the source is an and/or with immediate, transform it. This
4086 // frequently occurs for bitfield accesses.
4087 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4088 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4089 CastOp->getNumOperands() == 2)
4090 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4091 if (CastOp->getOpcode() == Instruction::And) {
4092 // Change: and (cast (and X, C1) to T), C2
4093 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4094 // This will fold the two constants together, which may allow
4095 // other simplifications.
4096 Value *NewCast = Builder->CreateTruncOrBitCast(
4097 CastOp->getOperand(0), I.getType(),
4098 CastOp->getName()+".shrunk");
4099 // trunc_or_bitcast(C1)&C2
4100 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4101 C3 = ConstantExpr::getAnd(C3, AndRHS);
4102 return BinaryOperator::CreateAnd(NewCast, C3);
4103 } else if (CastOp->getOpcode() == Instruction::Or) {
4104 // Change: and (cast (or X, C1) to T), C2
4105 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4106 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4107 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4109 return ReplaceInstUsesWith(I, AndRHS);
4115 // Try to fold constant and into select arguments.
4116 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4117 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4119 if (isa<PHINode>(Op0))
4120 if (Instruction *NV = FoldOpIntoPhi(I))
4124 Value *Op0NotVal = dyn_castNotVal(Op0);
4125 Value *Op1NotVal = dyn_castNotVal(Op1);
4127 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4128 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4130 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4131 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4132 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4133 I.getName()+".demorgan");
4134 return BinaryOperator::CreateNot(Or);
4138 Value *A = 0, *B = 0, *C = 0, *D = 0;
4139 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4140 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4141 return ReplaceInstUsesWith(I, Op1);
4143 // (A|B) & ~(A&B) -> A^B
4144 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4145 if ((A == C && B == D) || (A == D && B == C))
4146 return BinaryOperator::CreateXor(A, B);
4150 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4151 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4152 return ReplaceInstUsesWith(I, Op0);
4154 // ~(A&B) & (A|B) -> A^B
4155 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4156 if ((A == C && B == D) || (A == D && B == C))
4157 return BinaryOperator::CreateXor(A, B);
4161 if (Op0->hasOneUse() &&
4162 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4163 if (A == Op1) { // (A^B)&A -> A&(A^B)
4164 I.swapOperands(); // Simplify below
4165 std::swap(Op0, Op1);
4166 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4167 cast<BinaryOperator>(Op0)->swapOperands();
4168 I.swapOperands(); // Simplify below
4169 std::swap(Op0, Op1);
4173 if (Op1->hasOneUse() &&
4174 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4175 if (B == Op0) { // B&(A^B) -> B&(B^A)
4176 cast<BinaryOperator>(Op1)->swapOperands();
4179 if (A == Op0) // A&(A^B) -> A & ~B
4180 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4183 // (A&((~A)|B)) -> A&B
4184 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4185 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4186 return BinaryOperator::CreateAnd(A, Op1);
4187 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4188 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4189 return BinaryOperator::CreateAnd(A, Op0);
4192 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4193 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4194 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4197 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4198 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4202 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4203 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4204 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4205 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4206 const Type *SrcTy = Op0C->getOperand(0)->getType();
4207 if (SrcTy == Op1C->getOperand(0)->getType() &&
4208 SrcTy->isIntOrIntVector() &&
4209 // Only do this if the casts both really cause code to be generated.
4210 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4212 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4214 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4215 Op1C->getOperand(0), I.getName());
4216 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4220 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4221 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4222 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4223 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4224 SI0->getOperand(1) == SI1->getOperand(1) &&
4225 (SI0->hasOneUse() || SI1->hasOneUse())) {
4227 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4229 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4230 SI1->getOperand(1));
4234 // If and'ing two fcmp, try combine them into one.
4235 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4236 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4237 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4241 return Changed ? &I : 0;
4244 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4245 /// capable of providing pieces of a bswap. The subexpression provides pieces
4246 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4247 /// the expression came from the corresponding "byte swapped" byte in some other
4248 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4249 /// we know that the expression deposits the low byte of %X into the high byte
4250 /// of the bswap result and that all other bytes are zero. This expression is
4251 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4254 /// This function returns true if the match was unsuccessful and false if so.
4255 /// On entry to the function the "OverallLeftShift" is a signed integer value
4256 /// indicating the number of bytes that the subexpression is later shifted. For
4257 /// example, if the expression is later right shifted by 16 bits, the
4258 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4259 /// byte of ByteValues is actually being set.
4261 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4262 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4263 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4264 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4265 /// always in the local (OverallLeftShift) coordinate space.
4267 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4268 SmallVector<Value*, 8> &ByteValues) {
4269 if (Instruction *I = dyn_cast<Instruction>(V)) {
4270 // If this is an or instruction, it may be an inner node of the bswap.
4271 if (I->getOpcode() == Instruction::Or) {
4272 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4274 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4278 // If this is a logical shift by a constant multiple of 8, recurse with
4279 // OverallLeftShift and ByteMask adjusted.
4280 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4282 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4283 // Ensure the shift amount is defined and of a byte value.
4284 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4287 unsigned ByteShift = ShAmt >> 3;
4288 if (I->getOpcode() == Instruction::Shl) {
4289 // X << 2 -> collect(X, +2)
4290 OverallLeftShift += ByteShift;
4291 ByteMask >>= ByteShift;
4293 // X >>u 2 -> collect(X, -2)
4294 OverallLeftShift -= ByteShift;
4295 ByteMask <<= ByteShift;
4296 ByteMask &= (~0U >> (32-ByteValues.size()));
4299 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4300 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4302 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4306 // If this is a logical 'and' with a mask that clears bytes, clear the
4307 // corresponding bytes in ByteMask.
4308 if (I->getOpcode() == Instruction::And &&
4309 isa<ConstantInt>(I->getOperand(1))) {
4310 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4311 unsigned NumBytes = ByteValues.size();
4312 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4313 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4315 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4316 // If this byte is masked out by a later operation, we don't care what
4318 if ((ByteMask & (1 << i)) == 0)
4321 // If the AndMask is all zeros for this byte, clear the bit.
4322 APInt MaskB = AndMask & Byte;
4324 ByteMask &= ~(1U << i);
4328 // If the AndMask is not all ones for this byte, it's not a bytezap.
4332 // Otherwise, this byte is kept.
4335 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4340 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4341 // the input value to the bswap. Some observations: 1) if more than one byte
4342 // is demanded from this input, then it could not be successfully assembled
4343 // into a byteswap. At least one of the two bytes would not be aligned with
4344 // their ultimate destination.
4345 if (!isPowerOf2_32(ByteMask)) return true;
4346 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4348 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4349 // is demanded, it needs to go into byte 0 of the result. This means that the
4350 // byte needs to be shifted until it lands in the right byte bucket. The
4351 // shift amount depends on the position: if the byte is coming from the high
4352 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4353 // low part, it must be shifted left.
4354 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4355 if (InputByteNo < ByteValues.size()/2) {
4356 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4359 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4363 // If the destination byte value is already defined, the values are or'd
4364 // together, which isn't a bswap (unless it's an or of the same bits).
4365 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4367 ByteValues[DestByteNo] = V;
4371 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4372 /// If so, insert the new bswap intrinsic and return it.
4373 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4374 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4375 if (!ITy || ITy->getBitWidth() % 16 ||
4376 // ByteMask only allows up to 32-byte values.
4377 ITy->getBitWidth() > 32*8)
4378 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4380 /// ByteValues - For each byte of the result, we keep track of which value
4381 /// defines each byte.
4382 SmallVector<Value*, 8> ByteValues;
4383 ByteValues.resize(ITy->getBitWidth()/8);
4385 // Try to find all the pieces corresponding to the bswap.
4386 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4387 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4390 // Check to see if all of the bytes come from the same value.
4391 Value *V = ByteValues[0];
4392 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4394 // Check to make sure that all of the bytes come from the same value.
4395 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4396 if (ByteValues[i] != V)
4398 const Type *Tys[] = { ITy };
4399 Module *M = I.getParent()->getParent()->getParent();
4400 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4401 return CallInst::Create(F, V);
4404 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4405 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4406 /// we can simplify this expression to "cond ? C : D or B".
4407 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4409 LLVMContext *Context) {
4410 // If A is not a select of -1/0, this cannot match.
4412 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4415 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4416 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4417 return SelectInst::Create(Cond, C, B);
4418 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4419 return SelectInst::Create(Cond, C, B);
4420 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4421 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4422 return SelectInst::Create(Cond, C, D);
4423 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4424 return SelectInst::Create(Cond, C, D);
4428 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4429 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4430 ICmpInst *LHS, ICmpInst *RHS) {
4432 ConstantInt *LHSCst, *RHSCst;
4433 ICmpInst::Predicate LHSCC, RHSCC;
4435 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4436 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4437 m_ConstantInt(LHSCst))) ||
4438 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4439 m_ConstantInt(RHSCst))))
4442 // From here on, we only handle:
4443 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4444 if (Val != Val2) return 0;
4446 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4447 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4448 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4449 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4450 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4453 // We can't fold (ugt x, C) | (sgt x, C2).
4454 if (!PredicatesFoldable(LHSCC, RHSCC))
4457 // Ensure that the larger constant is on the RHS.
4459 if (ICmpInst::isSignedPredicate(LHSCC) ||
4460 (ICmpInst::isEquality(LHSCC) &&
4461 ICmpInst::isSignedPredicate(RHSCC)))
4462 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4464 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4467 std::swap(LHS, RHS);
4468 std::swap(LHSCst, RHSCst);
4469 std::swap(LHSCC, RHSCC);
4472 // At this point, we know we have have two icmp instructions
4473 // comparing a value against two constants and or'ing the result
4474 // together. Because of the above check, we know that we only have
4475 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4476 // FoldICmpLogical check above), that the two constants are not
4478 assert(LHSCst != RHSCst && "Compares not folded above?");
4481 default: llvm_unreachable("Unknown integer condition code!");
4482 case ICmpInst::ICMP_EQ:
4484 default: llvm_unreachable("Unknown integer condition code!");
4485 case ICmpInst::ICMP_EQ:
4486 if (LHSCst == SubOne(RHSCst)) {
4487 // (X == 13 | X == 14) -> X-13 <u 2
4488 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4489 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4490 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4491 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4493 break; // (X == 13 | X == 15) -> no change
4494 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4495 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4497 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4498 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4499 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4500 return ReplaceInstUsesWith(I, RHS);
4503 case ICmpInst::ICMP_NE:
4505 default: llvm_unreachable("Unknown integer condition code!");
4506 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4507 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4508 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4509 return ReplaceInstUsesWith(I, LHS);
4510 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4511 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4512 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4513 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4516 case ICmpInst::ICMP_ULT:
4518 default: llvm_unreachable("Unknown integer condition code!");
4519 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4521 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4522 // If RHSCst is [us]MAXINT, it is always false. Not handling
4523 // this can cause overflow.
4524 if (RHSCst->isMaxValue(false))
4525 return ReplaceInstUsesWith(I, LHS);
4526 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4528 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4530 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4531 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4532 return ReplaceInstUsesWith(I, RHS);
4533 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4537 case ICmpInst::ICMP_SLT:
4539 default: llvm_unreachable("Unknown integer condition code!");
4540 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4542 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4543 // If RHSCst is [us]MAXINT, it is always false. Not handling
4544 // this can cause overflow.
4545 if (RHSCst->isMaxValue(true))
4546 return ReplaceInstUsesWith(I, LHS);
4547 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4549 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4551 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4552 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4553 return ReplaceInstUsesWith(I, RHS);
4554 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4558 case ICmpInst::ICMP_UGT:
4560 default: llvm_unreachable("Unknown integer condition code!");
4561 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4562 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4563 return ReplaceInstUsesWith(I, LHS);
4564 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4566 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4567 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4568 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4569 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4573 case ICmpInst::ICMP_SGT:
4575 default: llvm_unreachable("Unknown integer condition code!");
4576 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4577 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4578 return ReplaceInstUsesWith(I, LHS);
4579 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4581 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4582 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4583 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4584 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4592 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4594 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4595 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4596 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4597 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4598 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4599 // If either of the constants are nans, then the whole thing returns
4601 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4602 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4604 // Otherwise, no need to compare the two constants, compare the
4606 return new FCmpInst(FCmpInst::FCMP_UNO,
4607 LHS->getOperand(0), RHS->getOperand(0));
4610 // Handle vector zeros. This occurs because the canonical form of
4611 // "fcmp uno x,x" is "fcmp uno x, 0".
4612 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4613 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4614 return new FCmpInst(FCmpInst::FCMP_UNO,
4615 LHS->getOperand(0), RHS->getOperand(0));
4620 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4621 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4622 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4624 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4625 // Swap RHS operands to match LHS.
4626 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4627 std::swap(Op1LHS, Op1RHS);
4629 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4630 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4632 return new FCmpInst((FCmpInst::Predicate)Op0CC,
4634 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4635 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4636 if (Op0CC == FCmpInst::FCMP_FALSE)
4637 return ReplaceInstUsesWith(I, RHS);
4638 if (Op1CC == FCmpInst::FCMP_FALSE)
4639 return ReplaceInstUsesWith(I, LHS);
4642 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4643 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4644 if (Op0Ordered == Op1Ordered) {
4645 // If both are ordered or unordered, return a new fcmp with
4646 // or'ed predicates.
4647 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4648 Op0LHS, Op0RHS, Context);
4649 if (Instruction *I = dyn_cast<Instruction>(RV))
4651 // Otherwise, it's a constant boolean value...
4652 return ReplaceInstUsesWith(I, RV);
4658 /// FoldOrWithConstants - This helper function folds:
4660 /// ((A | B) & C1) | (B & C2)
4666 /// when the XOR of the two constants is "all ones" (-1).
4667 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4668 Value *A, Value *B, Value *C) {
4669 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4673 ConstantInt *CI2 = 0;
4674 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4676 APInt Xor = CI1->getValue() ^ CI2->getValue();
4677 if (!Xor.isAllOnesValue()) return 0;
4679 if (V1 == A || V1 == B) {
4680 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4681 return BinaryOperator::CreateOr(NewOp, V1);
4687 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4688 bool Changed = SimplifyCommutative(I);
4689 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4691 if (isa<UndefValue>(Op1)) // X | undef -> -1
4692 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4696 return ReplaceInstUsesWith(I, Op0);
4698 // See if we can simplify any instructions used by the instruction whose sole
4699 // purpose is to compute bits we don't care about.
4700 if (SimplifyDemandedInstructionBits(I))
4702 if (isa<VectorType>(I.getType())) {
4703 if (isa<ConstantAggregateZero>(Op1)) {
4704 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4705 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4706 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4707 return ReplaceInstUsesWith(I, I.getOperand(1));
4712 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4713 ConstantInt *C1 = 0; Value *X = 0;
4714 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4715 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4717 Value *Or = Builder->CreateOr(X, RHS);
4719 return BinaryOperator::CreateAnd(Or,
4720 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4723 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4724 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4726 Value *Or = Builder->CreateOr(X, RHS);
4728 return BinaryOperator::CreateXor(Or,
4729 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4732 // Try to fold constant and into select arguments.
4733 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4734 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4736 if (isa<PHINode>(Op0))
4737 if (Instruction *NV = FoldOpIntoPhi(I))
4741 Value *A = 0, *B = 0;
4742 ConstantInt *C1 = 0, *C2 = 0;
4744 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4745 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4746 return ReplaceInstUsesWith(I, Op1);
4747 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4748 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4749 return ReplaceInstUsesWith(I, Op0);
4751 // (A | B) | C and A | (B | C) -> bswap if possible.
4752 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4753 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4754 match(Op1, m_Or(m_Value(), m_Value())) ||
4755 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4756 match(Op1, m_Shift(m_Value(), m_Value())))) {
4757 if (Instruction *BSwap = MatchBSwap(I))
4761 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4762 if (Op0->hasOneUse() &&
4763 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4764 MaskedValueIsZero(Op1, C1->getValue())) {
4765 Value *NOr = Builder->CreateOr(A, Op1);
4767 return BinaryOperator::CreateXor(NOr, C1);
4770 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4771 if (Op1->hasOneUse() &&
4772 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4773 MaskedValueIsZero(Op0, C1->getValue())) {
4774 Value *NOr = Builder->CreateOr(A, Op0);
4776 return BinaryOperator::CreateXor(NOr, C1);
4780 Value *C = 0, *D = 0;
4781 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4782 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4783 Value *V1 = 0, *V2 = 0, *V3 = 0;
4784 C1 = dyn_cast<ConstantInt>(C);
4785 C2 = dyn_cast<ConstantInt>(D);
4786 if (C1 && C2) { // (A & C1)|(B & C2)
4787 // If we have: ((V + N) & C1) | (V & C2)
4788 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4789 // replace with V+N.
4790 if (C1->getValue() == ~C2->getValue()) {
4791 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4792 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4793 // Add commutes, try both ways.
4794 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4795 return ReplaceInstUsesWith(I, A);
4796 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4797 return ReplaceInstUsesWith(I, A);
4799 // Or commutes, try both ways.
4800 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4801 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4802 // Add commutes, try both ways.
4803 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4804 return ReplaceInstUsesWith(I, B);
4805 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4806 return ReplaceInstUsesWith(I, B);
4809 V1 = 0; V2 = 0; V3 = 0;
4812 // Check to see if we have any common things being and'ed. If so, find the
4813 // terms for V1 & (V2|V3).
4814 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4815 if (A == B) // (A & C)|(A & D) == A & (C|D)
4816 V1 = A, V2 = C, V3 = D;
4817 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4818 V1 = A, V2 = B, V3 = C;
4819 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4820 V1 = C, V2 = A, V3 = D;
4821 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4822 V1 = C, V2 = A, V3 = B;
4825 Value *Or = Builder->CreateOr(V2, V3, "tmp");
4826 return BinaryOperator::CreateAnd(V1, Or);
4830 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4831 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4833 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4835 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4837 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4840 // ((A&~B)|(~A&B)) -> A^B
4841 if ((match(C, m_Not(m_Specific(D))) &&
4842 match(B, m_Not(m_Specific(A)))))
4843 return BinaryOperator::CreateXor(A, D);
4844 // ((~B&A)|(~A&B)) -> A^B
4845 if ((match(A, m_Not(m_Specific(D))) &&
4846 match(B, m_Not(m_Specific(C)))))
4847 return BinaryOperator::CreateXor(C, D);
4848 // ((A&~B)|(B&~A)) -> A^B
4849 if ((match(C, m_Not(m_Specific(B))) &&
4850 match(D, m_Not(m_Specific(A)))))
4851 return BinaryOperator::CreateXor(A, B);
4852 // ((~B&A)|(B&~A)) -> A^B
4853 if ((match(A, m_Not(m_Specific(B))) &&
4854 match(D, m_Not(m_Specific(C)))))
4855 return BinaryOperator::CreateXor(C, B);
4858 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4859 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4860 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4861 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4862 SI0->getOperand(1) == SI1->getOperand(1) &&
4863 (SI0->hasOneUse() || SI1->hasOneUse())) {
4864 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4866 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4867 SI1->getOperand(1));
4871 // ((A|B)&1)|(B&-2) -> (A&1) | B
4872 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4873 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4874 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4875 if (Ret) return Ret;
4877 // (B&-2)|((A|B)&1) -> (A&1) | B
4878 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4879 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4880 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4881 if (Ret) return Ret;
4884 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4885 if (A == Op1) // ~A | A == -1
4886 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4890 // Note, A is still live here!
4891 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4893 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4895 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4896 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4897 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4898 return BinaryOperator::CreateNot(And);
4902 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4903 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4904 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4907 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4908 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4912 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4913 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4914 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4915 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4916 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4917 !isa<ICmpInst>(Op1C->getOperand(0))) {
4918 const Type *SrcTy = Op0C->getOperand(0)->getType();
4919 if (SrcTy == Op1C->getOperand(0)->getType() &&
4920 SrcTy->isIntOrIntVector() &&
4921 // Only do this if the casts both really cause code to be
4923 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4925 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4927 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4928 Op1C->getOperand(0), I.getName());
4929 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4936 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4937 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4938 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4939 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4943 return Changed ? &I : 0;
4948 // XorSelf - Implements: X ^ X --> 0
4951 XorSelf(Value *rhs) : RHS(rhs) {}
4952 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4953 Instruction *apply(BinaryOperator &Xor) const {
4960 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4961 bool Changed = SimplifyCommutative(I);
4962 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4964 if (isa<UndefValue>(Op1)) {
4965 if (isa<UndefValue>(Op0))
4966 // Handle undef ^ undef -> 0 special case. This is a common
4968 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4969 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4972 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4973 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4974 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4975 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4978 // See if we can simplify any instructions used by the instruction whose sole
4979 // purpose is to compute bits we don't care about.
4980 if (SimplifyDemandedInstructionBits(I))
4982 if (isa<VectorType>(I.getType()))
4983 if (isa<ConstantAggregateZero>(Op1))
4984 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4986 // Is this a ~ operation?
4987 if (Value *NotOp = dyn_castNotVal(&I)) {
4988 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4989 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4990 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4991 if (Op0I->getOpcode() == Instruction::And ||
4992 Op0I->getOpcode() == Instruction::Or) {
4993 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4994 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4996 Builder->CreateNot(Op0I->getOperand(1),
4997 Op0I->getOperand(1)->getName()+".not");
4998 if (Op0I->getOpcode() == Instruction::And)
4999 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5000 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5007 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5008 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5009 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5010 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5011 return new ICmpInst(ICI->getInversePredicate(),
5012 ICI->getOperand(0), ICI->getOperand(1));
5014 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5015 return new FCmpInst(FCI->getInversePredicate(),
5016 FCI->getOperand(0), FCI->getOperand(1));
5019 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5020 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5021 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5022 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5023 Instruction::CastOps Opcode = Op0C->getOpcode();
5024 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5025 (RHS == ConstantExpr::getCast(Opcode,
5026 ConstantInt::getTrue(*Context),
5027 Op0C->getDestTy()))) {
5028 CI->setPredicate(CI->getInversePredicate());
5029 return CastInst::Create(Opcode, CI, Op0C->getType());
5035 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5036 // ~(c-X) == X-c-1 == X+(-c-1)
5037 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5038 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5039 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5040 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5041 ConstantInt::get(I.getType(), 1));
5042 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5045 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5046 if (Op0I->getOpcode() == Instruction::Add) {
5047 // ~(X-c) --> (-c-1)-X
5048 if (RHS->isAllOnesValue()) {
5049 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5050 return BinaryOperator::CreateSub(
5051 ConstantExpr::getSub(NegOp0CI,
5052 ConstantInt::get(I.getType(), 1)),
5053 Op0I->getOperand(0));
5054 } else if (RHS->getValue().isSignBit()) {
5055 // (X + C) ^ signbit -> (X + C + signbit)
5056 Constant *C = ConstantInt::get(*Context,
5057 RHS->getValue() + Op0CI->getValue());
5058 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5061 } else if (Op0I->getOpcode() == Instruction::Or) {
5062 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5063 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5064 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5065 // Anything in both C1 and C2 is known to be zero, remove it from
5067 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5068 NewRHS = ConstantExpr::getAnd(NewRHS,
5069 ConstantExpr::getNot(CommonBits));
5071 I.setOperand(0, Op0I->getOperand(0));
5072 I.setOperand(1, NewRHS);
5079 // Try to fold constant and into select arguments.
5080 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5081 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5083 if (isa<PHINode>(Op0))
5084 if (Instruction *NV = FoldOpIntoPhi(I))
5088 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5090 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5092 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5094 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5097 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5100 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5101 if (A == Op0) { // B^(B|A) == (A|B)^B
5102 Op1I->swapOperands();
5104 std::swap(Op0, Op1);
5105 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5106 I.swapOperands(); // Simplified below.
5107 std::swap(Op0, Op1);
5109 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5110 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5111 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5112 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5113 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
5115 if (A == Op0) { // A^(A&B) -> A^(B&A)
5116 Op1I->swapOperands();
5119 if (B == Op0) { // A^(B&A) -> (B&A)^A
5120 I.swapOperands(); // Simplified below.
5121 std::swap(Op0, Op1);
5126 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5129 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5130 Op0I->hasOneUse()) {
5131 if (A == Op1) // (B|A)^B == (A|B)^B
5133 if (B == Op1) // (A|B)^B == A & ~B
5134 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5135 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5136 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5137 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5138 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5139 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5141 if (A == Op1) // (A&B)^A -> (B&A)^A
5143 if (B == Op1 && // (B&A)^A == ~B & A
5144 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5145 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5150 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5151 if (Op0I && Op1I && Op0I->isShift() &&
5152 Op0I->getOpcode() == Op1I->getOpcode() &&
5153 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5154 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5156 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5158 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5159 Op1I->getOperand(1));
5163 Value *A, *B, *C, *D;
5164 // (A & B)^(A | B) -> A ^ B
5165 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5166 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5167 if ((A == C && B == D) || (A == D && B == C))
5168 return BinaryOperator::CreateXor(A, B);
5170 // (A | B)^(A & B) -> A ^ B
5171 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5172 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5173 if ((A == C && B == D) || (A == D && B == C))
5174 return BinaryOperator::CreateXor(A, B);
5178 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5179 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5180 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5181 // (X & Y)^(X & Y) -> (Y^Z) & X
5182 Value *X = 0, *Y = 0, *Z = 0;
5184 X = A, Y = B, Z = D;
5186 X = A, Y = B, Z = C;
5188 X = B, Y = A, Z = D;
5190 X = B, Y = A, Z = C;
5193 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5194 return BinaryOperator::CreateAnd(NewOp, X);
5199 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5200 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5201 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5204 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5205 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5206 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5207 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5208 const Type *SrcTy = Op0C->getOperand(0)->getType();
5209 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5210 // Only do this if the casts both really cause code to be generated.
5211 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5213 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5215 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5216 Op1C->getOperand(0), I.getName());
5217 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5222 return Changed ? &I : 0;
5225 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5226 LLVMContext *Context) {
5227 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5230 static bool HasAddOverflow(ConstantInt *Result,
5231 ConstantInt *In1, ConstantInt *In2,
5234 if (In2->getValue().isNegative())
5235 return Result->getValue().sgt(In1->getValue());
5237 return Result->getValue().slt(In1->getValue());
5239 return Result->getValue().ult(In1->getValue());
5242 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5243 /// overflowed for this type.
5244 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5245 Constant *In2, LLVMContext *Context,
5246 bool IsSigned = false) {
5247 Result = ConstantExpr::getAdd(In1, In2);
5249 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5250 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5251 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5252 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5253 ExtractElement(In1, Idx, Context),
5254 ExtractElement(In2, Idx, Context),
5261 return HasAddOverflow(cast<ConstantInt>(Result),
5262 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5266 static bool HasSubOverflow(ConstantInt *Result,
5267 ConstantInt *In1, ConstantInt *In2,
5270 if (In2->getValue().isNegative())
5271 return Result->getValue().slt(In1->getValue());
5273 return Result->getValue().sgt(In1->getValue());
5275 return Result->getValue().ugt(In1->getValue());
5278 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5279 /// overflowed for this type.
5280 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5281 Constant *In2, LLVMContext *Context,
5282 bool IsSigned = false) {
5283 Result = ConstantExpr::getSub(In1, In2);
5285 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5286 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5287 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5288 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5289 ExtractElement(In1, Idx, Context),
5290 ExtractElement(In2, Idx, Context),
5297 return HasSubOverflow(cast<ConstantInt>(Result),
5298 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5302 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5303 /// code necessary to compute the offset from the base pointer (without adding
5304 /// in the base pointer). Return the result as a signed integer of intptr size.
5305 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5306 TargetData &TD = *IC.getTargetData();
5307 gep_type_iterator GTI = gep_type_begin(GEP);
5308 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5309 Value *Result = Constant::getNullValue(IntPtrTy);
5311 // Build a mask for high order bits.
5312 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5313 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5315 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5318 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5319 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5320 if (OpC->isZero()) continue;
5322 // Handle a struct index, which adds its field offset to the pointer.
5323 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5324 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5326 Result = IC.Builder->CreateAdd(Result,
5327 ConstantInt::get(IntPtrTy, Size),
5328 GEP->getName()+".offs");
5332 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5334 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5335 Scale = ConstantExpr::getMul(OC, Scale);
5336 // Emit an add instruction.
5337 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5340 // Convert to correct type.
5341 if (Op->getType() != IntPtrTy)
5342 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5344 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5345 // We'll let instcombine(mul) convert this to a shl if possible.
5346 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5349 // Emit an add instruction.
5350 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5356 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5357 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5358 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5359 /// be complex, and scales are involved. The above expression would also be
5360 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5361 /// This later form is less amenable to optimization though, and we are allowed
5362 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5364 /// If we can't emit an optimized form for this expression, this returns null.
5366 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5368 TargetData &TD = *IC.getTargetData();
5369 gep_type_iterator GTI = gep_type_begin(GEP);
5371 // Check to see if this gep only has a single variable index. If so, and if
5372 // any constant indices are a multiple of its scale, then we can compute this
5373 // in terms of the scale of the variable index. For example, if the GEP
5374 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5375 // because the expression will cross zero at the same point.
5376 unsigned i, e = GEP->getNumOperands();
5378 for (i = 1; i != e; ++i, ++GTI) {
5379 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5380 // Compute the aggregate offset of constant indices.
5381 if (CI->isZero()) continue;
5383 // Handle a struct index, which adds its field offset to the pointer.
5384 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5385 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5387 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5388 Offset += Size*CI->getSExtValue();
5391 // Found our variable index.
5396 // If there are no variable indices, we must have a constant offset, just
5397 // evaluate it the general way.
5398 if (i == e) return 0;
5400 Value *VariableIdx = GEP->getOperand(i);
5401 // Determine the scale factor of the variable element. For example, this is
5402 // 4 if the variable index is into an array of i32.
5403 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5405 // Verify that there are no other variable indices. If so, emit the hard way.
5406 for (++i, ++GTI; i != e; ++i, ++GTI) {
5407 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5410 // Compute the aggregate offset of constant indices.
5411 if (CI->isZero()) continue;
5413 // Handle a struct index, which adds its field offset to the pointer.
5414 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5415 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5417 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5418 Offset += Size*CI->getSExtValue();
5422 // Okay, we know we have a single variable index, which must be a
5423 // pointer/array/vector index. If there is no offset, life is simple, return
5425 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5427 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5428 // we don't need to bother extending: the extension won't affect where the
5429 // computation crosses zero.
5430 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5431 VariableIdx = new TruncInst(VariableIdx,
5432 TD.getIntPtrType(VariableIdx->getContext()),
5433 VariableIdx->getName(), &I);
5437 // Otherwise, there is an index. The computation we will do will be modulo
5438 // the pointer size, so get it.
5439 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5441 Offset &= PtrSizeMask;
5442 VariableScale &= PtrSizeMask;
5444 // To do this transformation, any constant index must be a multiple of the
5445 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5446 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5447 // multiple of the variable scale.
5448 int64_t NewOffs = Offset / (int64_t)VariableScale;
5449 if (Offset != NewOffs*(int64_t)VariableScale)
5452 // Okay, we can do this evaluation. Start by converting the index to intptr.
5453 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5454 if (VariableIdx->getType() != IntPtrTy)
5455 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5457 VariableIdx->getName(), &I);
5458 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5459 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5463 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5464 /// else. At this point we know that the GEP is on the LHS of the comparison.
5465 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5466 ICmpInst::Predicate Cond,
5468 // Look through bitcasts.
5469 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5470 RHS = BCI->getOperand(0);
5472 Value *PtrBase = GEPLHS->getOperand(0);
5473 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5474 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5475 // This transformation (ignoring the base and scales) is valid because we
5476 // know pointers can't overflow since the gep is inbounds. See if we can
5477 // output an optimized form.
5478 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5480 // If not, synthesize the offset the hard way.
5482 Offset = EmitGEPOffset(GEPLHS, I, *this);
5483 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5484 Constant::getNullValue(Offset->getType()));
5485 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5486 // If the base pointers are different, but the indices are the same, just
5487 // compare the base pointer.
5488 if (PtrBase != GEPRHS->getOperand(0)) {
5489 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5490 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5491 GEPRHS->getOperand(0)->getType();
5493 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5494 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5495 IndicesTheSame = false;
5499 // If all indices are the same, just compare the base pointers.
5501 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5502 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5504 // Otherwise, the base pointers are different and the indices are
5505 // different, bail out.
5509 // If one of the GEPs has all zero indices, recurse.
5510 bool AllZeros = true;
5511 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5512 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5513 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5518 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5519 ICmpInst::getSwappedPredicate(Cond), I);
5521 // If the other GEP has all zero indices, recurse.
5523 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5524 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5525 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5530 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5532 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5533 // If the GEPs only differ by one index, compare it.
5534 unsigned NumDifferences = 0; // Keep track of # differences.
5535 unsigned DiffOperand = 0; // The operand that differs.
5536 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5537 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5538 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5539 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5540 // Irreconcilable differences.
5544 if (NumDifferences++) break;
5549 if (NumDifferences == 0) // SAME GEP?
5550 return ReplaceInstUsesWith(I, // No comparison is needed here.
5551 ConstantInt::get(Type::getInt1Ty(*Context),
5552 ICmpInst::isTrueWhenEqual(Cond)));
5554 else if (NumDifferences == 1) {
5555 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5556 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5557 // Make sure we do a signed comparison here.
5558 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5562 // Only lower this if the icmp is the only user of the GEP or if we expect
5563 // the result to fold to a constant!
5565 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5566 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5567 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5568 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5569 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5570 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5576 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5578 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5581 if (!isa<ConstantFP>(RHSC)) return 0;
5582 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5584 // Get the width of the mantissa. We don't want to hack on conversions that
5585 // might lose information from the integer, e.g. "i64 -> float"
5586 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5587 if (MantissaWidth == -1) return 0; // Unknown.
5589 // Check to see that the input is converted from an integer type that is small
5590 // enough that preserves all bits. TODO: check here for "known" sign bits.
5591 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5592 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5594 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5595 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5599 // If the conversion would lose info, don't hack on this.
5600 if ((int)InputSize > MantissaWidth)
5603 // Otherwise, we can potentially simplify the comparison. We know that it
5604 // will always come through as an integer value and we know the constant is
5605 // not a NAN (it would have been previously simplified).
5606 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5608 ICmpInst::Predicate Pred;
5609 switch (I.getPredicate()) {
5610 default: llvm_unreachable("Unexpected predicate!");
5611 case FCmpInst::FCMP_UEQ:
5612 case FCmpInst::FCMP_OEQ:
5613 Pred = ICmpInst::ICMP_EQ;
5615 case FCmpInst::FCMP_UGT:
5616 case FCmpInst::FCMP_OGT:
5617 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5619 case FCmpInst::FCMP_UGE:
5620 case FCmpInst::FCMP_OGE:
5621 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5623 case FCmpInst::FCMP_ULT:
5624 case FCmpInst::FCMP_OLT:
5625 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5627 case FCmpInst::FCMP_ULE:
5628 case FCmpInst::FCMP_OLE:
5629 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5631 case FCmpInst::FCMP_UNE:
5632 case FCmpInst::FCMP_ONE:
5633 Pred = ICmpInst::ICMP_NE;
5635 case FCmpInst::FCMP_ORD:
5636 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5637 case FCmpInst::FCMP_UNO:
5638 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5641 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5643 // Now we know that the APFloat is a normal number, zero or inf.
5645 // See if the FP constant is too large for the integer. For example,
5646 // comparing an i8 to 300.0.
5647 unsigned IntWidth = IntTy->getScalarSizeInBits();
5650 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5651 // and large values.
5652 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5653 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5654 APFloat::rmNearestTiesToEven);
5655 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5656 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5657 Pred == ICmpInst::ICMP_SLE)
5658 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5659 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5662 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5663 // +INF and large values.
5664 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5665 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5666 APFloat::rmNearestTiesToEven);
5667 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5668 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5669 Pred == ICmpInst::ICMP_ULE)
5670 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5671 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5676 // See if the RHS value is < SignedMin.
5677 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5678 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5679 APFloat::rmNearestTiesToEven);
5680 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5681 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5682 Pred == ICmpInst::ICMP_SGE)
5683 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5684 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5688 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5689 // [0, UMAX], but it may still be fractional. See if it is fractional by
5690 // casting the FP value to the integer value and back, checking for equality.
5691 // Don't do this for zero, because -0.0 is not fractional.
5692 Constant *RHSInt = LHSUnsigned
5693 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5694 : ConstantExpr::getFPToSI(RHSC, IntTy);
5695 if (!RHS.isZero()) {
5696 bool Equal = LHSUnsigned
5697 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5698 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5700 // If we had a comparison against a fractional value, we have to adjust
5701 // the compare predicate and sometimes the value. RHSC is rounded towards
5702 // zero at this point.
5704 default: llvm_unreachable("Unexpected integer comparison!");
5705 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5706 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5707 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5708 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5709 case ICmpInst::ICMP_ULE:
5710 // (float)int <= 4.4 --> int <= 4
5711 // (float)int <= -4.4 --> false
5712 if (RHS.isNegative())
5713 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5715 case ICmpInst::ICMP_SLE:
5716 // (float)int <= 4.4 --> int <= 4
5717 // (float)int <= -4.4 --> int < -4
5718 if (RHS.isNegative())
5719 Pred = ICmpInst::ICMP_SLT;
5721 case ICmpInst::ICMP_ULT:
5722 // (float)int < -4.4 --> false
5723 // (float)int < 4.4 --> int <= 4
5724 if (RHS.isNegative())
5725 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5726 Pred = ICmpInst::ICMP_ULE;
5728 case ICmpInst::ICMP_SLT:
5729 // (float)int < -4.4 --> int < -4
5730 // (float)int < 4.4 --> int <= 4
5731 if (!RHS.isNegative())
5732 Pred = ICmpInst::ICMP_SLE;
5734 case ICmpInst::ICMP_UGT:
5735 // (float)int > 4.4 --> int > 4
5736 // (float)int > -4.4 --> true
5737 if (RHS.isNegative())
5738 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5740 case ICmpInst::ICMP_SGT:
5741 // (float)int > 4.4 --> int > 4
5742 // (float)int > -4.4 --> int >= -4
5743 if (RHS.isNegative())
5744 Pred = ICmpInst::ICMP_SGE;
5746 case ICmpInst::ICMP_UGE:
5747 // (float)int >= -4.4 --> true
5748 // (float)int >= 4.4 --> int > 4
5749 if (!RHS.isNegative())
5750 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5751 Pred = ICmpInst::ICMP_UGT;
5753 case ICmpInst::ICMP_SGE:
5754 // (float)int >= -4.4 --> int >= -4
5755 // (float)int >= 4.4 --> int > 4
5756 if (!RHS.isNegative())
5757 Pred = ICmpInst::ICMP_SGT;
5763 // Lower this FP comparison into an appropriate integer version of the
5765 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5768 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5769 bool Changed = SimplifyCompare(I);
5770 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5772 // Fold trivial predicates.
5773 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5774 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5775 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5776 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5778 // Simplify 'fcmp pred X, X'
5780 switch (I.getPredicate()) {
5781 default: llvm_unreachable("Unknown predicate!");
5782 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5783 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5784 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5785 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5786 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5787 case FCmpInst::FCMP_OLT: // True if ordered and less than
5788 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5789 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5791 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5792 case FCmpInst::FCMP_ULT: // True if unordered or less than
5793 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5794 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5795 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5796 I.setPredicate(FCmpInst::FCMP_UNO);
5797 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5800 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5801 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5802 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5803 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5804 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5805 I.setPredicate(FCmpInst::FCMP_ORD);
5806 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5811 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5812 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5814 // Handle fcmp with constant RHS
5815 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5816 // If the constant is a nan, see if we can fold the comparison based on it.
5817 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5818 if (CFP->getValueAPF().isNaN()) {
5819 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5820 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5821 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5822 "Comparison must be either ordered or unordered!");
5823 // True if unordered.
5824 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5828 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5829 switch (LHSI->getOpcode()) {
5830 case Instruction::PHI:
5831 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5832 // block. If in the same block, we're encouraging jump threading. If
5833 // not, we are just pessimizing the code by making an i1 phi.
5834 if (LHSI->getParent() == I.getParent())
5835 if (Instruction *NV = FoldOpIntoPhi(I))
5838 case Instruction::SIToFP:
5839 case Instruction::UIToFP:
5840 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5843 case Instruction::Select:
5844 // If either operand of the select is a constant, we can fold the
5845 // comparison into the select arms, which will cause one to be
5846 // constant folded and the select turned into a bitwise or.
5847 Value *Op1 = 0, *Op2 = 0;
5848 if (LHSI->hasOneUse()) {
5849 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5850 // Fold the known value into the constant operand.
5851 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5852 // Insert a new FCmp of the other select operand.
5853 Op2 = Builder->CreateFCmp(I.getPredicate(),
5854 LHSI->getOperand(2), RHSC, I.getName());
5855 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5856 // Fold the known value into the constant operand.
5857 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5858 // Insert a new FCmp of the other select operand.
5859 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5865 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5870 return Changed ? &I : 0;
5873 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5874 bool Changed = SimplifyCompare(I);
5875 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5876 const Type *Ty = Op0->getType();
5880 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
5881 I.isTrueWhenEqual()));
5883 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5884 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5886 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5887 // addresses never equal each other! We already know that Op0 != Op1.
5888 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5889 isa<ConstantPointerNull>(Op0)) &&
5890 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5891 isa<ConstantPointerNull>(Op1)))
5892 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
5893 !I.isTrueWhenEqual()));
5895 // icmp's with boolean values can always be turned into bitwise operations
5896 if (Ty == Type::getInt1Ty(*Context)) {
5897 switch (I.getPredicate()) {
5898 default: llvm_unreachable("Invalid icmp instruction!");
5899 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5900 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5901 return BinaryOperator::CreateNot(Xor);
5903 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5904 return BinaryOperator::CreateXor(Op0, Op1);
5906 case ICmpInst::ICMP_UGT:
5907 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5909 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5910 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5911 return BinaryOperator::CreateAnd(Not, Op1);
5913 case ICmpInst::ICMP_SGT:
5914 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
5916 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5917 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5918 return BinaryOperator::CreateAnd(Not, Op0);
5920 case ICmpInst::ICMP_UGE:
5921 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5923 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
5924 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5925 return BinaryOperator::CreateOr(Not, Op1);
5927 case ICmpInst::ICMP_SGE:
5928 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5930 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5931 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5932 return BinaryOperator::CreateOr(Not, Op0);
5937 unsigned BitWidth = 0;
5939 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5940 else if (Ty->isIntOrIntVector())
5941 BitWidth = Ty->getScalarSizeInBits();
5943 bool isSignBit = false;
5945 // See if we are doing a comparison with a constant.
5946 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5947 Value *A = 0, *B = 0;
5949 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5950 if (I.isEquality() && CI->isNullValue() &&
5951 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5952 // (icmp cond A B) if cond is equality
5953 return new ICmpInst(I.getPredicate(), A, B);
5956 // If we have an icmp le or icmp ge instruction, turn it into the
5957 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5958 // them being folded in the code below.
5959 switch (I.getPredicate()) {
5961 case ICmpInst::ICMP_ULE:
5962 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5963 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5964 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
5966 case ICmpInst::ICMP_SLE:
5967 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5968 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5969 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5971 case ICmpInst::ICMP_UGE:
5972 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5973 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5974 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
5976 case ICmpInst::ICMP_SGE:
5977 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5978 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5979 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5983 // If this comparison is a normal comparison, it demands all
5984 // bits, if it is a sign bit comparison, it only demands the sign bit.
5986 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5989 // See if we can fold the comparison based on range information we can get
5990 // by checking whether bits are known to be zero or one in the input.
5991 if (BitWidth != 0) {
5992 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5993 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
5995 if (SimplifyDemandedBits(I.getOperandUse(0),
5996 isSignBit ? APInt::getSignBit(BitWidth)
5997 : APInt::getAllOnesValue(BitWidth),
5998 Op0KnownZero, Op0KnownOne, 0))
6000 if (SimplifyDemandedBits(I.getOperandUse(1),
6001 APInt::getAllOnesValue(BitWidth),
6002 Op1KnownZero, Op1KnownOne, 0))
6005 // Given the known and unknown bits, compute a range that the LHS could be
6006 // in. Compute the Min, Max and RHS values based on the known bits. For the
6007 // EQ and NE we use unsigned values.
6008 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6009 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6010 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6011 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6013 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6016 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6018 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6022 // If Min and Max are known to be the same, then SimplifyDemandedBits
6023 // figured out that the LHS is a constant. Just constant fold this now so
6024 // that code below can assume that Min != Max.
6025 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6026 return new ICmpInst(I.getPredicate(),
6027 ConstantInt::get(*Context, Op0Min), Op1);
6028 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6029 return new ICmpInst(I.getPredicate(), Op0,
6030 ConstantInt::get(*Context, Op1Min));
6032 // Based on the range information we know about the LHS, see if we can
6033 // simplify this comparison. For example, (x&4) < 8 is always true.
6034 switch (I.getPredicate()) {
6035 default: llvm_unreachable("Unknown icmp opcode!");
6036 case ICmpInst::ICMP_EQ:
6037 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6038 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6040 case ICmpInst::ICMP_NE:
6041 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6042 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6044 case ICmpInst::ICMP_ULT:
6045 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6046 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6047 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6048 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6049 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6050 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6051 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6052 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6053 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6056 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6057 if (CI->isMinValue(true))
6058 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6059 Constant::getAllOnesValue(Op0->getType()));
6062 case ICmpInst::ICMP_UGT:
6063 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6064 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6065 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6066 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6068 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6069 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6070 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6071 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6072 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6075 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6076 if (CI->isMaxValue(true))
6077 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6078 Constant::getNullValue(Op0->getType()));
6081 case ICmpInst::ICMP_SLT:
6082 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6083 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6084 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6085 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6086 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6087 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6088 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6089 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6090 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6094 case ICmpInst::ICMP_SGT:
6095 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6096 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6097 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6098 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6100 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6101 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6102 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6103 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6104 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6108 case ICmpInst::ICMP_SGE:
6109 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6110 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6111 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6112 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6113 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6115 case ICmpInst::ICMP_SLE:
6116 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6117 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6118 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6119 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6120 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6122 case ICmpInst::ICMP_UGE:
6123 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6124 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6125 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6126 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6127 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6129 case ICmpInst::ICMP_ULE:
6130 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6131 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6132 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6133 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6134 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6138 // Turn a signed comparison into an unsigned one if both operands
6139 // are known to have the same sign.
6140 if (I.isSignedPredicate() &&
6141 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6142 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6143 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6146 // Test if the ICmpInst instruction is used exclusively by a select as
6147 // part of a minimum or maximum operation. If so, refrain from doing
6148 // any other folding. This helps out other analyses which understand
6149 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6150 // and CodeGen. And in this case, at least one of the comparison
6151 // operands has at least one user besides the compare (the select),
6152 // which would often largely negate the benefit of folding anyway.
6154 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6155 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6156 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6159 // See if we are doing a comparison between a constant and an instruction that
6160 // can be folded into the comparison.
6161 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6162 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6163 // instruction, see if that instruction also has constants so that the
6164 // instruction can be folded into the icmp
6165 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6166 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6170 // Handle icmp with constant (but not simple integer constant) RHS
6171 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6172 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6173 switch (LHSI->getOpcode()) {
6174 case Instruction::GetElementPtr:
6175 if (RHSC->isNullValue()) {
6176 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6177 bool isAllZeros = true;
6178 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6179 if (!isa<Constant>(LHSI->getOperand(i)) ||
6180 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6185 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6186 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6190 case Instruction::PHI:
6191 // Only fold icmp into the PHI if the phi and fcmp are in the same
6192 // block. If in the same block, we're encouraging jump threading. If
6193 // not, we are just pessimizing the code by making an i1 phi.
6194 if (LHSI->getParent() == I.getParent())
6195 if (Instruction *NV = FoldOpIntoPhi(I))
6198 case Instruction::Select: {
6199 // If either operand of the select is a constant, we can fold the
6200 // comparison into the select arms, which will cause one to be
6201 // constant folded and the select turned into a bitwise or.
6202 Value *Op1 = 0, *Op2 = 0;
6203 if (LHSI->hasOneUse()) {
6204 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6205 // Fold the known value into the constant operand.
6206 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6207 // Insert a new ICmp of the other select operand.
6208 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6210 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6211 // Fold the known value into the constant operand.
6212 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6213 // Insert a new ICmp of the other select operand.
6214 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6220 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6223 case Instruction::Malloc:
6224 // If we have (malloc != null), and if the malloc has a single use, we
6225 // can assume it is successful and remove the malloc.
6226 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6228 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6229 !I.isTrueWhenEqual()));
6235 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6236 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6237 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6239 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6240 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6241 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6244 // Test to see if the operands of the icmp are casted versions of other
6245 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6247 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6248 if (isa<PointerType>(Op0->getType()) &&
6249 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6250 // We keep moving the cast from the left operand over to the right
6251 // operand, where it can often be eliminated completely.
6252 Op0 = CI->getOperand(0);
6254 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6255 // so eliminate it as well.
6256 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6257 Op1 = CI2->getOperand(0);
6259 // If Op1 is a constant, we can fold the cast into the constant.
6260 if (Op0->getType() != Op1->getType()) {
6261 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6262 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6264 // Otherwise, cast the RHS right before the icmp
6265 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6268 return new ICmpInst(I.getPredicate(), Op0, Op1);
6272 if (isa<CastInst>(Op0)) {
6273 // Handle the special case of: icmp (cast bool to X), <cst>
6274 // This comes up when you have code like
6277 // For generality, we handle any zero-extension of any operand comparison
6278 // with a constant or another cast from the same type.
6279 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6280 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6284 // See if it's the same type of instruction on the left and right.
6285 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6286 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6287 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6288 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6289 switch (Op0I->getOpcode()) {
6291 case Instruction::Add:
6292 case Instruction::Sub:
6293 case Instruction::Xor:
6294 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6295 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6296 Op1I->getOperand(0));
6297 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6298 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6299 if (CI->getValue().isSignBit()) {
6300 ICmpInst::Predicate Pred = I.isSignedPredicate()
6301 ? I.getUnsignedPredicate()
6302 : I.getSignedPredicate();
6303 return new ICmpInst(Pred, Op0I->getOperand(0),
6304 Op1I->getOperand(0));
6307 if (CI->getValue().isMaxSignedValue()) {
6308 ICmpInst::Predicate Pred = I.isSignedPredicate()
6309 ? I.getUnsignedPredicate()
6310 : I.getSignedPredicate();
6311 Pred = I.getSwappedPredicate(Pred);
6312 return new ICmpInst(Pred, Op0I->getOperand(0),
6313 Op1I->getOperand(0));
6317 case Instruction::Mul:
6318 if (!I.isEquality())
6321 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6322 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6323 // Mask = -1 >> count-trailing-zeros(Cst).
6324 if (!CI->isZero() && !CI->isOne()) {
6325 const APInt &AP = CI->getValue();
6326 ConstantInt *Mask = ConstantInt::get(*Context,
6327 APInt::getLowBitsSet(AP.getBitWidth(),
6329 AP.countTrailingZeros()));
6330 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6331 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6332 return new ICmpInst(I.getPredicate(), And1, And2);
6341 // ~x < ~y --> y < x
6343 if (match(Op0, m_Not(m_Value(A))) &&
6344 match(Op1, m_Not(m_Value(B))))
6345 return new ICmpInst(I.getPredicate(), B, A);
6348 if (I.isEquality()) {
6349 Value *A, *B, *C, *D;
6351 // -x == -y --> x == y
6352 if (match(Op0, m_Neg(m_Value(A))) &&
6353 match(Op1, m_Neg(m_Value(B))))
6354 return new ICmpInst(I.getPredicate(), A, B);
6356 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6357 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6358 Value *OtherVal = A == Op1 ? B : A;
6359 return new ICmpInst(I.getPredicate(), OtherVal,
6360 Constant::getNullValue(A->getType()));
6363 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6364 // A^c1 == C^c2 --> A == C^(c1^c2)
6365 ConstantInt *C1, *C2;
6366 if (match(B, m_ConstantInt(C1)) &&
6367 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6369 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6370 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6371 return new ICmpInst(I.getPredicate(), A, Xor);
6374 // A^B == A^D -> B == D
6375 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6376 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6377 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6378 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6382 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6383 (A == Op0 || B == Op0)) {
6384 // A == (A^B) -> B == 0
6385 Value *OtherVal = A == Op0 ? B : A;
6386 return new ICmpInst(I.getPredicate(), OtherVal,
6387 Constant::getNullValue(A->getType()));
6390 // (A-B) == A -> B == 0
6391 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6392 return new ICmpInst(I.getPredicate(), B,
6393 Constant::getNullValue(B->getType()));
6395 // A == (A-B) -> B == 0
6396 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6397 return new ICmpInst(I.getPredicate(), B,
6398 Constant::getNullValue(B->getType()));
6400 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6401 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6402 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6403 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6404 Value *X = 0, *Y = 0, *Z = 0;
6407 X = B; Y = D; Z = A;
6408 } else if (A == D) {
6409 X = B; Y = C; Z = A;
6410 } else if (B == C) {
6411 X = A; Y = D; Z = B;
6412 } else if (B == D) {
6413 X = A; Y = C; Z = B;
6416 if (X) { // Build (X^Y) & Z
6417 Op1 = Builder->CreateXor(X, Y, "tmp");
6418 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6419 I.setOperand(0, Op1);
6420 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6425 return Changed ? &I : 0;
6429 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6430 /// and CmpRHS are both known to be integer constants.
6431 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6432 ConstantInt *DivRHS) {
6433 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6434 const APInt &CmpRHSV = CmpRHS->getValue();
6436 // FIXME: If the operand types don't match the type of the divide
6437 // then don't attempt this transform. The code below doesn't have the
6438 // logic to deal with a signed divide and an unsigned compare (and
6439 // vice versa). This is because (x /s C1) <s C2 produces different
6440 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6441 // (x /u C1) <u C2. Simply casting the operands and result won't
6442 // work. :( The if statement below tests that condition and bails
6444 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6445 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6447 if (DivRHS->isZero())
6448 return 0; // The ProdOV computation fails on divide by zero.
6449 if (DivIsSigned && DivRHS->isAllOnesValue())
6450 return 0; // The overflow computation also screws up here
6451 if (DivRHS->isOne())
6452 return 0; // Not worth bothering, and eliminates some funny cases
6455 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6456 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6457 // C2 (CI). By solving for X we can turn this into a range check
6458 // instead of computing a divide.
6459 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6461 // Determine if the product overflows by seeing if the product is
6462 // not equal to the divide. Make sure we do the same kind of divide
6463 // as in the LHS instruction that we're folding.
6464 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6465 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6467 // Get the ICmp opcode
6468 ICmpInst::Predicate Pred = ICI.getPredicate();
6470 // Figure out the interval that is being checked. For example, a comparison
6471 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6472 // Compute this interval based on the constants involved and the signedness of
6473 // the compare/divide. This computes a half-open interval, keeping track of
6474 // whether either value in the interval overflows. After analysis each
6475 // overflow variable is set to 0 if it's corresponding bound variable is valid
6476 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6477 int LoOverflow = 0, HiOverflow = 0;
6478 Constant *LoBound = 0, *HiBound = 0;
6480 if (!DivIsSigned) { // udiv
6481 // e.g. X/5 op 3 --> [15, 20)
6483 HiOverflow = LoOverflow = ProdOV;
6485 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6486 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6487 if (CmpRHSV == 0) { // (X / pos) op 0
6488 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6489 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6491 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6492 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6493 HiOverflow = LoOverflow = ProdOV;
6495 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6496 } else { // (X / pos) op neg
6497 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6498 HiBound = AddOne(Prod);
6499 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6501 ConstantInt* DivNeg =
6502 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6503 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6507 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6508 if (CmpRHSV == 0) { // (X / neg) op 0
6509 // e.g. X/-5 op 0 --> [-4, 5)
6510 LoBound = AddOne(DivRHS);
6511 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6512 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6513 HiOverflow = 1; // [INTMIN+1, overflow)
6514 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6516 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6517 // e.g. X/-5 op 3 --> [-19, -14)
6518 HiBound = AddOne(Prod);
6519 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6521 LoOverflow = AddWithOverflow(LoBound, HiBound,
6522 DivRHS, Context, true) ? -1 : 0;
6523 } else { // (X / neg) op neg
6524 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6525 LoOverflow = HiOverflow = ProdOV;
6527 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6530 // Dividing by a negative swaps the condition. LT <-> GT
6531 Pred = ICmpInst::getSwappedPredicate(Pred);
6534 Value *X = DivI->getOperand(0);
6536 default: llvm_unreachable("Unhandled icmp opcode!");
6537 case ICmpInst::ICMP_EQ:
6538 if (LoOverflow && HiOverflow)
6539 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6540 else if (HiOverflow)
6541 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6542 ICmpInst::ICMP_UGE, X, LoBound);
6543 else if (LoOverflow)
6544 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6545 ICmpInst::ICMP_ULT, X, HiBound);
6547 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6548 case ICmpInst::ICMP_NE:
6549 if (LoOverflow && HiOverflow)
6550 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6551 else if (HiOverflow)
6552 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6553 ICmpInst::ICMP_ULT, X, LoBound);
6554 else if (LoOverflow)
6555 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6556 ICmpInst::ICMP_UGE, X, HiBound);
6558 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6559 case ICmpInst::ICMP_ULT:
6560 case ICmpInst::ICMP_SLT:
6561 if (LoOverflow == +1) // Low bound is greater than input range.
6562 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6563 if (LoOverflow == -1) // Low bound is less than input range.
6564 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6565 return new ICmpInst(Pred, X, LoBound);
6566 case ICmpInst::ICMP_UGT:
6567 case ICmpInst::ICMP_SGT:
6568 if (HiOverflow == +1) // High bound greater than input range.
6569 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6570 else if (HiOverflow == -1) // High bound less than input range.
6571 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6572 if (Pred == ICmpInst::ICMP_UGT)
6573 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6575 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6580 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6582 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6585 const APInt &RHSV = RHS->getValue();
6587 switch (LHSI->getOpcode()) {
6588 case Instruction::Trunc:
6589 if (ICI.isEquality() && LHSI->hasOneUse()) {
6590 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6591 // of the high bits truncated out of x are known.
6592 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6593 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6594 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6595 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6596 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6598 // If all the high bits are known, we can do this xform.
6599 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6600 // Pull in the high bits from known-ones set.
6601 APInt NewRHS(RHS->getValue());
6602 NewRHS.zext(SrcBits);
6604 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6605 ConstantInt::get(*Context, NewRHS));
6610 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6611 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6612 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6614 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6615 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6616 Value *CompareVal = LHSI->getOperand(0);
6618 // If the sign bit of the XorCST is not set, there is no change to
6619 // the operation, just stop using the Xor.
6620 if (!XorCST->getValue().isNegative()) {
6621 ICI.setOperand(0, CompareVal);
6626 // Was the old condition true if the operand is positive?
6627 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6629 // If so, the new one isn't.
6630 isTrueIfPositive ^= true;
6632 if (isTrueIfPositive)
6633 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6636 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6640 if (LHSI->hasOneUse()) {
6641 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6642 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6643 const APInt &SignBit = XorCST->getValue();
6644 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6645 ? ICI.getUnsignedPredicate()
6646 : ICI.getSignedPredicate();
6647 return new ICmpInst(Pred, LHSI->getOperand(0),
6648 ConstantInt::get(*Context, RHSV ^ SignBit));
6651 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6652 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6653 const APInt &NotSignBit = XorCST->getValue();
6654 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6655 ? ICI.getUnsignedPredicate()
6656 : ICI.getSignedPredicate();
6657 Pred = ICI.getSwappedPredicate(Pred);
6658 return new ICmpInst(Pred, LHSI->getOperand(0),
6659 ConstantInt::get(*Context, RHSV ^ NotSignBit));
6664 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6665 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6666 LHSI->getOperand(0)->hasOneUse()) {
6667 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6669 // If the LHS is an AND of a truncating cast, we can widen the
6670 // and/compare to be the input width without changing the value
6671 // produced, eliminating a cast.
6672 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6673 // We can do this transformation if either the AND constant does not
6674 // have its sign bit set or if it is an equality comparison.
6675 // Extending a relational comparison when we're checking the sign
6676 // bit would not work.
6677 if (Cast->hasOneUse() &&
6678 (ICI.isEquality() ||
6679 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6681 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6682 APInt NewCST = AndCST->getValue();
6683 NewCST.zext(BitWidth);
6685 NewCI.zext(BitWidth);
6687 Builder->CreateAnd(Cast->getOperand(0),
6688 ConstantInt::get(*Context, NewCST), LHSI->getName());
6689 return new ICmpInst(ICI.getPredicate(), NewAnd,
6690 ConstantInt::get(*Context, NewCI));
6694 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6695 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6696 // happens a LOT in code produced by the C front-end, for bitfield
6698 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6699 if (Shift && !Shift->isShift())
6703 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6704 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6705 const Type *AndTy = AndCST->getType(); // Type of the and.
6707 // We can fold this as long as we can't shift unknown bits
6708 // into the mask. This can only happen with signed shift
6709 // rights, as they sign-extend.
6711 bool CanFold = Shift->isLogicalShift();
6713 // To test for the bad case of the signed shr, see if any
6714 // of the bits shifted in could be tested after the mask.
6715 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6716 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6718 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6719 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6720 AndCST->getValue()) == 0)
6726 if (Shift->getOpcode() == Instruction::Shl)
6727 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6729 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6731 // Check to see if we are shifting out any of the bits being
6733 if (ConstantExpr::get(Shift->getOpcode(),
6734 NewCst, ShAmt) != RHS) {
6735 // If we shifted bits out, the fold is not going to work out.
6736 // As a special case, check to see if this means that the
6737 // result is always true or false now.
6738 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6739 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6740 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6741 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6743 ICI.setOperand(1, NewCst);
6744 Constant *NewAndCST;
6745 if (Shift->getOpcode() == Instruction::Shl)
6746 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6748 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6749 LHSI->setOperand(1, NewAndCST);
6750 LHSI->setOperand(0, Shift->getOperand(0));
6751 Worklist.Add(Shift); // Shift is dead.
6757 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6758 // preferable because it allows the C<<Y expression to be hoisted out
6759 // of a loop if Y is invariant and X is not.
6760 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6761 ICI.isEquality() && !Shift->isArithmeticShift() &&
6762 !isa<Constant>(Shift->getOperand(0))) {
6765 if (Shift->getOpcode() == Instruction::LShr) {
6766 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6768 // Insert a logical shift.
6769 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6772 // Compute X & (C << Y).
6774 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6776 ICI.setOperand(0, NewAnd);
6782 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6783 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6786 uint32_t TypeBits = RHSV.getBitWidth();
6788 // Check that the shift amount is in range. If not, don't perform
6789 // undefined shifts. When the shift is visited it will be
6791 if (ShAmt->uge(TypeBits))
6794 if (ICI.isEquality()) {
6795 // If we are comparing against bits always shifted out, the
6796 // comparison cannot succeed.
6798 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6800 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6801 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6802 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6803 return ReplaceInstUsesWith(ICI, Cst);
6806 if (LHSI->hasOneUse()) {
6807 // Otherwise strength reduce the shift into an and.
6808 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6810 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
6811 TypeBits-ShAmtVal));
6814 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6815 return new ICmpInst(ICI.getPredicate(), And,
6816 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6820 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6821 bool TrueIfSigned = false;
6822 if (LHSI->hasOneUse() &&
6823 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6824 // (X << 31) <s 0 --> (X&1) != 0
6825 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6826 (TypeBits-ShAmt->getZExtValue()-1));
6828 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6829 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6830 And, Constant::getNullValue(And->getType()));
6835 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6836 case Instruction::AShr: {
6837 // Only handle equality comparisons of shift-by-constant.
6838 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6839 if (!ShAmt || !ICI.isEquality()) break;
6841 // Check that the shift amount is in range. If not, don't perform
6842 // undefined shifts. When the shift is visited it will be
6844 uint32_t TypeBits = RHSV.getBitWidth();
6845 if (ShAmt->uge(TypeBits))
6848 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6850 // If we are comparing against bits always shifted out, the
6851 // comparison cannot succeed.
6852 APInt Comp = RHSV << ShAmtVal;
6853 if (LHSI->getOpcode() == Instruction::LShr)
6854 Comp = Comp.lshr(ShAmtVal);
6856 Comp = Comp.ashr(ShAmtVal);
6858 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6859 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6860 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6861 return ReplaceInstUsesWith(ICI, Cst);
6864 // Otherwise, check to see if the bits shifted out are known to be zero.
6865 // If so, we can compare against the unshifted value:
6866 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6867 if (LHSI->hasOneUse() &&
6868 MaskedValueIsZero(LHSI->getOperand(0),
6869 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6870 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6871 ConstantExpr::getShl(RHS, ShAmt));
6874 if (LHSI->hasOneUse()) {
6875 // Otherwise strength reduce the shift into an and.
6876 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6877 Constant *Mask = ConstantInt::get(*Context, Val);
6879 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6880 Mask, LHSI->getName()+".mask");
6881 return new ICmpInst(ICI.getPredicate(), And,
6882 ConstantExpr::getShl(RHS, ShAmt));
6887 case Instruction::SDiv:
6888 case Instruction::UDiv:
6889 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6890 // Fold this div into the comparison, producing a range check.
6891 // Determine, based on the divide type, what the range is being
6892 // checked. If there is an overflow on the low or high side, remember
6893 // it, otherwise compute the range [low, hi) bounding the new value.
6894 // See: InsertRangeTest above for the kinds of replacements possible.
6895 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6896 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6901 case Instruction::Add:
6902 // Fold: icmp pred (add, X, C1), C2
6904 if (!ICI.isEquality()) {
6905 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6907 const APInt &LHSV = LHSC->getValue();
6909 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6912 if (ICI.isSignedPredicate()) {
6913 if (CR.getLower().isSignBit()) {
6914 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6915 ConstantInt::get(*Context, CR.getUpper()));
6916 } else if (CR.getUpper().isSignBit()) {
6917 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6918 ConstantInt::get(*Context, CR.getLower()));
6921 if (CR.getLower().isMinValue()) {
6922 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6923 ConstantInt::get(*Context, CR.getUpper()));
6924 } else if (CR.getUpper().isMinValue()) {
6925 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6926 ConstantInt::get(*Context, CR.getLower()));
6933 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6934 if (ICI.isEquality()) {
6935 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6937 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6938 // the second operand is a constant, simplify a bit.
6939 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6940 switch (BO->getOpcode()) {
6941 case Instruction::SRem:
6942 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6943 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6944 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6945 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6947 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6949 return new ICmpInst(ICI.getPredicate(), NewRem,
6950 Constant::getNullValue(BO->getType()));
6954 case Instruction::Add:
6955 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6956 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6957 if (BO->hasOneUse())
6958 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6959 ConstantExpr::getSub(RHS, BOp1C));
6960 } else if (RHSV == 0) {
6961 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6962 // efficiently invertible, or if the add has just this one use.
6963 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6965 if (Value *NegVal = dyn_castNegVal(BOp1))
6966 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6967 else if (Value *NegVal = dyn_castNegVal(BOp0))
6968 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6969 else if (BO->hasOneUse()) {
6970 Value *Neg = Builder->CreateNeg(BOp1);
6972 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6976 case Instruction::Xor:
6977 // For the xor case, we can xor two constants together, eliminating
6978 // the explicit xor.
6979 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6980 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6981 ConstantExpr::getXor(RHS, BOC));
6984 case Instruction::Sub:
6985 // Replace (([sub|xor] A, B) != 0) with (A != B)
6987 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6991 case Instruction::Or:
6992 // If bits are being or'd in that are not present in the constant we
6993 // are comparing against, then the comparison could never succeed!
6994 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6995 Constant *NotCI = ConstantExpr::getNot(RHS);
6996 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6997 return ReplaceInstUsesWith(ICI,
6998 ConstantInt::get(Type::getInt1Ty(*Context),
7003 case Instruction::And:
7004 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7005 // If bits are being compared against that are and'd out, then the
7006 // comparison can never succeed!
7007 if ((RHSV & ~BOC->getValue()) != 0)
7008 return ReplaceInstUsesWith(ICI,
7009 ConstantInt::get(Type::getInt1Ty(*Context),
7012 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7013 if (RHS == BOC && RHSV.isPowerOf2())
7014 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7015 ICmpInst::ICMP_NE, LHSI,
7016 Constant::getNullValue(RHS->getType()));
7018 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7019 if (BOC->getValue().isSignBit()) {
7020 Value *X = BO->getOperand(0);
7021 Constant *Zero = Constant::getNullValue(X->getType());
7022 ICmpInst::Predicate pred = isICMP_NE ?
7023 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7024 return new ICmpInst(pred, X, Zero);
7027 // ((X & ~7) == 0) --> X < 8
7028 if (RHSV == 0 && isHighOnes(BOC)) {
7029 Value *X = BO->getOperand(0);
7030 Constant *NegX = ConstantExpr::getNeg(BOC);
7031 ICmpInst::Predicate pred = isICMP_NE ?
7032 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7033 return new ICmpInst(pred, X, NegX);
7038 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7039 // Handle icmp {eq|ne} <intrinsic>, intcst.
7040 if (II->getIntrinsicID() == Intrinsic::bswap) {
7042 ICI.setOperand(0, II->getOperand(1));
7043 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7051 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7052 /// We only handle extending casts so far.
7054 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7055 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7056 Value *LHSCIOp = LHSCI->getOperand(0);
7057 const Type *SrcTy = LHSCIOp->getType();
7058 const Type *DestTy = LHSCI->getType();
7061 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7062 // integer type is the same size as the pointer type.
7063 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7064 TD->getPointerSizeInBits() ==
7065 cast<IntegerType>(DestTy)->getBitWidth()) {
7067 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7068 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7069 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7070 RHSOp = RHSC->getOperand(0);
7071 // If the pointer types don't match, insert a bitcast.
7072 if (LHSCIOp->getType() != RHSOp->getType())
7073 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7077 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7080 // The code below only handles extension cast instructions, so far.
7082 if (LHSCI->getOpcode() != Instruction::ZExt &&
7083 LHSCI->getOpcode() != Instruction::SExt)
7086 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7087 bool isSignedCmp = ICI.isSignedPredicate();
7089 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7090 // Not an extension from the same type?
7091 RHSCIOp = CI->getOperand(0);
7092 if (RHSCIOp->getType() != LHSCIOp->getType())
7095 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7096 // and the other is a zext), then we can't handle this.
7097 if (CI->getOpcode() != LHSCI->getOpcode())
7100 // Deal with equality cases early.
7101 if (ICI.isEquality())
7102 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7104 // A signed comparison of sign extended values simplifies into a
7105 // signed comparison.
7106 if (isSignedCmp && isSignedExt)
7107 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7109 // The other three cases all fold into an unsigned comparison.
7110 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7113 // If we aren't dealing with a constant on the RHS, exit early
7114 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7118 // Compute the constant that would happen if we truncated to SrcTy then
7119 // reextended to DestTy.
7120 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7121 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7124 // If the re-extended constant didn't change...
7126 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7127 // For example, we might have:
7128 // %A = sext i16 %X to i32
7129 // %B = icmp ugt i32 %A, 1330
7130 // It is incorrect to transform this into
7131 // %B = icmp ugt i16 %X, 1330
7132 // because %A may have negative value.
7134 // However, we allow this when the compare is EQ/NE, because they are
7136 if (isSignedExt == isSignedCmp || ICI.isEquality())
7137 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7141 // The re-extended constant changed so the constant cannot be represented
7142 // in the shorter type. Consequently, we cannot emit a simple comparison.
7144 // First, handle some easy cases. We know the result cannot be equal at this
7145 // point so handle the ICI.isEquality() cases
7146 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7147 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7148 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7149 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7151 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7152 // should have been folded away previously and not enter in here.
7155 // We're performing a signed comparison.
7156 if (cast<ConstantInt>(CI)->getValue().isNegative())
7157 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
7159 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
7161 // We're performing an unsigned comparison.
7163 // We're performing an unsigned comp with a sign extended value.
7164 // This is true if the input is >= 0. [aka >s -1]
7165 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7166 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7168 // Unsigned extend & unsigned compare -> always true.
7169 Result = ConstantInt::getTrue(*Context);
7173 // Finally, return the value computed.
7174 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7175 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7176 return ReplaceInstUsesWith(ICI, Result);
7178 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7179 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7180 "ICmp should be folded!");
7181 if (Constant *CI = dyn_cast<Constant>(Result))
7182 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7183 return BinaryOperator::CreateNot(Result);
7186 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7187 return commonShiftTransforms(I);
7190 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7191 return commonShiftTransforms(I);
7194 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7195 if (Instruction *R = commonShiftTransforms(I))
7198 Value *Op0 = I.getOperand(0);
7200 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7201 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7202 if (CSI->isAllOnesValue())
7203 return ReplaceInstUsesWith(I, CSI);
7205 // See if we can turn a signed shr into an unsigned shr.
7206 if (MaskedValueIsZero(Op0,
7207 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7208 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7210 // Arithmetic shifting an all-sign-bit value is a no-op.
7211 unsigned NumSignBits = ComputeNumSignBits(Op0);
7212 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7213 return ReplaceInstUsesWith(I, Op0);
7218 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7219 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7220 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7222 // shl X, 0 == X and shr X, 0 == X
7223 // shl 0, X == 0 and shr 0, X == 0
7224 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7225 Op0 == Constant::getNullValue(Op0->getType()))
7226 return ReplaceInstUsesWith(I, Op0);
7228 if (isa<UndefValue>(Op0)) {
7229 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7230 return ReplaceInstUsesWith(I, Op0);
7231 else // undef << X -> 0, undef >>u X -> 0
7232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7234 if (isa<UndefValue>(Op1)) {
7235 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7236 return ReplaceInstUsesWith(I, Op0);
7237 else // X << undef, X >>u undef -> 0
7238 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7241 // See if we can fold away this shift.
7242 if (SimplifyDemandedInstructionBits(I))
7245 // Try to fold constant and into select arguments.
7246 if (isa<Constant>(Op0))
7247 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7248 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7251 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7252 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7257 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7258 BinaryOperator &I) {
7259 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7261 // See if we can simplify any instructions used by the instruction whose sole
7262 // purpose is to compute bits we don't care about.
7263 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7265 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7268 if (Op1->uge(TypeBits)) {
7269 if (I.getOpcode() != Instruction::AShr)
7270 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7272 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7277 // ((X*C1) << C2) == (X * (C1 << C2))
7278 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7279 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7280 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7281 return BinaryOperator::CreateMul(BO->getOperand(0),
7282 ConstantExpr::getShl(BOOp, Op1));
7284 // Try to fold constant and into select arguments.
7285 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7286 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7288 if (isa<PHINode>(Op0))
7289 if (Instruction *NV = FoldOpIntoPhi(I))
7292 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7293 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7294 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7295 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7296 // place. Don't try to do this transformation in this case. Also, we
7297 // require that the input operand is a shift-by-constant so that we have
7298 // confidence that the shifts will get folded together. We could do this
7299 // xform in more cases, but it is unlikely to be profitable.
7300 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7301 isa<ConstantInt>(TrOp->getOperand(1))) {
7302 // Okay, we'll do this xform. Make the shift of shift.
7303 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7304 // (shift2 (shift1 & 0x00FF), c2)
7305 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7307 // For logical shifts, the truncation has the effect of making the high
7308 // part of the register be zeros. Emulate this by inserting an AND to
7309 // clear the top bits as needed. This 'and' will usually be zapped by
7310 // other xforms later if dead.
7311 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7312 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7313 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7315 // The mask we constructed says what the trunc would do if occurring
7316 // between the shifts. We want to know the effect *after* the second
7317 // shift. We know that it is a logical shift by a constant, so adjust the
7318 // mask as appropriate.
7319 if (I.getOpcode() == Instruction::Shl)
7320 MaskV <<= Op1->getZExtValue();
7322 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7323 MaskV = MaskV.lshr(Op1->getZExtValue());
7327 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7330 // Return the value truncated to the interesting size.
7331 return new TruncInst(And, I.getType());
7335 if (Op0->hasOneUse()) {
7336 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7337 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7340 switch (Op0BO->getOpcode()) {
7342 case Instruction::Add:
7343 case Instruction::And:
7344 case Instruction::Or:
7345 case Instruction::Xor: {
7346 // These operators commute.
7347 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7348 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7349 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7350 m_Specific(Op1)))) {
7351 Value *YS = // (Y << C)
7352 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7354 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7355 Op0BO->getOperand(1)->getName());
7356 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7357 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7358 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7361 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7362 Value *Op0BOOp1 = Op0BO->getOperand(1);
7363 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7365 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7366 m_ConstantInt(CC))) &&
7367 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7368 Value *YS = // (Y << C)
7369 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7372 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7373 V1->getName()+".mask");
7374 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7379 case Instruction::Sub: {
7380 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7381 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7382 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7383 m_Specific(Op1)))) {
7384 Value *YS = // (Y << C)
7385 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7387 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7388 Op0BO->getOperand(0)->getName());
7389 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7390 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7391 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7394 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7395 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7396 match(Op0BO->getOperand(0),
7397 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7398 m_ConstantInt(CC))) && V2 == Op1 &&
7399 cast<BinaryOperator>(Op0BO->getOperand(0))
7400 ->getOperand(0)->hasOneUse()) {
7401 Value *YS = // (Y << C)
7402 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7404 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7405 V1->getName()+".mask");
7407 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7415 // If the operand is an bitwise operator with a constant RHS, and the
7416 // shift is the only use, we can pull it out of the shift.
7417 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7418 bool isValid = true; // Valid only for And, Or, Xor
7419 bool highBitSet = false; // Transform if high bit of constant set?
7421 switch (Op0BO->getOpcode()) {
7422 default: isValid = false; break; // Do not perform transform!
7423 case Instruction::Add:
7424 isValid = isLeftShift;
7426 case Instruction::Or:
7427 case Instruction::Xor:
7430 case Instruction::And:
7435 // If this is a signed shift right, and the high bit is modified
7436 // by the logical operation, do not perform the transformation.
7437 // The highBitSet boolean indicates the value of the high bit of
7438 // the constant which would cause it to be modified for this
7441 if (isValid && I.getOpcode() == Instruction::AShr)
7442 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7445 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7448 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7449 NewShift->takeName(Op0BO);
7451 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7458 // Find out if this is a shift of a shift by a constant.
7459 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7460 if (ShiftOp && !ShiftOp->isShift())
7463 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7464 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7465 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7466 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7467 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7468 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7469 Value *X = ShiftOp->getOperand(0);
7471 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7473 const IntegerType *Ty = cast<IntegerType>(I.getType());
7475 // Check for (X << c1) << c2 and (X >> c1) >> c2
7476 if (I.getOpcode() == ShiftOp->getOpcode()) {
7477 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7479 if (AmtSum >= TypeBits) {
7480 if (I.getOpcode() != Instruction::AShr)
7481 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7482 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7485 return BinaryOperator::Create(I.getOpcode(), X,
7486 ConstantInt::get(Ty, AmtSum));
7489 if (ShiftOp->getOpcode() == Instruction::LShr &&
7490 I.getOpcode() == Instruction::AShr) {
7491 if (AmtSum >= TypeBits)
7492 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7494 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7495 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7498 if (ShiftOp->getOpcode() == Instruction::AShr &&
7499 I.getOpcode() == Instruction::LShr) {
7500 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7501 if (AmtSum >= TypeBits)
7502 AmtSum = TypeBits-1;
7504 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7506 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7507 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7510 // Okay, if we get here, one shift must be left, and the other shift must be
7511 // right. See if the amounts are equal.
7512 if (ShiftAmt1 == ShiftAmt2) {
7513 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7514 if (I.getOpcode() == Instruction::Shl) {
7515 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7516 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7518 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7519 if (I.getOpcode() == Instruction::LShr) {
7520 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7521 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7523 // We can simplify ((X << C) >>s C) into a trunc + sext.
7524 // NOTE: we could do this for any C, but that would make 'unusual' integer
7525 // types. For now, just stick to ones well-supported by the code
7527 const Type *SExtType = 0;
7528 switch (Ty->getBitWidth() - ShiftAmt1) {
7535 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7540 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7541 // Otherwise, we can't handle it yet.
7542 } else if (ShiftAmt1 < ShiftAmt2) {
7543 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7545 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7546 if (I.getOpcode() == Instruction::Shl) {
7547 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7548 ShiftOp->getOpcode() == Instruction::AShr);
7549 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7551 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7552 return BinaryOperator::CreateAnd(Shift,
7553 ConstantInt::get(*Context, Mask));
7556 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7557 if (I.getOpcode() == Instruction::LShr) {
7558 assert(ShiftOp->getOpcode() == Instruction::Shl);
7559 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7561 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7562 return BinaryOperator::CreateAnd(Shift,
7563 ConstantInt::get(*Context, Mask));
7566 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7568 assert(ShiftAmt2 < ShiftAmt1);
7569 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7571 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7572 if (I.getOpcode() == Instruction::Shl) {
7573 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7574 ShiftOp->getOpcode() == Instruction::AShr);
7575 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7576 ConstantInt::get(Ty, ShiftDiff));
7578 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7579 return BinaryOperator::CreateAnd(Shift,
7580 ConstantInt::get(*Context, Mask));
7583 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7584 if (I.getOpcode() == Instruction::LShr) {
7585 assert(ShiftOp->getOpcode() == Instruction::Shl);
7586 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7588 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7589 return BinaryOperator::CreateAnd(Shift,
7590 ConstantInt::get(*Context, Mask));
7593 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7600 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7601 /// expression. If so, decompose it, returning some value X, such that Val is
7604 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7605 int &Offset, LLVMContext *Context) {
7606 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7607 "Unexpected allocation size type!");
7608 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7609 Offset = CI->getZExtValue();
7611 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7612 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7613 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7614 if (I->getOpcode() == Instruction::Shl) {
7615 // This is a value scaled by '1 << the shift amt'.
7616 Scale = 1U << RHS->getZExtValue();
7618 return I->getOperand(0);
7619 } else if (I->getOpcode() == Instruction::Mul) {
7620 // This value is scaled by 'RHS'.
7621 Scale = RHS->getZExtValue();
7623 return I->getOperand(0);
7624 } else if (I->getOpcode() == Instruction::Add) {
7625 // We have X+C. Check to see if we really have (X*C2)+C1,
7626 // where C1 is divisible by C2.
7629 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7631 Offset += RHS->getZExtValue();
7638 // Otherwise, we can't look past this.
7645 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7646 /// try to eliminate the cast by moving the type information into the alloc.
7647 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7648 AllocationInst &AI) {
7649 const PointerType *PTy = cast<PointerType>(CI.getType());
7651 BuilderTy AllocaBuilder(*Builder);
7652 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7654 // Remove any uses of AI that are dead.
7655 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7657 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7658 Instruction *User = cast<Instruction>(*UI++);
7659 if (isInstructionTriviallyDead(User)) {
7660 while (UI != E && *UI == User)
7661 ++UI; // If this instruction uses AI more than once, don't break UI.
7664 DEBUG(errs() << "IC: DCE: " << *User << '\n');
7665 EraseInstFromFunction(*User);
7669 // This requires TargetData to get the alloca alignment and size information.
7672 // Get the type really allocated and the type casted to.
7673 const Type *AllocElTy = AI.getAllocatedType();
7674 const Type *CastElTy = PTy->getElementType();
7675 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7677 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7678 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7679 if (CastElTyAlign < AllocElTyAlign) return 0;
7681 // If the allocation has multiple uses, only promote it if we are strictly
7682 // increasing the alignment of the resultant allocation. If we keep it the
7683 // same, we open the door to infinite loops of various kinds. (A reference
7684 // from a dbg.declare doesn't count as a use for this purpose.)
7685 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7686 CastElTyAlign == AllocElTyAlign) return 0;
7688 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7689 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7690 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7692 // See if we can satisfy the modulus by pulling a scale out of the array
7694 unsigned ArraySizeScale;
7696 Value *NumElements = // See if the array size is a decomposable linear expr.
7697 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7698 ArrayOffset, Context);
7700 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7702 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7703 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7705 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7710 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7711 // Insert before the alloca, not before the cast.
7712 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7715 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7716 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7717 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7720 AllocationInst *New;
7721 if (isa<MallocInst>(AI))
7722 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
7724 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7725 New->setAlignment(AI.getAlignment());
7728 // If the allocation has one real use plus a dbg.declare, just remove the
7730 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7731 EraseInstFromFunction(*DI);
7733 // If the allocation has multiple real uses, insert a cast and change all
7734 // things that used it to use the new cast. This will also hack on CI, but it
7736 else if (!AI.hasOneUse()) {
7737 // New is the allocation instruction, pointer typed. AI is the original
7738 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7739 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7740 AI.replaceAllUsesWith(NewCast);
7742 return ReplaceInstUsesWith(CI, New);
7745 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7746 /// and return it as type Ty without inserting any new casts and without
7747 /// changing the computed value. This is used by code that tries to decide
7748 /// whether promoting or shrinking integer operations to wider or smaller types
7749 /// will allow us to eliminate a truncate or extend.
7751 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7752 /// extension operation if Ty is larger.
7754 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7755 /// should return true if trunc(V) can be computed by computing V in the smaller
7756 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7757 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7758 /// efficiently truncated.
7760 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7761 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7762 /// the final result.
7763 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7765 int &NumCastsRemoved){
7766 // We can always evaluate constants in another type.
7767 if (isa<Constant>(V))
7770 Instruction *I = dyn_cast<Instruction>(V);
7771 if (!I) return false;
7773 const Type *OrigTy = V->getType();
7775 // If this is an extension or truncate, we can often eliminate it.
7776 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7777 // If this is a cast from the destination type, we can trivially eliminate
7778 // it, and this will remove a cast overall.
7779 if (I->getOperand(0)->getType() == Ty) {
7780 // If the first operand is itself a cast, and is eliminable, do not count
7781 // this as an eliminable cast. We would prefer to eliminate those two
7783 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7789 // We can't extend or shrink something that has multiple uses: doing so would
7790 // require duplicating the instruction in general, which isn't profitable.
7791 if (!I->hasOneUse()) return false;
7793 unsigned Opc = I->getOpcode();
7795 case Instruction::Add:
7796 case Instruction::Sub:
7797 case Instruction::Mul:
7798 case Instruction::And:
7799 case Instruction::Or:
7800 case Instruction::Xor:
7801 // These operators can all arbitrarily be extended or truncated.
7802 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7804 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7807 case Instruction::UDiv:
7808 case Instruction::URem: {
7809 // UDiv and URem can be truncated if all the truncated bits are zero.
7810 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7811 uint32_t BitWidth = Ty->getScalarSizeInBits();
7812 if (BitWidth < OrigBitWidth) {
7813 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7814 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7815 MaskedValueIsZero(I->getOperand(1), Mask)) {
7816 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7818 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7824 case Instruction::Shl:
7825 // If we are truncating the result of this SHL, and if it's a shift of a
7826 // constant amount, we can always perform a SHL in a smaller type.
7827 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7828 uint32_t BitWidth = Ty->getScalarSizeInBits();
7829 if (BitWidth < OrigTy->getScalarSizeInBits() &&
7830 CI->getLimitedValue(BitWidth) < BitWidth)
7831 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7835 case Instruction::LShr:
7836 // If this is a truncate of a logical shr, we can truncate it to a smaller
7837 // lshr iff we know that the bits we would otherwise be shifting in are
7839 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7840 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7841 uint32_t BitWidth = Ty->getScalarSizeInBits();
7842 if (BitWidth < OrigBitWidth &&
7843 MaskedValueIsZero(I->getOperand(0),
7844 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7845 CI->getLimitedValue(BitWidth) < BitWidth) {
7846 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7851 case Instruction::ZExt:
7852 case Instruction::SExt:
7853 case Instruction::Trunc:
7854 // If this is the same kind of case as our original (e.g. zext+zext), we
7855 // can safely replace it. Note that replacing it does not reduce the number
7856 // of casts in the input.
7860 // sext (zext ty1), ty2 -> zext ty2
7861 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7864 case Instruction::Select: {
7865 SelectInst *SI = cast<SelectInst>(I);
7866 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7868 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7871 case Instruction::PHI: {
7872 // We can change a phi if we can change all operands.
7873 PHINode *PN = cast<PHINode>(I);
7874 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7875 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7881 // TODO: Can handle more cases here.
7888 /// EvaluateInDifferentType - Given an expression that
7889 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7890 /// evaluate the expression.
7891 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7893 if (Constant *C = dyn_cast<Constant>(V))
7894 return ConstantExpr::getIntegerCast(C, Ty,
7895 isSigned /*Sext or ZExt*/);
7897 // Otherwise, it must be an instruction.
7898 Instruction *I = cast<Instruction>(V);
7899 Instruction *Res = 0;
7900 unsigned Opc = I->getOpcode();
7902 case Instruction::Add:
7903 case Instruction::Sub:
7904 case Instruction::Mul:
7905 case Instruction::And:
7906 case Instruction::Or:
7907 case Instruction::Xor:
7908 case Instruction::AShr:
7909 case Instruction::LShr:
7910 case Instruction::Shl:
7911 case Instruction::UDiv:
7912 case Instruction::URem: {
7913 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7914 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7915 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7918 case Instruction::Trunc:
7919 case Instruction::ZExt:
7920 case Instruction::SExt:
7921 // If the source type of the cast is the type we're trying for then we can
7922 // just return the source. There's no need to insert it because it is not
7924 if (I->getOperand(0)->getType() == Ty)
7925 return I->getOperand(0);
7927 // Otherwise, must be the same type of cast, so just reinsert a new one.
7928 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7931 case Instruction::Select: {
7932 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7933 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7934 Res = SelectInst::Create(I->getOperand(0), True, False);
7937 case Instruction::PHI: {
7938 PHINode *OPN = cast<PHINode>(I);
7939 PHINode *NPN = PHINode::Create(Ty);
7940 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7941 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7942 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7948 // TODO: Can handle more cases here.
7949 llvm_unreachable("Unreachable!");
7954 return InsertNewInstBefore(Res, *I);
7957 /// @brief Implement the transforms common to all CastInst visitors.
7958 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7959 Value *Src = CI.getOperand(0);
7961 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7962 // eliminate it now.
7963 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7964 if (Instruction::CastOps opc =
7965 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7966 // The first cast (CSrc) is eliminable so we need to fix up or replace
7967 // the second cast (CI). CSrc will then have a good chance of being dead.
7968 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7972 // If we are casting a select then fold the cast into the select
7973 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7974 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7977 // If we are casting a PHI then fold the cast into the PHI
7978 if (isa<PHINode>(Src))
7979 if (Instruction *NV = FoldOpIntoPhi(CI))
7985 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7986 /// or not there is a sequence of GEP indices into the type that will land us at
7987 /// the specified offset. If so, fill them into NewIndices and return the
7988 /// resultant element type, otherwise return null.
7989 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7990 SmallVectorImpl<Value*> &NewIndices,
7991 const TargetData *TD,
7992 LLVMContext *Context) {
7994 if (!Ty->isSized()) return 0;
7996 // Start with the index over the outer type. Note that the type size
7997 // might be zero (even if the offset isn't zero) if the indexed type
7998 // is something like [0 x {int, int}]
7999 const Type *IntPtrTy = TD->getIntPtrType(*Context);
8000 int64_t FirstIdx = 0;
8001 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8002 FirstIdx = Offset/TySize;
8003 Offset -= FirstIdx*TySize;
8005 // Handle hosts where % returns negative instead of values [0..TySize).
8009 assert(Offset >= 0);
8011 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8014 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8016 // Index into the types. If we fail, set OrigBase to null.
8018 // Indexing into tail padding between struct/array elements.
8019 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8022 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8023 const StructLayout *SL = TD->getStructLayout(STy);
8024 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8025 "Offset must stay within the indexed type");
8027 unsigned Elt = SL->getElementContainingOffset(Offset);
8028 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8030 Offset -= SL->getElementOffset(Elt);
8031 Ty = STy->getElementType(Elt);
8032 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8033 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8034 assert(EltSize && "Cannot index into a zero-sized array");
8035 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8037 Ty = AT->getElementType();
8039 // Otherwise, we can't index into the middle of this atomic type, bail.
8047 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8048 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8049 Value *Src = CI.getOperand(0);
8051 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8052 // If casting the result of a getelementptr instruction with no offset, turn
8053 // this into a cast of the original pointer!
8054 if (GEP->hasAllZeroIndices()) {
8055 // Changing the cast operand is usually not a good idea but it is safe
8056 // here because the pointer operand is being replaced with another
8057 // pointer operand so the opcode doesn't need to change.
8059 CI.setOperand(0, GEP->getOperand(0));
8063 // If the GEP has a single use, and the base pointer is a bitcast, and the
8064 // GEP computes a constant offset, see if we can convert these three
8065 // instructions into fewer. This typically happens with unions and other
8066 // non-type-safe code.
8067 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8068 if (GEP->hasAllConstantIndices()) {
8069 // We are guaranteed to get a constant from EmitGEPOffset.
8070 ConstantInt *OffsetV =
8071 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8072 int64_t Offset = OffsetV->getSExtValue();
8074 // Get the base pointer input of the bitcast, and the type it points to.
8075 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8076 const Type *GEPIdxTy =
8077 cast<PointerType>(OrigBase->getType())->getElementType();
8078 SmallVector<Value*, 8> NewIndices;
8079 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8080 // If we were able to index down into an element, create the GEP
8081 // and bitcast the result. This eliminates one bitcast, potentially
8083 Value *NGEP = Builder->CreateGEP(OrigBase, NewIndices.begin(),
8085 NGEP->takeName(GEP);
8086 if (isa<Instruction>(NGEP) && cast<GEPOperator>(GEP)->isInBounds())
8087 cast<GEPOperator>(NGEP)->setIsInBounds(true);
8089 if (isa<BitCastInst>(CI))
8090 return new BitCastInst(NGEP, CI.getType());
8091 assert(isa<PtrToIntInst>(CI));
8092 return new PtrToIntInst(NGEP, CI.getType());
8098 return commonCastTransforms(CI);
8101 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8102 /// type like i42. We don't want to introduce operations on random non-legal
8103 /// integer types where they don't already exist in the code. In the future,
8104 /// we should consider making this based off target-data, so that 32-bit targets
8105 /// won't get i64 operations etc.
8106 static bool isSafeIntegerType(const Type *Ty) {
8107 switch (Ty->getPrimitiveSizeInBits()) {
8118 /// commonIntCastTransforms - This function implements the common transforms
8119 /// for trunc, zext, and sext.
8120 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8121 if (Instruction *Result = commonCastTransforms(CI))
8124 Value *Src = CI.getOperand(0);
8125 const Type *SrcTy = Src->getType();
8126 const Type *DestTy = CI.getType();
8127 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8128 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8130 // See if we can simplify any instructions used by the LHS whose sole
8131 // purpose is to compute bits we don't care about.
8132 if (SimplifyDemandedInstructionBits(CI))
8135 // If the source isn't an instruction or has more than one use then we
8136 // can't do anything more.
8137 Instruction *SrcI = dyn_cast<Instruction>(Src);
8138 if (!SrcI || !Src->hasOneUse())
8141 // Attempt to propagate the cast into the instruction for int->int casts.
8142 int NumCastsRemoved = 0;
8143 // Only do this if the dest type is a simple type, don't convert the
8144 // expression tree to something weird like i93 unless the source is also
8146 if ((isSafeIntegerType(DestTy->getScalarType()) ||
8147 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8148 CanEvaluateInDifferentType(SrcI, DestTy,
8149 CI.getOpcode(), NumCastsRemoved)) {
8150 // If this cast is a truncate, evaluting in a different type always
8151 // eliminates the cast, so it is always a win. If this is a zero-extension,
8152 // we need to do an AND to maintain the clear top-part of the computation,
8153 // so we require that the input have eliminated at least one cast. If this
8154 // is a sign extension, we insert two new casts (to do the extension) so we
8155 // require that two casts have been eliminated.
8156 bool DoXForm = false;
8157 bool JustReplace = false;
8158 switch (CI.getOpcode()) {
8160 // All the others use floating point so we shouldn't actually
8161 // get here because of the check above.
8162 llvm_unreachable("Unknown cast type");
8163 case Instruction::Trunc:
8166 case Instruction::ZExt: {
8167 DoXForm = NumCastsRemoved >= 1;
8168 if (!DoXForm && 0) {
8169 // If it's unnecessary to issue an AND to clear the high bits, it's
8170 // always profitable to do this xform.
8171 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8172 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8173 if (MaskedValueIsZero(TryRes, Mask))
8174 return ReplaceInstUsesWith(CI, TryRes);
8176 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8177 if (TryI->use_empty())
8178 EraseInstFromFunction(*TryI);
8182 case Instruction::SExt: {
8183 DoXForm = NumCastsRemoved >= 2;
8184 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8185 // If we do not have to emit the truncate + sext pair, then it's always
8186 // profitable to do this xform.
8188 // It's not safe to eliminate the trunc + sext pair if one of the
8189 // eliminated cast is a truncate. e.g.
8190 // t2 = trunc i32 t1 to i16
8191 // t3 = sext i16 t2 to i32
8194 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8195 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8196 if (NumSignBits > (DestBitSize - SrcBitSize))
8197 return ReplaceInstUsesWith(CI, TryRes);
8199 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8200 if (TryI->use_empty())
8201 EraseInstFromFunction(*TryI);
8208 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8209 " to avoid cast: " << CI);
8210 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8211 CI.getOpcode() == Instruction::SExt);
8213 // Just replace this cast with the result.
8214 return ReplaceInstUsesWith(CI, Res);
8216 assert(Res->getType() == DestTy);
8217 switch (CI.getOpcode()) {
8218 default: llvm_unreachable("Unknown cast type!");
8219 case Instruction::Trunc:
8220 // Just replace this cast with the result.
8221 return ReplaceInstUsesWith(CI, Res);
8222 case Instruction::ZExt: {
8223 assert(SrcBitSize < DestBitSize && "Not a zext?");
8225 // If the high bits are already zero, just replace this cast with the
8227 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8228 if (MaskedValueIsZero(Res, Mask))
8229 return ReplaceInstUsesWith(CI, Res);
8231 // We need to emit an AND to clear the high bits.
8232 Constant *C = ConstantInt::get(*Context,
8233 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8234 return BinaryOperator::CreateAnd(Res, C);
8236 case Instruction::SExt: {
8237 // If the high bits are already filled with sign bit, just replace this
8238 // cast with the result.
8239 unsigned NumSignBits = ComputeNumSignBits(Res);
8240 if (NumSignBits > (DestBitSize - SrcBitSize))
8241 return ReplaceInstUsesWith(CI, Res);
8243 // We need to emit a cast to truncate, then a cast to sext.
8244 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8250 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8251 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8253 switch (SrcI->getOpcode()) {
8254 case Instruction::Add:
8255 case Instruction::Mul:
8256 case Instruction::And:
8257 case Instruction::Or:
8258 case Instruction::Xor:
8259 // If we are discarding information, rewrite.
8260 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8261 // Don't insert two casts unless at least one can be eliminated.
8262 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8263 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8264 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8265 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8266 return BinaryOperator::Create(
8267 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8271 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8272 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8273 SrcI->getOpcode() == Instruction::Xor &&
8274 Op1 == ConstantInt::getTrue(*Context) &&
8275 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8276 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8277 return BinaryOperator::CreateXor(New,
8278 ConstantInt::get(CI.getType(), 1));
8282 case Instruction::Shl: {
8283 // Canonicalize trunc inside shl, if we can.
8284 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8285 if (CI && DestBitSize < SrcBitSize &&
8286 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8287 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8288 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8289 return BinaryOperator::CreateShl(Op0c, Op1c);
8297 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8298 if (Instruction *Result = commonIntCastTransforms(CI))
8301 Value *Src = CI.getOperand(0);
8302 const Type *Ty = CI.getType();
8303 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8304 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8306 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8307 if (DestBitWidth == 1) {
8308 Constant *One = ConstantInt::get(Src->getType(), 1);
8309 Src = Builder->CreateAnd(Src, One, "tmp");
8310 Value *Zero = Constant::getNullValue(Src->getType());
8311 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8314 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8315 ConstantInt *ShAmtV = 0;
8317 if (Src->hasOneUse() &&
8318 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8319 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8321 // Get a mask for the bits shifting in.
8322 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8323 if (MaskedValueIsZero(ShiftOp, Mask)) {
8324 if (ShAmt >= DestBitWidth) // All zeros.
8325 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8327 // Okay, we can shrink this. Truncate the input, then return a new
8329 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8330 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8331 return BinaryOperator::CreateLShr(V1, V2);
8338 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8339 /// in order to eliminate the icmp.
8340 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8342 // If we are just checking for a icmp eq of a single bit and zext'ing it
8343 // to an integer, then shift the bit to the appropriate place and then
8344 // cast to integer to avoid the comparison.
8345 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8346 const APInt &Op1CV = Op1C->getValue();
8348 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8349 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8350 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8351 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8352 if (!DoXform) return ICI;
8354 Value *In = ICI->getOperand(0);
8355 Value *Sh = ConstantInt::get(In->getType(),
8356 In->getType()->getScalarSizeInBits()-1);
8357 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8358 if (In->getType() != CI.getType())
8359 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8361 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8362 Constant *One = ConstantInt::get(In->getType(), 1);
8363 In = Builder->CreateXor(In, One, In->getName()+".not");
8366 return ReplaceInstUsesWith(CI, In);
8371 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8372 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8373 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8374 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8375 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8376 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8377 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8378 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8379 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8380 // This only works for EQ and NE
8381 ICI->isEquality()) {
8382 // If Op1C some other power of two, convert:
8383 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8384 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8385 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8386 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8388 APInt KnownZeroMask(~KnownZero);
8389 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8390 if (!DoXform) return ICI;
8392 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8393 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8394 // (X&4) == 2 --> false
8395 // (X&4) != 2 --> true
8396 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8397 Res = ConstantExpr::getZExt(Res, CI.getType());
8398 return ReplaceInstUsesWith(CI, Res);
8401 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8402 Value *In = ICI->getOperand(0);
8404 // Perform a logical shr by shiftamt.
8405 // Insert the shift to put the result in the low bit.
8406 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8407 In->getName()+".lobit");
8410 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8411 Constant *One = ConstantInt::get(In->getType(), 1);
8412 In = Builder->CreateXor(In, One, "tmp");
8415 if (CI.getType() == In->getType())
8416 return ReplaceInstUsesWith(CI, In);
8418 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8426 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8427 // If one of the common conversion will work ..
8428 if (Instruction *Result = commonIntCastTransforms(CI))
8431 Value *Src = CI.getOperand(0);
8433 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8434 // types and if the sizes are just right we can convert this into a logical
8435 // 'and' which will be much cheaper than the pair of casts.
8436 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8437 // Get the sizes of the types involved. We know that the intermediate type
8438 // will be smaller than A or C, but don't know the relation between A and C.
8439 Value *A = CSrc->getOperand(0);
8440 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8441 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8442 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8443 // If we're actually extending zero bits, then if
8444 // SrcSize < DstSize: zext(a & mask)
8445 // SrcSize == DstSize: a & mask
8446 // SrcSize > DstSize: trunc(a) & mask
8447 if (SrcSize < DstSize) {
8448 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8449 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8450 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8451 return new ZExtInst(And, CI.getType());
8454 if (SrcSize == DstSize) {
8455 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8456 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8459 if (SrcSize > DstSize) {
8460 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8461 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8462 return BinaryOperator::CreateAnd(Trunc,
8463 ConstantInt::get(Trunc->getType(),
8468 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8469 return transformZExtICmp(ICI, CI);
8471 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8472 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8473 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8474 // of the (zext icmp) will be transformed.
8475 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8476 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8477 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8478 (transformZExtICmp(LHS, CI, false) ||
8479 transformZExtICmp(RHS, CI, false))) {
8480 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8481 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8482 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8486 // zext(trunc(t) & C) -> (t & zext(C)).
8487 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8488 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8489 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8490 Value *TI0 = TI->getOperand(0);
8491 if (TI0->getType() == CI.getType())
8493 BinaryOperator::CreateAnd(TI0,
8494 ConstantExpr::getZExt(C, CI.getType()));
8497 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8498 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8499 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8500 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8501 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8502 And->getOperand(1) == C)
8503 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8504 Value *TI0 = TI->getOperand(0);
8505 if (TI0->getType() == CI.getType()) {
8506 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8507 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8508 return BinaryOperator::CreateXor(NewAnd, ZC);
8515 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8516 if (Instruction *I = commonIntCastTransforms(CI))
8519 Value *Src = CI.getOperand(0);
8521 // Canonicalize sign-extend from i1 to a select.
8522 if (Src->getType() == Type::getInt1Ty(*Context))
8523 return SelectInst::Create(Src,
8524 Constant::getAllOnesValue(CI.getType()),
8525 Constant::getNullValue(CI.getType()));
8527 // See if the value being truncated is already sign extended. If so, just
8528 // eliminate the trunc/sext pair.
8529 if (Operator::getOpcode(Src) == Instruction::Trunc) {
8530 Value *Op = cast<User>(Src)->getOperand(0);
8531 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8532 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8533 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8534 unsigned NumSignBits = ComputeNumSignBits(Op);
8536 if (OpBits == DestBits) {
8537 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8538 // bits, it is already ready.
8539 if (NumSignBits > DestBits-MidBits)
8540 return ReplaceInstUsesWith(CI, Op);
8541 } else if (OpBits < DestBits) {
8542 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8543 // bits, just sext from i32.
8544 if (NumSignBits > OpBits-MidBits)
8545 return new SExtInst(Op, CI.getType(), "tmp");
8547 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8548 // bits, just truncate to i32.
8549 if (NumSignBits > OpBits-MidBits)
8550 return new TruncInst(Op, CI.getType(), "tmp");
8554 // If the input is a shl/ashr pair of a same constant, then this is a sign
8555 // extension from a smaller value. If we could trust arbitrary bitwidth
8556 // integers, we could turn this into a truncate to the smaller bit and then
8557 // use a sext for the whole extension. Since we don't, look deeper and check
8558 // for a truncate. If the source and dest are the same type, eliminate the
8559 // trunc and extend and just do shifts. For example, turn:
8560 // %a = trunc i32 %i to i8
8561 // %b = shl i8 %a, 6
8562 // %c = ashr i8 %b, 6
8563 // %d = sext i8 %c to i32
8565 // %a = shl i32 %i, 30
8566 // %d = ashr i32 %a, 30
8568 ConstantInt *BA = 0, *CA = 0;
8569 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8570 m_ConstantInt(CA))) &&
8571 BA == CA && isa<TruncInst>(A)) {
8572 Value *I = cast<TruncInst>(A)->getOperand(0);
8573 if (I->getType() == CI.getType()) {
8574 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8575 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8576 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8577 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8578 I = Builder->CreateShl(I, ShAmtV, CI.getName());
8579 return BinaryOperator::CreateAShr(I, ShAmtV);
8586 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8587 /// in the specified FP type without changing its value.
8588 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8589 LLVMContext *Context) {
8591 APFloat F = CFP->getValueAPF();
8592 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8594 return ConstantFP::get(*Context, F);
8598 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8599 /// through it until we get the source value.
8600 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8601 if (Instruction *I = dyn_cast<Instruction>(V))
8602 if (I->getOpcode() == Instruction::FPExt)
8603 return LookThroughFPExtensions(I->getOperand(0), Context);
8605 // If this value is a constant, return the constant in the smallest FP type
8606 // that can accurately represent it. This allows us to turn
8607 // (float)((double)X+2.0) into x+2.0f.
8608 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8609 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8610 return V; // No constant folding of this.
8611 // See if the value can be truncated to float and then reextended.
8612 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8614 if (CFP->getType() == Type::getDoubleTy(*Context))
8615 return V; // Won't shrink.
8616 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8618 // Don't try to shrink to various long double types.
8624 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8625 if (Instruction *I = commonCastTransforms(CI))
8628 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8629 // smaller than the destination type, we can eliminate the truncate by doing
8630 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8631 // many builtins (sqrt, etc).
8632 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8633 if (OpI && OpI->hasOneUse()) {
8634 switch (OpI->getOpcode()) {
8636 case Instruction::FAdd:
8637 case Instruction::FSub:
8638 case Instruction::FMul:
8639 case Instruction::FDiv:
8640 case Instruction::FRem:
8641 const Type *SrcTy = OpI->getType();
8642 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8643 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8644 if (LHSTrunc->getType() != SrcTy &&
8645 RHSTrunc->getType() != SrcTy) {
8646 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8647 // If the source types were both smaller than the destination type of
8648 // the cast, do this xform.
8649 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8650 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8651 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8652 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8653 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8662 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8663 return commonCastTransforms(CI);
8666 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8667 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8669 return commonCastTransforms(FI);
8671 // fptoui(uitofp(X)) --> X
8672 // fptoui(sitofp(X)) --> X
8673 // This is safe if the intermediate type has enough bits in its mantissa to
8674 // accurately represent all values of X. For example, do not do this with
8675 // i64->float->i64. This is also safe for sitofp case, because any negative
8676 // 'X' value would cause an undefined result for the fptoui.
8677 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8678 OpI->getOperand(0)->getType() == FI.getType() &&
8679 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8680 OpI->getType()->getFPMantissaWidth())
8681 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8683 return commonCastTransforms(FI);
8686 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8687 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8689 return commonCastTransforms(FI);
8691 // fptosi(sitofp(X)) --> X
8692 // fptosi(uitofp(X)) --> X
8693 // This is safe if the intermediate type has enough bits in its mantissa to
8694 // accurately represent all values of X. For example, do not do this with
8695 // i64->float->i64. This is also safe for sitofp case, because any negative
8696 // 'X' value would cause an undefined result for the fptoui.
8697 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8698 OpI->getOperand(0)->getType() == FI.getType() &&
8699 (int)FI.getType()->getScalarSizeInBits() <=
8700 OpI->getType()->getFPMantissaWidth())
8701 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8703 return commonCastTransforms(FI);
8706 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8707 return commonCastTransforms(CI);
8710 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8711 return commonCastTransforms(CI);
8714 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8715 // If the destination integer type is smaller than the intptr_t type for
8716 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8717 // trunc to be exposed to other transforms. Don't do this for extending
8718 // ptrtoint's, because we don't know if the target sign or zero extends its
8721 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8722 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8723 TD->getIntPtrType(CI.getContext()),
8725 return new TruncInst(P, CI.getType());
8728 return commonPointerCastTransforms(CI);
8731 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8732 // If the source integer type is larger than the intptr_t type for
8733 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8734 // allows the trunc to be exposed to other transforms. Don't do this for
8735 // extending inttoptr's, because we don't know if the target sign or zero
8736 // extends to pointers.
8737 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8738 TD->getPointerSizeInBits()) {
8739 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8740 TD->getIntPtrType(CI.getContext()), "tmp");
8741 return new IntToPtrInst(P, CI.getType());
8744 if (Instruction *I = commonCastTransforms(CI))
8750 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8751 // If the operands are integer typed then apply the integer transforms,
8752 // otherwise just apply the common ones.
8753 Value *Src = CI.getOperand(0);
8754 const Type *SrcTy = Src->getType();
8755 const Type *DestTy = CI.getType();
8757 if (isa<PointerType>(SrcTy)) {
8758 if (Instruction *I = commonPointerCastTransforms(CI))
8761 if (Instruction *Result = commonCastTransforms(CI))
8766 // Get rid of casts from one type to the same type. These are useless and can
8767 // be replaced by the operand.
8768 if (DestTy == Src->getType())
8769 return ReplaceInstUsesWith(CI, Src);
8771 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8772 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8773 const Type *DstElTy = DstPTy->getElementType();
8774 const Type *SrcElTy = SrcPTy->getElementType();
8776 // If the address spaces don't match, don't eliminate the bitcast, which is
8777 // required for changing types.
8778 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8781 // If we are casting a malloc or alloca to a pointer to a type of the same
8782 // size, rewrite the allocation instruction to allocate the "right" type.
8783 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8784 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8787 // If the source and destination are pointers, and this cast is equivalent
8788 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8789 // This can enhance SROA and other transforms that want type-safe pointers.
8790 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8791 unsigned NumZeros = 0;
8792 while (SrcElTy != DstElTy &&
8793 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8794 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8795 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8799 // If we found a path from the src to dest, create the getelementptr now.
8800 if (SrcElTy == DstElTy) {
8801 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8802 Instruction *GEP = GetElementPtrInst::Create(Src,
8803 Idxs.begin(), Idxs.end(), "",
8804 ((Instruction*) NULL));
8805 cast<GEPOperator>(GEP)->setIsInBounds(true);
8810 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8811 if (DestVTy->getNumElements() == 1) {
8812 if (!isa<VectorType>(SrcTy)) {
8813 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8814 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8815 Constant::getNullValue(Type::getInt32Ty(*Context)));
8817 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8821 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8822 if (SrcVTy->getNumElements() == 1) {
8823 if (!isa<VectorType>(DestTy)) {
8825 Builder->CreateExtractElement(Src,
8826 Constant::getNullValue(Type::getInt32Ty(*Context)));
8827 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8832 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8833 if (SVI->hasOneUse()) {
8834 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8835 // a bitconvert to a vector with the same # elts.
8836 if (isa<VectorType>(DestTy) &&
8837 cast<VectorType>(DestTy)->getNumElements() ==
8838 SVI->getType()->getNumElements() &&
8839 SVI->getType()->getNumElements() ==
8840 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8842 // If either of the operands is a cast from CI.getType(), then
8843 // evaluating the shuffle in the casted destination's type will allow
8844 // us to eliminate at least one cast.
8845 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8846 Tmp->getOperand(0)->getType() == DestTy) ||
8847 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8848 Tmp->getOperand(0)->getType() == DestTy)) {
8849 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8850 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8851 // Return a new shuffle vector. Use the same element ID's, as we
8852 // know the vector types match #elts.
8853 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8861 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8863 /// %D = select %cond, %C, %A
8865 /// %C = select %cond, %B, 0
8868 /// Assuming that the specified instruction is an operand to the select, return
8869 /// a bitmask indicating which operands of this instruction are foldable if they
8870 /// equal the other incoming value of the select.
8872 static unsigned GetSelectFoldableOperands(Instruction *I) {
8873 switch (I->getOpcode()) {
8874 case Instruction::Add:
8875 case Instruction::Mul:
8876 case Instruction::And:
8877 case Instruction::Or:
8878 case Instruction::Xor:
8879 return 3; // Can fold through either operand.
8880 case Instruction::Sub: // Can only fold on the amount subtracted.
8881 case Instruction::Shl: // Can only fold on the shift amount.
8882 case Instruction::LShr:
8883 case Instruction::AShr:
8886 return 0; // Cannot fold
8890 /// GetSelectFoldableConstant - For the same transformation as the previous
8891 /// function, return the identity constant that goes into the select.
8892 static Constant *GetSelectFoldableConstant(Instruction *I,
8893 LLVMContext *Context) {
8894 switch (I->getOpcode()) {
8895 default: llvm_unreachable("This cannot happen!");
8896 case Instruction::Add:
8897 case Instruction::Sub:
8898 case Instruction::Or:
8899 case Instruction::Xor:
8900 case Instruction::Shl:
8901 case Instruction::LShr:
8902 case Instruction::AShr:
8903 return Constant::getNullValue(I->getType());
8904 case Instruction::And:
8905 return Constant::getAllOnesValue(I->getType());
8906 case Instruction::Mul:
8907 return ConstantInt::get(I->getType(), 1);
8911 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8912 /// have the same opcode and only one use each. Try to simplify this.
8913 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8915 if (TI->getNumOperands() == 1) {
8916 // If this is a non-volatile load or a cast from the same type,
8919 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8922 return 0; // unknown unary op.
8925 // Fold this by inserting a select from the input values.
8926 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8927 FI->getOperand(0), SI.getName()+".v");
8928 InsertNewInstBefore(NewSI, SI);
8929 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
8933 // Only handle binary operators here.
8934 if (!isa<BinaryOperator>(TI))
8937 // Figure out if the operations have any operands in common.
8938 Value *MatchOp, *OtherOpT, *OtherOpF;
8940 if (TI->getOperand(0) == FI->getOperand(0)) {
8941 MatchOp = TI->getOperand(0);
8942 OtherOpT = TI->getOperand(1);
8943 OtherOpF = FI->getOperand(1);
8944 MatchIsOpZero = true;
8945 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8946 MatchOp = TI->getOperand(1);
8947 OtherOpT = TI->getOperand(0);
8948 OtherOpF = FI->getOperand(0);
8949 MatchIsOpZero = false;
8950 } else if (!TI->isCommutative()) {
8952 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8953 MatchOp = TI->getOperand(0);
8954 OtherOpT = TI->getOperand(1);
8955 OtherOpF = FI->getOperand(0);
8956 MatchIsOpZero = true;
8957 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8958 MatchOp = TI->getOperand(1);
8959 OtherOpT = TI->getOperand(0);
8960 OtherOpF = FI->getOperand(1);
8961 MatchIsOpZero = true;
8966 // If we reach here, they do have operations in common.
8967 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8968 OtherOpF, SI.getName()+".v");
8969 InsertNewInstBefore(NewSI, SI);
8971 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8973 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8975 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8977 llvm_unreachable("Shouldn't get here");
8981 static bool isSelect01(Constant *C1, Constant *C2) {
8982 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8985 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8988 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8991 /// FoldSelectIntoOp - Try fold the select into one of the operands to
8992 /// facilitate further optimization.
8993 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8995 // See the comment above GetSelectFoldableOperands for a description of the
8996 // transformation we are doing here.
8997 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
8998 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8999 !isa<Constant>(FalseVal)) {
9000 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9001 unsigned OpToFold = 0;
9002 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9004 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9009 Constant *C = GetSelectFoldableConstant(TVI, Context);
9010 Value *OOp = TVI->getOperand(2-OpToFold);
9011 // Avoid creating select between 2 constants unless it's selecting
9013 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9014 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9015 InsertNewInstBefore(NewSel, SI);
9016 NewSel->takeName(TVI);
9017 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9018 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9019 llvm_unreachable("Unknown instruction!!");
9026 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9027 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9028 !isa<Constant>(TrueVal)) {
9029 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9030 unsigned OpToFold = 0;
9031 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9033 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9038 Constant *C = GetSelectFoldableConstant(FVI, Context);
9039 Value *OOp = FVI->getOperand(2-OpToFold);
9040 // Avoid creating select between 2 constants unless it's selecting
9042 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9043 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9044 InsertNewInstBefore(NewSel, SI);
9045 NewSel->takeName(FVI);
9046 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9047 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9048 llvm_unreachable("Unknown instruction!!");
9058 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9059 /// ICmpInst as its first operand.
9061 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9063 bool Changed = false;
9064 ICmpInst::Predicate Pred = ICI->getPredicate();
9065 Value *CmpLHS = ICI->getOperand(0);
9066 Value *CmpRHS = ICI->getOperand(1);
9067 Value *TrueVal = SI.getTrueValue();
9068 Value *FalseVal = SI.getFalseValue();
9070 // Check cases where the comparison is with a constant that
9071 // can be adjusted to fit the min/max idiom. We may edit ICI in
9072 // place here, so make sure the select is the only user.
9073 if (ICI->hasOneUse())
9074 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9077 case ICmpInst::ICMP_ULT:
9078 case ICmpInst::ICMP_SLT: {
9079 // X < MIN ? T : F --> F
9080 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9081 return ReplaceInstUsesWith(SI, FalseVal);
9082 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9083 Constant *AdjustedRHS = SubOne(CI);
9084 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9085 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9086 Pred = ICmpInst::getSwappedPredicate(Pred);
9087 CmpRHS = AdjustedRHS;
9088 std::swap(FalseVal, TrueVal);
9089 ICI->setPredicate(Pred);
9090 ICI->setOperand(1, CmpRHS);
9091 SI.setOperand(1, TrueVal);
9092 SI.setOperand(2, FalseVal);
9097 case ICmpInst::ICMP_UGT:
9098 case ICmpInst::ICMP_SGT: {
9099 // X > MAX ? T : F --> F
9100 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9101 return ReplaceInstUsesWith(SI, FalseVal);
9102 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9103 Constant *AdjustedRHS = AddOne(CI);
9104 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9105 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9106 Pred = ICmpInst::getSwappedPredicate(Pred);
9107 CmpRHS = AdjustedRHS;
9108 std::swap(FalseVal, TrueVal);
9109 ICI->setPredicate(Pred);
9110 ICI->setOperand(1, CmpRHS);
9111 SI.setOperand(1, TrueVal);
9112 SI.setOperand(2, FalseVal);
9119 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9120 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9121 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9122 if (match(TrueVal, m_ConstantInt<-1>()) &&
9123 match(FalseVal, m_ConstantInt<0>()))
9124 Pred = ICI->getPredicate();
9125 else if (match(TrueVal, m_ConstantInt<0>()) &&
9126 match(FalseVal, m_ConstantInt<-1>()))
9127 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9129 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9130 // If we are just checking for a icmp eq of a single bit and zext'ing it
9131 // to an integer, then shift the bit to the appropriate place and then
9132 // cast to integer to avoid the comparison.
9133 const APInt &Op1CV = CI->getValue();
9135 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9136 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9137 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9138 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9139 Value *In = ICI->getOperand(0);
9140 Value *Sh = ConstantInt::get(In->getType(),
9141 In->getType()->getScalarSizeInBits()-1);
9142 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9143 In->getName()+".lobit"),
9145 if (In->getType() != SI.getType())
9146 In = CastInst::CreateIntegerCast(In, SI.getType(),
9147 true/*SExt*/, "tmp", ICI);
9149 if (Pred == ICmpInst::ICMP_SGT)
9150 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9151 In->getName()+".not"), *ICI);
9153 return ReplaceInstUsesWith(SI, In);
9158 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9159 // Transform (X == Y) ? X : Y -> Y
9160 if (Pred == ICmpInst::ICMP_EQ)
9161 return ReplaceInstUsesWith(SI, FalseVal);
9162 // Transform (X != Y) ? X : Y -> X
9163 if (Pred == ICmpInst::ICMP_NE)
9164 return ReplaceInstUsesWith(SI, TrueVal);
9165 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9167 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9168 // Transform (X == Y) ? Y : X -> X
9169 if (Pred == ICmpInst::ICMP_EQ)
9170 return ReplaceInstUsesWith(SI, FalseVal);
9171 // Transform (X != Y) ? Y : X -> Y
9172 if (Pred == ICmpInst::ICMP_NE)
9173 return ReplaceInstUsesWith(SI, TrueVal);
9174 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9177 /// NOTE: if we wanted to, this is where to detect integer ABS
9179 return Changed ? &SI : 0;
9182 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9183 Value *CondVal = SI.getCondition();
9184 Value *TrueVal = SI.getTrueValue();
9185 Value *FalseVal = SI.getFalseValue();
9187 // select true, X, Y -> X
9188 // select false, X, Y -> Y
9189 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9190 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9192 // select C, X, X -> X
9193 if (TrueVal == FalseVal)
9194 return ReplaceInstUsesWith(SI, TrueVal);
9196 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9197 return ReplaceInstUsesWith(SI, FalseVal);
9198 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9199 return ReplaceInstUsesWith(SI, TrueVal);
9200 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9201 if (isa<Constant>(TrueVal))
9202 return ReplaceInstUsesWith(SI, TrueVal);
9204 return ReplaceInstUsesWith(SI, FalseVal);
9207 if (SI.getType() == Type::getInt1Ty(*Context)) {
9208 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9209 if (C->getZExtValue()) {
9210 // Change: A = select B, true, C --> A = or B, C
9211 return BinaryOperator::CreateOr(CondVal, FalseVal);
9213 // Change: A = select B, false, C --> A = and !B, C
9215 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9216 "not."+CondVal->getName()), SI);
9217 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9219 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9220 if (C->getZExtValue() == false) {
9221 // Change: A = select B, C, false --> A = and B, C
9222 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9224 // Change: A = select B, C, true --> A = or !B, C
9226 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9227 "not."+CondVal->getName()), SI);
9228 return BinaryOperator::CreateOr(NotCond, TrueVal);
9232 // select a, b, a -> a&b
9233 // select a, a, b -> a|b
9234 if (CondVal == TrueVal)
9235 return BinaryOperator::CreateOr(CondVal, FalseVal);
9236 else if (CondVal == FalseVal)
9237 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9240 // Selecting between two integer constants?
9241 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9242 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9243 // select C, 1, 0 -> zext C to int
9244 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9245 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9246 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9247 // select C, 0, 1 -> zext !C to int
9249 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9250 "not."+CondVal->getName()), SI);
9251 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9254 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9255 // If one of the constants is zero (we know they can't both be) and we
9256 // have an icmp instruction with zero, and we have an 'and' with the
9257 // non-constant value, eliminate this whole mess. This corresponds to
9258 // cases like this: ((X & 27) ? 27 : 0)
9259 if (TrueValC->isZero() || FalseValC->isZero())
9260 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9261 cast<Constant>(IC->getOperand(1))->isNullValue())
9262 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9263 if (ICA->getOpcode() == Instruction::And &&
9264 isa<ConstantInt>(ICA->getOperand(1)) &&
9265 (ICA->getOperand(1) == TrueValC ||
9266 ICA->getOperand(1) == FalseValC) &&
9267 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9268 // Okay, now we know that everything is set up, we just don't
9269 // know whether we have a icmp_ne or icmp_eq and whether the
9270 // true or false val is the zero.
9271 bool ShouldNotVal = !TrueValC->isZero();
9272 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9275 V = InsertNewInstBefore(BinaryOperator::Create(
9276 Instruction::Xor, V, ICA->getOperand(1)), SI);
9277 return ReplaceInstUsesWith(SI, V);
9282 // See if we are selecting two values based on a comparison of the two values.
9283 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9284 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9285 // Transform (X == Y) ? X : Y -> Y
9286 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9287 // This is not safe in general for floating point:
9288 // consider X== -0, Y== +0.
9289 // It becomes safe if either operand is a nonzero constant.
9290 ConstantFP *CFPt, *CFPf;
9291 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9292 !CFPt->getValueAPF().isZero()) ||
9293 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9294 !CFPf->getValueAPF().isZero()))
9295 return ReplaceInstUsesWith(SI, FalseVal);
9297 // Transform (X != Y) ? X : Y -> X
9298 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9299 return ReplaceInstUsesWith(SI, TrueVal);
9300 // NOTE: if we wanted to, this is where to detect MIN/MAX
9302 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9303 // Transform (X == Y) ? Y : X -> X
9304 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9305 // This is not safe in general for floating point:
9306 // consider X== -0, Y== +0.
9307 // It becomes safe if either operand is a nonzero constant.
9308 ConstantFP *CFPt, *CFPf;
9309 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9310 !CFPt->getValueAPF().isZero()) ||
9311 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9312 !CFPf->getValueAPF().isZero()))
9313 return ReplaceInstUsesWith(SI, FalseVal);
9315 // Transform (X != Y) ? Y : X -> Y
9316 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9317 return ReplaceInstUsesWith(SI, TrueVal);
9318 // NOTE: if we wanted to, this is where to detect MIN/MAX
9320 // NOTE: if we wanted to, this is where to detect ABS
9323 // See if we are selecting two values based on a comparison of the two values.
9324 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9325 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9328 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9329 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9330 if (TI->hasOneUse() && FI->hasOneUse()) {
9331 Instruction *AddOp = 0, *SubOp = 0;
9333 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9334 if (TI->getOpcode() == FI->getOpcode())
9335 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9338 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9339 // even legal for FP.
9340 if ((TI->getOpcode() == Instruction::Sub &&
9341 FI->getOpcode() == Instruction::Add) ||
9342 (TI->getOpcode() == Instruction::FSub &&
9343 FI->getOpcode() == Instruction::FAdd)) {
9344 AddOp = FI; SubOp = TI;
9345 } else if ((FI->getOpcode() == Instruction::Sub &&
9346 TI->getOpcode() == Instruction::Add) ||
9347 (FI->getOpcode() == Instruction::FSub &&
9348 TI->getOpcode() == Instruction::FAdd)) {
9349 AddOp = TI; SubOp = FI;
9353 Value *OtherAddOp = 0;
9354 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9355 OtherAddOp = AddOp->getOperand(1);
9356 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9357 OtherAddOp = AddOp->getOperand(0);
9361 // So at this point we know we have (Y -> OtherAddOp):
9362 // select C, (add X, Y), (sub X, Z)
9363 Value *NegVal; // Compute -Z
9364 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9365 NegVal = ConstantExpr::getNeg(C);
9367 NegVal = InsertNewInstBefore(
9368 BinaryOperator::CreateNeg(SubOp->getOperand(1),
9372 Value *NewTrueOp = OtherAddOp;
9373 Value *NewFalseOp = NegVal;
9375 std::swap(NewTrueOp, NewFalseOp);
9376 Instruction *NewSel =
9377 SelectInst::Create(CondVal, NewTrueOp,
9378 NewFalseOp, SI.getName() + ".p");
9380 NewSel = InsertNewInstBefore(NewSel, SI);
9381 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9386 // See if we can fold the select into one of our operands.
9387 if (SI.getType()->isInteger()) {
9388 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9393 if (BinaryOperator::isNot(CondVal)) {
9394 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9395 SI.setOperand(1, FalseVal);
9396 SI.setOperand(2, TrueVal);
9403 /// EnforceKnownAlignment - If the specified pointer points to an object that
9404 /// we control, modify the object's alignment to PrefAlign. This isn't
9405 /// often possible though. If alignment is important, a more reliable approach
9406 /// is to simply align all global variables and allocation instructions to
9407 /// their preferred alignment from the beginning.
9409 static unsigned EnforceKnownAlignment(Value *V,
9410 unsigned Align, unsigned PrefAlign) {
9412 User *U = dyn_cast<User>(V);
9413 if (!U) return Align;
9415 switch (Operator::getOpcode(U)) {
9417 case Instruction::BitCast:
9418 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9419 case Instruction::GetElementPtr: {
9420 // If all indexes are zero, it is just the alignment of the base pointer.
9421 bool AllZeroOperands = true;
9422 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9423 if (!isa<Constant>(*i) ||
9424 !cast<Constant>(*i)->isNullValue()) {
9425 AllZeroOperands = false;
9429 if (AllZeroOperands) {
9430 // Treat this like a bitcast.
9431 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9437 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9438 // If there is a large requested alignment and we can, bump up the alignment
9440 if (!GV->isDeclaration()) {
9441 if (GV->getAlignment() >= PrefAlign)
9442 Align = GV->getAlignment();
9444 GV->setAlignment(PrefAlign);
9448 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9449 // If there is a requested alignment and if this is an alloca, round up. We
9450 // don't do this for malloc, because some systems can't respect the request.
9451 if (isa<AllocaInst>(AI)) {
9452 if (AI->getAlignment() >= PrefAlign)
9453 Align = AI->getAlignment();
9455 AI->setAlignment(PrefAlign);
9464 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9465 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9466 /// and it is more than the alignment of the ultimate object, see if we can
9467 /// increase the alignment of the ultimate object, making this check succeed.
9468 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9469 unsigned PrefAlign) {
9470 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9471 sizeof(PrefAlign) * CHAR_BIT;
9472 APInt Mask = APInt::getAllOnesValue(BitWidth);
9473 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9474 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9475 unsigned TrailZ = KnownZero.countTrailingOnes();
9476 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9478 if (PrefAlign > Align)
9479 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9481 // We don't need to make any adjustment.
9485 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9486 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9487 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9488 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9489 unsigned CopyAlign = MI->getAlignment();
9491 if (CopyAlign < MinAlign) {
9492 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9497 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9499 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9500 if (MemOpLength == 0) return 0;
9502 // Source and destination pointer types are always "i8*" for intrinsic. See
9503 // if the size is something we can handle with a single primitive load/store.
9504 // A single load+store correctly handles overlapping memory in the memmove
9506 unsigned Size = MemOpLength->getZExtValue();
9507 if (Size == 0) return MI; // Delete this mem transfer.
9509 if (Size > 8 || (Size&(Size-1)))
9510 return 0; // If not 1/2/4/8 bytes, exit.
9512 // Use an integer load+store unless we can find something better.
9514 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9516 // Memcpy forces the use of i8* for the source and destination. That means
9517 // that if you're using memcpy to move one double around, you'll get a cast
9518 // from double* to i8*. We'd much rather use a double load+store rather than
9519 // an i64 load+store, here because this improves the odds that the source or
9520 // dest address will be promotable. See if we can find a better type than the
9521 // integer datatype.
9522 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9523 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9524 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9525 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9526 // down through these levels if so.
9527 while (!SrcETy->isSingleValueType()) {
9528 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9529 if (STy->getNumElements() == 1)
9530 SrcETy = STy->getElementType(0);
9533 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9534 if (ATy->getNumElements() == 1)
9535 SrcETy = ATy->getElementType();
9542 if (SrcETy->isSingleValueType())
9543 NewPtrTy = PointerType::getUnqual(SrcETy);
9548 // If the memcpy/memmove provides better alignment info than we can
9550 SrcAlign = std::max(SrcAlign, CopyAlign);
9551 DstAlign = std::max(DstAlign, CopyAlign);
9553 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9554 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9555 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9556 InsertNewInstBefore(L, *MI);
9557 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9559 // Set the size of the copy to 0, it will be deleted on the next iteration.
9560 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9564 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9565 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9566 if (MI->getAlignment() < Alignment) {
9567 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9572 // Extract the length and alignment and fill if they are constant.
9573 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9574 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9575 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9577 uint64_t Len = LenC->getZExtValue();
9578 Alignment = MI->getAlignment();
9580 // If the length is zero, this is a no-op
9581 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9583 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9584 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9585 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
9587 Value *Dest = MI->getDest();
9588 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9590 // Alignment 0 is identity for alignment 1 for memset, but not store.
9591 if (Alignment == 0) Alignment = 1;
9593 // Extract the fill value and store.
9594 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9595 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9596 Dest, false, Alignment), *MI);
9598 // Set the size of the copy to 0, it will be deleted on the next iteration.
9599 MI->setLength(Constant::getNullValue(LenC->getType()));
9607 /// visitCallInst - CallInst simplification. This mostly only handles folding
9608 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9609 /// the heavy lifting.
9611 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9612 // If the caller function is nounwind, mark the call as nounwind, even if the
9614 if (CI.getParent()->getParent()->doesNotThrow() &&
9615 !CI.doesNotThrow()) {
9616 CI.setDoesNotThrow();
9620 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9621 if (!II) return visitCallSite(&CI);
9623 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9625 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9626 bool Changed = false;
9628 // memmove/cpy/set of zero bytes is a noop.
9629 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9630 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9632 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9633 if (CI->getZExtValue() == 1) {
9634 // Replace the instruction with just byte operations. We would
9635 // transform other cases to loads/stores, but we don't know if
9636 // alignment is sufficient.
9640 // If we have a memmove and the source operation is a constant global,
9641 // then the source and dest pointers can't alias, so we can change this
9642 // into a call to memcpy.
9643 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9644 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9645 if (GVSrc->isConstant()) {
9646 Module *M = CI.getParent()->getParent()->getParent();
9647 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9649 Tys[0] = CI.getOperand(3)->getType();
9651 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9655 // memmove(x,x,size) -> noop.
9656 if (MMI->getSource() == MMI->getDest())
9657 return EraseInstFromFunction(CI);
9660 // If we can determine a pointer alignment that is bigger than currently
9661 // set, update the alignment.
9662 if (isa<MemTransferInst>(MI)) {
9663 if (Instruction *I = SimplifyMemTransfer(MI))
9665 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9666 if (Instruction *I = SimplifyMemSet(MSI))
9670 if (Changed) return II;
9673 switch (II->getIntrinsicID()) {
9675 case Intrinsic::bswap:
9676 // bswap(bswap(x)) -> x
9677 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9678 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9679 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9681 case Intrinsic::ppc_altivec_lvx:
9682 case Intrinsic::ppc_altivec_lvxl:
9683 case Intrinsic::x86_sse_loadu_ps:
9684 case Intrinsic::x86_sse2_loadu_pd:
9685 case Intrinsic::x86_sse2_loadu_dq:
9686 // Turn PPC lvx -> load if the pointer is known aligned.
9687 // Turn X86 loadups -> load if the pointer is known aligned.
9688 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9689 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9690 PointerType::getUnqual(II->getType()));
9691 return new LoadInst(Ptr);
9694 case Intrinsic::ppc_altivec_stvx:
9695 case Intrinsic::ppc_altivec_stvxl:
9696 // Turn stvx -> store if the pointer is known aligned.
9697 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9698 const Type *OpPtrTy =
9699 PointerType::getUnqual(II->getOperand(1)->getType());
9700 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9701 return new StoreInst(II->getOperand(1), Ptr);
9704 case Intrinsic::x86_sse_storeu_ps:
9705 case Intrinsic::x86_sse2_storeu_pd:
9706 case Intrinsic::x86_sse2_storeu_dq:
9707 // Turn X86 storeu -> store if the pointer is known aligned.
9708 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9709 const Type *OpPtrTy =
9710 PointerType::getUnqual(II->getOperand(2)->getType());
9711 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9712 return new StoreInst(II->getOperand(2), Ptr);
9716 case Intrinsic::x86_sse_cvttss2si: {
9717 // These intrinsics only demands the 0th element of its input vector. If
9718 // we can simplify the input based on that, do so now.
9720 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9721 APInt DemandedElts(VWidth, 1);
9722 APInt UndefElts(VWidth, 0);
9723 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9725 II->setOperand(1, V);
9731 case Intrinsic::ppc_altivec_vperm:
9732 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9733 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9734 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9736 // Check that all of the elements are integer constants or undefs.
9737 bool AllEltsOk = true;
9738 for (unsigned i = 0; i != 16; ++i) {
9739 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9740 !isa<UndefValue>(Mask->getOperand(i))) {
9747 // Cast the input vectors to byte vectors.
9748 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9749 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9750 Value *Result = UndefValue::get(Op0->getType());
9752 // Only extract each element once.
9753 Value *ExtractedElts[32];
9754 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9756 for (unsigned i = 0; i != 16; ++i) {
9757 if (isa<UndefValue>(Mask->getOperand(i)))
9759 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9760 Idx &= 31; // Match the hardware behavior.
9762 if (ExtractedElts[Idx] == 0) {
9763 ExtractedElts[Idx] =
9764 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9765 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9769 // Insert this value into the result vector.
9770 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9771 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9774 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9779 case Intrinsic::stackrestore: {
9780 // If the save is right next to the restore, remove the restore. This can
9781 // happen when variable allocas are DCE'd.
9782 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9783 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9784 BasicBlock::iterator BI = SS;
9786 return EraseInstFromFunction(CI);
9790 // Scan down this block to see if there is another stack restore in the
9791 // same block without an intervening call/alloca.
9792 BasicBlock::iterator BI = II;
9793 TerminatorInst *TI = II->getParent()->getTerminator();
9794 bool CannotRemove = false;
9795 for (++BI; &*BI != TI; ++BI) {
9796 if (isa<AllocaInst>(BI)) {
9797 CannotRemove = true;
9800 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9801 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9802 // If there is a stackrestore below this one, remove this one.
9803 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9804 return EraseInstFromFunction(CI);
9805 // Otherwise, ignore the intrinsic.
9807 // If we found a non-intrinsic call, we can't remove the stack
9809 CannotRemove = true;
9815 // If the stack restore is in a return/unwind block and if there are no
9816 // allocas or calls between the restore and the return, nuke the restore.
9817 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9818 return EraseInstFromFunction(CI);
9823 return visitCallSite(II);
9826 // InvokeInst simplification
9828 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9829 return visitCallSite(&II);
9832 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
9833 /// passed through the varargs area, we can eliminate the use of the cast.
9834 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9835 const CastInst * const CI,
9836 const TargetData * const TD,
9838 if (!CI->isLosslessCast())
9841 // The size of ByVal arguments is derived from the type, so we
9842 // can't change to a type with a different size. If the size were
9843 // passed explicitly we could avoid this check.
9844 if (!CS.paramHasAttr(ix, Attribute::ByVal))
9848 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9849 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9850 if (!SrcTy->isSized() || !DstTy->isSized())
9852 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9857 // visitCallSite - Improvements for call and invoke instructions.
9859 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9860 bool Changed = false;
9862 // If the callee is a constexpr cast of a function, attempt to move the cast
9863 // to the arguments of the call/invoke.
9864 if (transformConstExprCastCall(CS)) return 0;
9866 Value *Callee = CS.getCalledValue();
9868 if (Function *CalleeF = dyn_cast<Function>(Callee))
9869 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9870 Instruction *OldCall = CS.getInstruction();
9871 // If the call and callee calling conventions don't match, this call must
9872 // be unreachable, as the call is undefined.
9873 new StoreInst(ConstantInt::getTrue(*Context),
9874 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9876 if (!OldCall->use_empty())
9877 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9878 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9879 return EraseInstFromFunction(*OldCall);
9883 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9884 // This instruction is not reachable, just remove it. We insert a store to
9885 // undef so that we know that this code is not reachable, despite the fact
9886 // that we can't modify the CFG here.
9887 new StoreInst(ConstantInt::getTrue(*Context),
9888 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9889 CS.getInstruction());
9891 if (!CS.getInstruction()->use_empty())
9892 CS.getInstruction()->
9893 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9895 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9896 // Don't break the CFG, insert a dummy cond branch.
9897 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9898 ConstantInt::getTrue(*Context), II);
9900 return EraseInstFromFunction(*CS.getInstruction());
9903 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9904 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9905 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9906 return transformCallThroughTrampoline(CS);
9908 const PointerType *PTy = cast<PointerType>(Callee->getType());
9909 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9910 if (FTy->isVarArg()) {
9911 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9912 // See if we can optimize any arguments passed through the varargs area of
9914 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9915 E = CS.arg_end(); I != E; ++I, ++ix) {
9916 CastInst *CI = dyn_cast<CastInst>(*I);
9917 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9918 *I = CI->getOperand(0);
9924 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9925 // Inline asm calls cannot throw - mark them 'nounwind'.
9926 CS.setDoesNotThrow();
9930 return Changed ? CS.getInstruction() : 0;
9933 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9934 // attempt to move the cast to the arguments of the call/invoke.
9936 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9937 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9938 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9939 if (CE->getOpcode() != Instruction::BitCast ||
9940 !isa<Function>(CE->getOperand(0)))
9942 Function *Callee = cast<Function>(CE->getOperand(0));
9943 Instruction *Caller = CS.getInstruction();
9944 const AttrListPtr &CallerPAL = CS.getAttributes();
9946 // Okay, this is a cast from a function to a different type. Unless doing so
9947 // would cause a type conversion of one of our arguments, change this call to
9948 // be a direct call with arguments casted to the appropriate types.
9950 const FunctionType *FT = Callee->getFunctionType();
9951 const Type *OldRetTy = Caller->getType();
9952 const Type *NewRetTy = FT->getReturnType();
9954 if (isa<StructType>(NewRetTy))
9955 return false; // TODO: Handle multiple return values.
9957 // Check to see if we are changing the return type...
9958 if (OldRetTy != NewRetTy) {
9959 if (Callee->isDeclaration() &&
9960 // Conversion is ok if changing from one pointer type to another or from
9961 // a pointer to an integer of the same size.
9962 !((isa<PointerType>(OldRetTy) || !TD ||
9963 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
9964 (isa<PointerType>(NewRetTy) || !TD ||
9965 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
9966 return false; // Cannot transform this return value.
9968 if (!Caller->use_empty() &&
9969 // void -> non-void is handled specially
9970 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
9971 return false; // Cannot transform this return value.
9973 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9974 Attributes RAttrs = CallerPAL.getRetAttributes();
9975 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9976 return false; // Attribute not compatible with transformed value.
9979 // If the callsite is an invoke instruction, and the return value is used by
9980 // a PHI node in a successor, we cannot change the return type of the call
9981 // because there is no place to put the cast instruction (without breaking
9982 // the critical edge). Bail out in this case.
9983 if (!Caller->use_empty())
9984 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9985 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9987 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9988 if (PN->getParent() == II->getNormalDest() ||
9989 PN->getParent() == II->getUnwindDest())
9993 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9994 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9996 CallSite::arg_iterator AI = CS.arg_begin();
9997 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9998 const Type *ParamTy = FT->getParamType(i);
9999 const Type *ActTy = (*AI)->getType();
10001 if (!CastInst::isCastable(ActTy, ParamTy))
10002 return false; // Cannot transform this parameter value.
10004 if (CallerPAL.getParamAttributes(i + 1)
10005 & Attribute::typeIncompatible(ParamTy))
10006 return false; // Attribute not compatible with transformed value.
10008 // Converting from one pointer type to another or between a pointer and an
10009 // integer of the same size is safe even if we do not have a body.
10010 bool isConvertible = ActTy == ParamTy ||
10011 (TD && ((isa<PointerType>(ParamTy) ||
10012 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10013 (isa<PointerType>(ActTy) ||
10014 ActTy == TD->getIntPtrType(Caller->getContext()))));
10015 if (Callee->isDeclaration() && !isConvertible) return false;
10018 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10019 Callee->isDeclaration())
10020 return false; // Do not delete arguments unless we have a function body.
10022 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10023 !CallerPAL.isEmpty())
10024 // In this case we have more arguments than the new function type, but we
10025 // won't be dropping them. Check that these extra arguments have attributes
10026 // that are compatible with being a vararg call argument.
10027 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10028 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10030 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10031 if (PAttrs & Attribute::VarArgsIncompatible)
10035 // Okay, we decided that this is a safe thing to do: go ahead and start
10036 // inserting cast instructions as necessary...
10037 std::vector<Value*> Args;
10038 Args.reserve(NumActualArgs);
10039 SmallVector<AttributeWithIndex, 8> attrVec;
10040 attrVec.reserve(NumCommonArgs);
10042 // Get any return attributes.
10043 Attributes RAttrs = CallerPAL.getRetAttributes();
10045 // If the return value is not being used, the type may not be compatible
10046 // with the existing attributes. Wipe out any problematic attributes.
10047 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10049 // Add the new return attributes.
10051 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10053 AI = CS.arg_begin();
10054 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10055 const Type *ParamTy = FT->getParamType(i);
10056 if ((*AI)->getType() == ParamTy) {
10057 Args.push_back(*AI);
10059 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10060 false, ParamTy, false);
10061 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10064 // Add any parameter attributes.
10065 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10066 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10069 // If the function takes more arguments than the call was taking, add them
10071 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10072 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10074 // If we are removing arguments to the function, emit an obnoxious warning.
10075 if (FT->getNumParams() < NumActualArgs) {
10076 if (!FT->isVarArg()) {
10077 errs() << "WARNING: While resolving call to function '"
10078 << Callee->getName() << "' arguments were dropped!\n";
10080 // Add all of the arguments in their promoted form to the arg list.
10081 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10082 const Type *PTy = getPromotedType((*AI)->getType());
10083 if (PTy != (*AI)->getType()) {
10084 // Must promote to pass through va_arg area!
10085 Instruction::CastOps opcode =
10086 CastInst::getCastOpcode(*AI, false, PTy, false);
10087 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10089 Args.push_back(*AI);
10092 // Add any parameter attributes.
10093 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10094 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10099 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10100 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10102 if (NewRetTy == Type::getVoidTy(*Context))
10103 Caller->setName(""); // Void type should not have a name.
10105 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10109 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10110 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10111 Args.begin(), Args.end(),
10112 Caller->getName(), Caller);
10113 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10114 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10116 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10117 Caller->getName(), Caller);
10118 CallInst *CI = cast<CallInst>(Caller);
10119 if (CI->isTailCall())
10120 cast<CallInst>(NC)->setTailCall();
10121 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10122 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10125 // Insert a cast of the return type as necessary.
10127 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10128 if (NV->getType() != Type::getVoidTy(*Context)) {
10129 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10131 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10133 // If this is an invoke instruction, we should insert it after the first
10134 // non-phi, instruction in the normal successor block.
10135 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10136 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10137 InsertNewInstBefore(NC, *I);
10139 // Otherwise, it's a call, just insert cast right after the call instr
10140 InsertNewInstBefore(NC, *Caller);
10142 Worklist.AddUsersToWorkList(*Caller);
10144 NV = UndefValue::get(Caller->getType());
10148 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10149 Caller->replaceAllUsesWith(NV);
10150 Caller->eraseFromParent();
10151 Worklist.Remove(Caller);
10155 // transformCallThroughTrampoline - Turn a call to a function created by the
10156 // init_trampoline intrinsic into a direct call to the underlying function.
10158 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10159 Value *Callee = CS.getCalledValue();
10160 const PointerType *PTy = cast<PointerType>(Callee->getType());
10161 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10162 const AttrListPtr &Attrs = CS.getAttributes();
10164 // If the call already has the 'nest' attribute somewhere then give up -
10165 // otherwise 'nest' would occur twice after splicing in the chain.
10166 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10169 IntrinsicInst *Tramp =
10170 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10172 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10173 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10174 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10176 const AttrListPtr &NestAttrs = NestF->getAttributes();
10177 if (!NestAttrs.isEmpty()) {
10178 unsigned NestIdx = 1;
10179 const Type *NestTy = 0;
10180 Attributes NestAttr = Attribute::None;
10182 // Look for a parameter marked with the 'nest' attribute.
10183 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10184 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10185 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10186 // Record the parameter type and any other attributes.
10188 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10193 Instruction *Caller = CS.getInstruction();
10194 std::vector<Value*> NewArgs;
10195 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10197 SmallVector<AttributeWithIndex, 8> NewAttrs;
10198 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10200 // Insert the nest argument into the call argument list, which may
10201 // mean appending it. Likewise for attributes.
10203 // Add any result attributes.
10204 if (Attributes Attr = Attrs.getRetAttributes())
10205 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10209 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10211 if (Idx == NestIdx) {
10212 // Add the chain argument and attributes.
10213 Value *NestVal = Tramp->getOperand(3);
10214 if (NestVal->getType() != NestTy)
10215 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10216 NewArgs.push_back(NestVal);
10217 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10223 // Add the original argument and attributes.
10224 NewArgs.push_back(*I);
10225 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10227 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10233 // Add any function attributes.
10234 if (Attributes Attr = Attrs.getFnAttributes())
10235 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10237 // The trampoline may have been bitcast to a bogus type (FTy).
10238 // Handle this by synthesizing a new function type, equal to FTy
10239 // with the chain parameter inserted.
10241 std::vector<const Type*> NewTypes;
10242 NewTypes.reserve(FTy->getNumParams()+1);
10244 // Insert the chain's type into the list of parameter types, which may
10245 // mean appending it.
10248 FunctionType::param_iterator I = FTy->param_begin(),
10249 E = FTy->param_end();
10252 if (Idx == NestIdx)
10253 // Add the chain's type.
10254 NewTypes.push_back(NestTy);
10259 // Add the original type.
10260 NewTypes.push_back(*I);
10266 // Replace the trampoline call with a direct call. Let the generic
10267 // code sort out any function type mismatches.
10268 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
10270 Constant *NewCallee =
10271 NestF->getType() == PointerType::getUnqual(NewFTy) ?
10272 NestF : ConstantExpr::getBitCast(NestF,
10273 PointerType::getUnqual(NewFTy));
10274 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10277 Instruction *NewCaller;
10278 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10279 NewCaller = InvokeInst::Create(NewCallee,
10280 II->getNormalDest(), II->getUnwindDest(),
10281 NewArgs.begin(), NewArgs.end(),
10282 Caller->getName(), Caller);
10283 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10284 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10286 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10287 Caller->getName(), Caller);
10288 if (cast<CallInst>(Caller)->isTailCall())
10289 cast<CallInst>(NewCaller)->setTailCall();
10290 cast<CallInst>(NewCaller)->
10291 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10292 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10294 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10295 Caller->replaceAllUsesWith(NewCaller);
10296 Caller->eraseFromParent();
10297 Worklist.Remove(Caller);
10302 // Replace the trampoline call with a direct call. Since there is no 'nest'
10303 // parameter, there is no need to adjust the argument list. Let the generic
10304 // code sort out any function type mismatches.
10305 Constant *NewCallee =
10306 NestF->getType() == PTy ? NestF :
10307 ConstantExpr::getBitCast(NestF, PTy);
10308 CS.setCalledFunction(NewCallee);
10309 return CS.getInstruction();
10312 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10313 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10314 /// and a single binop.
10315 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10316 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10317 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10318 unsigned Opc = FirstInst->getOpcode();
10319 Value *LHSVal = FirstInst->getOperand(0);
10320 Value *RHSVal = FirstInst->getOperand(1);
10322 const Type *LHSType = LHSVal->getType();
10323 const Type *RHSType = RHSVal->getType();
10325 // Scan to see if all operands are the same opcode, all have one use, and all
10326 // kill their operands (i.e. the operands have one use).
10327 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10328 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10329 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10330 // Verify type of the LHS matches so we don't fold cmp's of different
10331 // types or GEP's with different index types.
10332 I->getOperand(0)->getType() != LHSType ||
10333 I->getOperand(1)->getType() != RHSType)
10336 // If they are CmpInst instructions, check their predicates
10337 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10338 if (cast<CmpInst>(I)->getPredicate() !=
10339 cast<CmpInst>(FirstInst)->getPredicate())
10342 // Keep track of which operand needs a phi node.
10343 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10344 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10347 // Otherwise, this is safe to transform!
10349 Value *InLHS = FirstInst->getOperand(0);
10350 Value *InRHS = FirstInst->getOperand(1);
10351 PHINode *NewLHS = 0, *NewRHS = 0;
10353 NewLHS = PHINode::Create(LHSType,
10354 FirstInst->getOperand(0)->getName() + ".pn");
10355 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10356 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10357 InsertNewInstBefore(NewLHS, PN);
10362 NewRHS = PHINode::Create(RHSType,
10363 FirstInst->getOperand(1)->getName() + ".pn");
10364 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10365 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10366 InsertNewInstBefore(NewRHS, PN);
10370 // Add all operands to the new PHIs.
10371 if (NewLHS || NewRHS) {
10372 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10373 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10375 Value *NewInLHS = InInst->getOperand(0);
10376 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10379 Value *NewInRHS = InInst->getOperand(1);
10380 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10385 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10386 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10387 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10388 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10392 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10393 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10395 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10396 FirstInst->op_end());
10397 // This is true if all GEP bases are allocas and if all indices into them are
10399 bool AllBasePointersAreAllocas = true;
10401 // Scan to see if all operands are the same opcode, all have one use, and all
10402 // kill their operands (i.e. the operands have one use).
10403 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10404 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10405 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10406 GEP->getNumOperands() != FirstInst->getNumOperands())
10409 // Keep track of whether or not all GEPs are of alloca pointers.
10410 if (AllBasePointersAreAllocas &&
10411 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10412 !GEP->hasAllConstantIndices()))
10413 AllBasePointersAreAllocas = false;
10415 // Compare the operand lists.
10416 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10417 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10420 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10421 // if one of the PHIs has a constant for the index. The index may be
10422 // substantially cheaper to compute for the constants, so making it a
10423 // variable index could pessimize the path. This also handles the case
10424 // for struct indices, which must always be constant.
10425 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10426 isa<ConstantInt>(GEP->getOperand(op)))
10429 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10431 FixedOperands[op] = 0; // Needs a PHI.
10435 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10436 // bother doing this transformation. At best, this will just save a bit of
10437 // offset calculation, but all the predecessors will have to materialize the
10438 // stack address into a register anyway. We'd actually rather *clone* the
10439 // load up into the predecessors so that we have a load of a gep of an alloca,
10440 // which can usually all be folded into the load.
10441 if (AllBasePointersAreAllocas)
10444 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10445 // that is variable.
10446 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10448 bool HasAnyPHIs = false;
10449 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10450 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10451 Value *FirstOp = FirstInst->getOperand(i);
10452 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10453 FirstOp->getName()+".pn");
10454 InsertNewInstBefore(NewPN, PN);
10456 NewPN->reserveOperandSpace(e);
10457 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10458 OperandPhis[i] = NewPN;
10459 FixedOperands[i] = NewPN;
10464 // Add all operands to the new PHIs.
10466 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10467 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10468 BasicBlock *InBB = PN.getIncomingBlock(i);
10470 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10471 if (PHINode *OpPhi = OperandPhis[op])
10472 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10476 Value *Base = FixedOperands[0];
10477 GetElementPtrInst *GEP =
10478 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10479 FixedOperands.end());
10480 if (cast<GEPOperator>(FirstInst)->isInBounds())
10481 cast<GEPOperator>(GEP)->setIsInBounds(true);
10486 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10487 /// sink the load out of the block that defines it. This means that it must be
10488 /// obvious the value of the load is not changed from the point of the load to
10489 /// the end of the block it is in.
10491 /// Finally, it is safe, but not profitable, to sink a load targetting a
10492 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10494 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10495 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10497 for (++BBI; BBI != E; ++BBI)
10498 if (BBI->mayWriteToMemory())
10501 // Check for non-address taken alloca. If not address-taken already, it isn't
10502 // profitable to do this xform.
10503 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10504 bool isAddressTaken = false;
10505 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10507 if (isa<LoadInst>(UI)) continue;
10508 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10509 // If storing TO the alloca, then the address isn't taken.
10510 if (SI->getOperand(1) == AI) continue;
10512 isAddressTaken = true;
10516 if (!isAddressTaken && AI->isStaticAlloca())
10520 // If this load is a load from a GEP with a constant offset from an alloca,
10521 // then we don't want to sink it. In its present form, it will be
10522 // load [constant stack offset]. Sinking it will cause us to have to
10523 // materialize the stack addresses in each predecessor in a register only to
10524 // do a shared load from register in the successor.
10525 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10526 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10527 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10534 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10535 // operator and they all are only used by the PHI, PHI together their
10536 // inputs, and do the operation once, to the result of the PHI.
10537 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10538 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10540 // Scan the instruction, looking for input operations that can be folded away.
10541 // If all input operands to the phi are the same instruction (e.g. a cast from
10542 // the same type or "+42") we can pull the operation through the PHI, reducing
10543 // code size and simplifying code.
10544 Constant *ConstantOp = 0;
10545 const Type *CastSrcTy = 0;
10546 bool isVolatile = false;
10547 if (isa<CastInst>(FirstInst)) {
10548 CastSrcTy = FirstInst->getOperand(0)->getType();
10549 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10550 // Can fold binop, compare or shift here if the RHS is a constant,
10551 // otherwise call FoldPHIArgBinOpIntoPHI.
10552 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10553 if (ConstantOp == 0)
10554 return FoldPHIArgBinOpIntoPHI(PN);
10555 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10556 isVolatile = LI->isVolatile();
10557 // We can't sink the load if the loaded value could be modified between the
10558 // load and the PHI.
10559 if (LI->getParent() != PN.getIncomingBlock(0) ||
10560 !isSafeAndProfitableToSinkLoad(LI))
10563 // If the PHI is of volatile loads and the load block has multiple
10564 // successors, sinking it would remove a load of the volatile value from
10565 // the path through the other successor.
10567 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10570 } else if (isa<GetElementPtrInst>(FirstInst)) {
10571 return FoldPHIArgGEPIntoPHI(PN);
10573 return 0; // Cannot fold this operation.
10576 // Check to see if all arguments are the same operation.
10577 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10578 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10579 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10580 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10583 if (I->getOperand(0)->getType() != CastSrcTy)
10584 return 0; // Cast operation must match.
10585 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10586 // We can't sink the load if the loaded value could be modified between
10587 // the load and the PHI.
10588 if (LI->isVolatile() != isVolatile ||
10589 LI->getParent() != PN.getIncomingBlock(i) ||
10590 !isSafeAndProfitableToSinkLoad(LI))
10593 // If the PHI is of volatile loads and the load block has multiple
10594 // successors, sinking it would remove a load of the volatile value from
10595 // the path through the other successor.
10597 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10600 } else if (I->getOperand(1) != ConstantOp) {
10605 // Okay, they are all the same operation. Create a new PHI node of the
10606 // correct type, and PHI together all of the LHS's of the instructions.
10607 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10608 PN.getName()+".in");
10609 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10611 Value *InVal = FirstInst->getOperand(0);
10612 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10614 // Add all operands to the new PHI.
10615 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10616 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10617 if (NewInVal != InVal)
10619 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10624 // The new PHI unions all of the same values together. This is really
10625 // common, so we handle it intelligently here for compile-time speed.
10629 InsertNewInstBefore(NewPN, PN);
10633 // Insert and return the new operation.
10634 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10635 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10636 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10637 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10638 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10639 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10640 PhiVal, ConstantOp);
10641 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10643 // If this was a volatile load that we are merging, make sure to loop through
10644 // and mark all the input loads as non-volatile. If we don't do this, we will
10645 // insert a new volatile load and the old ones will not be deletable.
10647 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10648 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10650 return new LoadInst(PhiVal, "", isVolatile);
10653 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10655 static bool DeadPHICycle(PHINode *PN,
10656 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10657 if (PN->use_empty()) return true;
10658 if (!PN->hasOneUse()) return false;
10660 // Remember this node, and if we find the cycle, return.
10661 if (!PotentiallyDeadPHIs.insert(PN))
10664 // Don't scan crazily complex things.
10665 if (PotentiallyDeadPHIs.size() == 16)
10668 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10669 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10674 /// PHIsEqualValue - Return true if this phi node is always equal to
10675 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10676 /// z = some value; x = phi (y, z); y = phi (x, z)
10677 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10678 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10679 // See if we already saw this PHI node.
10680 if (!ValueEqualPHIs.insert(PN))
10683 // Don't scan crazily complex things.
10684 if (ValueEqualPHIs.size() == 16)
10687 // Scan the operands to see if they are either phi nodes or are equal to
10689 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10690 Value *Op = PN->getIncomingValue(i);
10691 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10692 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10694 } else if (Op != NonPhiInVal)
10702 // PHINode simplification
10704 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10705 // If LCSSA is around, don't mess with Phi nodes
10706 if (MustPreserveLCSSA) return 0;
10708 if (Value *V = PN.hasConstantValue())
10709 return ReplaceInstUsesWith(PN, V);
10711 // If all PHI operands are the same operation, pull them through the PHI,
10712 // reducing code size.
10713 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10714 isa<Instruction>(PN.getIncomingValue(1)) &&
10715 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10716 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10717 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10718 // than themselves more than once.
10719 PN.getIncomingValue(0)->hasOneUse())
10720 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10723 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10724 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10725 // PHI)... break the cycle.
10726 if (PN.hasOneUse()) {
10727 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10728 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10729 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10730 PotentiallyDeadPHIs.insert(&PN);
10731 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10732 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10735 // If this phi has a single use, and if that use just computes a value for
10736 // the next iteration of a loop, delete the phi. This occurs with unused
10737 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10738 // common case here is good because the only other things that catch this
10739 // are induction variable analysis (sometimes) and ADCE, which is only run
10741 if (PHIUser->hasOneUse() &&
10742 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10743 PHIUser->use_back() == &PN) {
10744 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10748 // We sometimes end up with phi cycles that non-obviously end up being the
10749 // same value, for example:
10750 // z = some value; x = phi (y, z); y = phi (x, z)
10751 // where the phi nodes don't necessarily need to be in the same block. Do a
10752 // quick check to see if the PHI node only contains a single non-phi value, if
10753 // so, scan to see if the phi cycle is actually equal to that value.
10755 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10756 // Scan for the first non-phi operand.
10757 while (InValNo != NumOperandVals &&
10758 isa<PHINode>(PN.getIncomingValue(InValNo)))
10761 if (InValNo != NumOperandVals) {
10762 Value *NonPhiInVal = PN.getOperand(InValNo);
10764 // Scan the rest of the operands to see if there are any conflicts, if so
10765 // there is no need to recursively scan other phis.
10766 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10767 Value *OpVal = PN.getIncomingValue(InValNo);
10768 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10772 // If we scanned over all operands, then we have one unique value plus
10773 // phi values. Scan PHI nodes to see if they all merge in each other or
10775 if (InValNo == NumOperandVals) {
10776 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10777 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10778 return ReplaceInstUsesWith(PN, NonPhiInVal);
10785 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10786 Value *PtrOp = GEP.getOperand(0);
10787 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10788 if (GEP.getNumOperands() == 1)
10789 return ReplaceInstUsesWith(GEP, PtrOp);
10791 if (isa<UndefValue>(GEP.getOperand(0)))
10792 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10794 bool HasZeroPointerIndex = false;
10795 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10796 HasZeroPointerIndex = C->isNullValue();
10798 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10799 return ReplaceInstUsesWith(GEP, PtrOp);
10801 // Eliminate unneeded casts for indices.
10803 bool MadeChange = false;
10804 unsigned PtrSize = TD->getPointerSizeInBits();
10806 gep_type_iterator GTI = gep_type_begin(GEP);
10807 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10808 I != E; ++I, ++GTI) {
10809 if (!isa<SequentialType>(*GTI)) continue;
10811 // If we are using a wider index than needed for this platform, shrink it
10812 // to what we need. If narrower, sign-extend it to what we need. This
10813 // explicit cast can make subsequent optimizations more obvious.
10814 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10815 if (OpBits == PtrSize)
10818 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10821 if (MadeChange) return &GEP;
10824 // Combine Indices - If the source pointer to this getelementptr instruction
10825 // is a getelementptr instruction, combine the indices of the two
10826 // getelementptr instructions into a single instruction.
10828 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10829 // Note that if our source is a gep chain itself that we wait for that
10830 // chain to be resolved before we perform this transformation. This
10831 // avoids us creating a TON of code in some cases.
10833 if (GetElementPtrInst *SrcGEP =
10834 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10835 if (SrcGEP->getNumOperands() == 2)
10836 return 0; // Wait until our source is folded to completion.
10838 SmallVector<Value*, 8> Indices;
10840 // Find out whether the last index in the source GEP is a sequential idx.
10841 bool EndsWithSequential = false;
10842 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10844 EndsWithSequential = !isa<StructType>(*I);
10846 // Can we combine the two pointer arithmetics offsets?
10847 if (EndsWithSequential) {
10848 // Replace: gep (gep %P, long B), long A, ...
10849 // With: T = long A+B; gep %P, T, ...
10852 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10853 Value *GO1 = GEP.getOperand(1);
10854 if (SO1 == Constant::getNullValue(SO1->getType())) {
10856 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10859 // If they aren't the same type, then the input hasn't been processed
10860 // by the loop above yet (which canonicalizes sequential index types to
10861 // intptr_t). Just avoid transforming this until the input has been
10863 if (SO1->getType() != GO1->getType())
10865 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10868 // Update the GEP in place if possible.
10869 if (Src->getNumOperands() == 2) {
10870 GEP.setOperand(0, Src->getOperand(0));
10871 GEP.setOperand(1, Sum);
10874 Indices.append(Src->op_begin()+1, Src->op_end()-1);
10875 Indices.push_back(Sum);
10876 Indices.append(GEP.op_begin()+2, GEP.op_end());
10877 } else if (isa<Constant>(*GEP.idx_begin()) &&
10878 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10879 Src->getNumOperands() != 1) {
10880 // Otherwise we can do the fold if the first index of the GEP is a zero
10881 Indices.append(Src->op_begin()+1, Src->op_end());
10882 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
10885 if (!Indices.empty()) {
10886 GetElementPtrInst *NewGEP =
10887 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
10888 Indices.end(), GEP.getName());
10889 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
10890 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10895 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10896 if (Value *X = getBitCastOperand(PtrOp)) {
10897 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10899 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10900 // want to change the gep until the bitcasts are eliminated.
10901 if (getBitCastOperand(X)) {
10902 Worklist.AddValue(PtrOp);
10906 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10907 // into : GEP [10 x i8]* X, i32 0, ...
10909 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10910 // into : GEP i8* X, ...
10912 // This occurs when the program declares an array extern like "int X[];"
10913 if (HasZeroPointerIndex) {
10914 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10915 const PointerType *XTy = cast<PointerType>(X->getType());
10916 if (const ArrayType *CATy =
10917 dyn_cast<ArrayType>(CPTy->getElementType())) {
10918 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10919 if (CATy->getElementType() == XTy->getElementType()) {
10920 // -> GEP i8* X, ...
10921 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10922 GetElementPtrInst *NewGEP =
10923 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10925 if (cast<GEPOperator>(&GEP)->isInBounds())
10926 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10930 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
10931 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
10932 if (CATy->getElementType() == XATy->getElementType()) {
10933 // -> GEP [10 x i8]* X, i32 0, ...
10934 // At this point, we know that the cast source type is a pointer
10935 // to an array of the same type as the destination pointer
10936 // array. Because the array type is never stepped over (there
10937 // is a leading zero) we can fold the cast into this GEP.
10938 GEP.setOperand(0, X);
10943 } else if (GEP.getNumOperands() == 2) {
10944 // Transform things like:
10945 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10946 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10947 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10948 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10949 if (TD && isa<ArrayType>(SrcElTy) &&
10950 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10951 TD->getTypeAllocSize(ResElTy)) {
10953 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
10954 Idx[1] = GEP.getOperand(1);
10956 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
10957 if (cast<GEPOperator>(&GEP)->isInBounds())
10958 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10959 // V and GEP are both pointer types --> BitCast
10960 return new BitCastInst(NewGEP, GEP.getType());
10963 // Transform things like:
10964 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10965 // (where tmp = 8*tmp2) into:
10966 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10968 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
10969 uint64_t ArrayEltSize =
10970 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
10972 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10973 // allow either a mul, shift, or constant here.
10975 ConstantInt *Scale = 0;
10976 if (ArrayEltSize == 1) {
10977 NewIdx = GEP.getOperand(1);
10978 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
10979 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10980 NewIdx = ConstantInt::get(CI->getType(), 1);
10982 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10983 if (Inst->getOpcode() == Instruction::Shl &&
10984 isa<ConstantInt>(Inst->getOperand(1))) {
10985 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10986 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10987 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
10989 NewIdx = Inst->getOperand(0);
10990 } else if (Inst->getOpcode() == Instruction::Mul &&
10991 isa<ConstantInt>(Inst->getOperand(1))) {
10992 Scale = cast<ConstantInt>(Inst->getOperand(1));
10993 NewIdx = Inst->getOperand(0);
10997 // If the index will be to exactly the right offset with the scale taken
10998 // out, perform the transformation. Note, we don't know whether Scale is
10999 // signed or not. We'll use unsigned version of division/modulo
11000 // operation after making sure Scale doesn't have the sign bit set.
11001 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11002 Scale->getZExtValue() % ArrayEltSize == 0) {
11003 Scale = ConstantInt::get(Scale->getType(),
11004 Scale->getZExtValue() / ArrayEltSize);
11005 if (Scale->getZExtValue() != 1) {
11006 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11008 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11011 // Insert the new GEP instruction.
11013 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11015 Value *NewGEP = Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11016 if (cast<GEPOperator>(&GEP)->isInBounds())
11017 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11018 // The NewGEP must be pointer typed, so must the old one -> BitCast
11019 return new BitCastInst(NewGEP, GEP.getType());
11025 /// See if we can simplify:
11026 /// X = bitcast A* to B*
11027 /// Y = gep X, <...constant indices...>
11028 /// into a gep of the original struct. This is important for SROA and alias
11029 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11030 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11032 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11033 // Determine how much the GEP moves the pointer. We are guaranteed to get
11034 // a constant back from EmitGEPOffset.
11035 ConstantInt *OffsetV =
11036 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11037 int64_t Offset = OffsetV->getSExtValue();
11039 // If this GEP instruction doesn't move the pointer, just replace the GEP
11040 // with a bitcast of the real input to the dest type.
11042 // If the bitcast is of an allocation, and the allocation will be
11043 // converted to match the type of the cast, don't touch this.
11044 if (isa<AllocationInst>(BCI->getOperand(0))) {
11045 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11046 if (Instruction *I = visitBitCast(*BCI)) {
11049 BCI->getParent()->getInstList().insert(BCI, I);
11050 ReplaceInstUsesWith(*BCI, I);
11055 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11058 // Otherwise, if the offset is non-zero, we need to find out if there is a
11059 // field at Offset in 'A's type. If so, we can pull the cast through the
11061 SmallVector<Value*, 8> NewIndices;
11063 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11064 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11065 Value *NGEP = Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11067 if (cast<GEPOperator>(&GEP)->isInBounds())
11068 cast<GEPOperator>(NGEP)->setIsInBounds(true);
11070 if (NGEP->getType() == GEP.getType())
11071 return ReplaceInstUsesWith(GEP, NGEP);
11072 NGEP->takeName(&GEP);
11073 return new BitCastInst(NGEP, GEP.getType());
11081 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11082 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11083 if (AI.isArrayAllocation()) { // Check C != 1
11084 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11085 const Type *NewTy =
11086 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11087 AllocationInst *New = 0;
11089 // Create and insert the replacement instruction...
11090 if (isa<MallocInst>(AI))
11091 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
11093 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11094 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11096 New->setAlignment(AI.getAlignment());
11098 // Scan to the end of the allocation instructions, to skip over a block of
11099 // allocas if possible...also skip interleaved debug info
11101 BasicBlock::iterator It = New;
11102 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11104 // Now that I is pointing to the first non-allocation-inst in the block,
11105 // insert our getelementptr instruction...
11107 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11111 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11112 New->getName()+".sub", It);
11113 cast<GEPOperator>(V)->setIsInBounds(true);
11115 // Now make everything use the getelementptr instead of the original
11117 return ReplaceInstUsesWith(AI, V);
11118 } else if (isa<UndefValue>(AI.getArraySize())) {
11119 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11123 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11124 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11125 // Note that we only do this for alloca's, because malloc should allocate
11126 // and return a unique pointer, even for a zero byte allocation.
11127 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11128 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11130 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11131 if (AI.getAlignment() == 0)
11132 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11138 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11139 Value *Op = FI.getOperand(0);
11141 // free undef -> unreachable.
11142 if (isa<UndefValue>(Op)) {
11143 // Insert a new store to null because we cannot modify the CFG here.
11144 new StoreInst(ConstantInt::getTrue(*Context),
11145 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11146 return EraseInstFromFunction(FI);
11149 // If we have 'free null' delete the instruction. This can happen in stl code
11150 // when lots of inlining happens.
11151 if (isa<ConstantPointerNull>(Op))
11152 return EraseInstFromFunction(FI);
11154 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11155 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11156 FI.setOperand(0, CI->getOperand(0));
11160 // Change free (gep X, 0,0,0,0) into free(X)
11161 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11162 if (GEPI->hasAllZeroIndices()) {
11163 Worklist.Add(GEPI);
11164 FI.setOperand(0, GEPI->getOperand(0));
11169 // Change free(malloc) into nothing, if the malloc has a single use.
11170 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11171 if (MI->hasOneUse()) {
11172 EraseInstFromFunction(FI);
11173 return EraseInstFromFunction(*MI);
11180 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11181 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11182 const TargetData *TD) {
11183 User *CI = cast<User>(LI.getOperand(0));
11184 Value *CastOp = CI->getOperand(0);
11185 LLVMContext *Context = IC.getContext();
11188 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11189 // Instead of loading constant c string, use corresponding integer value
11190 // directly if string length is small enough.
11192 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11193 unsigned len = Str.length();
11194 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11195 unsigned numBits = Ty->getPrimitiveSizeInBits();
11196 // Replace LI with immediate integer store.
11197 if ((numBits >> 3) == len + 1) {
11198 APInt StrVal(numBits, 0);
11199 APInt SingleChar(numBits, 0);
11200 if (TD->isLittleEndian()) {
11201 for (signed i = len-1; i >= 0; i--) {
11202 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11203 StrVal = (StrVal << 8) | SingleChar;
11206 for (unsigned i = 0; i < len; i++) {
11207 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11208 StrVal = (StrVal << 8) | SingleChar;
11210 // Append NULL at the end.
11212 StrVal = (StrVal << 8) | SingleChar;
11214 Value *NL = ConstantInt::get(*Context, StrVal);
11215 return IC.ReplaceInstUsesWith(LI, NL);
11221 const PointerType *DestTy = cast<PointerType>(CI->getType());
11222 const Type *DestPTy = DestTy->getElementType();
11223 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11225 // If the address spaces don't match, don't eliminate the cast.
11226 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11229 const Type *SrcPTy = SrcTy->getElementType();
11231 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11232 isa<VectorType>(DestPTy)) {
11233 // If the source is an array, the code below will not succeed. Check to
11234 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11236 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11237 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11238 if (ASrcTy->getNumElements() != 0) {
11240 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11241 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11242 SrcTy = cast<PointerType>(CastOp->getType());
11243 SrcPTy = SrcTy->getElementType();
11246 if (IC.getTargetData() &&
11247 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11248 isa<VectorType>(SrcPTy)) &&
11249 // Do not allow turning this into a load of an integer, which is then
11250 // casted to a pointer, this pessimizes pointer analysis a lot.
11251 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11252 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11253 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11255 // Okay, we are casting from one integer or pointer type to another of
11256 // the same size. Instead of casting the pointer before the load, cast
11257 // the result of the loaded value.
11259 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11260 // Now cast the result of the load.
11261 return new BitCastInst(NewLoad, LI.getType());
11268 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11269 Value *Op = LI.getOperand(0);
11271 // Attempt to improve the alignment.
11273 unsigned KnownAlign =
11274 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11276 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11277 LI.getAlignment()))
11278 LI.setAlignment(KnownAlign);
11281 // load (cast X) --> cast (load X) iff safe.
11282 if (isa<CastInst>(Op))
11283 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11286 // None of the following transforms are legal for volatile loads.
11287 if (LI.isVolatile()) return 0;
11289 // Do really simple store-to-load forwarding and load CSE, to catch cases
11290 // where there are several consequtive memory accesses to the same location,
11291 // separated by a few arithmetic operations.
11292 BasicBlock::iterator BBI = &LI;
11293 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11294 return ReplaceInstUsesWith(LI, AvailableVal);
11296 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11297 const Value *GEPI0 = GEPI->getOperand(0);
11298 // TODO: Consider a target hook for valid address spaces for this xform.
11299 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11300 // Insert a new store to null instruction before the load to indicate
11301 // that this code is not reachable. We do this instead of inserting
11302 // an unreachable instruction directly because we cannot modify the
11304 new StoreInst(UndefValue::get(LI.getType()),
11305 Constant::getNullValue(Op->getType()), &LI);
11306 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11310 if (Constant *C = dyn_cast<Constant>(Op)) {
11311 // load null/undef -> undef
11312 // TODO: Consider a target hook for valid address spaces for this xform.
11313 if (isa<UndefValue>(C) ||
11314 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11315 // Insert a new store to null instruction before the load to indicate that
11316 // this code is not reachable. We do this instead of inserting an
11317 // unreachable instruction directly because we cannot modify the CFG.
11318 new StoreInst(UndefValue::get(LI.getType()),
11319 Constant::getNullValue(Op->getType()), &LI);
11320 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11323 // Instcombine load (constant global) into the value loaded.
11324 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11325 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11326 return ReplaceInstUsesWith(LI, GV->getInitializer());
11328 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11329 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11330 if (CE->getOpcode() == Instruction::GetElementPtr) {
11331 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11332 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11334 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11336 return ReplaceInstUsesWith(LI, V);
11337 if (CE->getOperand(0)->isNullValue()) {
11338 // Insert a new store to null instruction before the load to indicate
11339 // that this code is not reachable. We do this instead of inserting
11340 // an unreachable instruction directly because we cannot modify the
11342 new StoreInst(UndefValue::get(LI.getType()),
11343 Constant::getNullValue(Op->getType()), &LI);
11344 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11347 } else if (CE->isCast()) {
11348 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11354 // If this load comes from anywhere in a constant global, and if the global
11355 // is all undef or zero, we know what it loads.
11356 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11357 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11358 if (GV->getInitializer()->isNullValue())
11359 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11360 else if (isa<UndefValue>(GV->getInitializer()))
11361 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11365 if (Op->hasOneUse()) {
11366 // Change select and PHI nodes to select values instead of addresses: this
11367 // helps alias analysis out a lot, allows many others simplifications, and
11368 // exposes redundancy in the code.
11370 // Note that we cannot do the transformation unless we know that the
11371 // introduced loads cannot trap! Something like this is valid as long as
11372 // the condition is always false: load (select bool %C, int* null, int* %G),
11373 // but it would not be valid if we transformed it to load from null
11374 // unconditionally.
11376 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11377 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11378 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11379 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11380 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11381 SI->getOperand(1)->getName()+".val");
11382 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11383 SI->getOperand(2)->getName()+".val");
11384 return SelectInst::Create(SI->getCondition(), V1, V2);
11387 // load (select (cond, null, P)) -> load P
11388 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11389 if (C->isNullValue()) {
11390 LI.setOperand(0, SI->getOperand(2));
11394 // load (select (cond, P, null)) -> load P
11395 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11396 if (C->isNullValue()) {
11397 LI.setOperand(0, SI->getOperand(1));
11405 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11406 /// when possible. This makes it generally easy to do alias analysis and/or
11407 /// SROA/mem2reg of the memory object.
11408 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11409 User *CI = cast<User>(SI.getOperand(1));
11410 Value *CastOp = CI->getOperand(0);
11412 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11413 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11414 if (SrcTy == 0) return 0;
11416 const Type *SrcPTy = SrcTy->getElementType();
11418 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11421 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11422 /// to its first element. This allows us to handle things like:
11423 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11424 /// on 32-bit hosts.
11425 SmallVector<Value*, 4> NewGEPIndices;
11427 // If the source is an array, the code below will not succeed. Check to
11428 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11430 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11431 // Index through pointer.
11432 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11433 NewGEPIndices.push_back(Zero);
11436 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11437 if (!STy->getNumElements()) /* Struct can be empty {} */
11439 NewGEPIndices.push_back(Zero);
11440 SrcPTy = STy->getElementType(0);
11441 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11442 NewGEPIndices.push_back(Zero);
11443 SrcPTy = ATy->getElementType();
11449 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11452 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11455 // If the pointers point into different address spaces or if they point to
11456 // values with different sizes, we can't do the transformation.
11457 if (!IC.getTargetData() ||
11458 SrcTy->getAddressSpace() !=
11459 cast<PointerType>(CI->getType())->getAddressSpace() ||
11460 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11461 IC.getTargetData()->getTypeSizeInBits(DestPTy))
11464 // Okay, we are casting from one integer or pointer type to another of
11465 // the same size. Instead of casting the pointer before
11466 // the store, cast the value to be stored.
11468 Value *SIOp0 = SI.getOperand(0);
11469 Instruction::CastOps opcode = Instruction::BitCast;
11470 const Type* CastSrcTy = SIOp0->getType();
11471 const Type* CastDstTy = SrcPTy;
11472 if (isa<PointerType>(CastDstTy)) {
11473 if (CastSrcTy->isInteger())
11474 opcode = Instruction::IntToPtr;
11475 } else if (isa<IntegerType>(CastDstTy)) {
11476 if (isa<PointerType>(SIOp0->getType()))
11477 opcode = Instruction::PtrToInt;
11480 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11481 // emit a GEP to index into its first field.
11482 if (!NewGEPIndices.empty()) {
11483 CastOp = IC.Builder->CreateGEP(CastOp, NewGEPIndices.begin(),
11484 NewGEPIndices.end());
11485 cast<GEPOperator>(CastOp)->setIsInBounds(true);
11488 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11489 SIOp0->getName()+".c");
11490 return new StoreInst(NewCast, CastOp);
11493 /// equivalentAddressValues - Test if A and B will obviously have the same
11494 /// value. This includes recognizing that %t0 and %t1 will have the same
11495 /// value in code like this:
11496 /// %t0 = getelementptr \@a, 0, 3
11497 /// store i32 0, i32* %t0
11498 /// %t1 = getelementptr \@a, 0, 3
11499 /// %t2 = load i32* %t1
11501 static bool equivalentAddressValues(Value *A, Value *B) {
11502 // Test if the values are trivially equivalent.
11503 if (A == B) return true;
11505 // Test if the values come form identical arithmetic instructions.
11506 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11507 // its only used to compare two uses within the same basic block, which
11508 // means that they'll always either have the same value or one of them
11509 // will have an undefined value.
11510 if (isa<BinaryOperator>(A) ||
11511 isa<CastInst>(A) ||
11513 isa<GetElementPtrInst>(A))
11514 if (Instruction *BI = dyn_cast<Instruction>(B))
11515 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11518 // Otherwise they may not be equivalent.
11522 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11523 // return the llvm.dbg.declare.
11524 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11525 if (!V->hasNUses(2))
11527 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11529 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11531 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11532 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11539 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11540 Value *Val = SI.getOperand(0);
11541 Value *Ptr = SI.getOperand(1);
11543 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11544 EraseInstFromFunction(SI);
11549 // If the RHS is an alloca with a single use, zapify the store, making the
11551 // If the RHS is an alloca with a two uses, the other one being a
11552 // llvm.dbg.declare, zapify the store and the declare, making the
11553 // alloca dead. We must do this to prevent declare's from affecting
11555 if (!SI.isVolatile()) {
11556 if (Ptr->hasOneUse()) {
11557 if (isa<AllocaInst>(Ptr)) {
11558 EraseInstFromFunction(SI);
11562 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11563 if (isa<AllocaInst>(GEP->getOperand(0))) {
11564 if (GEP->getOperand(0)->hasOneUse()) {
11565 EraseInstFromFunction(SI);
11569 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11570 EraseInstFromFunction(*DI);
11571 EraseInstFromFunction(SI);
11578 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11579 EraseInstFromFunction(*DI);
11580 EraseInstFromFunction(SI);
11586 // Attempt to improve the alignment.
11588 unsigned KnownAlign =
11589 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11591 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11592 SI.getAlignment()))
11593 SI.setAlignment(KnownAlign);
11596 // Do really simple DSE, to catch cases where there are several consecutive
11597 // stores to the same location, separated by a few arithmetic operations. This
11598 // situation often occurs with bitfield accesses.
11599 BasicBlock::iterator BBI = &SI;
11600 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11603 // Don't count debug info directives, lest they affect codegen,
11604 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11605 // It is necessary for correctness to skip those that feed into a
11606 // llvm.dbg.declare, as these are not present when debugging is off.
11607 if (isa<DbgInfoIntrinsic>(BBI) ||
11608 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11613 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11614 // Prev store isn't volatile, and stores to the same location?
11615 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11616 SI.getOperand(1))) {
11619 EraseInstFromFunction(*PrevSI);
11625 // If this is a load, we have to stop. However, if the loaded value is from
11626 // the pointer we're loading and is producing the pointer we're storing,
11627 // then *this* store is dead (X = load P; store X -> P).
11628 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11629 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11630 !SI.isVolatile()) {
11631 EraseInstFromFunction(SI);
11635 // Otherwise, this is a load from some other location. Stores before it
11636 // may not be dead.
11640 // Don't skip over loads or things that can modify memory.
11641 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11646 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11648 // store X, null -> turns into 'unreachable' in SimplifyCFG
11649 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11650 if (!isa<UndefValue>(Val)) {
11651 SI.setOperand(0, UndefValue::get(Val->getType()));
11652 if (Instruction *U = dyn_cast<Instruction>(Val))
11653 Worklist.Add(U); // Dropped a use.
11656 return 0; // Do not modify these!
11659 // store undef, Ptr -> noop
11660 if (isa<UndefValue>(Val)) {
11661 EraseInstFromFunction(SI);
11666 // If the pointer destination is a cast, see if we can fold the cast into the
11668 if (isa<CastInst>(Ptr))
11669 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11671 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11673 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11677 // If this store is the last instruction in the basic block (possibly
11678 // excepting debug info instructions and the pointer bitcasts that feed
11679 // into them), and if the block ends with an unconditional branch, try
11680 // to move it to the successor block.
11684 } while (isa<DbgInfoIntrinsic>(BBI) ||
11685 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11686 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11687 if (BI->isUnconditional())
11688 if (SimplifyStoreAtEndOfBlock(SI))
11689 return 0; // xform done!
11694 /// SimplifyStoreAtEndOfBlock - Turn things like:
11695 /// if () { *P = v1; } else { *P = v2 }
11696 /// into a phi node with a store in the successor.
11698 /// Simplify things like:
11699 /// *P = v1; if () { *P = v2; }
11700 /// into a phi node with a store in the successor.
11702 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11703 BasicBlock *StoreBB = SI.getParent();
11705 // Check to see if the successor block has exactly two incoming edges. If
11706 // so, see if the other predecessor contains a store to the same location.
11707 // if so, insert a PHI node (if needed) and move the stores down.
11708 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11710 // Determine whether Dest has exactly two predecessors and, if so, compute
11711 // the other predecessor.
11712 pred_iterator PI = pred_begin(DestBB);
11713 BasicBlock *OtherBB = 0;
11714 if (*PI != StoreBB)
11717 if (PI == pred_end(DestBB))
11720 if (*PI != StoreBB) {
11725 if (++PI != pred_end(DestBB))
11728 // Bail out if all the relevant blocks aren't distinct (this can happen,
11729 // for example, if SI is in an infinite loop)
11730 if (StoreBB == DestBB || OtherBB == DestBB)
11733 // Verify that the other block ends in a branch and is not otherwise empty.
11734 BasicBlock::iterator BBI = OtherBB->getTerminator();
11735 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11736 if (!OtherBr || BBI == OtherBB->begin())
11739 // If the other block ends in an unconditional branch, check for the 'if then
11740 // else' case. there is an instruction before the branch.
11741 StoreInst *OtherStore = 0;
11742 if (OtherBr->isUnconditional()) {
11744 // Skip over debugging info.
11745 while (isa<DbgInfoIntrinsic>(BBI) ||
11746 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11747 if (BBI==OtherBB->begin())
11751 // If this isn't a store, or isn't a store to the same location, bail out.
11752 OtherStore = dyn_cast<StoreInst>(BBI);
11753 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11756 // Otherwise, the other block ended with a conditional branch. If one of the
11757 // destinations is StoreBB, then we have the if/then case.
11758 if (OtherBr->getSuccessor(0) != StoreBB &&
11759 OtherBr->getSuccessor(1) != StoreBB)
11762 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11763 // if/then triangle. See if there is a store to the same ptr as SI that
11764 // lives in OtherBB.
11766 // Check to see if we find the matching store.
11767 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11768 if (OtherStore->getOperand(1) != SI.getOperand(1))
11772 // If we find something that may be using or overwriting the stored
11773 // value, or if we run out of instructions, we can't do the xform.
11774 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11775 BBI == OtherBB->begin())
11779 // In order to eliminate the store in OtherBr, we have to
11780 // make sure nothing reads or overwrites the stored value in
11782 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11783 // FIXME: This should really be AA driven.
11784 if (I->mayReadFromMemory() || I->mayWriteToMemory())
11789 // Insert a PHI node now if we need it.
11790 Value *MergedVal = OtherStore->getOperand(0);
11791 if (MergedVal != SI.getOperand(0)) {
11792 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11793 PN->reserveOperandSpace(2);
11794 PN->addIncoming(SI.getOperand(0), SI.getParent());
11795 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11796 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11799 // Advance to a place where it is safe to insert the new store and
11801 BBI = DestBB->getFirstNonPHI();
11802 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11803 OtherStore->isVolatile()), *BBI);
11805 // Nuke the old stores.
11806 EraseInstFromFunction(SI);
11807 EraseInstFromFunction(*OtherStore);
11813 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11814 // Change br (not X), label True, label False to: br X, label False, True
11816 BasicBlock *TrueDest;
11817 BasicBlock *FalseDest;
11818 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11819 !isa<Constant>(X)) {
11820 // Swap Destinations and condition...
11821 BI.setCondition(X);
11822 BI.setSuccessor(0, FalseDest);
11823 BI.setSuccessor(1, TrueDest);
11827 // Cannonicalize fcmp_one -> fcmp_oeq
11828 FCmpInst::Predicate FPred; Value *Y;
11829 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11830 TrueDest, FalseDest)) &&
11831 BI.getCondition()->hasOneUse())
11832 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11833 FPred == FCmpInst::FCMP_OGE) {
11834 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11835 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11837 // Swap Destinations and condition.
11838 BI.setSuccessor(0, FalseDest);
11839 BI.setSuccessor(1, TrueDest);
11840 Worklist.Add(Cond);
11844 // Cannonicalize icmp_ne -> icmp_eq
11845 ICmpInst::Predicate IPred;
11846 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11847 TrueDest, FalseDest)) &&
11848 BI.getCondition()->hasOneUse())
11849 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11850 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11851 IPred == ICmpInst::ICMP_SGE) {
11852 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11853 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11854 // Swap Destinations and condition.
11855 BI.setSuccessor(0, FalseDest);
11856 BI.setSuccessor(1, TrueDest);
11857 Worklist.Add(Cond);
11864 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11865 Value *Cond = SI.getCondition();
11866 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11867 if (I->getOpcode() == Instruction::Add)
11868 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11869 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11870 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11872 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11874 SI.setOperand(0, I->getOperand(0));
11882 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11883 Value *Agg = EV.getAggregateOperand();
11885 if (!EV.hasIndices())
11886 return ReplaceInstUsesWith(EV, Agg);
11888 if (Constant *C = dyn_cast<Constant>(Agg)) {
11889 if (isa<UndefValue>(C))
11890 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11892 if (isa<ConstantAggregateZero>(C))
11893 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11895 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11896 // Extract the element indexed by the first index out of the constant
11897 Value *V = C->getOperand(*EV.idx_begin());
11898 if (EV.getNumIndices() > 1)
11899 // Extract the remaining indices out of the constant indexed by the
11901 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11903 return ReplaceInstUsesWith(EV, V);
11905 return 0; // Can't handle other constants
11907 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11908 // We're extracting from an insertvalue instruction, compare the indices
11909 const unsigned *exti, *exte, *insi, *inse;
11910 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11911 exte = EV.idx_end(), inse = IV->idx_end();
11912 exti != exte && insi != inse;
11914 if (*insi != *exti)
11915 // The insert and extract both reference distinctly different elements.
11916 // This means the extract is not influenced by the insert, and we can
11917 // replace the aggregate operand of the extract with the aggregate
11918 // operand of the insert. i.e., replace
11919 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11920 // %E = extractvalue { i32, { i32 } } %I, 0
11922 // %E = extractvalue { i32, { i32 } } %A, 0
11923 return ExtractValueInst::Create(IV->getAggregateOperand(),
11924 EV.idx_begin(), EV.idx_end());
11926 if (exti == exte && insi == inse)
11927 // Both iterators are at the end: Index lists are identical. Replace
11928 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11929 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11931 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11932 if (exti == exte) {
11933 // The extract list is a prefix of the insert list. i.e. replace
11934 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11935 // %E = extractvalue { i32, { i32 } } %I, 1
11937 // %X = extractvalue { i32, { i32 } } %A, 1
11938 // %E = insertvalue { i32 } %X, i32 42, 0
11939 // by switching the order of the insert and extract (though the
11940 // insertvalue should be left in, since it may have other uses).
11941 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11942 EV.idx_begin(), EV.idx_end());
11943 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11947 // The insert list is a prefix of the extract list
11948 // We can simply remove the common indices from the extract and make it
11949 // operate on the inserted value instead of the insertvalue result.
11951 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11952 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11954 // %E extractvalue { i32 } { i32 42 }, 0
11955 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11958 // Can't simplify extracts from other values. Note that nested extracts are
11959 // already simplified implicitely by the above (extract ( extract (insert) )
11960 // will be translated into extract ( insert ( extract ) ) first and then just
11961 // the value inserted, if appropriate).
11965 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11966 /// is to leave as a vector operation.
11967 static bool CheapToScalarize(Value *V, bool isConstant) {
11968 if (isa<ConstantAggregateZero>(V))
11970 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11971 if (isConstant) return true;
11972 // If all elts are the same, we can extract.
11973 Constant *Op0 = C->getOperand(0);
11974 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11975 if (C->getOperand(i) != Op0)
11979 Instruction *I = dyn_cast<Instruction>(V);
11980 if (!I) return false;
11982 // Insert element gets simplified to the inserted element or is deleted if
11983 // this is constant idx extract element and its a constant idx insertelt.
11984 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11985 isa<ConstantInt>(I->getOperand(2)))
11987 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11989 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11990 if (BO->hasOneUse() &&
11991 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11992 CheapToScalarize(BO->getOperand(1), isConstant)))
11994 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11995 if (CI->hasOneUse() &&
11996 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11997 CheapToScalarize(CI->getOperand(1), isConstant)))
12003 /// Read and decode a shufflevector mask.
12005 /// It turns undef elements into values that are larger than the number of
12006 /// elements in the input.
12007 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12008 unsigned NElts = SVI->getType()->getNumElements();
12009 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12010 return std::vector<unsigned>(NElts, 0);
12011 if (isa<UndefValue>(SVI->getOperand(2)))
12012 return std::vector<unsigned>(NElts, 2*NElts);
12014 std::vector<unsigned> Result;
12015 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12016 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12017 if (isa<UndefValue>(*i))
12018 Result.push_back(NElts*2); // undef -> 8
12020 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12024 /// FindScalarElement - Given a vector and an element number, see if the scalar
12025 /// value is already around as a register, for example if it were inserted then
12026 /// extracted from the vector.
12027 static Value *FindScalarElement(Value *V, unsigned EltNo,
12028 LLVMContext *Context) {
12029 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12030 const VectorType *PTy = cast<VectorType>(V->getType());
12031 unsigned Width = PTy->getNumElements();
12032 if (EltNo >= Width) // Out of range access.
12033 return UndefValue::get(PTy->getElementType());
12035 if (isa<UndefValue>(V))
12036 return UndefValue::get(PTy->getElementType());
12037 else if (isa<ConstantAggregateZero>(V))
12038 return Constant::getNullValue(PTy->getElementType());
12039 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12040 return CP->getOperand(EltNo);
12041 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12042 // If this is an insert to a variable element, we don't know what it is.
12043 if (!isa<ConstantInt>(III->getOperand(2)))
12045 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12047 // If this is an insert to the element we are looking for, return the
12049 if (EltNo == IIElt)
12050 return III->getOperand(1);
12052 // Otherwise, the insertelement doesn't modify the value, recurse on its
12054 return FindScalarElement(III->getOperand(0), EltNo, Context);
12055 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12056 unsigned LHSWidth =
12057 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12058 unsigned InEl = getShuffleMask(SVI)[EltNo];
12059 if (InEl < LHSWidth)
12060 return FindScalarElement(SVI->getOperand(0), InEl, Context);
12061 else if (InEl < LHSWidth*2)
12062 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12064 return UndefValue::get(PTy->getElementType());
12067 // Otherwise, we don't know.
12071 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12072 // If vector val is undef, replace extract with scalar undef.
12073 if (isa<UndefValue>(EI.getOperand(0)))
12074 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12076 // If vector val is constant 0, replace extract with scalar 0.
12077 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12078 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12080 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12081 // If vector val is constant with all elements the same, replace EI with
12082 // that element. When the elements are not identical, we cannot replace yet
12083 // (we do that below, but only when the index is constant).
12084 Constant *op0 = C->getOperand(0);
12085 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12086 if (C->getOperand(i) != op0) {
12091 return ReplaceInstUsesWith(EI, op0);
12094 // If extracting a specified index from the vector, see if we can recursively
12095 // find a previously computed scalar that was inserted into the vector.
12096 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12097 unsigned IndexVal = IdxC->getZExtValue();
12098 unsigned VectorWidth =
12099 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12101 // If this is extracting an invalid index, turn this into undef, to avoid
12102 // crashing the code below.
12103 if (IndexVal >= VectorWidth)
12104 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12106 // This instruction only demands the single element from the input vector.
12107 // If the input vector has a single use, simplify it based on this use
12109 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12110 APInt UndefElts(VectorWidth, 0);
12111 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12112 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12113 DemandedMask, UndefElts)) {
12114 EI.setOperand(0, V);
12119 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12120 return ReplaceInstUsesWith(EI, Elt);
12122 // If the this extractelement is directly using a bitcast from a vector of
12123 // the same number of elements, see if we can find the source element from
12124 // it. In this case, we will end up needing to bitcast the scalars.
12125 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12126 if (const VectorType *VT =
12127 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12128 if (VT->getNumElements() == VectorWidth)
12129 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12130 IndexVal, Context))
12131 return new BitCastInst(Elt, EI.getType());
12135 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12136 if (I->hasOneUse()) {
12137 // Push extractelement into predecessor operation if legal and
12138 // profitable to do so
12139 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12140 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12141 if (CheapToScalarize(BO, isConstantElt)) {
12143 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12144 EI.getName()+".lhs");
12146 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12147 EI.getName()+".rhs");
12148 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12150 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
12151 unsigned AS = LI->getPointerAddressSpace();
12152 Value *Ptr = Builder->CreateBitCast(I->getOperand(0),
12153 PointerType::get(EI.getType(), AS),
12154 I->getOperand(0)->getName());
12156 Builder->CreateGEP(Ptr, EI.getOperand(1), I->getName()+".gep");
12157 cast<GEPOperator>(GEP)->setIsInBounds(true);
12159 LoadInst *Load = Builder->CreateLoad(GEP, "tmp");
12161 // Make sure the Load goes before the load instruction in the source,
12162 // not wherever the extract happens to be.
12163 if (Instruction *P = dyn_cast<Instruction>(Ptr))
12165 if (Instruction *G = dyn_cast<Instruction>(GEP))
12167 Load->moveBefore(I);
12169 return ReplaceInstUsesWith(EI, Load);
12172 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12173 // Extracting the inserted element?
12174 if (IE->getOperand(2) == EI.getOperand(1))
12175 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12176 // If the inserted and extracted elements are constants, they must not
12177 // be the same value, extract from the pre-inserted value instead.
12178 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12179 Worklist.AddValue(EI.getOperand(0));
12180 EI.setOperand(0, IE->getOperand(0));
12183 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12184 // If this is extracting an element from a shufflevector, figure out where
12185 // it came from and extract from the appropriate input element instead.
12186 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12187 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12189 unsigned LHSWidth =
12190 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12192 if (SrcIdx < LHSWidth)
12193 Src = SVI->getOperand(0);
12194 else if (SrcIdx < LHSWidth*2) {
12195 SrcIdx -= LHSWidth;
12196 Src = SVI->getOperand(1);
12198 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12200 return ExtractElementInst::Create(Src,
12201 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12205 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12210 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12211 /// elements from either LHS or RHS, return the shuffle mask and true.
12212 /// Otherwise, return false.
12213 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12214 std::vector<Constant*> &Mask,
12215 LLVMContext *Context) {
12216 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12217 "Invalid CollectSingleShuffleElements");
12218 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12220 if (isa<UndefValue>(V)) {
12221 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12223 } else if (V == LHS) {
12224 for (unsigned i = 0; i != NumElts; ++i)
12225 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12227 } else if (V == RHS) {
12228 for (unsigned i = 0; i != NumElts; ++i)
12229 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12231 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12232 // If this is an insert of an extract from some other vector, include it.
12233 Value *VecOp = IEI->getOperand(0);
12234 Value *ScalarOp = IEI->getOperand(1);
12235 Value *IdxOp = IEI->getOperand(2);
12237 if (!isa<ConstantInt>(IdxOp))
12239 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12241 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12242 // Okay, we can handle this if the vector we are insertinting into is
12243 // transitively ok.
12244 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12245 // If so, update the mask to reflect the inserted undef.
12246 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12249 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12250 if (isa<ConstantInt>(EI->getOperand(1)) &&
12251 EI->getOperand(0)->getType() == V->getType()) {
12252 unsigned ExtractedIdx =
12253 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12255 // This must be extracting from either LHS or RHS.
12256 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12257 // Okay, we can handle this if the vector we are insertinting into is
12258 // transitively ok.
12259 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12260 // If so, update the mask to reflect the inserted value.
12261 if (EI->getOperand(0) == LHS) {
12262 Mask[InsertedIdx % NumElts] =
12263 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12265 assert(EI->getOperand(0) == RHS);
12266 Mask[InsertedIdx % NumElts] =
12267 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12276 // TODO: Handle shufflevector here!
12281 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12282 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12283 /// that computes V and the LHS value of the shuffle.
12284 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12285 Value *&RHS, LLVMContext *Context) {
12286 assert(isa<VectorType>(V->getType()) &&
12287 (RHS == 0 || V->getType() == RHS->getType()) &&
12288 "Invalid shuffle!");
12289 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12291 if (isa<UndefValue>(V)) {
12292 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12294 } else if (isa<ConstantAggregateZero>(V)) {
12295 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12297 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12298 // If this is an insert of an extract from some other vector, include it.
12299 Value *VecOp = IEI->getOperand(0);
12300 Value *ScalarOp = IEI->getOperand(1);
12301 Value *IdxOp = IEI->getOperand(2);
12303 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12304 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12305 EI->getOperand(0)->getType() == V->getType()) {
12306 unsigned ExtractedIdx =
12307 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12308 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12310 // Either the extracted from or inserted into vector must be RHSVec,
12311 // otherwise we'd end up with a shuffle of three inputs.
12312 if (EI->getOperand(0) == RHS || RHS == 0) {
12313 RHS = EI->getOperand(0);
12314 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12315 Mask[InsertedIdx % NumElts] =
12316 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12320 if (VecOp == RHS) {
12321 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12323 // Everything but the extracted element is replaced with the RHS.
12324 for (unsigned i = 0; i != NumElts; ++i) {
12325 if (i != InsertedIdx)
12326 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12331 // If this insertelement is a chain that comes from exactly these two
12332 // vectors, return the vector and the effective shuffle.
12333 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12335 return EI->getOperand(0);
12340 // TODO: Handle shufflevector here!
12342 // Otherwise, can't do anything fancy. Return an identity vector.
12343 for (unsigned i = 0; i != NumElts; ++i)
12344 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12348 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12349 Value *VecOp = IE.getOperand(0);
12350 Value *ScalarOp = IE.getOperand(1);
12351 Value *IdxOp = IE.getOperand(2);
12353 // Inserting an undef or into an undefined place, remove this.
12354 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12355 ReplaceInstUsesWith(IE, VecOp);
12357 // If the inserted element was extracted from some other vector, and if the
12358 // indexes are constant, try to turn this into a shufflevector operation.
12359 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12360 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12361 EI->getOperand(0)->getType() == IE.getType()) {
12362 unsigned NumVectorElts = IE.getType()->getNumElements();
12363 unsigned ExtractedIdx =
12364 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12365 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12367 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12368 return ReplaceInstUsesWith(IE, VecOp);
12370 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12371 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12373 // If we are extracting a value from a vector, then inserting it right
12374 // back into the same place, just use the input vector.
12375 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12376 return ReplaceInstUsesWith(IE, VecOp);
12378 // We could theoretically do this for ANY input. However, doing so could
12379 // turn chains of insertelement instructions into a chain of shufflevector
12380 // instructions, and right now we do not merge shufflevectors. As such,
12381 // only do this in a situation where it is clear that there is benefit.
12382 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12383 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12384 // the values of VecOp, except then one read from EIOp0.
12385 // Build a new shuffle mask.
12386 std::vector<Constant*> Mask;
12387 if (isa<UndefValue>(VecOp))
12388 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12390 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12391 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12394 Mask[InsertedIdx] =
12395 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12396 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12397 ConstantVector::get(Mask));
12400 // If this insertelement isn't used by some other insertelement, turn it
12401 // (and any insertelements it points to), into one big shuffle.
12402 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12403 std::vector<Constant*> Mask;
12405 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12406 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12407 // We now have a shuffle of LHS, RHS, Mask.
12408 return new ShuffleVectorInst(LHS, RHS,
12409 ConstantVector::get(Mask));
12414 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12415 APInt UndefElts(VWidth, 0);
12416 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12417 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12424 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12425 Value *LHS = SVI.getOperand(0);
12426 Value *RHS = SVI.getOperand(1);
12427 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12429 bool MadeChange = false;
12431 // Undefined shuffle mask -> undefined value.
12432 if (isa<UndefValue>(SVI.getOperand(2)))
12433 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12435 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12437 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12440 APInt UndefElts(VWidth, 0);
12441 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12442 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12443 LHS = SVI.getOperand(0);
12444 RHS = SVI.getOperand(1);
12448 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12449 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12450 if (LHS == RHS || isa<UndefValue>(LHS)) {
12451 if (isa<UndefValue>(LHS) && LHS == RHS) {
12452 // shuffle(undef,undef,mask) -> undef.
12453 return ReplaceInstUsesWith(SVI, LHS);
12456 // Remap any references to RHS to use LHS.
12457 std::vector<Constant*> Elts;
12458 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12459 if (Mask[i] >= 2*e)
12460 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12462 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12463 (Mask[i] < e && isa<UndefValue>(LHS))) {
12464 Mask[i] = 2*e; // Turn into undef.
12465 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12467 Mask[i] = Mask[i] % e; // Force to LHS.
12468 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12472 SVI.setOperand(0, SVI.getOperand(1));
12473 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12474 SVI.setOperand(2, ConstantVector::get(Elts));
12475 LHS = SVI.getOperand(0);
12476 RHS = SVI.getOperand(1);
12480 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12481 bool isLHSID = true, isRHSID = true;
12483 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12484 if (Mask[i] >= e*2) continue; // Ignore undef values.
12485 // Is this an identity shuffle of the LHS value?
12486 isLHSID &= (Mask[i] == i);
12488 // Is this an identity shuffle of the RHS value?
12489 isRHSID &= (Mask[i]-e == i);
12492 // Eliminate identity shuffles.
12493 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12494 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12496 // If the LHS is a shufflevector itself, see if we can combine it with this
12497 // one without producing an unusual shuffle. Here we are really conservative:
12498 // we are absolutely afraid of producing a shuffle mask not in the input
12499 // program, because the code gen may not be smart enough to turn a merged
12500 // shuffle into two specific shuffles: it may produce worse code. As such,
12501 // we only merge two shuffles if the result is one of the two input shuffle
12502 // masks. In this case, merging the shuffles just removes one instruction,
12503 // which we know is safe. This is good for things like turning:
12504 // (splat(splat)) -> splat.
12505 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12506 if (isa<UndefValue>(RHS)) {
12507 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12509 std::vector<unsigned> NewMask;
12510 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12511 if (Mask[i] >= 2*e)
12512 NewMask.push_back(2*e);
12514 NewMask.push_back(LHSMask[Mask[i]]);
12516 // If the result mask is equal to the src shuffle or this shuffle mask, do
12517 // the replacement.
12518 if (NewMask == LHSMask || NewMask == Mask) {
12519 unsigned LHSInNElts =
12520 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12521 std::vector<Constant*> Elts;
12522 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12523 if (NewMask[i] >= LHSInNElts*2) {
12524 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12526 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12529 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12530 LHSSVI->getOperand(1),
12531 ConstantVector::get(Elts));
12536 return MadeChange ? &SVI : 0;
12542 /// TryToSinkInstruction - Try to move the specified instruction from its
12543 /// current block into the beginning of DestBlock, which can only happen if it's
12544 /// safe to move the instruction past all of the instructions between it and the
12545 /// end of its block.
12546 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12547 assert(I->hasOneUse() && "Invariants didn't hold!");
12549 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12550 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12553 // Do not sink alloca instructions out of the entry block.
12554 if (isa<AllocaInst>(I) && I->getParent() ==
12555 &DestBlock->getParent()->getEntryBlock())
12558 // We can only sink load instructions if there is nothing between the load and
12559 // the end of block that could change the value.
12560 if (I->mayReadFromMemory()) {
12561 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12563 if (Scan->mayWriteToMemory())
12567 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12569 CopyPrecedingStopPoint(I, InsertPos);
12570 I->moveBefore(InsertPos);
12576 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12577 /// all reachable code to the worklist.
12579 /// This has a couple of tricks to make the code faster and more powerful. In
12580 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12581 /// them to the worklist (this significantly speeds up instcombine on code where
12582 /// many instructions are dead or constant). Additionally, if we find a branch
12583 /// whose condition is a known constant, we only visit the reachable successors.
12585 static void AddReachableCodeToWorklist(BasicBlock *BB,
12586 SmallPtrSet<BasicBlock*, 64> &Visited,
12588 const TargetData *TD) {
12589 SmallVector<BasicBlock*, 256> Worklist;
12590 Worklist.push_back(BB);
12592 while (!Worklist.empty()) {
12593 BB = Worklist.back();
12594 Worklist.pop_back();
12596 // We have now visited this block! If we've already been here, ignore it.
12597 if (!Visited.insert(BB)) continue;
12599 DbgInfoIntrinsic *DBI_Prev = NULL;
12600 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12601 Instruction *Inst = BBI++;
12603 // DCE instruction if trivially dead.
12604 if (isInstructionTriviallyDead(Inst)) {
12606 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12607 Inst->eraseFromParent();
12611 // ConstantProp instruction if trivially constant.
12612 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12613 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12615 Inst->replaceAllUsesWith(C);
12617 Inst->eraseFromParent();
12621 // If there are two consecutive llvm.dbg.stoppoint calls then
12622 // it is likely that the optimizer deleted code in between these
12624 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12627 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12628 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12629 IC.Worklist.Remove(DBI_Prev);
12630 DBI_Prev->eraseFromParent();
12632 DBI_Prev = DBI_Next;
12637 IC.Worklist.Add(Inst);
12640 // Recursively visit successors. If this is a branch or switch on a
12641 // constant, only visit the reachable successor.
12642 TerminatorInst *TI = BB->getTerminator();
12643 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12644 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12645 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12646 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12647 Worklist.push_back(ReachableBB);
12650 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12651 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12652 // See if this is an explicit destination.
12653 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12654 if (SI->getCaseValue(i) == Cond) {
12655 BasicBlock *ReachableBB = SI->getSuccessor(i);
12656 Worklist.push_back(ReachableBB);
12660 // Otherwise it is the default destination.
12661 Worklist.push_back(SI->getSuccessor(0));
12666 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12667 Worklist.push_back(TI->getSuccessor(i));
12671 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12672 bool Changed = false;
12673 TD = getAnalysisIfAvailable<TargetData>();
12675 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12676 << F.getNameStr() << "\n");
12679 // Do a depth-first traversal of the function, populate the worklist with
12680 // the reachable instructions. Ignore blocks that are not reachable. Keep
12681 // track of which blocks we visit.
12682 SmallPtrSet<BasicBlock*, 64> Visited;
12683 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12685 // Do a quick scan over the function. If we find any blocks that are
12686 // unreachable, remove any instructions inside of them. This prevents
12687 // the instcombine code from having to deal with some bad special cases.
12688 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12689 if (!Visited.count(BB)) {
12690 Instruction *Term = BB->getTerminator();
12691 while (Term != BB->begin()) { // Remove instrs bottom-up
12692 BasicBlock::iterator I = Term; --I;
12694 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12695 // A debug intrinsic shouldn't force another iteration if we weren't
12696 // going to do one without it.
12697 if (!isa<DbgInfoIntrinsic>(I)) {
12701 if (!I->use_empty())
12702 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12703 I->eraseFromParent();
12708 while (!Worklist.isEmpty()) {
12709 Instruction *I = Worklist.RemoveOne();
12710 if (I == 0) continue; // skip null values.
12712 // Check to see if we can DCE the instruction.
12713 if (isInstructionTriviallyDead(I)) {
12714 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12715 EraseInstFromFunction(*I);
12721 // Instruction isn't dead, see if we can constant propagate it.
12722 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12723 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12725 // Add operands to the worklist.
12726 ReplaceInstUsesWith(*I, C);
12728 EraseInstFromFunction(*I);
12734 // See if we can constant fold its operands.
12735 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12736 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12737 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12738 F.getContext(), TD))
12745 // See if we can trivially sink this instruction to a successor basic block.
12746 if (I->hasOneUse()) {
12747 BasicBlock *BB = I->getParent();
12748 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12749 if (UserParent != BB) {
12750 bool UserIsSuccessor = false;
12751 // See if the user is one of our successors.
12752 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12753 if (*SI == UserParent) {
12754 UserIsSuccessor = true;
12758 // If the user is one of our immediate successors, and if that successor
12759 // only has us as a predecessors (we'd have to split the critical edge
12760 // otherwise), we can keep going.
12761 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12762 next(pred_begin(UserParent)) == pred_end(UserParent))
12763 // Okay, the CFG is simple enough, try to sink this instruction.
12764 Changed |= TryToSinkInstruction(I, UserParent);
12768 // Now that we have an instruction, try combining it to simplify it.
12769 Builder->SetInsertPoint(I->getParent(), I);
12774 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12776 if (Instruction *Result = visit(*I)) {
12778 // Should we replace the old instruction with a new one?
12780 DEBUG(errs() << "IC: Old = " << *I << '\n'
12781 << " New = " << *Result << '\n');
12783 // Everything uses the new instruction now.
12784 I->replaceAllUsesWith(Result);
12786 // Push the new instruction and any users onto the worklist.
12787 Worklist.Add(Result);
12788 Worklist.AddUsersToWorkList(*Result);
12790 // Move the name to the new instruction first.
12791 Result->takeName(I);
12793 // Insert the new instruction into the basic block...
12794 BasicBlock *InstParent = I->getParent();
12795 BasicBlock::iterator InsertPos = I;
12797 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12798 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12801 InstParent->getInstList().insert(InsertPos, Result);
12803 EraseInstFromFunction(*I);
12806 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12807 << " New = " << *I << '\n');
12810 // If the instruction was modified, it's possible that it is now dead.
12811 // if so, remove it.
12812 if (isInstructionTriviallyDead(I)) {
12813 EraseInstFromFunction(*I);
12816 Worklist.AddUsersToWorkList(*I);
12828 bool InstCombiner::runOnFunction(Function &F) {
12829 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12830 Context = &F.getContext();
12833 /// Builder - This is an IRBuilder that automatically inserts new
12834 /// instructions into the worklist when they are created.
12835 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12836 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12837 InstCombineIRInserter(Worklist));
12838 Builder = &TheBuilder;
12840 bool EverMadeChange = false;
12842 // Iterate while there is work to do.
12843 unsigned Iteration = 0;
12844 while (DoOneIteration(F, Iteration++))
12845 EverMadeChange = true;
12848 return EverMadeChange;
12851 FunctionPass *llvm::createInstructionCombiningPass() {
12852 return new InstCombiner();