1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG. This pass is where
12 // algebraic simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
64 using namespace llvm::PatternMatch;
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
73 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
76 // Worklist of all of the instructions that need to be simplified.
77 SmallVector<Instruction*, 256> Worklist;
78 DenseMap<Instruction*, unsigned> WorklistMap;
80 bool MustPreserveLCSSA;
82 static char ID; // Pass identification, replacement for typeid
83 InstCombiner() : FunctionPass(&ID) {}
85 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
88 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
89 Worklist.push_back(I);
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
100 WorklistMap.erase(It);
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
106 WorklistMap.erase(I);
111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
115 void AddUsersToWorkList(Value &I) {
116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
118 AddToWorkList(cast<Instruction>(*UI));
121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
124 void AddUsesToWorkList(Instruction &I) {
125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
134 /// Return the specified operand before it is turned into an undef.
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
142 // Set the operand to undef to drop the use.
143 *i = UndefValue::get(Op->getType());
150 virtual bool runOnFunction(Function &F);
152 bool DoOneIteration(Function &F, unsigned ItNum);
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155 AU.addRequired<TargetData>();
156 AU.addPreservedID(LCSSAID);
157 AU.setPreservesCFG();
160 TargetData &getTargetData() const { return *TD; }
162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
165 // null - No change was made
166 // I - Change was made, I is still valid, I may be dead though
167 // otherwise - Change was made, replace I with returned instruction
169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitFAdd(BinaryOperator &I);
171 Instruction *visitSub(BinaryOperator &I);
172 Instruction *visitFSub(BinaryOperator &I);
173 Instruction *visitMul(BinaryOperator &I);
174 Instruction *visitFMul(BinaryOperator &I);
175 Instruction *visitURem(BinaryOperator &I);
176 Instruction *visitSRem(BinaryOperator &I);
177 Instruction *visitFRem(BinaryOperator &I);
178 bool SimplifyDivRemOfSelect(BinaryOperator &I);
179 Instruction *commonRemTransforms(BinaryOperator &I);
180 Instruction *commonIRemTransforms(BinaryOperator &I);
181 Instruction *commonDivTransforms(BinaryOperator &I);
182 Instruction *commonIDivTransforms(BinaryOperator &I);
183 Instruction *visitUDiv(BinaryOperator &I);
184 Instruction *visitSDiv(BinaryOperator &I);
185 Instruction *visitFDiv(BinaryOperator &I);
186 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
187 Instruction *visitAnd(BinaryOperator &I);
188 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
189 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
190 Value *A, Value *B, Value *C);
191 Instruction *visitOr (BinaryOperator &I);
192 Instruction *visitXor(BinaryOperator &I);
193 Instruction *visitShl(BinaryOperator &I);
194 Instruction *visitAShr(BinaryOperator &I);
195 Instruction *visitLShr(BinaryOperator &I);
196 Instruction *commonShiftTransforms(BinaryOperator &I);
197 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
199 Instruction *visitFCmpInst(FCmpInst &I);
200 Instruction *visitICmpInst(ICmpInst &I);
201 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
202 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
205 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
206 ConstantInt *DivRHS);
208 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
209 ICmpInst::Predicate Cond, Instruction &I);
210 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
212 Instruction *commonCastTransforms(CastInst &CI);
213 Instruction *commonIntCastTransforms(CastInst &CI);
214 Instruction *commonPointerCastTransforms(CastInst &CI);
215 Instruction *visitTrunc(TruncInst &CI);
216 Instruction *visitZExt(ZExtInst &CI);
217 Instruction *visitSExt(SExtInst &CI);
218 Instruction *visitFPTrunc(FPTruncInst &CI);
219 Instruction *visitFPExt(CastInst &CI);
220 Instruction *visitFPToUI(FPToUIInst &FI);
221 Instruction *visitFPToSI(FPToSIInst &FI);
222 Instruction *visitUIToFP(CastInst &CI);
223 Instruction *visitSIToFP(CastInst &CI);
224 Instruction *visitPtrToInt(PtrToIntInst &CI);
225 Instruction *visitIntToPtr(IntToPtrInst &CI);
226 Instruction *visitBitCast(BitCastInst &CI);
227 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
229 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
230 Instruction *visitSelectInst(SelectInst &SI);
231 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
232 Instruction *visitCallInst(CallInst &CI);
233 Instruction *visitInvokeInst(InvokeInst &II);
234 Instruction *visitPHINode(PHINode &PN);
235 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
236 Instruction *visitAllocationInst(AllocationInst &AI);
237 Instruction *visitFreeInst(FreeInst &FI);
238 Instruction *visitLoadInst(LoadInst &LI);
239 Instruction *visitStoreInst(StoreInst &SI);
240 Instruction *visitBranchInst(BranchInst &BI);
241 Instruction *visitSwitchInst(SwitchInst &SI);
242 Instruction *visitInsertElementInst(InsertElementInst &IE);
243 Instruction *visitExtractElementInst(ExtractElementInst &EI);
244 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
245 Instruction *visitExtractValueInst(ExtractValueInst &EV);
247 // visitInstruction - Specify what to return for unhandled instructions...
248 Instruction *visitInstruction(Instruction &I) { return 0; }
251 Instruction *visitCallSite(CallSite CS);
252 bool transformConstExprCastCall(CallSite CS);
253 Instruction *transformCallThroughTrampoline(CallSite CS);
254 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
255 bool DoXform = true);
256 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
257 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
261 // InsertNewInstBefore - insert an instruction New before instruction Old
262 // in the program. Add the new instruction to the worklist.
264 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
265 assert(New && New->getParent() == 0 &&
266 "New instruction already inserted into a basic block!");
267 BasicBlock *BB = Old.getParent();
268 BB->getInstList().insert(&Old, New); // Insert inst
273 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
274 /// This also adds the cast to the worklist. Finally, this returns the
276 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
278 if (V->getType() == Ty) return V;
280 if (Constant *CV = dyn_cast<Constant>(V))
281 return ConstantExpr::getCast(opc, CV, Ty);
283 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
288 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
289 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
293 // ReplaceInstUsesWith - This method is to be used when an instruction is
294 // found to be dead, replacable with another preexisting expression. Here
295 // we add all uses of I to the worklist, replace all uses of I with the new
296 // value, then return I, so that the inst combiner will know that I was
299 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
300 AddUsersToWorkList(I); // Add all modified instrs to worklist
302 I.replaceAllUsesWith(V);
305 // If we are replacing the instruction with itself, this must be in a
306 // segment of unreachable code, so just clobber the instruction.
307 I.replaceAllUsesWith(UndefValue::get(I.getType()));
312 // EraseInstFromFunction - When dealing with an instruction that has side
313 // effects or produces a void value, we can't rely on DCE to delete the
314 // instruction. Instead, visit methods should return the value returned by
316 Instruction *EraseInstFromFunction(Instruction &I) {
317 assert(I.use_empty() && "Cannot erase instruction that is used!");
318 AddUsesToWorkList(I);
319 RemoveFromWorkList(&I);
321 return 0; // Don't do anything with FI
324 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
325 APInt &KnownOne, unsigned Depth = 0) const {
326 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
329 bool MaskedValueIsZero(Value *V, const APInt &Mask,
330 unsigned Depth = 0) const {
331 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
333 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
334 return llvm::ComputeNumSignBits(Op, TD, Depth);
339 /// SimplifyCommutative - This performs a few simplifications for
340 /// commutative operators.
341 bool SimplifyCommutative(BinaryOperator &I);
343 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
344 /// most-complex to least-complex order.
345 bool SimplifyCompare(CmpInst &I);
347 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
348 /// based on the demanded bits.
349 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
350 APInt& KnownZero, APInt& KnownOne,
352 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
353 APInt& KnownZero, APInt& KnownOne,
356 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
357 /// SimplifyDemandedBits knows about. See if the instruction has any
358 /// properties that allow us to simplify its operands.
359 bool SimplifyDemandedInstructionBits(Instruction &Inst);
361 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
362 APInt& UndefElts, unsigned Depth = 0);
364 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
365 // PHI node as operand #0, see if we can fold the instruction into the PHI
366 // (which is only possible if all operands to the PHI are constants).
367 Instruction *FoldOpIntoPhi(Instruction &I);
369 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
370 // operator and they all are only used by the PHI, PHI together their
371 // inputs, and do the operation once, to the result of the PHI.
372 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
373 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
374 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
377 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
378 ConstantInt *AndRHS, BinaryOperator &TheAnd);
380 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
381 bool isSub, Instruction &I);
382 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
383 bool isSigned, bool Inside, Instruction &IB);
384 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
385 Instruction *MatchBSwap(BinaryOperator &I);
386 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
387 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
388 Instruction *SimplifyMemSet(MemSetInst *MI);
391 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
393 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
394 unsigned CastOpc, int &NumCastsRemoved);
395 unsigned GetOrEnforceKnownAlignment(Value *V,
396 unsigned PrefAlign = 0);
401 char InstCombiner::ID = 0;
402 static RegisterPass<InstCombiner>
403 X("instcombine", "Combine redundant instructions");
405 // getComplexity: Assign a complexity or rank value to LLVM Values...
406 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
407 static unsigned getComplexity(Value *V) {
408 if (isa<Instruction>(V)) {
409 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
410 BinaryOperator::isNot(V))
414 if (isa<Argument>(V)) return 3;
415 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
418 // isOnlyUse - Return true if this instruction will be deleted if we stop using
420 static bool isOnlyUse(Value *V) {
421 return V->hasOneUse() || isa<Constant>(V);
424 // getPromotedType - Return the specified type promoted as it would be to pass
425 // though a va_arg area...
426 static const Type *getPromotedType(const Type *Ty) {
427 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
428 if (ITy->getBitWidth() < 32)
429 return Type::Int32Ty;
434 /// getBitCastOperand - If the specified operand is a CastInst, a constant
435 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
436 /// operand value, otherwise return null.
437 static Value *getBitCastOperand(Value *V) {
438 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
440 return I->getOperand(0);
441 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
442 // GetElementPtrInst?
443 if (GEP->hasAllZeroIndices())
444 return GEP->getOperand(0);
445 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
446 if (CE->getOpcode() == Instruction::BitCast)
447 // BitCast ConstantExp?
448 return CE->getOperand(0);
449 else if (CE->getOpcode() == Instruction::GetElementPtr) {
450 // GetElementPtr ConstantExp?
451 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
453 ConstantInt *CI = dyn_cast<ConstantInt>(I);
454 if (!CI || !CI->isZero())
455 // Any non-zero indices? Not cast-like.
458 // All-zero indices? This is just like casting.
459 return CE->getOperand(0);
465 /// This function is a wrapper around CastInst::isEliminableCastPair. It
466 /// simply extracts arguments and returns what that function returns.
467 static Instruction::CastOps
468 isEliminableCastPair(
469 const CastInst *CI, ///< The first cast instruction
470 unsigned opcode, ///< The opcode of the second cast instruction
471 const Type *DstTy, ///< The target type for the second cast instruction
472 TargetData *TD ///< The target data for pointer size
475 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
476 const Type *MidTy = CI->getType(); // B from above
478 // Get the opcodes of the two Cast instructions
479 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
480 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
482 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
483 DstTy, TD->getIntPtrType());
485 // We don't want to form an inttoptr or ptrtoint that converts to an integer
486 // type that differs from the pointer size.
487 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
488 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
491 return Instruction::CastOps(Res);
494 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
495 /// in any code being generated. It does not require codegen if V is simple
496 /// enough or if the cast can be folded into other casts.
497 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
498 const Type *Ty, TargetData *TD) {
499 if (V->getType() == Ty || isa<Constant>(V)) return false;
501 // If this is another cast that can be eliminated, it isn't codegen either.
502 if (const CastInst *CI = dyn_cast<CastInst>(V))
503 if (isEliminableCastPair(CI, opcode, Ty, TD))
508 // SimplifyCommutative - This performs a few simplifications for commutative
511 // 1. Order operands such that they are listed from right (least complex) to
512 // left (most complex). This puts constants before unary operators before
515 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
516 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
518 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
519 bool Changed = false;
520 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
521 Changed = !I.swapOperands();
523 if (!I.isAssociative()) return Changed;
524 Instruction::BinaryOps Opcode = I.getOpcode();
525 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
526 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
527 if (isa<Constant>(I.getOperand(1))) {
528 Constant *Folded = ConstantExpr::get(I.getOpcode(),
529 cast<Constant>(I.getOperand(1)),
530 cast<Constant>(Op->getOperand(1)));
531 I.setOperand(0, Op->getOperand(0));
532 I.setOperand(1, Folded);
534 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
535 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
536 isOnlyUse(Op) && isOnlyUse(Op1)) {
537 Constant *C1 = cast<Constant>(Op->getOperand(1));
538 Constant *C2 = cast<Constant>(Op1->getOperand(1));
540 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
541 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
542 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
546 I.setOperand(0, New);
547 I.setOperand(1, Folded);
554 /// SimplifyCompare - For a CmpInst this function just orders the operands
555 /// so that theyare listed from right (least complex) to left (most complex).
556 /// This puts constants before unary operators before binary operators.
557 bool InstCombiner::SimplifyCompare(CmpInst &I) {
558 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
561 // Compare instructions are not associative so there's nothing else we can do.
565 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
566 // if the LHS is a constant zero (which is the 'negate' form).
568 static inline Value *dyn_castNegVal(Value *V) {
569 if (BinaryOperator::isNeg(V))
570 return BinaryOperator::getNegArgument(V);
572 // Constants can be considered to be negated values if they can be folded.
573 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
574 return ConstantExpr::getNeg(C);
576 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
577 if (C->getType()->getElementType()->isInteger())
578 return ConstantExpr::getNeg(C);
583 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
584 // instruction if the LHS is a constant negative zero (which is the 'negate'
587 static inline Value *dyn_castFNegVal(Value *V) {
588 if (BinaryOperator::isFNeg(V))
589 return BinaryOperator::getFNegArgument(V);
591 // Constants can be considered to be negated values if they can be folded.
592 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
593 return ConstantExpr::getFNeg(C);
595 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
596 if (C->getType()->getElementType()->isFloatingPoint())
597 return ConstantExpr::getFNeg(C);
602 static inline Value *dyn_castNotVal(Value *V) {
603 if (BinaryOperator::isNot(V))
604 return BinaryOperator::getNotArgument(V);
606 // Constants can be considered to be not'ed values...
607 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
608 return ConstantInt::get(~C->getValue());
612 // dyn_castFoldableMul - If this value is a multiply that can be folded into
613 // other computations (because it has a constant operand), return the
614 // non-constant operand of the multiply, and set CST to point to the multiplier.
615 // Otherwise, return null.
617 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
618 if (V->hasOneUse() && V->getType()->isInteger())
619 if (Instruction *I = dyn_cast<Instruction>(V)) {
620 if (I->getOpcode() == Instruction::Mul)
621 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
622 return I->getOperand(0);
623 if (I->getOpcode() == Instruction::Shl)
624 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
625 // The multiplier is really 1 << CST.
626 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
627 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
628 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
629 return I->getOperand(0);
635 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
636 /// expression, return it.
637 static User *dyn_castGetElementPtr(Value *V) {
638 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
639 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
640 if (CE->getOpcode() == Instruction::GetElementPtr)
641 return cast<User>(V);
645 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
646 /// opcode value. Otherwise return UserOp1.
647 static unsigned getOpcode(const Value *V) {
648 if (const Instruction *I = dyn_cast<Instruction>(V))
649 return I->getOpcode();
650 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
651 return CE->getOpcode();
652 // Use UserOp1 to mean there's no opcode.
653 return Instruction::UserOp1;
656 /// AddOne - Add one to a ConstantInt
657 static Constant *AddOne(Constant *C) {
658 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
660 /// SubOne - Subtract one from a ConstantInt
661 static Constant *SubOne(ConstantInt *C) {
662 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
664 /// MultiplyOverflows - True if the multiply can not be expressed in an int
666 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
667 uint32_t W = C1->getBitWidth();
668 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
677 APInt MulExt = LHSExt * RHSExt;
680 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
681 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
682 return MulExt.slt(Min) || MulExt.sgt(Max);
684 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
688 /// ShrinkDemandedConstant - Check to see if the specified operand of the
689 /// specified instruction is a constant integer. If so, check to see if there
690 /// are any bits set in the constant that are not demanded. If so, shrink the
691 /// constant and return true.
692 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
694 assert(I && "No instruction?");
695 assert(OpNo < I->getNumOperands() && "Operand index too large");
697 // If the operand is not a constant integer, nothing to do.
698 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
699 if (!OpC) return false;
701 // If there are no bits set that aren't demanded, nothing to do.
702 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
703 if ((~Demanded & OpC->getValue()) == 0)
706 // This instruction is producing bits that are not demanded. Shrink the RHS.
707 Demanded &= OpC->getValue();
708 I->setOperand(OpNo, ConstantInt::get(Demanded));
712 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
713 // set of known zero and one bits, compute the maximum and minimum values that
714 // could have the specified known zero and known one bits, returning them in
716 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
717 const APInt& KnownOne,
718 APInt& Min, APInt& Max) {
719 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
720 KnownZero.getBitWidth() == Min.getBitWidth() &&
721 KnownZero.getBitWidth() == Max.getBitWidth() &&
722 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
723 APInt UnknownBits = ~(KnownZero|KnownOne);
725 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
726 // bit if it is unknown.
728 Max = KnownOne|UnknownBits;
730 if (UnknownBits.isNegative()) { // Sign bit is unknown
731 Min.set(Min.getBitWidth()-1);
732 Max.clear(Max.getBitWidth()-1);
736 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
737 // a set of known zero and one bits, compute the maximum and minimum values that
738 // could have the specified known zero and known one bits, returning them in
740 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
741 const APInt &KnownOne,
742 APInt &Min, APInt &Max) {
743 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
744 KnownZero.getBitWidth() == Min.getBitWidth() &&
745 KnownZero.getBitWidth() == Max.getBitWidth() &&
746 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
747 APInt UnknownBits = ~(KnownZero|KnownOne);
749 // The minimum value is when the unknown bits are all zeros.
751 // The maximum value is when the unknown bits are all ones.
752 Max = KnownOne|UnknownBits;
755 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
756 /// SimplifyDemandedBits knows about. See if the instruction has any
757 /// properties that allow us to simplify its operands.
758 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
759 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
760 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
761 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
763 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
764 KnownZero, KnownOne, 0);
765 if (V == 0) return false;
766 if (V == &Inst) return true;
767 ReplaceInstUsesWith(Inst, V);
771 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
772 /// specified instruction operand if possible, updating it in place. It returns
773 /// true if it made any change and false otherwise.
774 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
775 APInt &KnownZero, APInt &KnownOne,
777 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
778 KnownZero, KnownOne, Depth);
779 if (NewVal == 0) return false;
785 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
786 /// value based on the demanded bits. When this function is called, it is known
787 /// that only the bits set in DemandedMask of the result of V are ever used
788 /// downstream. Consequently, depending on the mask and V, it may be possible
789 /// to replace V with a constant or one of its operands. In such cases, this
790 /// function does the replacement and returns true. In all other cases, it
791 /// returns false after analyzing the expression and setting KnownOne and known
792 /// to be one in the expression. KnownZero contains all the bits that are known
793 /// to be zero in the expression. These are provided to potentially allow the
794 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
795 /// the expression. KnownOne and KnownZero always follow the invariant that
796 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
797 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
798 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
799 /// and KnownOne must all be the same.
801 /// This returns null if it did not change anything and it permits no
802 /// simplification. This returns V itself if it did some simplification of V's
803 /// operands based on the information about what bits are demanded. This returns
804 /// some other non-null value if it found out that V is equal to another value
805 /// in the context where the specified bits are demanded, but not for all users.
806 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
807 APInt &KnownZero, APInt &KnownOne,
809 assert(V != 0 && "Null pointer of Value???");
810 assert(Depth <= 6 && "Limit Search Depth");
811 uint32_t BitWidth = DemandedMask.getBitWidth();
812 const Type *VTy = V->getType();
813 assert((TD || !isa<PointerType>(VTy)) &&
814 "SimplifyDemandedBits needs to know bit widths!");
815 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
816 (!VTy->isIntOrIntVector() ||
817 VTy->getScalarSizeInBits() == BitWidth) &&
818 KnownZero.getBitWidth() == BitWidth &&
819 KnownOne.getBitWidth() == BitWidth &&
820 "Value *V, DemandedMask, KnownZero and KnownOne "
821 "must have same BitWidth");
822 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
823 // We know all of the bits for a constant!
824 KnownOne = CI->getValue() & DemandedMask;
825 KnownZero = ~KnownOne & DemandedMask;
828 if (isa<ConstantPointerNull>(V)) {
829 // We know all of the bits for a constant!
831 KnownZero = DemandedMask;
837 if (DemandedMask == 0) { // Not demanding any bits from V.
838 if (isa<UndefValue>(V))
840 return UndefValue::get(VTy);
843 if (Depth == 6) // Limit search depth.
846 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
847 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
849 Instruction *I = dyn_cast<Instruction>(V);
851 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
852 return 0; // Only analyze instructions.
855 // If there are multiple uses of this value and we aren't at the root, then
856 // we can't do any simplifications of the operands, because DemandedMask
857 // only reflects the bits demanded by *one* of the users.
858 if (Depth != 0 && !I->hasOneUse()) {
859 // Despite the fact that we can't simplify this instruction in all User's
860 // context, we can at least compute the knownzero/knownone bits, and we can
861 // do simplifications that apply to *just* the one user if we know that
862 // this instruction has a simpler value in that context.
863 if (I->getOpcode() == Instruction::And) {
864 // If either the LHS or the RHS are Zero, the result is zero.
865 ComputeMaskedBits(I->getOperand(1), DemandedMask,
866 RHSKnownZero, RHSKnownOne, Depth+1);
867 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
868 LHSKnownZero, LHSKnownOne, Depth+1);
870 // If all of the demanded bits are known 1 on one side, return the other.
871 // These bits cannot contribute to the result of the 'and' in this
873 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
874 (DemandedMask & ~LHSKnownZero))
875 return I->getOperand(0);
876 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
877 (DemandedMask & ~RHSKnownZero))
878 return I->getOperand(1);
880 // If all of the demanded bits in the inputs are known zeros, return zero.
881 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
882 return Constant::getNullValue(VTy);
884 } else if (I->getOpcode() == Instruction::Or) {
885 // We can simplify (X|Y) -> X or Y in the user's context if we know that
886 // only bits from X or Y are demanded.
888 // If either the LHS or the RHS are One, the result is One.
889 ComputeMaskedBits(I->getOperand(1), DemandedMask,
890 RHSKnownZero, RHSKnownOne, Depth+1);
891 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
892 LHSKnownZero, LHSKnownOne, Depth+1);
894 // If all of the demanded bits are known zero on one side, return the
895 // other. These bits cannot contribute to the result of the 'or' in this
897 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
898 (DemandedMask & ~LHSKnownOne))
899 return I->getOperand(0);
900 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
901 (DemandedMask & ~RHSKnownOne))
902 return I->getOperand(1);
904 // If all of the potentially set bits on one side are known to be set on
905 // the other side, just use the 'other' side.
906 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
907 (DemandedMask & (~RHSKnownZero)))
908 return I->getOperand(0);
909 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
910 (DemandedMask & (~LHSKnownZero)))
911 return I->getOperand(1);
914 // Compute the KnownZero/KnownOne bits to simplify things downstream.
915 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
919 // If this is the root being simplified, allow it to have multiple uses,
920 // just set the DemandedMask to all bits so that we can try to simplify the
921 // operands. This allows visitTruncInst (for example) to simplify the
922 // operand of a trunc without duplicating all the logic below.
923 if (Depth == 0 && !V->hasOneUse())
924 DemandedMask = APInt::getAllOnesValue(BitWidth);
926 switch (I->getOpcode()) {
928 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
930 case Instruction::And:
931 // If either the LHS or the RHS are Zero, the result is zero.
932 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
933 RHSKnownZero, RHSKnownOne, Depth+1) ||
934 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
935 LHSKnownZero, LHSKnownOne, Depth+1))
937 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
938 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
940 // If all of the demanded bits are known 1 on one side, return the other.
941 // These bits cannot contribute to the result of the 'and'.
942 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
943 (DemandedMask & ~LHSKnownZero))
944 return I->getOperand(0);
945 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
946 (DemandedMask & ~RHSKnownZero))
947 return I->getOperand(1);
949 // If all of the demanded bits in the inputs are known zeros, return zero.
950 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
951 return Constant::getNullValue(VTy);
953 // If the RHS is a constant, see if we can simplify it.
954 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
957 // Output known-1 bits are only known if set in both the LHS & RHS.
958 RHSKnownOne &= LHSKnownOne;
959 // Output known-0 are known to be clear if zero in either the LHS | RHS.
960 RHSKnownZero |= LHSKnownZero;
962 case Instruction::Or:
963 // If either the LHS or the RHS are One, the result is One.
964 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
965 RHSKnownZero, RHSKnownOne, Depth+1) ||
966 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
967 LHSKnownZero, LHSKnownOne, Depth+1))
969 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
970 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
972 // If all of the demanded bits are known zero on one side, return the other.
973 // These bits cannot contribute to the result of the 'or'.
974 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
975 (DemandedMask & ~LHSKnownOne))
976 return I->getOperand(0);
977 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
978 (DemandedMask & ~RHSKnownOne))
979 return I->getOperand(1);
981 // If all of the potentially set bits on one side are known to be set on
982 // the other side, just use the 'other' side.
983 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
984 (DemandedMask & (~RHSKnownZero)))
985 return I->getOperand(0);
986 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
987 (DemandedMask & (~LHSKnownZero)))
988 return I->getOperand(1);
990 // If the RHS is a constant, see if we can simplify it.
991 if (ShrinkDemandedConstant(I, 1, DemandedMask))
994 // Output known-0 bits are only known if clear in both the LHS & RHS.
995 RHSKnownZero &= LHSKnownZero;
996 // Output known-1 are known to be set if set in either the LHS | RHS.
997 RHSKnownOne |= LHSKnownOne;
999 case Instruction::Xor: {
1000 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1001 RHSKnownZero, RHSKnownOne, Depth+1) ||
1002 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1003 LHSKnownZero, LHSKnownOne, Depth+1))
1005 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1006 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1008 // If all of the demanded bits are known zero on one side, return the other.
1009 // These bits cannot contribute to the result of the 'xor'.
1010 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1011 return I->getOperand(0);
1012 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1013 return I->getOperand(1);
1015 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1016 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1017 (RHSKnownOne & LHSKnownOne);
1018 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1019 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1020 (RHSKnownOne & LHSKnownZero);
1022 // If all of the demanded bits are known to be zero on one side or the
1023 // other, turn this into an *inclusive* or.
1024 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1025 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1027 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1029 return InsertNewInstBefore(Or, *I);
1032 // If all of the demanded bits on one side are known, and all of the set
1033 // bits on that side are also known to be set on the other side, turn this
1034 // into an AND, as we know the bits will be cleared.
1035 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1036 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1038 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1039 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1041 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1042 return InsertNewInstBefore(And, *I);
1046 // If the RHS is a constant, see if we can simplify it.
1047 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1048 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1051 RHSKnownZero = KnownZeroOut;
1052 RHSKnownOne = KnownOneOut;
1055 case Instruction::Select:
1056 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1057 RHSKnownZero, RHSKnownOne, Depth+1) ||
1058 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1059 LHSKnownZero, LHSKnownOne, Depth+1))
1061 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1062 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1064 // If the operands are constants, see if we can simplify them.
1065 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1066 ShrinkDemandedConstant(I, 2, DemandedMask))
1069 // Only known if known in both the LHS and RHS.
1070 RHSKnownOne &= LHSKnownOne;
1071 RHSKnownZero &= LHSKnownZero;
1073 case Instruction::Trunc: {
1074 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1075 DemandedMask.zext(truncBf);
1076 RHSKnownZero.zext(truncBf);
1077 RHSKnownOne.zext(truncBf);
1078 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1079 RHSKnownZero, RHSKnownOne, Depth+1))
1081 DemandedMask.trunc(BitWidth);
1082 RHSKnownZero.trunc(BitWidth);
1083 RHSKnownOne.trunc(BitWidth);
1084 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1087 case Instruction::BitCast:
1088 if (!I->getOperand(0)->getType()->isInteger())
1089 return false; // vector->int or fp->int?
1090 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1091 RHSKnownZero, RHSKnownOne, Depth+1))
1093 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1095 case Instruction::ZExt: {
1096 // Compute the bits in the result that are not present in the input.
1097 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1099 DemandedMask.trunc(SrcBitWidth);
1100 RHSKnownZero.trunc(SrcBitWidth);
1101 RHSKnownOne.trunc(SrcBitWidth);
1102 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1103 RHSKnownZero, RHSKnownOne, Depth+1))
1105 DemandedMask.zext(BitWidth);
1106 RHSKnownZero.zext(BitWidth);
1107 RHSKnownOne.zext(BitWidth);
1108 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1109 // The top bits are known to be zero.
1110 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1113 case Instruction::SExt: {
1114 // Compute the bits in the result that are not present in the input.
1115 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1117 APInt InputDemandedBits = DemandedMask &
1118 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1120 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1121 // If any of the sign extended bits are demanded, we know that the sign
1123 if ((NewBits & DemandedMask) != 0)
1124 InputDemandedBits.set(SrcBitWidth-1);
1126 InputDemandedBits.trunc(SrcBitWidth);
1127 RHSKnownZero.trunc(SrcBitWidth);
1128 RHSKnownOne.trunc(SrcBitWidth);
1129 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1130 RHSKnownZero, RHSKnownOne, Depth+1))
1132 InputDemandedBits.zext(BitWidth);
1133 RHSKnownZero.zext(BitWidth);
1134 RHSKnownOne.zext(BitWidth);
1135 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1137 // If the sign bit of the input is known set or clear, then we know the
1138 // top bits of the result.
1140 // If the input sign bit is known zero, or if the NewBits are not demanded
1141 // convert this into a zero extension.
1142 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1143 // Convert to ZExt cast
1144 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1145 return InsertNewInstBefore(NewCast, *I);
1146 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1147 RHSKnownOne |= NewBits;
1151 case Instruction::Add: {
1152 // Figure out what the input bits are. If the top bits of the and result
1153 // are not demanded, then the add doesn't demand them from its input
1155 unsigned NLZ = DemandedMask.countLeadingZeros();
1157 // If there is a constant on the RHS, there are a variety of xformations
1159 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1160 // If null, this should be simplified elsewhere. Some of the xforms here
1161 // won't work if the RHS is zero.
1165 // If the top bit of the output is demanded, demand everything from the
1166 // input. Otherwise, we demand all the input bits except NLZ top bits.
1167 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1169 // Find information about known zero/one bits in the input.
1170 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1171 LHSKnownZero, LHSKnownOne, Depth+1))
1174 // If the RHS of the add has bits set that can't affect the input, reduce
1176 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1179 // Avoid excess work.
1180 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1183 // Turn it into OR if input bits are zero.
1184 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1186 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1188 return InsertNewInstBefore(Or, *I);
1191 // We can say something about the output known-zero and known-one bits,
1192 // depending on potential carries from the input constant and the
1193 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1194 // bits set and the RHS constant is 0x01001, then we know we have a known
1195 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1197 // To compute this, we first compute the potential carry bits. These are
1198 // the bits which may be modified. I'm not aware of a better way to do
1200 const APInt &RHSVal = RHS->getValue();
1201 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1203 // Now that we know which bits have carries, compute the known-1/0 sets.
1205 // Bits are known one if they are known zero in one operand and one in the
1206 // other, and there is no input carry.
1207 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1208 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1210 // Bits are known zero if they are known zero in both operands and there
1211 // is no input carry.
1212 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1214 // If the high-bits of this ADD are not demanded, then it does not demand
1215 // the high bits of its LHS or RHS.
1216 if (DemandedMask[BitWidth-1] == 0) {
1217 // Right fill the mask of bits for this ADD to demand the most
1218 // significant bit and all those below it.
1219 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1220 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1221 LHSKnownZero, LHSKnownOne, Depth+1) ||
1222 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1223 LHSKnownZero, LHSKnownOne, Depth+1))
1229 case Instruction::Sub:
1230 // If the high-bits of this SUB are not demanded, then it does not demand
1231 // the high bits of its LHS or RHS.
1232 if (DemandedMask[BitWidth-1] == 0) {
1233 // Right fill the mask of bits for this SUB to demand the most
1234 // significant bit and all those below it.
1235 uint32_t NLZ = DemandedMask.countLeadingZeros();
1236 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1237 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1238 LHSKnownZero, LHSKnownOne, Depth+1) ||
1239 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1240 LHSKnownZero, LHSKnownOne, Depth+1))
1243 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1244 // the known zeros and ones.
1245 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1247 case Instruction::Shl:
1248 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1249 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1250 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1251 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1252 RHSKnownZero, RHSKnownOne, Depth+1))
1254 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1255 RHSKnownZero <<= ShiftAmt;
1256 RHSKnownOne <<= ShiftAmt;
1257 // low bits known zero.
1259 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1262 case Instruction::LShr:
1263 // For a logical shift right
1264 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1265 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1267 // Unsigned shift right.
1268 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1269 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1270 RHSKnownZero, RHSKnownOne, Depth+1))
1272 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1273 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1274 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1276 // Compute the new bits that are at the top now.
1277 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1278 RHSKnownZero |= HighBits; // high bits known zero.
1282 case Instruction::AShr:
1283 // If this is an arithmetic shift right and only the low-bit is set, we can
1284 // always convert this into a logical shr, even if the shift amount is
1285 // variable. The low bit of the shift cannot be an input sign bit unless
1286 // the shift amount is >= the size of the datatype, which is undefined.
1287 if (DemandedMask == 1) {
1288 // Perform the logical shift right.
1289 Instruction *NewVal = BinaryOperator::CreateLShr(
1290 I->getOperand(0), I->getOperand(1), I->getName());
1291 return InsertNewInstBefore(NewVal, *I);
1294 // If the sign bit is the only bit demanded by this ashr, then there is no
1295 // need to do it, the shift doesn't change the high bit.
1296 if (DemandedMask.isSignBit())
1297 return I->getOperand(0);
1299 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1300 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1302 // Signed shift right.
1303 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1304 // If any of the "high bits" are demanded, we should set the sign bit as
1306 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1307 DemandedMaskIn.set(BitWidth-1);
1308 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1309 RHSKnownZero, RHSKnownOne, Depth+1))
1311 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1312 // Compute the new bits that are at the top now.
1313 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1314 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1315 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1317 // Handle the sign bits.
1318 APInt SignBit(APInt::getSignBit(BitWidth));
1319 // Adjust to where it is now in the mask.
1320 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1322 // If the input sign bit is known to be zero, or if none of the top bits
1323 // are demanded, turn this into an unsigned shift right.
1324 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1325 (HighBits & ~DemandedMask) == HighBits) {
1326 // Perform the logical shift right.
1327 Instruction *NewVal = BinaryOperator::CreateLShr(
1328 I->getOperand(0), SA, I->getName());
1329 return InsertNewInstBefore(NewVal, *I);
1330 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1331 RHSKnownOne |= HighBits;
1335 case Instruction::SRem:
1336 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1337 APInt RA = Rem->getValue().abs();
1338 if (RA.isPowerOf2()) {
1339 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
1340 return I->getOperand(0);
1342 APInt LowBits = RA - 1;
1343 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1344 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1345 LHSKnownZero, LHSKnownOne, Depth+1))
1348 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1349 LHSKnownZero |= ~LowBits;
1351 KnownZero |= LHSKnownZero & DemandedMask;
1353 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
1357 case Instruction::URem: {
1358 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1359 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1360 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1361 KnownZero2, KnownOne2, Depth+1) ||
1362 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1363 KnownZero2, KnownOne2, Depth+1))
1366 unsigned Leaders = KnownZero2.countLeadingOnes();
1367 Leaders = std::max(Leaders,
1368 KnownZero2.countLeadingOnes());
1369 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1372 case Instruction::Call:
1373 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1374 switch (II->getIntrinsicID()) {
1376 case Intrinsic::bswap: {
1377 // If the only bits demanded come from one byte of the bswap result,
1378 // just shift the input byte into position to eliminate the bswap.
1379 unsigned NLZ = DemandedMask.countLeadingZeros();
1380 unsigned NTZ = DemandedMask.countTrailingZeros();
1382 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1383 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1384 // have 14 leading zeros, round to 8.
1387 // If we need exactly one byte, we can do this transformation.
1388 if (BitWidth-NLZ-NTZ == 8) {
1389 unsigned ResultBit = NTZ;
1390 unsigned InputBit = BitWidth-NTZ-8;
1392 // Replace this with either a left or right shift to get the byte into
1394 Instruction *NewVal;
1395 if (InputBit > ResultBit)
1396 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1397 ConstantInt::get(I->getType(), InputBit-ResultBit));
1399 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1400 ConstantInt::get(I->getType(), ResultBit-InputBit));
1401 NewVal->takeName(I);
1402 return InsertNewInstBefore(NewVal, *I);
1405 // TODO: Could compute known zero/one bits based on the input.
1410 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1414 // If the client is only demanding bits that we know, return the known
1416 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1417 Constant *C = ConstantInt::get(RHSKnownOne);
1418 if (isa<PointerType>(V->getType()))
1419 C = ConstantExpr::getIntToPtr(C, V->getType());
1426 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1427 /// any number of elements. DemandedElts contains the set of elements that are
1428 /// actually used by the caller. This method analyzes which elements of the
1429 /// operand are undef and returns that information in UndefElts.
1431 /// If the information about demanded elements can be used to simplify the
1432 /// operation, the operation is simplified, then the resultant value is
1433 /// returned. This returns null if no change was made.
1434 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1437 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1438 APInt EltMask(APInt::getAllOnesValue(VWidth));
1439 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1441 if (isa<UndefValue>(V)) {
1442 // If the entire vector is undefined, just return this info.
1443 UndefElts = EltMask;
1445 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1446 UndefElts = EltMask;
1447 return UndefValue::get(V->getType());
1451 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1452 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1453 Constant *Undef = UndefValue::get(EltTy);
1455 std::vector<Constant*> Elts;
1456 for (unsigned i = 0; i != VWidth; ++i)
1457 if (!DemandedElts[i]) { // If not demanded, set to undef.
1458 Elts.push_back(Undef);
1460 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1461 Elts.push_back(Undef);
1463 } else { // Otherwise, defined.
1464 Elts.push_back(CP->getOperand(i));
1467 // If we changed the constant, return it.
1468 Constant *NewCP = ConstantVector::get(Elts);
1469 return NewCP != CP ? NewCP : 0;
1470 } else if (isa<ConstantAggregateZero>(V)) {
1471 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1474 // Check if this is identity. If so, return 0 since we are not simplifying
1476 if (DemandedElts == ((1ULL << VWidth) -1))
1479 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1480 Constant *Zero = Constant::getNullValue(EltTy);
1481 Constant *Undef = UndefValue::get(EltTy);
1482 std::vector<Constant*> Elts;
1483 for (unsigned i = 0; i != VWidth; ++i) {
1484 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1485 Elts.push_back(Elt);
1487 UndefElts = DemandedElts ^ EltMask;
1488 return ConstantVector::get(Elts);
1491 // Limit search depth.
1495 // If multiple users are using the root value, procede with
1496 // simplification conservatively assuming that all elements
1498 if (!V->hasOneUse()) {
1499 // Quit if we find multiple users of a non-root value though.
1500 // They'll be handled when it's their turn to be visited by
1501 // the main instcombine process.
1503 // TODO: Just compute the UndefElts information recursively.
1506 // Conservatively assume that all elements are needed.
1507 DemandedElts = EltMask;
1510 Instruction *I = dyn_cast<Instruction>(V);
1511 if (!I) return 0; // Only analyze instructions.
1513 bool MadeChange = false;
1514 APInt UndefElts2(VWidth, 0);
1516 switch (I->getOpcode()) {
1519 case Instruction::InsertElement: {
1520 // If this is a variable index, we don't know which element it overwrites.
1521 // demand exactly the same input as we produce.
1522 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1524 // Note that we can't propagate undef elt info, because we don't know
1525 // which elt is getting updated.
1526 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1527 UndefElts2, Depth+1);
1528 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1532 // If this is inserting an element that isn't demanded, remove this
1534 unsigned IdxNo = Idx->getZExtValue();
1535 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1536 return AddSoonDeadInstToWorklist(*I, 0);
1538 // Otherwise, the element inserted overwrites whatever was there, so the
1539 // input demanded set is simpler than the output set.
1540 APInt DemandedElts2 = DemandedElts;
1541 DemandedElts2.clear(IdxNo);
1542 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1543 UndefElts, Depth+1);
1544 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1546 // The inserted element is defined.
1547 UndefElts.clear(IdxNo);
1550 case Instruction::ShuffleVector: {
1551 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1552 uint64_t LHSVWidth =
1553 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1554 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1555 for (unsigned i = 0; i < VWidth; i++) {
1556 if (DemandedElts[i]) {
1557 unsigned MaskVal = Shuffle->getMaskValue(i);
1558 if (MaskVal != -1u) {
1559 assert(MaskVal < LHSVWidth * 2 &&
1560 "shufflevector mask index out of range!");
1561 if (MaskVal < LHSVWidth)
1562 LeftDemanded.set(MaskVal);
1564 RightDemanded.set(MaskVal - LHSVWidth);
1569 APInt UndefElts4(LHSVWidth, 0);
1570 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1571 UndefElts4, Depth+1);
1572 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1574 APInt UndefElts3(LHSVWidth, 0);
1575 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1576 UndefElts3, Depth+1);
1577 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1579 bool NewUndefElts = false;
1580 for (unsigned i = 0; i < VWidth; i++) {
1581 unsigned MaskVal = Shuffle->getMaskValue(i);
1582 if (MaskVal == -1u) {
1584 } else if (MaskVal < LHSVWidth) {
1585 if (UndefElts4[MaskVal]) {
1586 NewUndefElts = true;
1590 if (UndefElts3[MaskVal - LHSVWidth]) {
1591 NewUndefElts = true;
1598 // Add additional discovered undefs.
1599 std::vector<Constant*> Elts;
1600 for (unsigned i = 0; i < VWidth; ++i) {
1602 Elts.push_back(UndefValue::get(Type::Int32Ty));
1604 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1605 Shuffle->getMaskValue(i)));
1607 I->setOperand(2, ConstantVector::get(Elts));
1612 case Instruction::BitCast: {
1613 // Vector->vector casts only.
1614 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1616 unsigned InVWidth = VTy->getNumElements();
1617 APInt InputDemandedElts(InVWidth, 0);
1620 if (VWidth == InVWidth) {
1621 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1622 // elements as are demanded of us.
1624 InputDemandedElts = DemandedElts;
1625 } else if (VWidth > InVWidth) {
1629 // If there are more elements in the result than there are in the source,
1630 // then an input element is live if any of the corresponding output
1631 // elements are live.
1632 Ratio = VWidth/InVWidth;
1633 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1634 if (DemandedElts[OutIdx])
1635 InputDemandedElts.set(OutIdx/Ratio);
1641 // If there are more elements in the source than there are in the result,
1642 // then an input element is live if the corresponding output element is
1644 Ratio = InVWidth/VWidth;
1645 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1646 if (DemandedElts[InIdx/Ratio])
1647 InputDemandedElts.set(InIdx);
1650 // div/rem demand all inputs, because they don't want divide by zero.
1651 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1652 UndefElts2, Depth+1);
1654 I->setOperand(0, TmpV);
1658 UndefElts = UndefElts2;
1659 if (VWidth > InVWidth) {
1660 assert(0 && "Unimp");
1661 // If there are more elements in the result than there are in the source,
1662 // then an output element is undef if the corresponding input element is
1664 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1665 if (UndefElts2[OutIdx/Ratio])
1666 UndefElts.set(OutIdx);
1667 } else if (VWidth < InVWidth) {
1668 assert(0 && "Unimp");
1669 // If there are more elements in the source than there are in the result,
1670 // then a result element is undef if all of the corresponding input
1671 // elements are undef.
1672 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1673 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1674 if (!UndefElts2[InIdx]) // Not undef?
1675 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
1679 case Instruction::And:
1680 case Instruction::Or:
1681 case Instruction::Xor:
1682 case Instruction::Add:
1683 case Instruction::Sub:
1684 case Instruction::Mul:
1685 // div/rem demand all inputs, because they don't want divide by zero.
1686 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1687 UndefElts, Depth+1);
1688 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1689 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1690 UndefElts2, Depth+1);
1691 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1693 // Output elements are undefined if both are undefined. Consider things
1694 // like undef&0. The result is known zero, not undef.
1695 UndefElts &= UndefElts2;
1698 case Instruction::Call: {
1699 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1701 switch (II->getIntrinsicID()) {
1704 // Binary vector operations that work column-wise. A dest element is a
1705 // function of the corresponding input elements from the two inputs.
1706 case Intrinsic::x86_sse_sub_ss:
1707 case Intrinsic::x86_sse_mul_ss:
1708 case Intrinsic::x86_sse_min_ss:
1709 case Intrinsic::x86_sse_max_ss:
1710 case Intrinsic::x86_sse2_sub_sd:
1711 case Intrinsic::x86_sse2_mul_sd:
1712 case Intrinsic::x86_sse2_min_sd:
1713 case Intrinsic::x86_sse2_max_sd:
1714 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1715 UndefElts, Depth+1);
1716 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1717 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1718 UndefElts2, Depth+1);
1719 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1721 // If only the low elt is demanded and this is a scalarizable intrinsic,
1722 // scalarize it now.
1723 if (DemandedElts == 1) {
1724 switch (II->getIntrinsicID()) {
1726 case Intrinsic::x86_sse_sub_ss:
1727 case Intrinsic::x86_sse_mul_ss:
1728 case Intrinsic::x86_sse2_sub_sd:
1729 case Intrinsic::x86_sse2_mul_sd:
1730 // TODO: Lower MIN/MAX/ABS/etc
1731 Value *LHS = II->getOperand(1);
1732 Value *RHS = II->getOperand(2);
1733 // Extract the element as scalars.
1734 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1735 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1737 switch (II->getIntrinsicID()) {
1738 default: assert(0 && "Case stmts out of sync!");
1739 case Intrinsic::x86_sse_sub_ss:
1740 case Intrinsic::x86_sse2_sub_sd:
1741 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1742 II->getName()), *II);
1744 case Intrinsic::x86_sse_mul_ss:
1745 case Intrinsic::x86_sse2_mul_sd:
1746 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1747 II->getName()), *II);
1752 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1754 InsertNewInstBefore(New, *II);
1755 AddSoonDeadInstToWorklist(*II, 0);
1760 // Output elements are undefined if both are undefined. Consider things
1761 // like undef&0. The result is known zero, not undef.
1762 UndefElts &= UndefElts2;
1768 return MadeChange ? I : 0;
1772 /// AssociativeOpt - Perform an optimization on an associative operator. This
1773 /// function is designed to check a chain of associative operators for a
1774 /// potential to apply a certain optimization. Since the optimization may be
1775 /// applicable if the expression was reassociated, this checks the chain, then
1776 /// reassociates the expression as necessary to expose the optimization
1777 /// opportunity. This makes use of a special Functor, which must define
1778 /// 'shouldApply' and 'apply' methods.
1780 template<typename Functor>
1781 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1782 unsigned Opcode = Root.getOpcode();
1783 Value *LHS = Root.getOperand(0);
1785 // Quick check, see if the immediate LHS matches...
1786 if (F.shouldApply(LHS))
1787 return F.apply(Root);
1789 // Otherwise, if the LHS is not of the same opcode as the root, return.
1790 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1791 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1792 // Should we apply this transform to the RHS?
1793 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1795 // If not to the RHS, check to see if we should apply to the LHS...
1796 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1797 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1801 // If the functor wants to apply the optimization to the RHS of LHSI,
1802 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1804 // Now all of the instructions are in the current basic block, go ahead
1805 // and perform the reassociation.
1806 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1808 // First move the selected RHS to the LHS of the root...
1809 Root.setOperand(0, LHSI->getOperand(1));
1811 // Make what used to be the LHS of the root be the user of the root...
1812 Value *ExtraOperand = TmpLHSI->getOperand(1);
1813 if (&Root == TmpLHSI) {
1814 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1817 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1818 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1819 BasicBlock::iterator ARI = &Root; ++ARI;
1820 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1823 // Now propagate the ExtraOperand down the chain of instructions until we
1825 while (TmpLHSI != LHSI) {
1826 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1827 // Move the instruction to immediately before the chain we are
1828 // constructing to avoid breaking dominance properties.
1829 NextLHSI->moveBefore(ARI);
1832 Value *NextOp = NextLHSI->getOperand(1);
1833 NextLHSI->setOperand(1, ExtraOperand);
1835 ExtraOperand = NextOp;
1838 // Now that the instructions are reassociated, have the functor perform
1839 // the transformation...
1840 return F.apply(Root);
1843 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1850 // AddRHS - Implements: X + X --> X << 1
1853 AddRHS(Value *rhs) : RHS(rhs) {}
1854 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1855 Instruction *apply(BinaryOperator &Add) const {
1856 return BinaryOperator::CreateShl(Add.getOperand(0),
1857 ConstantInt::get(Add.getType(), 1));
1861 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1863 struct AddMaskingAnd {
1865 AddMaskingAnd(Constant *c) : C2(c) {}
1866 bool shouldApply(Value *LHS) const {
1868 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1869 ConstantExpr::getAnd(C1, C2)->isNullValue();
1871 Instruction *apply(BinaryOperator &Add) const {
1872 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1878 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1880 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1881 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1884 // Figure out if the constant is the left or the right argument.
1885 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1886 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1888 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1890 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1891 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1894 Value *Op0 = SO, *Op1 = ConstOperand;
1896 std::swap(Op0, Op1);
1898 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1899 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1900 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1901 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1902 SO->getName()+".cmp");
1904 assert(0 && "Unknown binary instruction type!");
1907 return IC->InsertNewInstBefore(New, I);
1910 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1911 // constant as the other operand, try to fold the binary operator into the
1912 // select arguments. This also works for Cast instructions, which obviously do
1913 // not have a second operand.
1914 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1916 // Don't modify shared select instructions
1917 if (!SI->hasOneUse()) return 0;
1918 Value *TV = SI->getOperand(1);
1919 Value *FV = SI->getOperand(2);
1921 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1922 // Bool selects with constant operands can be folded to logical ops.
1923 if (SI->getType() == Type::Int1Ty) return 0;
1925 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1926 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1928 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1935 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1936 /// node as operand #0, see if we can fold the instruction into the PHI (which
1937 /// is only possible if all operands to the PHI are constants).
1938 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1939 PHINode *PN = cast<PHINode>(I.getOperand(0));
1940 unsigned NumPHIValues = PN->getNumIncomingValues();
1941 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1943 // Check to see if all of the operands of the PHI are constants. If there is
1944 // one non-constant value, remember the BB it is. If there is more than one
1945 // or if *it* is a PHI, bail out.
1946 BasicBlock *NonConstBB = 0;
1947 for (unsigned i = 0; i != NumPHIValues; ++i)
1948 if (!isa<Constant>(PN->getIncomingValue(i))) {
1949 if (NonConstBB) return 0; // More than one non-const value.
1950 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1951 NonConstBB = PN->getIncomingBlock(i);
1953 // If the incoming non-constant value is in I's block, we have an infinite
1955 if (NonConstBB == I.getParent())
1959 // If there is exactly one non-constant value, we can insert a copy of the
1960 // operation in that block. However, if this is a critical edge, we would be
1961 // inserting the computation one some other paths (e.g. inside a loop). Only
1962 // do this if the pred block is unconditionally branching into the phi block.
1964 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1965 if (!BI || !BI->isUnconditional()) return 0;
1968 // Okay, we can do the transformation: create the new PHI node.
1969 PHINode *NewPN = PHINode::Create(I.getType(), "");
1970 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1971 InsertNewInstBefore(NewPN, *PN);
1972 NewPN->takeName(PN);
1974 // Next, add all of the operands to the PHI.
1975 if (I.getNumOperands() == 2) {
1976 Constant *C = cast<Constant>(I.getOperand(1));
1977 for (unsigned i = 0; i != NumPHIValues; ++i) {
1979 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1980 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1981 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1983 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1985 assert(PN->getIncomingBlock(i) == NonConstBB);
1986 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1987 InV = BinaryOperator::Create(BO->getOpcode(),
1988 PN->getIncomingValue(i), C, "phitmp",
1989 NonConstBB->getTerminator());
1990 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1991 InV = CmpInst::Create(CI->getOpcode(),
1993 PN->getIncomingValue(i), C, "phitmp",
1994 NonConstBB->getTerminator());
1996 assert(0 && "Unknown binop!");
1998 AddToWorkList(cast<Instruction>(InV));
2000 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2003 CastInst *CI = cast<CastInst>(&I);
2004 const Type *RetTy = CI->getType();
2005 for (unsigned i = 0; i != NumPHIValues; ++i) {
2007 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2008 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2010 assert(PN->getIncomingBlock(i) == NonConstBB);
2011 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2012 I.getType(), "phitmp",
2013 NonConstBB->getTerminator());
2014 AddToWorkList(cast<Instruction>(InV));
2016 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2019 return ReplaceInstUsesWith(I, NewPN);
2023 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2024 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2025 /// This basically requires proving that the add in the original type would not
2026 /// overflow to change the sign bit or have a carry out.
2027 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2028 // There are different heuristics we can use for this. Here are some simple
2031 // Add has the property that adding any two 2's complement numbers can only
2032 // have one carry bit which can change a sign. As such, if LHS and RHS each
2033 // have at least two sign bits, we know that the addition of the two values will
2034 // sign extend fine.
2035 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2039 // If one of the operands only has one non-zero bit, and if the other operand
2040 // has a known-zero bit in a more significant place than it (not including the
2041 // sign bit) the ripple may go up to and fill the zero, but won't change the
2042 // sign. For example, (X & ~4) + 1.
2050 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2051 bool Changed = SimplifyCommutative(I);
2052 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2054 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2055 // X + undef -> undef
2056 if (isa<UndefValue>(RHS))
2057 return ReplaceInstUsesWith(I, RHS);
2060 if (RHSC->isNullValue())
2061 return ReplaceInstUsesWith(I, LHS);
2063 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2064 // X + (signbit) --> X ^ signbit
2065 const APInt& Val = CI->getValue();
2066 uint32_t BitWidth = Val.getBitWidth();
2067 if (Val == APInt::getSignBit(BitWidth))
2068 return BinaryOperator::CreateXor(LHS, RHS);
2070 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2071 // (X & 254)+1 -> (X&254)|1
2072 if (SimplifyDemandedInstructionBits(I))
2075 // zext(i1) - 1 -> select i1, 0, -1
2076 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2077 if (CI->isAllOnesValue() &&
2078 ZI->getOperand(0)->getType() == Type::Int1Ty)
2079 return SelectInst::Create(ZI->getOperand(0),
2080 Constant::getNullValue(I.getType()),
2081 ConstantInt::getAllOnesValue(I.getType()));
2084 if (isa<PHINode>(LHS))
2085 if (Instruction *NV = FoldOpIntoPhi(I))
2088 ConstantInt *XorRHS = 0;
2090 if (isa<ConstantInt>(RHSC) &&
2091 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2092 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2093 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2095 uint32_t Size = TySizeBits / 2;
2096 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2097 APInt CFF80Val(-C0080Val);
2099 if (TySizeBits > Size) {
2100 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2101 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2102 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2103 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2104 // This is a sign extend if the top bits are known zero.
2105 if (!MaskedValueIsZero(XorLHS,
2106 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2107 Size = 0; // Not a sign ext, but can't be any others either.
2112 C0080Val = APIntOps::lshr(C0080Val, Size);
2113 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2114 } while (Size >= 1);
2116 // FIXME: This shouldn't be necessary. When the backends can handle types
2117 // with funny bit widths then this switch statement should be removed. It
2118 // is just here to get the size of the "middle" type back up to something
2119 // that the back ends can handle.
2120 const Type *MiddleType = 0;
2123 case 32: MiddleType = Type::Int32Ty; break;
2124 case 16: MiddleType = Type::Int16Ty; break;
2125 case 8: MiddleType = Type::Int8Ty; break;
2128 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2129 InsertNewInstBefore(NewTrunc, I);
2130 return new SExtInst(NewTrunc, I.getType(), I.getName());
2135 if (I.getType() == Type::Int1Ty)
2136 return BinaryOperator::CreateXor(LHS, RHS);
2139 if (I.getType()->isInteger()) {
2140 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2142 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2143 if (RHSI->getOpcode() == Instruction::Sub)
2144 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2145 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2147 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2148 if (LHSI->getOpcode() == Instruction::Sub)
2149 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2150 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2155 // -A + -B --> -(A + B)
2156 if (Value *LHSV = dyn_castNegVal(LHS)) {
2157 if (LHS->getType()->isIntOrIntVector()) {
2158 if (Value *RHSV = dyn_castNegVal(RHS)) {
2159 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2160 InsertNewInstBefore(NewAdd, I);
2161 return BinaryOperator::CreateNeg(NewAdd);
2165 return BinaryOperator::CreateSub(RHS, LHSV);
2169 if (!isa<Constant>(RHS))
2170 if (Value *V = dyn_castNegVal(RHS))
2171 return BinaryOperator::CreateSub(LHS, V);
2175 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2176 if (X == RHS) // X*C + X --> X * (C+1)
2177 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2179 // X*C1 + X*C2 --> X * (C1+C2)
2181 if (X == dyn_castFoldableMul(RHS, C1))
2182 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2185 // X + X*C --> X * (C+1)
2186 if (dyn_castFoldableMul(RHS, C2) == LHS)
2187 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2189 // X + ~X --> -1 since ~X = -X-1
2190 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2191 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2194 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2195 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2196 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2199 // A+B --> A|B iff A and B have no bits set in common.
2200 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2201 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2202 APInt LHSKnownOne(IT->getBitWidth(), 0);
2203 APInt LHSKnownZero(IT->getBitWidth(), 0);
2204 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2205 if (LHSKnownZero != 0) {
2206 APInt RHSKnownOne(IT->getBitWidth(), 0);
2207 APInt RHSKnownZero(IT->getBitWidth(), 0);
2208 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2210 // No bits in common -> bitwise or.
2211 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2212 return BinaryOperator::CreateOr(LHS, RHS);
2216 // W*X + Y*Z --> W * (X+Z) iff W == Y
2217 if (I.getType()->isIntOrIntVector()) {
2218 Value *W, *X, *Y, *Z;
2219 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2220 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2224 } else if (Y == X) {
2226 } else if (X == Z) {
2233 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2234 LHS->getName()), I);
2235 return BinaryOperator::CreateMul(W, NewAdd);
2240 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2242 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2243 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2245 // (X & FF00) + xx00 -> (X+xx00) & FF00
2246 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2247 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2248 if (Anded == CRHS) {
2249 // See if all bits from the first bit set in the Add RHS up are included
2250 // in the mask. First, get the rightmost bit.
2251 const APInt& AddRHSV = CRHS->getValue();
2253 // Form a mask of all bits from the lowest bit added through the top.
2254 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2256 // See if the and mask includes all of these bits.
2257 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2259 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2260 // Okay, the xform is safe. Insert the new add pronto.
2261 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2262 LHS->getName()), I);
2263 return BinaryOperator::CreateAnd(NewAdd, C2);
2268 // Try to fold constant add into select arguments.
2269 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2270 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2274 // add (cast *A to intptrtype) B ->
2275 // cast (GEP (cast *A to i8*) B) --> intptrtype
2277 CastInst *CI = dyn_cast<CastInst>(LHS);
2280 CI = dyn_cast<CastInst>(RHS);
2283 if (CI && CI->getType()->isSized() &&
2284 (CI->getType()->getScalarSizeInBits() ==
2285 TD->getIntPtrType()->getPrimitiveSizeInBits())
2286 && isa<PointerType>(CI->getOperand(0)->getType())) {
2288 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2289 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2290 PointerType::get(Type::Int8Ty, AS), I);
2291 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2292 return new PtrToIntInst(I2, CI->getType());
2296 // add (select X 0 (sub n A)) A --> select X A n
2298 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2301 SI = dyn_cast<SelectInst>(RHS);
2304 if (SI && SI->hasOneUse()) {
2305 Value *TV = SI->getTrueValue();
2306 Value *FV = SI->getFalseValue();
2309 // Can we fold the add into the argument of the select?
2310 // We check both true and false select arguments for a matching subtract.
2311 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2312 // Fold the add into the true select value.
2313 return SelectInst::Create(SI->getCondition(), N, A);
2314 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2315 // Fold the add into the false select value.
2316 return SelectInst::Create(SI->getCondition(), A, N);
2320 // Check for (add (sext x), y), see if we can merge this into an
2321 // integer add followed by a sext.
2322 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2323 // (add (sext x), cst) --> (sext (add x, cst'))
2324 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2326 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2327 if (LHSConv->hasOneUse() &&
2328 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2329 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2330 // Insert the new, smaller add.
2331 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2333 InsertNewInstBefore(NewAdd, I);
2334 return new SExtInst(NewAdd, I.getType());
2338 // (add (sext x), (sext y)) --> (sext (add int x, y))
2339 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2340 // Only do this if x/y have the same type, if at last one of them has a
2341 // single use (so we don't increase the number of sexts), and if the
2342 // integer add will not overflow.
2343 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2344 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2345 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2346 RHSConv->getOperand(0))) {
2347 // Insert the new integer add.
2348 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2349 RHSConv->getOperand(0),
2351 InsertNewInstBefore(NewAdd, I);
2352 return new SExtInst(NewAdd, I.getType());
2357 return Changed ? &I : 0;
2360 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2361 bool Changed = SimplifyCommutative(I);
2362 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2364 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2366 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2367 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2368 (I.getType())->getValueAPF()))
2369 return ReplaceInstUsesWith(I, LHS);
2372 if (isa<PHINode>(LHS))
2373 if (Instruction *NV = FoldOpIntoPhi(I))
2378 // -A + -B --> -(A + B)
2379 if (Value *LHSV = dyn_castFNegVal(LHS))
2380 return BinaryOperator::CreateFSub(RHS, LHSV);
2383 if (!isa<Constant>(RHS))
2384 if (Value *V = dyn_castFNegVal(RHS))
2385 return BinaryOperator::CreateFSub(LHS, V);
2387 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2388 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2389 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2390 return ReplaceInstUsesWith(I, LHS);
2392 // Check for (add double (sitofp x), y), see if we can merge this into an
2393 // integer add followed by a promotion.
2394 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2395 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2396 // ... if the constant fits in the integer value. This is useful for things
2397 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2398 // requires a constant pool load, and generally allows the add to be better
2400 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2402 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2403 if (LHSConv->hasOneUse() &&
2404 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2405 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2406 // Insert the new integer add.
2407 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2409 InsertNewInstBefore(NewAdd, I);
2410 return new SIToFPInst(NewAdd, I.getType());
2414 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2415 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2416 // Only do this if x/y have the same type, if at last one of them has a
2417 // single use (so we don't increase the number of int->fp conversions),
2418 // and if the integer add will not overflow.
2419 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2420 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2421 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2422 RHSConv->getOperand(0))) {
2423 // Insert the new integer add.
2424 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2425 RHSConv->getOperand(0),
2427 InsertNewInstBefore(NewAdd, I);
2428 return new SIToFPInst(NewAdd, I.getType());
2433 return Changed ? &I : 0;
2436 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2437 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2439 if (Op0 == Op1) // sub X, X -> 0
2440 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2442 // If this is a 'B = x-(-A)', change to B = x+A...
2443 if (Value *V = dyn_castNegVal(Op1))
2444 return BinaryOperator::CreateAdd(Op0, V);
2446 if (isa<UndefValue>(Op0))
2447 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2448 if (isa<UndefValue>(Op1))
2449 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2451 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2452 // Replace (-1 - A) with (~A)...
2453 if (C->isAllOnesValue())
2454 return BinaryOperator::CreateNot(Op1);
2456 // C - ~X == X + (1+C)
2458 if (match(Op1, m_Not(m_Value(X))))
2459 return BinaryOperator::CreateAdd(X, AddOne(C));
2461 // -(X >>u 31) -> (X >>s 31)
2462 // -(X >>s 31) -> (X >>u 31)
2464 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2465 if (SI->getOpcode() == Instruction::LShr) {
2466 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2467 // Check to see if we are shifting out everything but the sign bit.
2468 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2469 SI->getType()->getPrimitiveSizeInBits()-1) {
2470 // Ok, the transformation is safe. Insert AShr.
2471 return BinaryOperator::Create(Instruction::AShr,
2472 SI->getOperand(0), CU, SI->getName());
2476 else if (SI->getOpcode() == Instruction::AShr) {
2477 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2478 // Check to see if we are shifting out everything but the sign bit.
2479 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2480 SI->getType()->getPrimitiveSizeInBits()-1) {
2481 // Ok, the transformation is safe. Insert LShr.
2482 return BinaryOperator::CreateLShr(
2483 SI->getOperand(0), CU, SI->getName());
2490 // Try to fold constant sub into select arguments.
2491 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2492 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2496 if (I.getType() == Type::Int1Ty)
2497 return BinaryOperator::CreateXor(Op0, Op1);
2499 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2500 if (Op1I->getOpcode() == Instruction::Add) {
2501 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2502 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2503 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2504 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2505 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2506 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2507 // C1-(X+C2) --> (C1-C2)-X
2508 return BinaryOperator::CreateSub(ConstantExpr::getSub(CI1, CI2),
2509 Op1I->getOperand(0));
2513 if (Op1I->hasOneUse()) {
2514 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2515 // is not used by anyone else...
2517 if (Op1I->getOpcode() == Instruction::Sub) {
2518 // Swap the two operands of the subexpr...
2519 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2520 Op1I->setOperand(0, IIOp1);
2521 Op1I->setOperand(1, IIOp0);
2523 // Create the new top level add instruction...
2524 return BinaryOperator::CreateAdd(Op0, Op1);
2527 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2529 if (Op1I->getOpcode() == Instruction::And &&
2530 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2531 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2534 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2535 return BinaryOperator::CreateAnd(Op0, NewNot);
2538 // 0 - (X sdiv C) -> (X sdiv -C)
2539 if (Op1I->getOpcode() == Instruction::SDiv)
2540 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2542 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2543 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2544 ConstantExpr::getNeg(DivRHS));
2546 // X - X*C --> X * (1-C)
2547 ConstantInt *C2 = 0;
2548 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2549 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2551 return BinaryOperator::CreateMul(Op0, CP1);
2556 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2557 if (Op0I->getOpcode() == Instruction::Add) {
2558 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2559 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2560 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2561 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2562 } else if (Op0I->getOpcode() == Instruction::Sub) {
2563 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2564 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2569 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2570 if (X == Op1) // X*C - X --> X * (C-1)
2571 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2573 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2574 if (X == dyn_castFoldableMul(Op1, C2))
2575 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2580 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2581 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2583 // If this is a 'B = x-(-A)', change to B = x+A...
2584 if (Value *V = dyn_castFNegVal(Op1))
2585 return BinaryOperator::CreateFAdd(Op0, V);
2587 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2588 if (Op1I->getOpcode() == Instruction::FAdd) {
2589 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2590 return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2591 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2592 return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2599 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2600 /// comparison only checks the sign bit. If it only checks the sign bit, set
2601 /// TrueIfSigned if the result of the comparison is true when the input value is
2603 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2604 bool &TrueIfSigned) {
2606 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2607 TrueIfSigned = true;
2608 return RHS->isZero();
2609 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2610 TrueIfSigned = true;
2611 return RHS->isAllOnesValue();
2612 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2613 TrueIfSigned = false;
2614 return RHS->isAllOnesValue();
2615 case ICmpInst::ICMP_UGT:
2616 // True if LHS u> RHS and RHS == high-bit-mask - 1
2617 TrueIfSigned = true;
2618 return RHS->getValue() ==
2619 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2620 case ICmpInst::ICMP_UGE:
2621 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2622 TrueIfSigned = true;
2623 return RHS->getValue().isSignBit();
2629 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2630 bool Changed = SimplifyCommutative(I);
2631 Value *Op0 = I.getOperand(0);
2633 // TODO: If Op1 is undef and Op0 is finite, return zero.
2634 if (!I.getType()->isFPOrFPVector() &&
2635 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2636 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2638 // Simplify mul instructions with a constant RHS...
2639 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2640 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2642 // ((X << C1)*C2) == (X * (C2 << C1))
2643 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2644 if (SI->getOpcode() == Instruction::Shl)
2645 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2646 return BinaryOperator::CreateMul(SI->getOperand(0),
2647 ConstantExpr::getShl(CI, ShOp));
2650 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2651 if (CI->equalsInt(1)) // X * 1 == X
2652 return ReplaceInstUsesWith(I, Op0);
2653 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2654 return BinaryOperator::CreateNeg(Op0, I.getName());
2656 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2657 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2658 return BinaryOperator::CreateShl(Op0,
2659 ConstantInt::get(Op0->getType(), Val.logBase2()));
2661 } else if (isa<VectorType>(Op1->getType())) {
2662 // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
2664 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2665 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2666 return BinaryOperator::CreateNeg(Op0, I.getName());
2668 // As above, vector X*splat(1.0) -> X in all defined cases.
2669 if (Constant *Splat = Op1V->getSplatValue()) {
2670 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2671 if (CI->equalsInt(1))
2672 return ReplaceInstUsesWith(I, Op0);
2677 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2678 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2679 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2680 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2681 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2683 InsertNewInstBefore(Add, I);
2684 Value *C1C2 = ConstantExpr::getMul(Op1,
2685 cast<Constant>(Op0I->getOperand(1)));
2686 return BinaryOperator::CreateAdd(Add, C1C2);
2690 // Try to fold constant mul into select arguments.
2691 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2692 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2695 if (isa<PHINode>(Op0))
2696 if (Instruction *NV = FoldOpIntoPhi(I))
2700 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2701 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2702 return BinaryOperator::CreateMul(Op0v, Op1v);
2704 // (X / Y) * Y = X - (X % Y)
2705 // (X / Y) * -Y = (X % Y) - X
2707 Value *Op1 = I.getOperand(1);
2708 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2710 (BO->getOpcode() != Instruction::UDiv &&
2711 BO->getOpcode() != Instruction::SDiv)) {
2713 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2715 Value *Neg = dyn_castNegVal(Op1);
2716 if (BO && BO->hasOneUse() &&
2717 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2718 (BO->getOpcode() == Instruction::UDiv ||
2719 BO->getOpcode() == Instruction::SDiv)) {
2720 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2723 if (BO->getOpcode() == Instruction::UDiv)
2724 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2726 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2728 InsertNewInstBefore(Rem, I);
2732 return BinaryOperator::CreateSub(Op0BO, Rem);
2734 return BinaryOperator::CreateSub(Rem, Op0BO);
2738 if (I.getType() == Type::Int1Ty)
2739 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2741 // If one of the operands of the multiply is a cast from a boolean value, then
2742 // we know the bool is either zero or one, so this is a 'masking' multiply.
2743 // See if we can simplify things based on how the boolean was originally
2745 CastInst *BoolCast = 0;
2746 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2747 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2750 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2751 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2754 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2755 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2756 const Type *SCOpTy = SCIOp0->getType();
2759 // If the icmp is true iff the sign bit of X is set, then convert this
2760 // multiply into a shift/and combination.
2761 if (isa<ConstantInt>(SCIOp1) &&
2762 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2764 // Shift the X value right to turn it into "all signbits".
2765 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2766 SCOpTy->getPrimitiveSizeInBits()-1);
2768 InsertNewInstBefore(
2769 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2770 BoolCast->getOperand(0)->getName()+
2773 // If the multiply type is not the same as the source type, sign extend
2774 // or truncate to the multiply type.
2775 if (I.getType() != V->getType()) {
2776 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2777 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2778 Instruction::CastOps opcode =
2779 (SrcBits == DstBits ? Instruction::BitCast :
2780 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2781 V = InsertCastBefore(opcode, V, I.getType(), I);
2784 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2785 return BinaryOperator::CreateAnd(V, OtherOp);
2790 return Changed ? &I : 0;
2793 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2794 bool Changed = SimplifyCommutative(I);
2795 Value *Op0 = I.getOperand(0);
2797 // Simplify mul instructions with a constant RHS...
2798 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2799 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2800 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2801 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2802 if (Op1F->isExactlyValue(1.0))
2803 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2804 } else if (isa<VectorType>(Op1->getType())) {
2805 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2806 // As above, vector X*splat(1.0) -> X in all defined cases.
2807 if (Constant *Splat = Op1V->getSplatValue()) {
2808 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2809 if (F->isExactlyValue(1.0))
2810 return ReplaceInstUsesWith(I, Op0);
2815 // Try to fold constant mul into select arguments.
2816 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2817 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2820 if (isa<PHINode>(Op0))
2821 if (Instruction *NV = FoldOpIntoPhi(I))
2825 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2826 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2827 return BinaryOperator::CreateFMul(Op0v, Op1v);
2829 return Changed ? &I : 0;
2832 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2834 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2835 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2837 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2838 int NonNullOperand = -1;
2839 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2840 if (ST->isNullValue())
2842 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2843 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2844 if (ST->isNullValue())
2847 if (NonNullOperand == -1)
2850 Value *SelectCond = SI->getOperand(0);
2852 // Change the div/rem to use 'Y' instead of the select.
2853 I.setOperand(1, SI->getOperand(NonNullOperand));
2855 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2856 // problem. However, the select, or the condition of the select may have
2857 // multiple uses. Based on our knowledge that the operand must be non-zero,
2858 // propagate the known value for the select into other uses of it, and
2859 // propagate a known value of the condition into its other users.
2861 // If the select and condition only have a single use, don't bother with this,
2863 if (SI->use_empty() && SelectCond->hasOneUse())
2866 // Scan the current block backward, looking for other uses of SI.
2867 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2869 while (BBI != BBFront) {
2871 // If we found a call to a function, we can't assume it will return, so
2872 // information from below it cannot be propagated above it.
2873 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2876 // Replace uses of the select or its condition with the known values.
2877 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2880 *I = SI->getOperand(NonNullOperand);
2882 } else if (*I == SelectCond) {
2883 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2884 ConstantInt::getFalse();
2889 // If we past the instruction, quit looking for it.
2892 if (&*BBI == SelectCond)
2895 // If we ran out of things to eliminate, break out of the loop.
2896 if (SelectCond == 0 && SI == 0)
2904 /// This function implements the transforms on div instructions that work
2905 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2906 /// used by the visitors to those instructions.
2907 /// @brief Transforms common to all three div instructions
2908 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2909 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2911 // undef / X -> 0 for integer.
2912 // undef / X -> undef for FP (the undef could be a snan).
2913 if (isa<UndefValue>(Op0)) {
2914 if (Op0->getType()->isFPOrFPVector())
2915 return ReplaceInstUsesWith(I, Op0);
2916 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2919 // X / undef -> undef
2920 if (isa<UndefValue>(Op1))
2921 return ReplaceInstUsesWith(I, Op1);
2926 /// This function implements the transforms common to both integer division
2927 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2928 /// division instructions.
2929 /// @brief Common integer divide transforms
2930 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2931 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2933 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2935 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2936 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2937 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2938 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2941 Constant *CI = ConstantInt::get(I.getType(), 1);
2942 return ReplaceInstUsesWith(I, CI);
2945 if (Instruction *Common = commonDivTransforms(I))
2948 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2949 // This does not apply for fdiv.
2950 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2953 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2955 if (RHS->equalsInt(1))
2956 return ReplaceInstUsesWith(I, Op0);
2958 // (X / C1) / C2 -> X / (C1*C2)
2959 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2960 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2961 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2962 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2963 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2965 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2966 ConstantExpr::getMul(RHS, LHSRHS));
2969 if (!RHS->isZero()) { // avoid X udiv 0
2970 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2971 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2973 if (isa<PHINode>(Op0))
2974 if (Instruction *NV = FoldOpIntoPhi(I))
2979 // 0 / X == 0, we don't need to preserve faults!
2980 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2981 if (LHS->equalsInt(0))
2982 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2984 // It can't be division by zero, hence it must be division by one.
2985 if (I.getType() == Type::Int1Ty)
2986 return ReplaceInstUsesWith(I, Op0);
2988 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2989 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2992 return ReplaceInstUsesWith(I, Op0);
2998 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2999 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3001 // Handle the integer div common cases
3002 if (Instruction *Common = commonIDivTransforms(I))
3005 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3006 // X udiv C^2 -> X >> C
3007 // Check to see if this is an unsigned division with an exact power of 2,
3008 // if so, convert to a right shift.
3009 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3010 return BinaryOperator::CreateLShr(Op0,
3011 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3013 // X udiv C, where C >= signbit
3014 if (C->getValue().isNegative()) {
3015 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3017 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3018 ConstantInt::get(I.getType(), 1));
3022 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3023 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3024 if (RHSI->getOpcode() == Instruction::Shl &&
3025 isa<ConstantInt>(RHSI->getOperand(0))) {
3026 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3027 if (C1.isPowerOf2()) {
3028 Value *N = RHSI->getOperand(1);
3029 const Type *NTy = N->getType();
3030 if (uint32_t C2 = C1.logBase2()) {
3031 Constant *C2V = ConstantInt::get(NTy, C2);
3032 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3034 return BinaryOperator::CreateLShr(Op0, N);
3039 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3040 // where C1&C2 are powers of two.
3041 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3042 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3043 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3044 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3045 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3046 // Compute the shift amounts
3047 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3048 // Construct the "on true" case of the select
3049 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3050 Instruction *TSI = BinaryOperator::CreateLShr(
3051 Op0, TC, SI->getName()+".t");
3052 TSI = InsertNewInstBefore(TSI, I);
3054 // Construct the "on false" case of the select
3055 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3056 Instruction *FSI = BinaryOperator::CreateLShr(
3057 Op0, FC, SI->getName()+".f");
3058 FSI = InsertNewInstBefore(FSI, I);
3060 // construct the select instruction and return it.
3061 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3067 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3068 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3070 // Handle the integer div common cases
3071 if (Instruction *Common = commonIDivTransforms(I))
3074 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3076 if (RHS->isAllOnesValue())
3077 return BinaryOperator::CreateNeg(Op0);
3080 // If the sign bits of both operands are zero (i.e. we can prove they are
3081 // unsigned inputs), turn this into a udiv.
3082 if (I.getType()->isInteger()) {
3083 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3084 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3085 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3086 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3093 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3094 return commonDivTransforms(I);
3097 /// This function implements the transforms on rem instructions that work
3098 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3099 /// is used by the visitors to those instructions.
3100 /// @brief Transforms common to all three rem instructions
3101 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3102 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3104 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3105 if (I.getType()->isFPOrFPVector())
3106 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3107 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3109 if (isa<UndefValue>(Op1))
3110 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3112 // Handle cases involving: rem X, (select Cond, Y, Z)
3113 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3119 /// This function implements the transforms common to both integer remainder
3120 /// instructions (urem and srem). It is called by the visitors to those integer
3121 /// remainder instructions.
3122 /// @brief Common integer remainder transforms
3123 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3124 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3126 if (Instruction *common = commonRemTransforms(I))
3129 // 0 % X == 0 for integer, we don't need to preserve faults!
3130 if (Constant *LHS = dyn_cast<Constant>(Op0))
3131 if (LHS->isNullValue())
3132 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3134 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3135 // X % 0 == undef, we don't need to preserve faults!
3136 if (RHS->equalsInt(0))
3137 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3139 if (RHS->equalsInt(1)) // X % 1 == 0
3140 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3142 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3143 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3144 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3146 } else if (isa<PHINode>(Op0I)) {
3147 if (Instruction *NV = FoldOpIntoPhi(I))
3151 // See if we can fold away this rem instruction.
3152 if (SimplifyDemandedInstructionBits(I))
3160 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3161 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3163 if (Instruction *common = commonIRemTransforms(I))
3166 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3167 // X urem C^2 -> X and C
3168 // Check to see if this is an unsigned remainder with an exact power of 2,
3169 // if so, convert to a bitwise and.
3170 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3171 if (C->getValue().isPowerOf2())
3172 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3175 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3176 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3177 if (RHSI->getOpcode() == Instruction::Shl &&
3178 isa<ConstantInt>(RHSI->getOperand(0))) {
3179 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3180 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3181 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3183 return BinaryOperator::CreateAnd(Op0, Add);
3188 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3189 // where C1&C2 are powers of two.
3190 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3191 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3192 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3193 // STO == 0 and SFO == 0 handled above.
3194 if ((STO->getValue().isPowerOf2()) &&
3195 (SFO->getValue().isPowerOf2())) {
3196 Value *TrueAnd = InsertNewInstBefore(
3197 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3198 Value *FalseAnd = InsertNewInstBefore(
3199 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3200 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3208 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3209 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3211 // Handle the integer rem common cases
3212 if (Instruction *common = commonIRemTransforms(I))
3215 if (Value *RHSNeg = dyn_castNegVal(Op1))
3216 if (!isa<Constant>(RHSNeg) ||
3217 (isa<ConstantInt>(RHSNeg) &&
3218 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3220 AddUsesToWorkList(I);
3221 I.setOperand(1, RHSNeg);
3225 // If the sign bits of both operands are zero (i.e. we can prove they are
3226 // unsigned inputs), turn this into a urem.
3227 if (I.getType()->isInteger()) {
3228 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3229 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3230 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3231 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3235 // If it's a constant vector, flip any negative values positive.
3236 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3237 unsigned VWidth = RHSV->getNumOperands();
3239 bool hasNegative = false;
3240 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3241 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3242 if (RHS->getValue().isNegative())
3246 std::vector<Constant *> Elts(VWidth);
3247 for (unsigned i = 0; i != VWidth; ++i) {
3248 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3249 if (RHS->getValue().isNegative())
3250 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3256 Constant *NewRHSV = ConstantVector::get(Elts);
3257 if (NewRHSV != RHSV) {
3258 AddUsesToWorkList(I);
3259 I.setOperand(1, NewRHSV);
3268 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3269 return commonRemTransforms(I);
3272 // isOneBitSet - Return true if there is exactly one bit set in the specified
3274 static bool isOneBitSet(const ConstantInt *CI) {
3275 return CI->getValue().isPowerOf2();
3278 // isHighOnes - Return true if the constant is of the form 1+0+.
3279 // This is the same as lowones(~X).
3280 static bool isHighOnes(const ConstantInt *CI) {
3281 return (~CI->getValue() + 1).isPowerOf2();
3284 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3285 /// are carefully arranged to allow folding of expressions such as:
3287 /// (A < B) | (A > B) --> (A != B)
3289 /// Note that this is only valid if the first and second predicates have the
3290 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3292 /// Three bits are used to represent the condition, as follows:
3297 /// <=> Value Definition
3298 /// 000 0 Always false
3305 /// 111 7 Always true
3307 static unsigned getICmpCode(const ICmpInst *ICI) {
3308 switch (ICI->getPredicate()) {
3310 case ICmpInst::ICMP_UGT: return 1; // 001
3311 case ICmpInst::ICMP_SGT: return 1; // 001
3312 case ICmpInst::ICMP_EQ: return 2; // 010
3313 case ICmpInst::ICMP_UGE: return 3; // 011
3314 case ICmpInst::ICMP_SGE: return 3; // 011
3315 case ICmpInst::ICMP_ULT: return 4; // 100
3316 case ICmpInst::ICMP_SLT: return 4; // 100
3317 case ICmpInst::ICMP_NE: return 5; // 101
3318 case ICmpInst::ICMP_ULE: return 6; // 110
3319 case ICmpInst::ICMP_SLE: return 6; // 110
3322 assert(0 && "Invalid ICmp predicate!");
3327 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3328 /// predicate into a three bit mask. It also returns whether it is an ordered
3329 /// predicate by reference.
3330 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3333 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3334 case FCmpInst::FCMP_UNO: return 0; // 000
3335 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3336 case FCmpInst::FCMP_UGT: return 1; // 001
3337 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3338 case FCmpInst::FCMP_UEQ: return 2; // 010
3339 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3340 case FCmpInst::FCMP_UGE: return 3; // 011
3341 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3342 case FCmpInst::FCMP_ULT: return 4; // 100
3343 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3344 case FCmpInst::FCMP_UNE: return 5; // 101
3345 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3346 case FCmpInst::FCMP_ULE: return 6; // 110
3349 // Not expecting FCMP_FALSE and FCMP_TRUE;
3350 assert(0 && "Unexpected FCmp predicate!");
3355 /// getICmpValue - This is the complement of getICmpCode, which turns an
3356 /// opcode and two operands into either a constant true or false, or a brand
3357 /// new ICmp instruction. The sign is passed in to determine which kind
3358 /// of predicate to use in the new icmp instruction.
3359 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3361 default: assert(0 && "Illegal ICmp code!");
3362 case 0: return ConstantInt::getFalse();
3365 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3367 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3368 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3371 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3373 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3376 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3378 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3379 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3382 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3384 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3385 case 7: return ConstantInt::getTrue();
3389 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3390 /// opcode and two operands into either a FCmp instruction. isordered is passed
3391 /// in to determine which kind of predicate to use in the new fcmp instruction.
3392 static Value *getFCmpValue(bool isordered, unsigned code,
3393 Value *LHS, Value *RHS) {
3395 default: assert(0 && "Illegal FCmp code!");
3398 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3400 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3403 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3405 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3408 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3410 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3413 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3415 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3418 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3420 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3423 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3425 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3428 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3430 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3431 case 7: return ConstantInt::getTrue();
3435 /// PredicatesFoldable - Return true if both predicates match sign or if at
3436 /// least one of them is an equality comparison (which is signless).
3437 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3438 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3439 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3440 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3444 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3445 struct FoldICmpLogical {
3448 ICmpInst::Predicate pred;
3449 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3450 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3451 pred(ICI->getPredicate()) {}
3452 bool shouldApply(Value *V) const {
3453 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3454 if (PredicatesFoldable(pred, ICI->getPredicate()))
3455 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3456 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3459 Instruction *apply(Instruction &Log) const {
3460 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3461 if (ICI->getOperand(0) != LHS) {
3462 assert(ICI->getOperand(1) == LHS);
3463 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3466 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3467 unsigned LHSCode = getICmpCode(ICI);
3468 unsigned RHSCode = getICmpCode(RHSICI);
3470 switch (Log.getOpcode()) {
3471 case Instruction::And: Code = LHSCode & RHSCode; break;
3472 case Instruction::Or: Code = LHSCode | RHSCode; break;
3473 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3474 default: assert(0 && "Illegal logical opcode!"); return 0;
3477 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3478 ICmpInst::isSignedPredicate(ICI->getPredicate());
3480 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3481 if (Instruction *I = dyn_cast<Instruction>(RV))
3483 // Otherwise, it's a constant boolean value...
3484 return IC.ReplaceInstUsesWith(Log, RV);
3487 } // end anonymous namespace
3489 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3490 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3491 // guaranteed to be a binary operator.
3492 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3494 ConstantInt *AndRHS,
3495 BinaryOperator &TheAnd) {
3496 Value *X = Op->getOperand(0);
3497 Constant *Together = 0;
3499 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3501 switch (Op->getOpcode()) {
3502 case Instruction::Xor:
3503 if (Op->hasOneUse()) {
3504 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3505 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3506 InsertNewInstBefore(And, TheAnd);
3508 return BinaryOperator::CreateXor(And, Together);
3511 case Instruction::Or:
3512 if (Together == AndRHS) // (X | C) & C --> C
3513 return ReplaceInstUsesWith(TheAnd, AndRHS);
3515 if (Op->hasOneUse() && Together != OpRHS) {
3516 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3517 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3518 InsertNewInstBefore(Or, TheAnd);
3520 return BinaryOperator::CreateAnd(Or, AndRHS);
3523 case Instruction::Add:
3524 if (Op->hasOneUse()) {
3525 // Adding a one to a single bit bit-field should be turned into an XOR
3526 // of the bit. First thing to check is to see if this AND is with a
3527 // single bit constant.
3528 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3530 // If there is only one bit set...
3531 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3532 // Ok, at this point, we know that we are masking the result of the
3533 // ADD down to exactly one bit. If the constant we are adding has
3534 // no bits set below this bit, then we can eliminate the ADD.
3535 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3537 // Check to see if any bits below the one bit set in AndRHSV are set.
3538 if ((AddRHS & (AndRHSV-1)) == 0) {
3539 // If not, the only thing that can effect the output of the AND is
3540 // the bit specified by AndRHSV. If that bit is set, the effect of
3541 // the XOR is to toggle the bit. If it is clear, then the ADD has
3543 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3544 TheAnd.setOperand(0, X);
3547 // Pull the XOR out of the AND.
3548 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3549 InsertNewInstBefore(NewAnd, TheAnd);
3550 NewAnd->takeName(Op);
3551 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3558 case Instruction::Shl: {
3559 // We know that the AND will not produce any of the bits shifted in, so if
3560 // the anded constant includes them, clear them now!
3562 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3563 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3564 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3565 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3567 if (CI->getValue() == ShlMask) {
3568 // Masking out bits that the shift already masks
3569 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3570 } else if (CI != AndRHS) { // Reducing bits set in and.
3571 TheAnd.setOperand(1, CI);
3576 case Instruction::LShr:
3578 // We know that the AND will not produce any of the bits shifted in, so if
3579 // the anded constant includes them, clear them now! This only applies to
3580 // unsigned shifts, because a signed shr may bring in set bits!
3582 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3583 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3584 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3585 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3587 if (CI->getValue() == ShrMask) {
3588 // Masking out bits that the shift already masks.
3589 return ReplaceInstUsesWith(TheAnd, Op);
3590 } else if (CI != AndRHS) {
3591 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3596 case Instruction::AShr:
3598 // See if this is shifting in some sign extension, then masking it out
3600 if (Op->hasOneUse()) {
3601 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3602 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3603 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3604 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3605 if (C == AndRHS) { // Masking out bits shifted in.
3606 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3607 // Make the argument unsigned.
3608 Value *ShVal = Op->getOperand(0);
3609 ShVal = InsertNewInstBefore(
3610 BinaryOperator::CreateLShr(ShVal, OpRHS,
3611 Op->getName()), TheAnd);
3612 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3621 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3622 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3623 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3624 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3625 /// insert new instructions.
3626 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3627 bool isSigned, bool Inside,
3629 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3630 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3631 "Lo is not <= Hi in range emission code!");
3634 if (Lo == Hi) // Trivially false.
3635 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3637 // V >= Min && V < Hi --> V < Hi
3638 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3639 ICmpInst::Predicate pred = (isSigned ?
3640 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3641 return new ICmpInst(pred, V, Hi);
3644 // Emit V-Lo <u Hi-Lo
3645 Constant *NegLo = ConstantExpr::getNeg(Lo);
3646 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3647 InsertNewInstBefore(Add, IB);
3648 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3649 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3652 if (Lo == Hi) // Trivially true.
3653 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3655 // V < Min || V >= Hi -> V > Hi-1
3656 Hi = SubOne(cast<ConstantInt>(Hi));
3657 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3658 ICmpInst::Predicate pred = (isSigned ?
3659 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3660 return new ICmpInst(pred, V, Hi);
3663 // Emit V-Lo >u Hi-1-Lo
3664 // Note that Hi has already had one subtracted from it, above.
3665 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3666 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3667 InsertNewInstBefore(Add, IB);
3668 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3669 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3672 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3673 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3674 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3675 // not, since all 1s are not contiguous.
3676 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3677 const APInt& V = Val->getValue();
3678 uint32_t BitWidth = Val->getType()->getBitWidth();
3679 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3681 // look for the first zero bit after the run of ones
3682 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3683 // look for the first non-zero bit
3684 ME = V.getActiveBits();
3688 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3689 /// where isSub determines whether the operator is a sub. If we can fold one of
3690 /// the following xforms:
3692 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3693 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3694 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3696 /// return (A +/- B).
3698 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3699 ConstantInt *Mask, bool isSub,
3701 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3702 if (!LHSI || LHSI->getNumOperands() != 2 ||
3703 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3705 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3707 switch (LHSI->getOpcode()) {
3709 case Instruction::And:
3710 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3711 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3712 if ((Mask->getValue().countLeadingZeros() +
3713 Mask->getValue().countPopulation()) ==
3714 Mask->getValue().getBitWidth())
3717 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3718 // part, we don't need any explicit masks to take them out of A. If that
3719 // is all N is, ignore it.
3720 uint32_t MB = 0, ME = 0;
3721 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3722 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3723 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3724 if (MaskedValueIsZero(RHS, Mask))
3729 case Instruction::Or:
3730 case Instruction::Xor:
3731 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3732 if ((Mask->getValue().countLeadingZeros() +
3733 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3734 && ConstantExpr::getAnd(N, Mask)->isNullValue())
3741 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3743 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3744 return InsertNewInstBefore(New, I);
3747 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3748 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3749 ICmpInst *LHS, ICmpInst *RHS) {
3751 ConstantInt *LHSCst, *RHSCst;
3752 ICmpInst::Predicate LHSCC, RHSCC;
3754 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3755 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3756 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3759 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3760 // where C is a power of 2
3761 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3762 LHSCst->getValue().isPowerOf2()) {
3763 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3764 InsertNewInstBefore(NewOr, I);
3765 return new ICmpInst(LHSCC, NewOr, LHSCst);
3768 // From here on, we only handle:
3769 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3770 if (Val != Val2) return 0;
3772 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3773 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3774 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3775 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3776 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3779 // We can't fold (ugt x, C) & (sgt x, C2).
3780 if (!PredicatesFoldable(LHSCC, RHSCC))
3783 // Ensure that the larger constant is on the RHS.
3785 if (ICmpInst::isSignedPredicate(LHSCC) ||
3786 (ICmpInst::isEquality(LHSCC) &&
3787 ICmpInst::isSignedPredicate(RHSCC)))
3788 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3790 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3793 std::swap(LHS, RHS);
3794 std::swap(LHSCst, RHSCst);
3795 std::swap(LHSCC, RHSCC);
3798 // At this point, we know we have have two icmp instructions
3799 // comparing a value against two constants and and'ing the result
3800 // together. Because of the above check, we know that we only have
3801 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3802 // (from the FoldICmpLogical check above), that the two constants
3803 // are not equal and that the larger constant is on the RHS
3804 assert(LHSCst != RHSCst && "Compares not folded above?");
3807 default: assert(0 && "Unknown integer condition code!");
3808 case ICmpInst::ICMP_EQ:
3810 default: assert(0 && "Unknown integer condition code!");
3811 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3812 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3813 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3814 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3815 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3816 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3817 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3818 return ReplaceInstUsesWith(I, LHS);
3820 case ICmpInst::ICMP_NE:
3822 default: assert(0 && "Unknown integer condition code!");
3823 case ICmpInst::ICMP_ULT:
3824 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3825 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3826 break; // (X != 13 & X u< 15) -> no change
3827 case ICmpInst::ICMP_SLT:
3828 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3829 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3830 break; // (X != 13 & X s< 15) -> no change
3831 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3832 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3833 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3834 return ReplaceInstUsesWith(I, RHS);
3835 case ICmpInst::ICMP_NE:
3836 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3837 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3838 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3839 Val->getName()+".off");
3840 InsertNewInstBefore(Add, I);
3841 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3842 ConstantInt::get(Add->getType(), 1));
3844 break; // (X != 13 & X != 15) -> no change
3847 case ICmpInst::ICMP_ULT:
3849 default: assert(0 && "Unknown integer condition code!");
3850 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3851 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3852 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3853 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3855 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3856 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3857 return ReplaceInstUsesWith(I, LHS);
3858 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3862 case ICmpInst::ICMP_SLT:
3864 default: assert(0 && "Unknown integer condition code!");
3865 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3866 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3867 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3868 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3870 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3871 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3872 return ReplaceInstUsesWith(I, LHS);
3873 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3877 case ICmpInst::ICMP_UGT:
3879 default: assert(0 && "Unknown integer condition code!");
3880 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3881 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3882 return ReplaceInstUsesWith(I, RHS);
3883 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3885 case ICmpInst::ICMP_NE:
3886 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3887 return new ICmpInst(LHSCC, Val, RHSCst);
3888 break; // (X u> 13 & X != 15) -> no change
3889 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3890 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3891 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3895 case ICmpInst::ICMP_SGT:
3897 default: assert(0 && "Unknown integer condition code!");
3898 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3899 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3900 return ReplaceInstUsesWith(I, RHS);
3901 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3903 case ICmpInst::ICMP_NE:
3904 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3905 return new ICmpInst(LHSCC, Val, RHSCst);
3906 break; // (X s> 13 & X != 15) -> no change
3907 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3908 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3909 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3919 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3920 bool Changed = SimplifyCommutative(I);
3921 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3923 if (isa<UndefValue>(Op1)) // X & undef -> 0
3924 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3928 return ReplaceInstUsesWith(I, Op1);
3930 // See if we can simplify any instructions used by the instruction whose sole
3931 // purpose is to compute bits we don't care about.
3932 if (SimplifyDemandedInstructionBits(I))
3934 if (isa<VectorType>(I.getType())) {
3935 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3936 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3937 return ReplaceInstUsesWith(I, I.getOperand(0));
3938 } else if (isa<ConstantAggregateZero>(Op1)) {
3939 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3943 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3944 const APInt& AndRHSMask = AndRHS->getValue();
3945 APInt NotAndRHS(~AndRHSMask);
3947 // Optimize a variety of ((val OP C1) & C2) combinations...
3948 if (isa<BinaryOperator>(Op0)) {
3949 Instruction *Op0I = cast<Instruction>(Op0);
3950 Value *Op0LHS = Op0I->getOperand(0);
3951 Value *Op0RHS = Op0I->getOperand(1);
3952 switch (Op0I->getOpcode()) {
3953 case Instruction::Xor:
3954 case Instruction::Or:
3955 // If the mask is only needed on one incoming arm, push it up.
3956 if (Op0I->hasOneUse()) {
3957 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3958 // Not masking anything out for the LHS, move to RHS.
3959 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3960 Op0RHS->getName()+".masked");
3961 InsertNewInstBefore(NewRHS, I);
3962 return BinaryOperator::Create(
3963 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3965 if (!isa<Constant>(Op0RHS) &&
3966 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3967 // Not masking anything out for the RHS, move to LHS.
3968 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3969 Op0LHS->getName()+".masked");
3970 InsertNewInstBefore(NewLHS, I);
3971 return BinaryOperator::Create(
3972 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3977 case Instruction::Add:
3978 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3979 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3980 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3981 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3982 return BinaryOperator::CreateAnd(V, AndRHS);
3983 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3984 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
3987 case Instruction::Sub:
3988 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3989 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3990 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3991 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3992 return BinaryOperator::CreateAnd(V, AndRHS);
3994 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3995 // has 1's for all bits that the subtraction with A might affect.
3996 if (Op0I->hasOneUse()) {
3997 uint32_t BitWidth = AndRHSMask.getBitWidth();
3998 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3999 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4001 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4002 if (!(A && A->isZero()) && // avoid infinite recursion.
4003 MaskedValueIsZero(Op0LHS, Mask)) {
4004 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4005 InsertNewInstBefore(NewNeg, I);
4006 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4011 case Instruction::Shl:
4012 case Instruction::LShr:
4013 // (1 << x) & 1 --> zext(x == 0)
4014 // (1 >> x) & 1 --> zext(x == 0)
4015 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4016 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
4017 Constant::getNullValue(I.getType()));
4018 InsertNewInstBefore(NewICmp, I);
4019 return new ZExtInst(NewICmp, I.getType());
4024 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4025 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4027 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4028 // If this is an integer truncation or change from signed-to-unsigned, and
4029 // if the source is an and/or with immediate, transform it. This
4030 // frequently occurs for bitfield accesses.
4031 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4032 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4033 CastOp->getNumOperands() == 2)
4034 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4035 if (CastOp->getOpcode() == Instruction::And) {
4036 // Change: and (cast (and X, C1) to T), C2
4037 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4038 // This will fold the two constants together, which may allow
4039 // other simplifications.
4040 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4041 CastOp->getOperand(0), I.getType(),
4042 CastOp->getName()+".shrunk");
4043 NewCast = InsertNewInstBefore(NewCast, I);
4044 // trunc_or_bitcast(C1)&C2
4045 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4046 C3 = ConstantExpr::getAnd(C3, AndRHS);
4047 return BinaryOperator::CreateAnd(NewCast, C3);
4048 } else if (CastOp->getOpcode() == Instruction::Or) {
4049 // Change: and (cast (or X, C1) to T), C2
4050 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4051 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4052 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4053 return ReplaceInstUsesWith(I, AndRHS);
4059 // Try to fold constant and into select arguments.
4060 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4061 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4063 if (isa<PHINode>(Op0))
4064 if (Instruction *NV = FoldOpIntoPhi(I))
4068 Value *Op0NotVal = dyn_castNotVal(Op0);
4069 Value *Op1NotVal = dyn_castNotVal(Op1);
4071 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4072 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4074 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4075 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4076 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4077 I.getName()+".demorgan");
4078 InsertNewInstBefore(Or, I);
4079 return BinaryOperator::CreateNot(Or);
4083 Value *A = 0, *B = 0, *C = 0, *D = 0;
4084 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4085 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4086 return ReplaceInstUsesWith(I, Op1);
4088 // (A|B) & ~(A&B) -> A^B
4089 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4090 if ((A == C && B == D) || (A == D && B == C))
4091 return BinaryOperator::CreateXor(A, B);
4095 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4096 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4097 return ReplaceInstUsesWith(I, Op0);
4099 // ~(A&B) & (A|B) -> A^B
4100 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4101 if ((A == C && B == D) || (A == D && B == C))
4102 return BinaryOperator::CreateXor(A, B);
4106 if (Op0->hasOneUse() &&
4107 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4108 if (A == Op1) { // (A^B)&A -> A&(A^B)
4109 I.swapOperands(); // Simplify below
4110 std::swap(Op0, Op1);
4111 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4112 cast<BinaryOperator>(Op0)->swapOperands();
4113 I.swapOperands(); // Simplify below
4114 std::swap(Op0, Op1);
4118 if (Op1->hasOneUse() &&
4119 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4120 if (B == Op0) { // B&(A^B) -> B&(B^A)
4121 cast<BinaryOperator>(Op1)->swapOperands();
4124 if (A == Op0) { // A&(A^B) -> A & ~B
4125 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4126 InsertNewInstBefore(NotB, I);
4127 return BinaryOperator::CreateAnd(A, NotB);
4131 // (A&((~A)|B)) -> A&B
4132 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4133 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4134 return BinaryOperator::CreateAnd(A, Op1);
4135 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4136 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4137 return BinaryOperator::CreateAnd(A, Op0);
4140 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4141 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4142 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4145 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4146 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4150 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4151 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4152 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4153 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4154 const Type *SrcTy = Op0C->getOperand(0)->getType();
4155 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4156 // Only do this if the casts both really cause code to be generated.
4157 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4159 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4161 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4162 Op1C->getOperand(0),
4164 InsertNewInstBefore(NewOp, I);
4165 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4169 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4170 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4171 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4172 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4173 SI0->getOperand(1) == SI1->getOperand(1) &&
4174 (SI0->hasOneUse() || SI1->hasOneUse())) {
4175 Instruction *NewOp =
4176 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4178 SI0->getName()), I);
4179 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4180 SI1->getOperand(1));
4184 // If and'ing two fcmp, try combine them into one.
4185 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4186 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4187 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4188 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4189 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4190 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4191 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4192 // If either of the constants are nans, then the whole thing returns
4194 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4195 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4196 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4197 RHS->getOperand(0));
4200 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4201 FCmpInst::Predicate Op0CC, Op1CC;
4202 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4203 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4204 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4205 // Swap RHS operands to match LHS.
4206 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4207 std::swap(Op1LHS, Op1RHS);
4209 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4210 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4212 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4213 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4214 Op1CC == FCmpInst::FCMP_FALSE)
4215 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4216 else if (Op0CC == FCmpInst::FCMP_TRUE)
4217 return ReplaceInstUsesWith(I, Op1);
4218 else if (Op1CC == FCmpInst::FCMP_TRUE)
4219 return ReplaceInstUsesWith(I, Op0);
4222 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4223 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4225 std::swap(Op0, Op1);
4226 std::swap(Op0Pred, Op1Pred);
4227 std::swap(Op0Ordered, Op1Ordered);
4230 // uno && ueq -> uno && (uno || eq) -> ueq
4231 // ord && olt -> ord && (ord && lt) -> olt
4232 if (Op0Ordered == Op1Ordered)
4233 return ReplaceInstUsesWith(I, Op1);
4234 // uno && oeq -> uno && (ord && eq) -> false
4235 // uno && ord -> false
4237 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4238 // ord && ueq -> ord && (uno || eq) -> oeq
4239 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4248 return Changed ? &I : 0;
4251 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4252 /// capable of providing pieces of a bswap. The subexpression provides pieces
4253 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4254 /// the expression came from the corresponding "byte swapped" byte in some other
4255 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4256 /// we know that the expression deposits the low byte of %X into the high byte
4257 /// of the bswap result and that all other bytes are zero. This expression is
4258 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4261 /// This function returns true if the match was unsuccessful and false if so.
4262 /// On entry to the function the "OverallLeftShift" is a signed integer value
4263 /// indicating the number of bytes that the subexpression is later shifted. For
4264 /// example, if the expression is later right shifted by 16 bits, the
4265 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4266 /// byte of ByteValues is actually being set.
4268 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4269 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4270 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4271 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4272 /// always in the local (OverallLeftShift) coordinate space.
4274 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4275 SmallVector<Value*, 8> &ByteValues) {
4276 if (Instruction *I = dyn_cast<Instruction>(V)) {
4277 // If this is an or instruction, it may be an inner node of the bswap.
4278 if (I->getOpcode() == Instruction::Or) {
4279 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4281 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4285 // If this is a logical shift by a constant multiple of 8, recurse with
4286 // OverallLeftShift and ByteMask adjusted.
4287 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4289 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4290 // Ensure the shift amount is defined and of a byte value.
4291 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4294 unsigned ByteShift = ShAmt >> 3;
4295 if (I->getOpcode() == Instruction::Shl) {
4296 // X << 2 -> collect(X, +2)
4297 OverallLeftShift += ByteShift;
4298 ByteMask >>= ByteShift;
4300 // X >>u 2 -> collect(X, -2)
4301 OverallLeftShift -= ByteShift;
4302 ByteMask <<= ByteShift;
4303 ByteMask &= (~0U >> (32-ByteValues.size()));
4306 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4307 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4309 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4313 // If this is a logical 'and' with a mask that clears bytes, clear the
4314 // corresponding bytes in ByteMask.
4315 if (I->getOpcode() == Instruction::And &&
4316 isa<ConstantInt>(I->getOperand(1))) {
4317 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4318 unsigned NumBytes = ByteValues.size();
4319 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4320 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4322 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4323 // If this byte is masked out by a later operation, we don't care what
4325 if ((ByteMask & (1 << i)) == 0)
4328 // If the AndMask is all zeros for this byte, clear the bit.
4329 APInt MaskB = AndMask & Byte;
4331 ByteMask &= ~(1U << i);
4335 // If the AndMask is not all ones for this byte, it's not a bytezap.
4339 // Otherwise, this byte is kept.
4342 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4347 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4348 // the input value to the bswap. Some observations: 1) if more than one byte
4349 // is demanded from this input, then it could not be successfully assembled
4350 // into a byteswap. At least one of the two bytes would not be aligned with
4351 // their ultimate destination.
4352 if (!isPowerOf2_32(ByteMask)) return true;
4353 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4355 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4356 // is demanded, it needs to go into byte 0 of the result. This means that the
4357 // byte needs to be shifted until it lands in the right byte bucket. The
4358 // shift amount depends on the position: if the byte is coming from the high
4359 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4360 // low part, it must be shifted left.
4361 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4362 if (InputByteNo < ByteValues.size()/2) {
4363 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4366 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4370 // If the destination byte value is already defined, the values are or'd
4371 // together, which isn't a bswap (unless it's an or of the same bits).
4372 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4374 ByteValues[DestByteNo] = V;
4378 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4379 /// If so, insert the new bswap intrinsic and return it.
4380 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4381 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4382 if (!ITy || ITy->getBitWidth() % 16 ||
4383 // ByteMask only allows up to 32-byte values.
4384 ITy->getBitWidth() > 32*8)
4385 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4387 /// ByteValues - For each byte of the result, we keep track of which value
4388 /// defines each byte.
4389 SmallVector<Value*, 8> ByteValues;
4390 ByteValues.resize(ITy->getBitWidth()/8);
4392 // Try to find all the pieces corresponding to the bswap.
4393 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4394 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4397 // Check to see if all of the bytes come from the same value.
4398 Value *V = ByteValues[0];
4399 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4401 // Check to make sure that all of the bytes come from the same value.
4402 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4403 if (ByteValues[i] != V)
4405 const Type *Tys[] = { ITy };
4406 Module *M = I.getParent()->getParent()->getParent();
4407 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4408 return CallInst::Create(F, V);
4411 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4412 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4413 /// we can simplify this expression to "cond ? C : D or B".
4414 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4415 Value *C, Value *D) {
4416 // If A is not a select of -1/0, this cannot match.
4418 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4421 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4422 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4423 return SelectInst::Create(Cond, C, B);
4424 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4425 return SelectInst::Create(Cond, C, B);
4426 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4427 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4428 return SelectInst::Create(Cond, C, D);
4429 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4430 return SelectInst::Create(Cond, C, D);
4434 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4435 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4436 ICmpInst *LHS, ICmpInst *RHS) {
4438 ConstantInt *LHSCst, *RHSCst;
4439 ICmpInst::Predicate LHSCC, RHSCC;
4441 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4442 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4443 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4446 // From here on, we only handle:
4447 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4448 if (Val != Val2) return 0;
4450 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4451 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4452 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4453 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4454 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4457 // We can't fold (ugt x, C) | (sgt x, C2).
4458 if (!PredicatesFoldable(LHSCC, RHSCC))
4461 // Ensure that the larger constant is on the RHS.
4463 if (ICmpInst::isSignedPredicate(LHSCC) ||
4464 (ICmpInst::isEquality(LHSCC) &&
4465 ICmpInst::isSignedPredicate(RHSCC)))
4466 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4468 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4471 std::swap(LHS, RHS);
4472 std::swap(LHSCst, RHSCst);
4473 std::swap(LHSCC, RHSCC);
4476 // At this point, we know we have have two icmp instructions
4477 // comparing a value against two constants and or'ing the result
4478 // together. Because of the above check, we know that we only have
4479 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4480 // FoldICmpLogical check above), that the two constants are not
4482 assert(LHSCst != RHSCst && "Compares not folded above?");
4485 default: assert(0 && "Unknown integer condition code!");
4486 case ICmpInst::ICMP_EQ:
4488 default: assert(0 && "Unknown integer condition code!");
4489 case ICmpInst::ICMP_EQ:
4490 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4491 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4492 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4493 Val->getName()+".off");
4494 InsertNewInstBefore(Add, I);
4495 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4496 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4498 break; // (X == 13 | X == 15) -> no change
4499 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4500 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4502 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4503 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4504 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4505 return ReplaceInstUsesWith(I, RHS);
4508 case ICmpInst::ICMP_NE:
4510 default: assert(0 && "Unknown integer condition code!");
4511 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4512 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4513 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4514 return ReplaceInstUsesWith(I, LHS);
4515 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4516 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4517 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4518 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4521 case ICmpInst::ICMP_ULT:
4523 default: assert(0 && "Unknown integer condition code!");
4524 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4526 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4527 // If RHSCst is [us]MAXINT, it is always false. Not handling
4528 // this can cause overflow.
4529 if (RHSCst->isMaxValue(false))
4530 return ReplaceInstUsesWith(I, LHS);
4531 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4532 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4534 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4535 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4536 return ReplaceInstUsesWith(I, RHS);
4537 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4541 case ICmpInst::ICMP_SLT:
4543 default: assert(0 && "Unknown integer condition code!");
4544 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4546 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4547 // If RHSCst is [us]MAXINT, it is always false. Not handling
4548 // this can cause overflow.
4549 if (RHSCst->isMaxValue(true))
4550 return ReplaceInstUsesWith(I, LHS);
4551 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4552 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4554 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4555 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4556 return ReplaceInstUsesWith(I, RHS);
4557 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4561 case ICmpInst::ICMP_UGT:
4563 default: assert(0 && "Unknown integer condition code!");
4564 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4565 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4566 return ReplaceInstUsesWith(I, LHS);
4567 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4569 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4570 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4571 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4572 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4576 case ICmpInst::ICMP_SGT:
4578 default: assert(0 && "Unknown integer condition code!");
4579 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4580 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4581 return ReplaceInstUsesWith(I, LHS);
4582 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4584 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4585 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4586 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4587 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4595 /// FoldOrWithConstants - This helper function folds:
4597 /// ((A | B) & C1) | (B & C2)
4603 /// when the XOR of the two constants is "all ones" (-1).
4604 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4605 Value *A, Value *B, Value *C) {
4606 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4610 ConstantInt *CI2 = 0;
4611 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4613 APInt Xor = CI1->getValue() ^ CI2->getValue();
4614 if (!Xor.isAllOnesValue()) return 0;
4616 if (V1 == A || V1 == B) {
4617 Instruction *NewOp =
4618 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4619 return BinaryOperator::CreateOr(NewOp, V1);
4625 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4626 bool Changed = SimplifyCommutative(I);
4627 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4629 if (isa<UndefValue>(Op1)) // X | undef -> -1
4630 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4634 return ReplaceInstUsesWith(I, Op0);
4636 // See if we can simplify any instructions used by the instruction whose sole
4637 // purpose is to compute bits we don't care about.
4638 if (SimplifyDemandedInstructionBits(I))
4640 if (isa<VectorType>(I.getType())) {
4641 if (isa<ConstantAggregateZero>(Op1)) {
4642 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4643 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4644 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4645 return ReplaceInstUsesWith(I, I.getOperand(1));
4650 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4651 ConstantInt *C1 = 0; Value *X = 0;
4652 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4653 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4654 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4655 InsertNewInstBefore(Or, I);
4657 return BinaryOperator::CreateAnd(Or,
4658 ConstantInt::get(RHS->getValue() | C1->getValue()));
4661 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4662 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4663 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4664 InsertNewInstBefore(Or, I);
4666 return BinaryOperator::CreateXor(Or,
4667 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4670 // Try to fold constant and into select arguments.
4671 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4672 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4674 if (isa<PHINode>(Op0))
4675 if (Instruction *NV = FoldOpIntoPhi(I))
4679 Value *A = 0, *B = 0;
4680 ConstantInt *C1 = 0, *C2 = 0;
4682 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4683 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4684 return ReplaceInstUsesWith(I, Op1);
4685 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4686 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4687 return ReplaceInstUsesWith(I, Op0);
4689 // (A | B) | C and A | (B | C) -> bswap if possible.
4690 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4691 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4692 match(Op1, m_Or(m_Value(), m_Value())) ||
4693 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4694 match(Op1, m_Shift(m_Value(), m_Value())))) {
4695 if (Instruction *BSwap = MatchBSwap(I))
4699 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4700 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4701 MaskedValueIsZero(Op1, C1->getValue())) {
4702 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4703 InsertNewInstBefore(NOr, I);
4705 return BinaryOperator::CreateXor(NOr, C1);
4708 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4709 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4710 MaskedValueIsZero(Op0, C1->getValue())) {
4711 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4712 InsertNewInstBefore(NOr, I);
4714 return BinaryOperator::CreateXor(NOr, C1);
4718 Value *C = 0, *D = 0;
4719 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4720 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4721 Value *V1 = 0, *V2 = 0, *V3 = 0;
4722 C1 = dyn_cast<ConstantInt>(C);
4723 C2 = dyn_cast<ConstantInt>(D);
4724 if (C1 && C2) { // (A & C1)|(B & C2)
4725 // If we have: ((V + N) & C1) | (V & C2)
4726 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4727 // replace with V+N.
4728 if (C1->getValue() == ~C2->getValue()) {
4729 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4730 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4731 // Add commutes, try both ways.
4732 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4733 return ReplaceInstUsesWith(I, A);
4734 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4735 return ReplaceInstUsesWith(I, A);
4737 // Or commutes, try both ways.
4738 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4739 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4740 // Add commutes, try both ways.
4741 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4742 return ReplaceInstUsesWith(I, B);
4743 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4744 return ReplaceInstUsesWith(I, B);
4747 V1 = 0; V2 = 0; V3 = 0;
4750 // Check to see if we have any common things being and'ed. If so, find the
4751 // terms for V1 & (V2|V3).
4752 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4753 if (A == B) // (A & C)|(A & D) == A & (C|D)
4754 V1 = A, V2 = C, V3 = D;
4755 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4756 V1 = A, V2 = B, V3 = C;
4757 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4758 V1 = C, V2 = A, V3 = D;
4759 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4760 V1 = C, V2 = A, V3 = B;
4764 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4765 return BinaryOperator::CreateAnd(V1, Or);
4769 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4770 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4772 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4774 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4776 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4779 // ((A&~B)|(~A&B)) -> A^B
4780 if ((match(C, m_Not(m_Specific(D))) &&
4781 match(B, m_Not(m_Specific(A)))))
4782 return BinaryOperator::CreateXor(A, D);
4783 // ((~B&A)|(~A&B)) -> A^B
4784 if ((match(A, m_Not(m_Specific(D))) &&
4785 match(B, m_Not(m_Specific(C)))))
4786 return BinaryOperator::CreateXor(C, D);
4787 // ((A&~B)|(B&~A)) -> A^B
4788 if ((match(C, m_Not(m_Specific(B))) &&
4789 match(D, m_Not(m_Specific(A)))))
4790 return BinaryOperator::CreateXor(A, B);
4791 // ((~B&A)|(B&~A)) -> A^B
4792 if ((match(A, m_Not(m_Specific(B))) &&
4793 match(D, m_Not(m_Specific(C)))))
4794 return BinaryOperator::CreateXor(C, B);
4797 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4798 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4799 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4800 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4801 SI0->getOperand(1) == SI1->getOperand(1) &&
4802 (SI0->hasOneUse() || SI1->hasOneUse())) {
4803 Instruction *NewOp =
4804 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4806 SI0->getName()), I);
4807 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4808 SI1->getOperand(1));
4812 // ((A|B)&1)|(B&-2) -> (A&1) | B
4813 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4814 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4815 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4816 if (Ret) return Ret;
4818 // (B&-2)|((A|B)&1) -> (A&1) | B
4819 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4820 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4821 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4822 if (Ret) return Ret;
4825 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4826 if (A == Op1) // ~A | A == -1
4827 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4831 // Note, A is still live here!
4832 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4834 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4836 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4837 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4838 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4839 I.getName()+".demorgan"), I);
4840 return BinaryOperator::CreateNot(And);
4844 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4845 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4846 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4849 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4850 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4854 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4855 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4856 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4857 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4858 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4859 !isa<ICmpInst>(Op1C->getOperand(0))) {
4860 const Type *SrcTy = Op0C->getOperand(0)->getType();
4861 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4862 // Only do this if the casts both really cause code to be
4864 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4866 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4868 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4869 Op1C->getOperand(0),
4871 InsertNewInstBefore(NewOp, I);
4872 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4879 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4880 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4881 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4882 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4883 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4884 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4885 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4886 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4887 // If either of the constants are nans, then the whole thing returns
4889 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4890 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4892 // Otherwise, no need to compare the two constants, compare the
4894 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4895 RHS->getOperand(0));
4898 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4899 FCmpInst::Predicate Op0CC, Op1CC;
4900 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4901 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4902 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4903 // Swap RHS operands to match LHS.
4904 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4905 std::swap(Op1LHS, Op1RHS);
4907 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4908 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4910 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4911 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4912 Op1CC == FCmpInst::FCMP_TRUE)
4913 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4914 else if (Op0CC == FCmpInst::FCMP_FALSE)
4915 return ReplaceInstUsesWith(I, Op1);
4916 else if (Op1CC == FCmpInst::FCMP_FALSE)
4917 return ReplaceInstUsesWith(I, Op0);
4920 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4921 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4922 if (Op0Ordered == Op1Ordered) {
4923 // If both are ordered or unordered, return a new fcmp with
4924 // or'ed predicates.
4925 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4927 if (Instruction *I = dyn_cast<Instruction>(RV))
4929 // Otherwise, it's a constant boolean value...
4930 return ReplaceInstUsesWith(I, RV);
4938 return Changed ? &I : 0;
4943 // XorSelf - Implements: X ^ X --> 0
4946 XorSelf(Value *rhs) : RHS(rhs) {}
4947 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4948 Instruction *apply(BinaryOperator &Xor) const {
4955 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4956 bool Changed = SimplifyCommutative(I);
4957 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4959 if (isa<UndefValue>(Op1)) {
4960 if (isa<UndefValue>(Op0))
4961 // Handle undef ^ undef -> 0 special case. This is a common
4963 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4964 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4967 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4968 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4969 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4970 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4973 // See if we can simplify any instructions used by the instruction whose sole
4974 // purpose is to compute bits we don't care about.
4975 if (SimplifyDemandedInstructionBits(I))
4977 if (isa<VectorType>(I.getType()))
4978 if (isa<ConstantAggregateZero>(Op1))
4979 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4981 // Is this a ~ operation?
4982 if (Value *NotOp = dyn_castNotVal(&I)) {
4983 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4984 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4985 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4986 if (Op0I->getOpcode() == Instruction::And ||
4987 Op0I->getOpcode() == Instruction::Or) {
4988 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4989 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4991 BinaryOperator::CreateNot(Op0I->getOperand(1),
4992 Op0I->getOperand(1)->getName()+".not");
4993 InsertNewInstBefore(NotY, I);
4994 if (Op0I->getOpcode() == Instruction::And)
4995 return BinaryOperator::CreateOr(Op0NotVal, NotY);
4997 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5004 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5005 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
5006 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5007 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5008 return new ICmpInst(ICI->getInversePredicate(),
5009 ICI->getOperand(0), ICI->getOperand(1));
5011 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5012 return new FCmpInst(FCI->getInversePredicate(),
5013 FCI->getOperand(0), FCI->getOperand(1));
5016 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5017 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5018 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5019 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5020 Instruction::CastOps Opcode = Op0C->getOpcode();
5021 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5022 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
5023 Op0C->getDestTy())) {
5024 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5025 CI->getOpcode(), CI->getInversePredicate(),
5026 CI->getOperand(0), CI->getOperand(1)), I);
5027 NewCI->takeName(CI);
5028 return CastInst::Create(Opcode, NewCI, 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(RHS->getValue() + Op0CI->getValue());
5057 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5060 } else if (Op0I->getOpcode() == Instruction::Or) {
5061 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5062 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5063 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5064 // Anything in both C1 and C2 is known to be zero, remove it from
5066 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5067 NewRHS = ConstantExpr::getAnd(NewRHS,
5068 ConstantExpr::getNot(CommonBits));
5069 AddToWorkList(Op0I);
5070 I.setOperand(0, Op0I->getOperand(0));
5071 I.setOperand(1, NewRHS);
5078 // Try to fold constant and into select arguments.
5079 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5080 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5082 if (isa<PHINode>(Op0))
5083 if (Instruction *NV = FoldOpIntoPhi(I))
5087 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5089 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5091 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5093 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5096 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5099 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5100 if (A == Op0) { // B^(B|A) == (A|B)^B
5101 Op1I->swapOperands();
5103 std::swap(Op0, Op1);
5104 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5105 I.swapOperands(); // Simplified below.
5106 std::swap(Op0, Op1);
5108 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5109 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5110 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5111 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5112 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5113 if (A == Op0) { // A^(A&B) -> A^(B&A)
5114 Op1I->swapOperands();
5117 if (B == Op0) { // A^(B&A) -> (B&A)^A
5118 I.swapOperands(); // Simplified below.
5119 std::swap(Op0, Op1);
5124 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5127 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5128 if (A == Op1) // (B|A)^B == (A|B)^B
5130 if (B == Op1) { // (A|B)^B == A & ~B
5132 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5133 return BinaryOperator::CreateAnd(A, NotB);
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))) && Op0I->hasOneUse()){
5140 if (A == Op1) // (A&B)^A -> (B&A)^A
5142 if (B == Op1 && // (B&A)^A == ~B & A
5143 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5145 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5146 return BinaryOperator::CreateAnd(N, Op1);
5151 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5152 if (Op0I && Op1I && Op0I->isShift() &&
5153 Op0I->getOpcode() == Op1I->getOpcode() &&
5154 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5155 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5156 Instruction *NewOp =
5157 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5158 Op1I->getOperand(0),
5159 Op0I->getName()), I);
5160 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5161 Op1I->getOperand(1));
5165 Value *A, *B, *C, *D;
5166 // (A & B)^(A | B) -> A ^ B
5167 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5168 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5169 if ((A == C && B == D) || (A == D && B == C))
5170 return BinaryOperator::CreateXor(A, B);
5172 // (A | B)^(A & B) -> A ^ B
5173 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5174 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5175 if ((A == C && B == D) || (A == D && B == C))
5176 return BinaryOperator::CreateXor(A, B);
5180 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5181 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5182 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5183 // (X & Y)^(X & Y) -> (Y^Z) & X
5184 Value *X = 0, *Y = 0, *Z = 0;
5186 X = A, Y = B, Z = D;
5188 X = A, Y = B, Z = C;
5190 X = B, Y = A, Z = D;
5192 X = B, Y = A, Z = C;
5195 Instruction *NewOp =
5196 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5197 return BinaryOperator::CreateAnd(NewOp, X);
5202 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5203 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5204 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5207 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5208 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5209 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5210 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5211 const Type *SrcTy = Op0C->getOperand(0)->getType();
5212 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5213 // Only do this if the casts both really cause code to be generated.
5214 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5216 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5218 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5219 Op1C->getOperand(0),
5221 InsertNewInstBefore(NewOp, I);
5222 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5227 return Changed ? &I : 0;
5230 static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
5231 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5234 static bool HasAddOverflow(ConstantInt *Result,
5235 ConstantInt *In1, ConstantInt *In2,
5238 if (In2->getValue().isNegative())
5239 return Result->getValue().sgt(In1->getValue());
5241 return Result->getValue().slt(In1->getValue());
5243 return Result->getValue().ult(In1->getValue());
5246 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5247 /// overflowed for this type.
5248 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5249 Constant *In2, bool IsSigned = false) {
5250 Result = ConstantExpr::getAdd(In1, In2);
5252 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5253 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5254 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5255 if (HasAddOverflow(ExtractElement(Result, Idx),
5256 ExtractElement(In1, Idx),
5257 ExtractElement(In2, Idx),
5264 return HasAddOverflow(cast<ConstantInt>(Result),
5265 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5269 static bool HasSubOverflow(ConstantInt *Result,
5270 ConstantInt *In1, ConstantInt *In2,
5273 if (In2->getValue().isNegative())
5274 return Result->getValue().slt(In1->getValue());
5276 return Result->getValue().sgt(In1->getValue());
5278 return Result->getValue().ugt(In1->getValue());
5281 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5282 /// overflowed for this type.
5283 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5284 Constant *In2, bool IsSigned = false) {
5285 Result = ConstantExpr::getSub(In1, In2);
5287 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5288 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5289 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5290 if (HasSubOverflow(ExtractElement(Result, Idx),
5291 ExtractElement(In1, Idx),
5292 ExtractElement(In2, Idx),
5299 return HasSubOverflow(cast<ConstantInt>(Result),
5300 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5304 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5305 /// code necessary to compute the offset from the base pointer (without adding
5306 /// in the base pointer). Return the result as a signed integer of intptr size.
5307 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5308 TargetData &TD = IC.getTargetData();
5309 gep_type_iterator GTI = gep_type_begin(GEP);
5310 const Type *IntPtrTy = TD.getIntPtrType();
5311 Value *Result = Constant::getNullValue(IntPtrTy);
5313 // Build a mask for high order bits.
5314 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5315 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5317 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5320 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5321 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5322 if (OpC->isZero()) continue;
5324 // Handle a struct index, which adds its field offset to the pointer.
5325 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5326 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5328 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5329 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5331 Result = IC.InsertNewInstBefore(
5332 BinaryOperator::CreateAdd(Result,
5333 ConstantInt::get(IntPtrTy, Size),
5334 GEP->getName()+".offs"), I);
5338 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5339 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5340 Scale = ConstantExpr::getMul(OC, Scale);
5341 if (Constant *RC = dyn_cast<Constant>(Result))
5342 Result = ConstantExpr::getAdd(RC, Scale);
5344 // Emit an add instruction.
5345 Result = IC.InsertNewInstBefore(
5346 BinaryOperator::CreateAdd(Result, Scale,
5347 GEP->getName()+".offs"), I);
5351 // Convert to correct type.
5352 if (Op->getType() != IntPtrTy) {
5353 if (Constant *OpC = dyn_cast<Constant>(Op))
5354 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5356 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5358 Op->getName()+".c"), I);
5361 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5362 if (Constant *OpC = dyn_cast<Constant>(Op))
5363 Op = ConstantExpr::getMul(OpC, Scale);
5364 else // We'll let instcombine(mul) convert this to a shl if possible.
5365 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5366 GEP->getName()+".idx"), I);
5369 // Emit an add instruction.
5370 if (isa<Constant>(Op) && isa<Constant>(Result))
5371 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5372 cast<Constant>(Result));
5374 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5375 GEP->getName()+".offs"), I);
5381 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5382 /// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5383 /// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5384 /// complex, and scales are involved. The above expression would also be legal
5385 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5386 /// later form is less amenable to optimization though, and we are allowed to
5387 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5389 /// If we can't emit an optimized form for this expression, this returns null.
5391 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5393 TargetData &TD = IC.getTargetData();
5394 gep_type_iterator GTI = gep_type_begin(GEP);
5396 // Check to see if this gep only has a single variable index. If so, and if
5397 // any constant indices are a multiple of its scale, then we can compute this
5398 // in terms of the scale of the variable index. For example, if the GEP
5399 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5400 // because the expression will cross zero at the same point.
5401 unsigned i, e = GEP->getNumOperands();
5403 for (i = 1; i != e; ++i, ++GTI) {
5404 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5405 // Compute the aggregate offset of constant indices.
5406 if (CI->isZero()) continue;
5408 // Handle a struct index, which adds its field offset to the pointer.
5409 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5410 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5412 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5413 Offset += Size*CI->getSExtValue();
5416 // Found our variable index.
5421 // If there are no variable indices, we must have a constant offset, just
5422 // evaluate it the general way.
5423 if (i == e) return 0;
5425 Value *VariableIdx = GEP->getOperand(i);
5426 // Determine the scale factor of the variable element. For example, this is
5427 // 4 if the variable index is into an array of i32.
5428 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5430 // Verify that there are no other variable indices. If so, emit the hard way.
5431 for (++i, ++GTI; i != e; ++i, ++GTI) {
5432 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5435 // Compute the aggregate offset of constant indices.
5436 if (CI->isZero()) continue;
5438 // Handle a struct index, which adds its field offset to the pointer.
5439 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5440 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5442 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5443 Offset += Size*CI->getSExtValue();
5447 // Okay, we know we have a single variable index, which must be a
5448 // pointer/array/vector index. If there is no offset, life is simple, return
5450 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5452 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5453 // we don't need to bother extending: the extension won't affect where the
5454 // computation crosses zero.
5455 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5456 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5457 VariableIdx->getNameStart(), &I);
5461 // Otherwise, there is an index. The computation we will do will be modulo
5462 // the pointer size, so get it.
5463 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5465 Offset &= PtrSizeMask;
5466 VariableScale &= PtrSizeMask;
5468 // To do this transformation, any constant index must be a multiple of the
5469 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5470 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5471 // multiple of the variable scale.
5472 int64_t NewOffs = Offset / (int64_t)VariableScale;
5473 if (Offset != NewOffs*(int64_t)VariableScale)
5476 // Okay, we can do this evaluation. Start by converting the index to intptr.
5477 const Type *IntPtrTy = TD.getIntPtrType();
5478 if (VariableIdx->getType() != IntPtrTy)
5479 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5481 VariableIdx->getNameStart(), &I);
5482 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5483 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5487 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5488 /// else. At this point we know that the GEP is on the LHS of the comparison.
5489 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5490 ICmpInst::Predicate Cond,
5492 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5494 // Look through bitcasts.
5495 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5496 RHS = BCI->getOperand(0);
5498 Value *PtrBase = GEPLHS->getOperand(0);
5499 if (PtrBase == RHS) {
5500 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5501 // This transformation (ignoring the base and scales) is valid because we
5502 // know pointers can't overflow. See if we can output an optimized form.
5503 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5505 // If not, synthesize the offset the hard way.
5507 Offset = EmitGEPOffset(GEPLHS, I, *this);
5508 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5509 Constant::getNullValue(Offset->getType()));
5510 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5511 // If the base pointers are different, but the indices are the same, just
5512 // compare the base pointer.
5513 if (PtrBase != GEPRHS->getOperand(0)) {
5514 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5515 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5516 GEPRHS->getOperand(0)->getType();
5518 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5519 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5520 IndicesTheSame = false;
5524 // If all indices are the same, just compare the base pointers.
5526 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5527 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5529 // Otherwise, the base pointers are different and the indices are
5530 // different, bail out.
5534 // If one of the GEPs has all zero indices, recurse.
5535 bool AllZeros = true;
5536 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5537 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5538 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5543 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5544 ICmpInst::getSwappedPredicate(Cond), I);
5546 // If the other GEP has all zero indices, recurse.
5548 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5549 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5550 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5555 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5557 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5558 // If the GEPs only differ by one index, compare it.
5559 unsigned NumDifferences = 0; // Keep track of # differences.
5560 unsigned DiffOperand = 0; // The operand that differs.
5561 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5562 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5563 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5564 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5565 // Irreconcilable differences.
5569 if (NumDifferences++) break;
5574 if (NumDifferences == 0) // SAME GEP?
5575 return ReplaceInstUsesWith(I, // No comparison is needed here.
5576 ConstantInt::get(Type::Int1Ty,
5577 ICmpInst::isTrueWhenEqual(Cond)));
5579 else if (NumDifferences == 1) {
5580 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5581 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5582 // Make sure we do a signed comparison here.
5583 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5587 // Only lower this if the icmp is the only user of the GEP or if we expect
5588 // the result to fold to a constant!
5589 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5590 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5591 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5592 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5593 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5594 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5600 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5602 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5605 if (!isa<ConstantFP>(RHSC)) return 0;
5606 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5608 // Get the width of the mantissa. We don't want to hack on conversions that
5609 // might lose information from the integer, e.g. "i64 -> float"
5610 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5611 if (MantissaWidth == -1) return 0; // Unknown.
5613 // Check to see that the input is converted from an integer type that is small
5614 // enough that preserves all bits. TODO: check here for "known" sign bits.
5615 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5616 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5618 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5619 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5623 // If the conversion would lose info, don't hack on this.
5624 if ((int)InputSize > MantissaWidth)
5627 // Otherwise, we can potentially simplify the comparison. We know that it
5628 // will always come through as an integer value and we know the constant is
5629 // not a NAN (it would have been previously simplified).
5630 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5632 ICmpInst::Predicate Pred;
5633 switch (I.getPredicate()) {
5634 default: assert(0 && "Unexpected predicate!");
5635 case FCmpInst::FCMP_UEQ:
5636 case FCmpInst::FCMP_OEQ:
5637 Pred = ICmpInst::ICMP_EQ;
5639 case FCmpInst::FCMP_UGT:
5640 case FCmpInst::FCMP_OGT:
5641 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5643 case FCmpInst::FCMP_UGE:
5644 case FCmpInst::FCMP_OGE:
5645 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5647 case FCmpInst::FCMP_ULT:
5648 case FCmpInst::FCMP_OLT:
5649 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5651 case FCmpInst::FCMP_ULE:
5652 case FCmpInst::FCMP_OLE:
5653 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5655 case FCmpInst::FCMP_UNE:
5656 case FCmpInst::FCMP_ONE:
5657 Pred = ICmpInst::ICMP_NE;
5659 case FCmpInst::FCMP_ORD:
5660 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5661 case FCmpInst::FCMP_UNO:
5662 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5665 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5667 // Now we know that the APFloat is a normal number, zero or inf.
5669 // See if the FP constant is too large for the integer. For example,
5670 // comparing an i8 to 300.0.
5671 unsigned IntWidth = IntTy->getScalarSizeInBits();
5674 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5675 // and large values.
5676 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5677 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5678 APFloat::rmNearestTiesToEven);
5679 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5680 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5681 Pred == ICmpInst::ICMP_SLE)
5682 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5683 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5686 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5687 // +INF and large values.
5688 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5689 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5690 APFloat::rmNearestTiesToEven);
5691 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5692 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5693 Pred == ICmpInst::ICMP_ULE)
5694 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5695 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5700 // See if the RHS value is < SignedMin.
5701 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5702 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5703 APFloat::rmNearestTiesToEven);
5704 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5705 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5706 Pred == ICmpInst::ICMP_SGE)
5707 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5708 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5712 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5713 // [0, UMAX], but it may still be fractional. See if it is fractional by
5714 // casting the FP value to the integer value and back, checking for equality.
5715 // Don't do this for zero, because -0.0 is not fractional.
5716 Constant *RHSInt = LHSUnsigned
5717 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5718 : ConstantExpr::getFPToSI(RHSC, IntTy);
5719 if (!RHS.isZero()) {
5720 bool Equal = LHSUnsigned
5721 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5722 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5724 // If we had a comparison against a fractional value, we have to adjust
5725 // the compare predicate and sometimes the value. RHSC is rounded towards
5726 // zero at this point.
5728 default: assert(0 && "Unexpected integer comparison!");
5729 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5730 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5731 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5732 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5733 case ICmpInst::ICMP_ULE:
5734 // (float)int <= 4.4 --> int <= 4
5735 // (float)int <= -4.4 --> false
5736 if (RHS.isNegative())
5737 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5739 case ICmpInst::ICMP_SLE:
5740 // (float)int <= 4.4 --> int <= 4
5741 // (float)int <= -4.4 --> int < -4
5742 if (RHS.isNegative())
5743 Pred = ICmpInst::ICMP_SLT;
5745 case ICmpInst::ICMP_ULT:
5746 // (float)int < -4.4 --> false
5747 // (float)int < 4.4 --> int <= 4
5748 if (RHS.isNegative())
5749 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5750 Pred = ICmpInst::ICMP_ULE;
5752 case ICmpInst::ICMP_SLT:
5753 // (float)int < -4.4 --> int < -4
5754 // (float)int < 4.4 --> int <= 4
5755 if (!RHS.isNegative())
5756 Pred = ICmpInst::ICMP_SLE;
5758 case ICmpInst::ICMP_UGT:
5759 // (float)int > 4.4 --> int > 4
5760 // (float)int > -4.4 --> true
5761 if (RHS.isNegative())
5762 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5764 case ICmpInst::ICMP_SGT:
5765 // (float)int > 4.4 --> int > 4
5766 // (float)int > -4.4 --> int >= -4
5767 if (RHS.isNegative())
5768 Pred = ICmpInst::ICMP_SGE;
5770 case ICmpInst::ICMP_UGE:
5771 // (float)int >= -4.4 --> true
5772 // (float)int >= 4.4 --> int > 4
5773 if (!RHS.isNegative())
5774 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5775 Pred = ICmpInst::ICMP_UGT;
5777 case ICmpInst::ICMP_SGE:
5778 // (float)int >= -4.4 --> int >= -4
5779 // (float)int >= 4.4 --> int > 4
5780 if (!RHS.isNegative())
5781 Pred = ICmpInst::ICMP_SGT;
5787 // Lower this FP comparison into an appropriate integer version of the
5789 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5792 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5793 bool Changed = SimplifyCompare(I);
5794 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5796 // Fold trivial predicates.
5797 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5798 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5799 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5800 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5802 // Simplify 'fcmp pred X, X'
5804 switch (I.getPredicate()) {
5805 default: assert(0 && "Unknown predicate!");
5806 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5807 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5808 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5809 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5810 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5811 case FCmpInst::FCMP_OLT: // True if ordered and less than
5812 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5813 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5815 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5816 case FCmpInst::FCMP_ULT: // True if unordered or less than
5817 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5818 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5819 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5820 I.setPredicate(FCmpInst::FCMP_UNO);
5821 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5824 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5825 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5826 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5827 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5828 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5829 I.setPredicate(FCmpInst::FCMP_ORD);
5830 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5835 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5836 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5838 // Handle fcmp with constant RHS
5839 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5840 // If the constant is a nan, see if we can fold the comparison based on it.
5841 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5842 if (CFP->getValueAPF().isNaN()) {
5843 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5844 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5845 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5846 "Comparison must be either ordered or unordered!");
5847 // True if unordered.
5848 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5852 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5853 switch (LHSI->getOpcode()) {
5854 case Instruction::PHI:
5855 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5856 // block. If in the same block, we're encouraging jump threading. If
5857 // not, we are just pessimizing the code by making an i1 phi.
5858 if (LHSI->getParent() == I.getParent())
5859 if (Instruction *NV = FoldOpIntoPhi(I))
5862 case Instruction::SIToFP:
5863 case Instruction::UIToFP:
5864 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5867 case Instruction::Select:
5868 // If either operand of the select is a constant, we can fold the
5869 // comparison into the select arms, which will cause one to be
5870 // constant folded and the select turned into a bitwise or.
5871 Value *Op1 = 0, *Op2 = 0;
5872 if (LHSI->hasOneUse()) {
5873 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5874 // Fold the known value into the constant operand.
5875 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5876 // Insert a new FCmp of the other select operand.
5877 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5878 LHSI->getOperand(2), RHSC,
5880 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5881 // Fold the known value into the constant operand.
5882 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5883 // Insert a new FCmp of the other select operand.
5884 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5885 LHSI->getOperand(1), RHSC,
5891 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5896 return Changed ? &I : 0;
5899 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5900 bool Changed = SimplifyCompare(I);
5901 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5902 const Type *Ty = Op0->getType();
5906 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5907 I.isTrueWhenEqual()));
5909 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5910 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5912 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5913 // addresses never equal each other! We already know that Op0 != Op1.
5914 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5915 isa<ConstantPointerNull>(Op0)) &&
5916 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5917 isa<ConstantPointerNull>(Op1)))
5918 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5919 !I.isTrueWhenEqual()));
5921 // icmp's with boolean values can always be turned into bitwise operations
5922 if (Ty == Type::Int1Ty) {
5923 switch (I.getPredicate()) {
5924 default: assert(0 && "Invalid icmp instruction!");
5925 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5926 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5927 InsertNewInstBefore(Xor, I);
5928 return BinaryOperator::CreateNot(Xor);
5930 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5931 return BinaryOperator::CreateXor(Op0, Op1);
5933 case ICmpInst::ICMP_UGT:
5934 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5936 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5937 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5938 InsertNewInstBefore(Not, I);
5939 return BinaryOperator::CreateAnd(Not, Op1);
5941 case ICmpInst::ICMP_SGT:
5942 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
5944 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5945 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5946 InsertNewInstBefore(Not, I);
5947 return BinaryOperator::CreateAnd(Not, Op0);
5949 case ICmpInst::ICMP_UGE:
5950 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5952 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
5953 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5954 InsertNewInstBefore(Not, I);
5955 return BinaryOperator::CreateOr(Not, Op1);
5957 case ICmpInst::ICMP_SGE:
5958 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5960 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5961 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5962 InsertNewInstBefore(Not, I);
5963 return BinaryOperator::CreateOr(Not, Op0);
5968 unsigned BitWidth = 0;
5970 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5971 else if (Ty->isIntOrIntVector())
5972 BitWidth = Ty->getScalarSizeInBits();
5974 bool isSignBit = false;
5976 // See if we are doing a comparison with a constant.
5977 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5978 Value *A = 0, *B = 0;
5980 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5981 if (I.isEquality() && CI->isNullValue() &&
5982 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5983 // (icmp cond A B) if cond is equality
5984 return new ICmpInst(I.getPredicate(), A, B);
5987 // If we have an icmp le or icmp ge instruction, turn it into the
5988 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5989 // them being folded in the code below.
5990 switch (I.getPredicate()) {
5992 case ICmpInst::ICMP_ULE:
5993 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5994 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5995 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5996 case ICmpInst::ICMP_SLE:
5997 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5998 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5999 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
6000 case ICmpInst::ICMP_UGE:
6001 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6002 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6003 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
6004 case ICmpInst::ICMP_SGE:
6005 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6006 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6007 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
6010 // If this comparison is a normal comparison, it demands all
6011 // bits, if it is a sign bit comparison, it only demands the sign bit.
6013 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6016 // See if we can fold the comparison based on range information we can get
6017 // by checking whether bits are known to be zero or one in the input.
6018 if (BitWidth != 0) {
6019 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6020 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6022 if (SimplifyDemandedBits(I.getOperandUse(0),
6023 isSignBit ? APInt::getSignBit(BitWidth)
6024 : APInt::getAllOnesValue(BitWidth),
6025 Op0KnownZero, Op0KnownOne, 0))
6027 if (SimplifyDemandedBits(I.getOperandUse(1),
6028 APInt::getAllOnesValue(BitWidth),
6029 Op1KnownZero, Op1KnownOne, 0))
6032 // Given the known and unknown bits, compute a range that the LHS could be
6033 // in. Compute the Min, Max and RHS values based on the known bits. For the
6034 // EQ and NE we use unsigned values.
6035 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6036 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6037 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6038 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6040 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6043 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6045 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6049 // If Min and Max are known to be the same, then SimplifyDemandedBits
6050 // figured out that the LHS is a constant. Just constant fold this now so
6051 // that code below can assume that Min != Max.
6052 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6053 return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
6054 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6055 return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
6057 // Based on the range information we know about the LHS, see if we can
6058 // simplify this comparison. For example, (x&4) < 8 is always true.
6059 switch (I.getPredicate()) {
6060 default: assert(0 && "Unknown icmp opcode!");
6061 case ICmpInst::ICMP_EQ:
6062 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6063 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6065 case ICmpInst::ICMP_NE:
6066 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6067 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6069 case ICmpInst::ICMP_ULT:
6070 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6071 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6072 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6073 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6074 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6075 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6076 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6077 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6078 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6080 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6081 if (CI->isMinValue(true))
6082 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6083 ConstantInt::getAllOnesValue(Op0->getType()));
6086 case ICmpInst::ICMP_UGT:
6087 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6088 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6089 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6090 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6092 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6093 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6094 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6095 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6096 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6098 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6099 if (CI->isMaxValue(true))
6100 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6101 ConstantInt::getNullValue(Op0->getType()));
6104 case ICmpInst::ICMP_SLT:
6105 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6106 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6107 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6108 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6109 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6110 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6112 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6113 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6116 case ICmpInst::ICMP_SGT:
6117 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6118 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6119 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6120 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6122 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6123 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6124 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6125 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6126 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6129 case ICmpInst::ICMP_SGE:
6130 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6131 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6132 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6133 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6134 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6136 case ICmpInst::ICMP_SLE:
6137 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6138 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6139 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6140 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6141 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6143 case ICmpInst::ICMP_UGE:
6144 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6145 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6146 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6147 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6148 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6150 case ICmpInst::ICMP_ULE:
6151 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6152 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6153 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6154 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6155 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6159 // Turn a signed comparison into an unsigned one if both operands
6160 // are known to have the same sign.
6161 if (I.isSignedPredicate() &&
6162 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6163 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6164 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6167 // Test if the ICmpInst instruction is used exclusively by a select as
6168 // part of a minimum or maximum operation. If so, refrain from doing
6169 // any other folding. This helps out other analyses which understand
6170 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6171 // and CodeGen. And in this case, at least one of the comparison
6172 // operands has at least one user besides the compare (the select),
6173 // which would often largely negate the benefit of folding anyway.
6175 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6176 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6177 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6180 // See if we are doing a comparison between a constant and an instruction that
6181 // can be folded into the comparison.
6182 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6183 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6184 // instruction, see if that instruction also has constants so that the
6185 // instruction can be folded into the icmp
6186 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6187 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6191 // Handle icmp with constant (but not simple integer constant) RHS
6192 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6193 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6194 switch (LHSI->getOpcode()) {
6195 case Instruction::GetElementPtr:
6196 if (RHSC->isNullValue()) {
6197 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6198 bool isAllZeros = true;
6199 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6200 if (!isa<Constant>(LHSI->getOperand(i)) ||
6201 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6206 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6207 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6211 case Instruction::PHI:
6212 // Only fold icmp into the PHI if the phi and fcmp are in the same
6213 // block. If in the same block, we're encouraging jump threading. If
6214 // not, we are just pessimizing the code by making an i1 phi.
6215 if (LHSI->getParent() == I.getParent())
6216 if (Instruction *NV = FoldOpIntoPhi(I))
6219 case Instruction::Select: {
6220 // If either operand of the select is a constant, we can fold the
6221 // comparison into the select arms, which will cause one to be
6222 // constant folded and the select turned into a bitwise or.
6223 Value *Op1 = 0, *Op2 = 0;
6224 if (LHSI->hasOneUse()) {
6225 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6226 // Fold the known value into the constant operand.
6227 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6228 // Insert a new ICmp of the other select operand.
6229 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6230 LHSI->getOperand(2), RHSC,
6232 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6233 // Fold the known value into the constant operand.
6234 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6235 // Insert a new ICmp of the other select operand.
6236 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6237 LHSI->getOperand(1), RHSC,
6243 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6246 case Instruction::Malloc:
6247 // If we have (malloc != null), and if the malloc has a single use, we
6248 // can assume it is successful and remove the malloc.
6249 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6250 AddToWorkList(LHSI);
6251 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6252 !I.isTrueWhenEqual()));
6258 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6259 if (User *GEP = dyn_castGetElementPtr(Op0))
6260 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6262 if (User *GEP = dyn_castGetElementPtr(Op1))
6263 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6264 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6267 // Test to see if the operands of the icmp are casted versions of other
6268 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6270 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6271 if (isa<PointerType>(Op0->getType()) &&
6272 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6273 // We keep moving the cast from the left operand over to the right
6274 // operand, where it can often be eliminated completely.
6275 Op0 = CI->getOperand(0);
6277 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6278 // so eliminate it as well.
6279 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6280 Op1 = CI2->getOperand(0);
6282 // If Op1 is a constant, we can fold the cast into the constant.
6283 if (Op0->getType() != Op1->getType()) {
6284 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6285 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6287 // Otherwise, cast the RHS right before the icmp
6288 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6291 return new ICmpInst(I.getPredicate(), Op0, Op1);
6295 if (isa<CastInst>(Op0)) {
6296 // Handle the special case of: icmp (cast bool to X), <cst>
6297 // This comes up when you have code like
6300 // For generality, we handle any zero-extension of any operand comparison
6301 // with a constant or another cast from the same type.
6302 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6303 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6307 // See if it's the same type of instruction on the left and right.
6308 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6309 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6310 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6311 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6312 switch (Op0I->getOpcode()) {
6314 case Instruction::Add:
6315 case Instruction::Sub:
6316 case Instruction::Xor:
6317 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6318 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6319 Op1I->getOperand(0));
6320 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6321 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6322 if (CI->getValue().isSignBit()) {
6323 ICmpInst::Predicate Pred = I.isSignedPredicate()
6324 ? I.getUnsignedPredicate()
6325 : I.getSignedPredicate();
6326 return new ICmpInst(Pred, Op0I->getOperand(0),
6327 Op1I->getOperand(0));
6330 if (CI->getValue().isMaxSignedValue()) {
6331 ICmpInst::Predicate Pred = I.isSignedPredicate()
6332 ? I.getUnsignedPredicate()
6333 : I.getSignedPredicate();
6334 Pred = I.getSwappedPredicate(Pred);
6335 return new ICmpInst(Pred, Op0I->getOperand(0),
6336 Op1I->getOperand(0));
6340 case Instruction::Mul:
6341 if (!I.isEquality())
6344 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6345 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6346 // Mask = -1 >> count-trailing-zeros(Cst).
6347 if (!CI->isZero() && !CI->isOne()) {
6348 const APInt &AP = CI->getValue();
6349 ConstantInt *Mask = ConstantInt::get(
6350 APInt::getLowBitsSet(AP.getBitWidth(),
6352 AP.countTrailingZeros()));
6353 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6355 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6357 InsertNewInstBefore(And1, I);
6358 InsertNewInstBefore(And2, I);
6359 return new ICmpInst(I.getPredicate(), And1, And2);
6368 // ~x < ~y --> y < x
6370 if (match(Op0, m_Not(m_Value(A))) &&
6371 match(Op1, m_Not(m_Value(B))))
6372 return new ICmpInst(I.getPredicate(), B, A);
6375 if (I.isEquality()) {
6376 Value *A, *B, *C, *D;
6378 // -x == -y --> x == y
6379 if (match(Op0, m_Neg(m_Value(A))) &&
6380 match(Op1, m_Neg(m_Value(B))))
6381 return new ICmpInst(I.getPredicate(), A, B);
6383 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6384 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6385 Value *OtherVal = A == Op1 ? B : A;
6386 return new ICmpInst(I.getPredicate(), OtherVal,
6387 Constant::getNullValue(A->getType()));
6390 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6391 // A^c1 == C^c2 --> A == C^(c1^c2)
6392 ConstantInt *C1, *C2;
6393 if (match(B, m_ConstantInt(C1)) &&
6394 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6395 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6396 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6397 return new ICmpInst(I.getPredicate(), A,
6398 InsertNewInstBefore(Xor, I));
6401 // A^B == A^D -> B == D
6402 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6403 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6404 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6405 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6409 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6410 (A == Op0 || B == Op0)) {
6411 // A == (A^B) -> B == 0
6412 Value *OtherVal = A == Op0 ? B : A;
6413 return new ICmpInst(I.getPredicate(), OtherVal,
6414 Constant::getNullValue(A->getType()));
6417 // (A-B) == A -> B == 0
6418 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6419 return new ICmpInst(I.getPredicate(), B,
6420 Constant::getNullValue(B->getType()));
6422 // A == (A-B) -> B == 0
6423 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6424 return new ICmpInst(I.getPredicate(), B,
6425 Constant::getNullValue(B->getType()));
6427 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6428 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6429 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6430 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6431 Value *X = 0, *Y = 0, *Z = 0;
6434 X = B; Y = D; Z = A;
6435 } else if (A == D) {
6436 X = B; Y = C; Z = A;
6437 } else if (B == C) {
6438 X = A; Y = D; Z = B;
6439 } else if (B == D) {
6440 X = A; Y = C; Z = B;
6443 if (X) { // Build (X^Y) & Z
6444 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6445 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6446 I.setOperand(0, Op1);
6447 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6452 return Changed ? &I : 0;
6456 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6457 /// and CmpRHS are both known to be integer constants.
6458 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6459 ConstantInt *DivRHS) {
6460 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6461 const APInt &CmpRHSV = CmpRHS->getValue();
6463 // FIXME: If the operand types don't match the type of the divide
6464 // then don't attempt this transform. The code below doesn't have the
6465 // logic to deal with a signed divide and an unsigned compare (and
6466 // vice versa). This is because (x /s C1) <s C2 produces different
6467 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6468 // (x /u C1) <u C2. Simply casting the operands and result won't
6469 // work. :( The if statement below tests that condition and bails
6471 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6472 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6474 if (DivRHS->isZero())
6475 return 0; // The ProdOV computation fails on divide by zero.
6476 if (DivIsSigned && DivRHS->isAllOnesValue())
6477 return 0; // The overflow computation also screws up here
6478 if (DivRHS->isOne())
6479 return 0; // Not worth bothering, and eliminates some funny cases
6482 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6483 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6484 // C2 (CI). By solving for X we can turn this into a range check
6485 // instead of computing a divide.
6486 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6488 // Determine if the product overflows by seeing if the product is
6489 // not equal to the divide. Make sure we do the same kind of divide
6490 // as in the LHS instruction that we're folding.
6491 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6492 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6494 // Get the ICmp opcode
6495 ICmpInst::Predicate Pred = ICI.getPredicate();
6497 // Figure out the interval that is being checked. For example, a comparison
6498 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6499 // Compute this interval based on the constants involved and the signedness of
6500 // the compare/divide. This computes a half-open interval, keeping track of
6501 // whether either value in the interval overflows. After analysis each
6502 // overflow variable is set to 0 if it's corresponding bound variable is valid
6503 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6504 int LoOverflow = 0, HiOverflow = 0;
6505 Constant *LoBound = 0, *HiBound = 0;
6507 if (!DivIsSigned) { // udiv
6508 // e.g. X/5 op 3 --> [15, 20)
6510 HiOverflow = LoOverflow = ProdOV;
6512 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6513 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6514 if (CmpRHSV == 0) { // (X / pos) op 0
6515 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6516 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6518 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6519 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6520 HiOverflow = LoOverflow = ProdOV;
6522 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6523 } else { // (X / pos) op neg
6524 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6525 HiBound = AddOne(Prod);
6526 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6528 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6529 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6533 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6534 if (CmpRHSV == 0) { // (X / neg) op 0
6535 // e.g. X/-5 op 0 --> [-4, 5)
6536 LoBound = AddOne(DivRHS);
6537 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6538 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6539 HiOverflow = 1; // [INTMIN+1, overflow)
6540 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6542 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6543 // e.g. X/-5 op 3 --> [-19, -14)
6544 HiBound = AddOne(Prod);
6545 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6547 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6548 } else { // (X / neg) op neg
6549 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6550 LoOverflow = HiOverflow = ProdOV;
6552 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6555 // Dividing by a negative swaps the condition. LT <-> GT
6556 Pred = ICmpInst::getSwappedPredicate(Pred);
6559 Value *X = DivI->getOperand(0);
6561 default: assert(0 && "Unhandled icmp opcode!");
6562 case ICmpInst::ICMP_EQ:
6563 if (LoOverflow && HiOverflow)
6564 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6565 else if (HiOverflow)
6566 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6567 ICmpInst::ICMP_UGE, X, LoBound);
6568 else if (LoOverflow)
6569 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6570 ICmpInst::ICMP_ULT, X, HiBound);
6572 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6573 case ICmpInst::ICMP_NE:
6574 if (LoOverflow && HiOverflow)
6575 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6576 else if (HiOverflow)
6577 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6578 ICmpInst::ICMP_ULT, X, LoBound);
6579 else if (LoOverflow)
6580 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6581 ICmpInst::ICMP_UGE, X, HiBound);
6583 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6584 case ICmpInst::ICMP_ULT:
6585 case ICmpInst::ICMP_SLT:
6586 if (LoOverflow == +1) // Low bound is greater than input range.
6587 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6588 if (LoOverflow == -1) // Low bound is less than input range.
6589 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6590 return new ICmpInst(Pred, X, LoBound);
6591 case ICmpInst::ICMP_UGT:
6592 case ICmpInst::ICMP_SGT:
6593 if (HiOverflow == +1) // High bound greater than input range.
6594 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6595 else if (HiOverflow == -1) // High bound less than input range.
6596 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6597 if (Pred == ICmpInst::ICMP_UGT)
6598 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6600 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6605 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6607 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6610 const APInt &RHSV = RHS->getValue();
6612 switch (LHSI->getOpcode()) {
6613 case Instruction::Trunc:
6614 if (ICI.isEquality() && LHSI->hasOneUse()) {
6615 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6616 // of the high bits truncated out of x are known.
6617 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6618 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6619 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6620 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6621 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6623 // If all the high bits are known, we can do this xform.
6624 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6625 // Pull in the high bits from known-ones set.
6626 APInt NewRHS(RHS->getValue());
6627 NewRHS.zext(SrcBits);
6629 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6630 ConstantInt::get(NewRHS));
6635 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6636 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6637 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6639 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6640 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6641 Value *CompareVal = LHSI->getOperand(0);
6643 // If the sign bit of the XorCST is not set, there is no change to
6644 // the operation, just stop using the Xor.
6645 if (!XorCST->getValue().isNegative()) {
6646 ICI.setOperand(0, CompareVal);
6647 AddToWorkList(LHSI);
6651 // Was the old condition true if the operand is positive?
6652 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6654 // If so, the new one isn't.
6655 isTrueIfPositive ^= true;
6657 if (isTrueIfPositive)
6658 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6660 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6663 if (LHSI->hasOneUse()) {
6664 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6665 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6666 const APInt &SignBit = XorCST->getValue();
6667 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6668 ? ICI.getUnsignedPredicate()
6669 : ICI.getSignedPredicate();
6670 return new ICmpInst(Pred, LHSI->getOperand(0),
6671 ConstantInt::get(RHSV ^ SignBit));
6674 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6675 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6676 const APInt &NotSignBit = XorCST->getValue();
6677 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6678 ? ICI.getUnsignedPredicate()
6679 : ICI.getSignedPredicate();
6680 Pred = ICI.getSwappedPredicate(Pred);
6681 return new ICmpInst(Pred, LHSI->getOperand(0),
6682 ConstantInt::get(RHSV ^ NotSignBit));
6687 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6688 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6689 LHSI->getOperand(0)->hasOneUse()) {
6690 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6692 // If the LHS is an AND of a truncating cast, we can widen the
6693 // and/compare to be the input width without changing the value
6694 // produced, eliminating a cast.
6695 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6696 // We can do this transformation if either the AND constant does not
6697 // have its sign bit set or if it is an equality comparison.
6698 // Extending a relational comparison when we're checking the sign
6699 // bit would not work.
6700 if (Cast->hasOneUse() &&
6701 (ICI.isEquality() ||
6702 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6704 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6705 APInt NewCST = AndCST->getValue();
6706 NewCST.zext(BitWidth);
6708 NewCI.zext(BitWidth);
6709 Instruction *NewAnd =
6710 BinaryOperator::CreateAnd(Cast->getOperand(0),
6711 ConstantInt::get(NewCST),LHSI->getName());
6712 InsertNewInstBefore(NewAnd, ICI);
6713 return new ICmpInst(ICI.getPredicate(), NewAnd,
6714 ConstantInt::get(NewCI));
6718 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6719 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6720 // happens a LOT in code produced by the C front-end, for bitfield
6722 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6723 if (Shift && !Shift->isShift())
6727 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6728 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6729 const Type *AndTy = AndCST->getType(); // Type of the and.
6731 // We can fold this as long as we can't shift unknown bits
6732 // into the mask. This can only happen with signed shift
6733 // rights, as they sign-extend.
6735 bool CanFold = Shift->isLogicalShift();
6737 // To test for the bad case of the signed shr, see if any
6738 // of the bits shifted in could be tested after the mask.
6739 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6740 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6742 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6743 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6744 AndCST->getValue()) == 0)
6750 if (Shift->getOpcode() == Instruction::Shl)
6751 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6753 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6755 // Check to see if we are shifting out any of the bits being
6757 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6758 // If we shifted bits out, the fold is not going to work out.
6759 // As a special case, check to see if this means that the
6760 // result is always true or false now.
6761 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6762 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6763 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6764 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6766 ICI.setOperand(1, NewCst);
6767 Constant *NewAndCST;
6768 if (Shift->getOpcode() == Instruction::Shl)
6769 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6771 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6772 LHSI->setOperand(1, NewAndCST);
6773 LHSI->setOperand(0, Shift->getOperand(0));
6774 AddToWorkList(Shift); // Shift is dead.
6775 AddUsesToWorkList(ICI);
6781 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6782 // preferable because it allows the C<<Y expression to be hoisted out
6783 // of a loop if Y is invariant and X is not.
6784 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6785 ICI.isEquality() && !Shift->isArithmeticShift() &&
6786 !isa<Constant>(Shift->getOperand(0))) {
6789 if (Shift->getOpcode() == Instruction::LShr) {
6790 NS = BinaryOperator::CreateShl(AndCST,
6791 Shift->getOperand(1), "tmp");
6793 // Insert a logical shift.
6794 NS = BinaryOperator::CreateLShr(AndCST,
6795 Shift->getOperand(1), "tmp");
6797 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6799 // Compute X & (C << Y).
6800 Instruction *NewAnd =
6801 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6802 InsertNewInstBefore(NewAnd, ICI);
6804 ICI.setOperand(0, NewAnd);
6810 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6811 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6814 uint32_t TypeBits = RHSV.getBitWidth();
6816 // Check that the shift amount is in range. If not, don't perform
6817 // undefined shifts. When the shift is visited it will be
6819 if (ShAmt->uge(TypeBits))
6822 if (ICI.isEquality()) {
6823 // If we are comparing against bits always shifted out, the
6824 // comparison cannot succeed.
6826 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6827 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6828 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6829 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6830 return ReplaceInstUsesWith(ICI, Cst);
6833 if (LHSI->hasOneUse()) {
6834 // Otherwise strength reduce the shift into an and.
6835 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6837 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6840 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6841 Mask, LHSI->getName()+".mask");
6842 Value *And = InsertNewInstBefore(AndI, ICI);
6843 return new ICmpInst(ICI.getPredicate(), And,
6844 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6848 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6849 bool TrueIfSigned = false;
6850 if (LHSI->hasOneUse() &&
6851 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6852 // (X << 31) <s 0 --> (X&1) != 0
6853 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6854 (TypeBits-ShAmt->getZExtValue()-1));
6856 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6857 Mask, LHSI->getName()+".mask");
6858 Value *And = InsertNewInstBefore(AndI, ICI);
6860 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6861 And, Constant::getNullValue(And->getType()));
6866 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6867 case Instruction::AShr: {
6868 // Only handle equality comparisons of shift-by-constant.
6869 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6870 if (!ShAmt || !ICI.isEquality()) break;
6872 // Check that the shift amount is in range. If not, don't perform
6873 // undefined shifts. When the shift is visited it will be
6875 uint32_t TypeBits = RHSV.getBitWidth();
6876 if (ShAmt->uge(TypeBits))
6879 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6881 // If we are comparing against bits always shifted out, the
6882 // comparison cannot succeed.
6883 APInt Comp = RHSV << ShAmtVal;
6884 if (LHSI->getOpcode() == Instruction::LShr)
6885 Comp = Comp.lshr(ShAmtVal);
6887 Comp = Comp.ashr(ShAmtVal);
6889 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6890 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6891 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6892 return ReplaceInstUsesWith(ICI, Cst);
6895 // Otherwise, check to see if the bits shifted out are known to be zero.
6896 // If so, we can compare against the unshifted value:
6897 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6898 if (LHSI->hasOneUse() &&
6899 MaskedValueIsZero(LHSI->getOperand(0),
6900 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6901 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6902 ConstantExpr::getShl(RHS, ShAmt));
6905 if (LHSI->hasOneUse()) {
6906 // Otherwise strength reduce the shift into an and.
6907 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6908 Constant *Mask = ConstantInt::get(Val);
6911 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6912 Mask, LHSI->getName()+".mask");
6913 Value *And = InsertNewInstBefore(AndI, ICI);
6914 return new ICmpInst(ICI.getPredicate(), And,
6915 ConstantExpr::getShl(RHS, ShAmt));
6920 case Instruction::SDiv:
6921 case Instruction::UDiv:
6922 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6923 // Fold this div into the comparison, producing a range check.
6924 // Determine, based on the divide type, what the range is being
6925 // checked. If there is an overflow on the low or high side, remember
6926 // it, otherwise compute the range [low, hi) bounding the new value.
6927 // See: InsertRangeTest above for the kinds of replacements possible.
6928 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6929 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6934 case Instruction::Add:
6935 // Fold: icmp pred (add, X, C1), C2
6937 if (!ICI.isEquality()) {
6938 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6940 const APInt &LHSV = LHSC->getValue();
6942 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6945 if (ICI.isSignedPredicate()) {
6946 if (CR.getLower().isSignBit()) {
6947 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6948 ConstantInt::get(CR.getUpper()));
6949 } else if (CR.getUpper().isSignBit()) {
6950 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6951 ConstantInt::get(CR.getLower()));
6954 if (CR.getLower().isMinValue()) {
6955 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6956 ConstantInt::get(CR.getUpper()));
6957 } else if (CR.getUpper().isMinValue()) {
6958 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6959 ConstantInt::get(CR.getLower()));
6966 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6967 if (ICI.isEquality()) {
6968 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6970 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6971 // the second operand is a constant, simplify a bit.
6972 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6973 switch (BO->getOpcode()) {
6974 case Instruction::SRem:
6975 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6976 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6977 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6978 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6979 Instruction *NewRem =
6980 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6982 InsertNewInstBefore(NewRem, ICI);
6983 return new ICmpInst(ICI.getPredicate(), NewRem,
6984 Constant::getNullValue(BO->getType()));
6988 case Instruction::Add:
6989 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6990 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6991 if (BO->hasOneUse())
6992 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6993 ConstantExpr::getSub(RHS, BOp1C));
6994 } else if (RHSV == 0) {
6995 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6996 // efficiently invertible, or if the add has just this one use.
6997 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6999 if (Value *NegVal = dyn_castNegVal(BOp1))
7000 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7001 else if (Value *NegVal = dyn_castNegVal(BOp0))
7002 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7003 else if (BO->hasOneUse()) {
7004 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7005 InsertNewInstBefore(Neg, ICI);
7007 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7011 case Instruction::Xor:
7012 // For the xor case, we can xor two constants together, eliminating
7013 // the explicit xor.
7014 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7015 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7016 ConstantExpr::getXor(RHS, BOC));
7019 case Instruction::Sub:
7020 // Replace (([sub|xor] A, B) != 0) with (A != B)
7022 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7026 case Instruction::Or:
7027 // If bits are being or'd in that are not present in the constant we
7028 // are comparing against, then the comparison could never succeed!
7029 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7030 Constant *NotCI = ConstantExpr::getNot(RHS);
7031 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7032 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7037 case Instruction::And:
7038 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7039 // If bits are being compared against that are and'd out, then the
7040 // comparison can never succeed!
7041 if ((RHSV & ~BOC->getValue()) != 0)
7042 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7045 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7046 if (RHS == BOC && RHSV.isPowerOf2())
7047 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7048 ICmpInst::ICMP_NE, LHSI,
7049 Constant::getNullValue(RHS->getType()));
7051 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7052 if (BOC->getValue().isSignBit()) {
7053 Value *X = BO->getOperand(0);
7054 Constant *Zero = Constant::getNullValue(X->getType());
7055 ICmpInst::Predicate pred = isICMP_NE ?
7056 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7057 return new ICmpInst(pred, X, Zero);
7060 // ((X & ~7) == 0) --> X < 8
7061 if (RHSV == 0 && isHighOnes(BOC)) {
7062 Value *X = BO->getOperand(0);
7063 Constant *NegX = ConstantExpr::getNeg(BOC);
7064 ICmpInst::Predicate pred = isICMP_NE ?
7065 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7066 return new ICmpInst(pred, X, NegX);
7071 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7072 // Handle icmp {eq|ne} <intrinsic>, intcst.
7073 if (II->getIntrinsicID() == Intrinsic::bswap) {
7075 ICI.setOperand(0, II->getOperand(1));
7076 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
7084 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7085 /// We only handle extending casts so far.
7087 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7088 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7089 Value *LHSCIOp = LHSCI->getOperand(0);
7090 const Type *SrcTy = LHSCIOp->getType();
7091 const Type *DestTy = LHSCI->getType();
7094 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7095 // integer type is the same size as the pointer type.
7096 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7097 getTargetData().getPointerSizeInBits() ==
7098 cast<IntegerType>(DestTy)->getBitWidth()) {
7100 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7101 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7102 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7103 RHSOp = RHSC->getOperand(0);
7104 // If the pointer types don't match, insert a bitcast.
7105 if (LHSCIOp->getType() != RHSOp->getType())
7106 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7110 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7113 // The code below only handles extension cast instructions, so far.
7115 if (LHSCI->getOpcode() != Instruction::ZExt &&
7116 LHSCI->getOpcode() != Instruction::SExt)
7119 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7120 bool isSignedCmp = ICI.isSignedPredicate();
7122 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7123 // Not an extension from the same type?
7124 RHSCIOp = CI->getOperand(0);
7125 if (RHSCIOp->getType() != LHSCIOp->getType())
7128 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7129 // and the other is a zext), then we can't handle this.
7130 if (CI->getOpcode() != LHSCI->getOpcode())
7133 // Deal with equality cases early.
7134 if (ICI.isEquality())
7135 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7137 // A signed comparison of sign extended values simplifies into a
7138 // signed comparison.
7139 if (isSignedCmp && isSignedExt)
7140 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7142 // The other three cases all fold into an unsigned comparison.
7143 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7146 // If we aren't dealing with a constant on the RHS, exit early
7147 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7151 // Compute the constant that would happen if we truncated to SrcTy then
7152 // reextended to DestTy.
7153 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7154 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7156 // If the re-extended constant didn't change...
7158 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7159 // For example, we might have:
7160 // %A = sext i16 %X to i32
7161 // %B = icmp ugt i32 %A, 1330
7162 // It is incorrect to transform this into
7163 // %B = icmp ugt i16 %X, 1330
7164 // because %A may have negative value.
7166 // However, we allow this when the compare is EQ/NE, because they are
7168 if (isSignedExt == isSignedCmp || ICI.isEquality())
7169 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7173 // The re-extended constant changed so the constant cannot be represented
7174 // in the shorter type. Consequently, we cannot emit a simple comparison.
7176 // First, handle some easy cases. We know the result cannot be equal at this
7177 // point so handle the ICI.isEquality() cases
7178 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7179 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
7180 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7181 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
7183 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7184 // should have been folded away previously and not enter in here.
7187 // We're performing a signed comparison.
7188 if (cast<ConstantInt>(CI)->getValue().isNegative())
7189 Result = ConstantInt::getFalse(); // X < (small) --> false
7191 Result = ConstantInt::getTrue(); // X < (large) --> true
7193 // We're performing an unsigned comparison.
7195 // We're performing an unsigned comp with a sign extended value.
7196 // This is true if the input is >= 0. [aka >s -1]
7197 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
7198 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7199 NegOne, ICI.getName()), ICI);
7201 // Unsigned extend & unsigned compare -> always true.
7202 Result = ConstantInt::getTrue();
7206 // Finally, return the value computed.
7207 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7208 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7209 return ReplaceInstUsesWith(ICI, Result);
7211 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7212 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7213 "ICmp should be folded!");
7214 if (Constant *CI = dyn_cast<Constant>(Result))
7215 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7216 return BinaryOperator::CreateNot(Result);
7219 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7220 return commonShiftTransforms(I);
7223 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7224 return commonShiftTransforms(I);
7227 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7228 if (Instruction *R = commonShiftTransforms(I))
7231 Value *Op0 = I.getOperand(0);
7233 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7234 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7235 if (CSI->isAllOnesValue())
7236 return ReplaceInstUsesWith(I, CSI);
7238 // See if we can turn a signed shr into an unsigned shr.
7239 if (MaskedValueIsZero(Op0,
7240 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7241 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7243 // Arithmetic shifting an all-sign-bit value is a no-op.
7244 unsigned NumSignBits = ComputeNumSignBits(Op0);
7245 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7246 return ReplaceInstUsesWith(I, Op0);
7251 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7252 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7255 // shl X, 0 == X and shr X, 0 == X
7256 // shl 0, X == 0 and shr 0, X == 0
7257 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7258 Op0 == Constant::getNullValue(Op0->getType()))
7259 return ReplaceInstUsesWith(I, Op0);
7261 if (isa<UndefValue>(Op0)) {
7262 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7263 return ReplaceInstUsesWith(I, Op0);
7264 else // undef << X -> 0, undef >>u X -> 0
7265 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7267 if (isa<UndefValue>(Op1)) {
7268 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7269 return ReplaceInstUsesWith(I, Op0);
7270 else // X << undef, X >>u undef -> 0
7271 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7274 // See if we can fold away this shift.
7275 if (SimplifyDemandedInstructionBits(I))
7278 // Try to fold constant and into select arguments.
7279 if (isa<Constant>(Op0))
7280 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7281 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7284 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7285 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7290 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7291 BinaryOperator &I) {
7292 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7294 // See if we can simplify any instructions used by the instruction whose sole
7295 // purpose is to compute bits we don't care about.
7296 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7298 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7301 if (Op1->uge(TypeBits)) {
7302 if (I.getOpcode() != Instruction::AShr)
7303 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7305 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7310 // ((X*C1) << C2) == (X * (C1 << C2))
7311 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7312 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7313 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7314 return BinaryOperator::CreateMul(BO->getOperand(0),
7315 ConstantExpr::getShl(BOOp, Op1));
7317 // Try to fold constant and into select arguments.
7318 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7319 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7321 if (isa<PHINode>(Op0))
7322 if (Instruction *NV = FoldOpIntoPhi(I))
7325 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7326 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7327 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7328 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7329 // place. Don't try to do this transformation in this case. Also, we
7330 // require that the input operand is a shift-by-constant so that we have
7331 // confidence that the shifts will get folded together. We could do this
7332 // xform in more cases, but it is unlikely to be profitable.
7333 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7334 isa<ConstantInt>(TrOp->getOperand(1))) {
7335 // Okay, we'll do this xform. Make the shift of shift.
7336 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7337 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7339 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7341 // For logical shifts, the truncation has the effect of making the high
7342 // part of the register be zeros. Emulate this by inserting an AND to
7343 // clear the top bits as needed. This 'and' will usually be zapped by
7344 // other xforms later if dead.
7345 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7346 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7347 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7349 // The mask we constructed says what the trunc would do if occurring
7350 // between the shifts. We want to know the effect *after* the second
7351 // shift. We know that it is a logical shift by a constant, so adjust the
7352 // mask as appropriate.
7353 if (I.getOpcode() == Instruction::Shl)
7354 MaskV <<= Op1->getZExtValue();
7356 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7357 MaskV = MaskV.lshr(Op1->getZExtValue());
7360 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7362 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7364 // Return the value truncated to the interesting size.
7365 return new TruncInst(And, I.getType());
7369 if (Op0->hasOneUse()) {
7370 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7371 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7374 switch (Op0BO->getOpcode()) {
7376 case Instruction::Add:
7377 case Instruction::And:
7378 case Instruction::Or:
7379 case Instruction::Xor: {
7380 // These operators commute.
7381 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7382 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7383 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7384 Instruction *YS = BinaryOperator::CreateShl(
7385 Op0BO->getOperand(0), Op1,
7387 InsertNewInstBefore(YS, I); // (Y << C)
7389 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7390 Op0BO->getOperand(1)->getName());
7391 InsertNewInstBefore(X, I); // (X + (Y << C))
7392 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7393 return BinaryOperator::CreateAnd(X, ConstantInt::get(
7394 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7397 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7398 Value *Op0BOOp1 = Op0BO->getOperand(1);
7399 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7401 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7402 m_ConstantInt(CC))) &&
7403 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7404 Instruction *YS = BinaryOperator::CreateShl(
7405 Op0BO->getOperand(0), Op1,
7407 InsertNewInstBefore(YS, I); // (Y << C)
7409 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7410 V1->getName()+".mask");
7411 InsertNewInstBefore(XM, I); // X & (CC << C)
7413 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7418 case Instruction::Sub: {
7419 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7420 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7421 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7422 Instruction *YS = BinaryOperator::CreateShl(
7423 Op0BO->getOperand(1), Op1,
7425 InsertNewInstBefore(YS, I); // (Y << C)
7427 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7428 Op0BO->getOperand(0)->getName());
7429 InsertNewInstBefore(X, I); // (X + (Y << C))
7430 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7431 return BinaryOperator::CreateAnd(X, ConstantInt::get(
7432 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7435 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7436 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7437 match(Op0BO->getOperand(0),
7438 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7439 m_ConstantInt(CC))) && V2 == Op1 &&
7440 cast<BinaryOperator>(Op0BO->getOperand(0))
7441 ->getOperand(0)->hasOneUse()) {
7442 Instruction *YS = BinaryOperator::CreateShl(
7443 Op0BO->getOperand(1), Op1,
7445 InsertNewInstBefore(YS, I); // (Y << C)
7447 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7448 V1->getName()+".mask");
7449 InsertNewInstBefore(XM, I); // X & (CC << C)
7451 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7459 // If the operand is an bitwise operator with a constant RHS, and the
7460 // shift is the only use, we can pull it out of the shift.
7461 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7462 bool isValid = true; // Valid only for And, Or, Xor
7463 bool highBitSet = false; // Transform if high bit of constant set?
7465 switch (Op0BO->getOpcode()) {
7466 default: isValid = false; break; // Do not perform transform!
7467 case Instruction::Add:
7468 isValid = isLeftShift;
7470 case Instruction::Or:
7471 case Instruction::Xor:
7474 case Instruction::And:
7479 // If this is a signed shift right, and the high bit is modified
7480 // by the logical operation, do not perform the transformation.
7481 // The highBitSet boolean indicates the value of the high bit of
7482 // the constant which would cause it to be modified for this
7485 if (isValid && I.getOpcode() == Instruction::AShr)
7486 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7489 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7491 Instruction *NewShift =
7492 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7493 InsertNewInstBefore(NewShift, I);
7494 NewShift->takeName(Op0BO);
7496 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7503 // Find out if this is a shift of a shift by a constant.
7504 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7505 if (ShiftOp && !ShiftOp->isShift())
7508 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7509 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7510 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7511 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7512 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7513 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7514 Value *X = ShiftOp->getOperand(0);
7516 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7518 const IntegerType *Ty = cast<IntegerType>(I.getType());
7520 // Check for (X << c1) << c2 and (X >> c1) >> c2
7521 if (I.getOpcode() == ShiftOp->getOpcode()) {
7522 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7524 if (AmtSum >= TypeBits) {
7525 if (I.getOpcode() != Instruction::AShr)
7526 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7527 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7530 return BinaryOperator::Create(I.getOpcode(), X,
7531 ConstantInt::get(Ty, AmtSum));
7532 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7533 I.getOpcode() == Instruction::AShr) {
7534 if (AmtSum >= TypeBits)
7535 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7537 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7538 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7539 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7540 I.getOpcode() == Instruction::LShr) {
7541 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7542 if (AmtSum >= TypeBits)
7543 AmtSum = TypeBits-1;
7545 Instruction *Shift =
7546 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7547 InsertNewInstBefore(Shift, I);
7549 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7550 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7553 // Okay, if we get here, one shift must be left, and the other shift must be
7554 // right. See if the amounts are equal.
7555 if (ShiftAmt1 == ShiftAmt2) {
7556 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7557 if (I.getOpcode() == Instruction::Shl) {
7558 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7559 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7561 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7562 if (I.getOpcode() == Instruction::LShr) {
7563 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7564 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7566 // We can simplify ((X << C) >>s C) into a trunc + sext.
7567 // NOTE: we could do this for any C, but that would make 'unusual' integer
7568 // types. For now, just stick to ones well-supported by the code
7570 const Type *SExtType = 0;
7571 switch (Ty->getBitWidth() - ShiftAmt1) {
7578 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7583 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7584 InsertNewInstBefore(NewTrunc, I);
7585 return new SExtInst(NewTrunc, Ty);
7587 // Otherwise, we can't handle it yet.
7588 } else if (ShiftAmt1 < ShiftAmt2) {
7589 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7591 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7592 if (I.getOpcode() == Instruction::Shl) {
7593 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7594 ShiftOp->getOpcode() == Instruction::AShr);
7595 Instruction *Shift =
7596 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7597 InsertNewInstBefore(Shift, I);
7599 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7600 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7603 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7604 if (I.getOpcode() == Instruction::LShr) {
7605 assert(ShiftOp->getOpcode() == Instruction::Shl);
7606 Instruction *Shift =
7607 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7608 InsertNewInstBefore(Shift, I);
7610 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7611 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7614 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7616 assert(ShiftAmt2 < ShiftAmt1);
7617 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7619 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7620 if (I.getOpcode() == Instruction::Shl) {
7621 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7622 ShiftOp->getOpcode() == Instruction::AShr);
7623 Instruction *Shift =
7624 BinaryOperator::Create(ShiftOp->getOpcode(), X,
7625 ConstantInt::get(Ty, ShiftDiff));
7626 InsertNewInstBefore(Shift, I);
7628 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7629 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7632 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7633 if (I.getOpcode() == Instruction::LShr) {
7634 assert(ShiftOp->getOpcode() == Instruction::Shl);
7635 Instruction *Shift =
7636 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7637 InsertNewInstBefore(Shift, I);
7639 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7640 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7643 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7650 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7651 /// expression. If so, decompose it, returning some value X, such that Val is
7654 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7656 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7657 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7658 Offset = CI->getZExtValue();
7660 return ConstantInt::get(Type::Int32Ty, 0);
7661 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7662 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7663 if (I->getOpcode() == Instruction::Shl) {
7664 // This is a value scaled by '1 << the shift amt'.
7665 Scale = 1U << RHS->getZExtValue();
7667 return I->getOperand(0);
7668 } else if (I->getOpcode() == Instruction::Mul) {
7669 // This value is scaled by 'RHS'.
7670 Scale = RHS->getZExtValue();
7672 return I->getOperand(0);
7673 } else if (I->getOpcode() == Instruction::Add) {
7674 // We have X+C. Check to see if we really have (X*C2)+C1,
7675 // where C1 is divisible by C2.
7678 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7679 Offset += RHS->getZExtValue();
7686 // Otherwise, we can't look past this.
7693 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7694 /// try to eliminate the cast by moving the type information into the alloc.
7695 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7696 AllocationInst &AI) {
7697 const PointerType *PTy = cast<PointerType>(CI.getType());
7699 // Remove any uses of AI that are dead.
7700 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7702 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7703 Instruction *User = cast<Instruction>(*UI++);
7704 if (isInstructionTriviallyDead(User)) {
7705 while (UI != E && *UI == User)
7706 ++UI; // If this instruction uses AI more than once, don't break UI.
7709 DOUT << "IC: DCE: " << *User;
7710 EraseInstFromFunction(*User);
7714 // Get the type really allocated and the type casted to.
7715 const Type *AllocElTy = AI.getAllocatedType();
7716 const Type *CastElTy = PTy->getElementType();
7717 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7719 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7720 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7721 if (CastElTyAlign < AllocElTyAlign) return 0;
7723 // If the allocation has multiple uses, only promote it if we are strictly
7724 // increasing the alignment of the resultant allocation. If we keep it the
7725 // same, we open the door to infinite loops of various kinds. (A reference
7726 // from a dbg.declare doesn't count as a use for this purpose.)
7727 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7728 CastElTyAlign == AllocElTyAlign) return 0;
7730 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7731 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7732 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7734 // See if we can satisfy the modulus by pulling a scale out of the array
7736 unsigned ArraySizeScale;
7738 Value *NumElements = // See if the array size is a decomposable linear expr.
7739 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7741 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7743 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7744 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7746 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7751 // If the allocation size is constant, form a constant mul expression
7752 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7753 if (isa<ConstantInt>(NumElements))
7754 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7755 cast<ConstantInt>(Amt));
7756 // otherwise multiply the amount and the number of elements
7758 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7759 Amt = InsertNewInstBefore(Tmp, AI);
7763 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7764 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7765 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7766 Amt = InsertNewInstBefore(Tmp, AI);
7769 AllocationInst *New;
7770 if (isa<MallocInst>(AI))
7771 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7773 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7774 InsertNewInstBefore(New, AI);
7777 // If the allocation has one real use plus a dbg.declare, just remove the
7779 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7780 EraseInstFromFunction(*DI);
7782 // If the allocation has multiple real uses, insert a cast and change all
7783 // things that used it to use the new cast. This will also hack on CI, but it
7785 else if (!AI.hasOneUse()) {
7786 AddUsesToWorkList(AI);
7787 // New is the allocation instruction, pointer typed. AI is the original
7788 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7789 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7790 InsertNewInstBefore(NewCast, AI);
7791 AI.replaceAllUsesWith(NewCast);
7793 return ReplaceInstUsesWith(CI, New);
7796 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7797 /// and return it as type Ty without inserting any new casts and without
7798 /// changing the computed value. This is used by code that tries to decide
7799 /// whether promoting or shrinking integer operations to wider or smaller types
7800 /// will allow us to eliminate a truncate or extend.
7802 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7803 /// extension operation if Ty is larger.
7805 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7806 /// should return true if trunc(V) can be computed by computing V in the smaller
7807 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7808 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7809 /// efficiently truncated.
7811 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7812 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7813 /// the final result.
7814 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7816 int &NumCastsRemoved){
7817 // We can always evaluate constants in another type.
7818 if (isa<Constant>(V))
7821 Instruction *I = dyn_cast<Instruction>(V);
7822 if (!I) return false;
7824 const Type *OrigTy = V->getType();
7826 // If this is an extension or truncate, we can often eliminate it.
7827 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7828 // If this is a cast from the destination type, we can trivially eliminate
7829 // it, and this will remove a cast overall.
7830 if (I->getOperand(0)->getType() == Ty) {
7831 // If the first operand is itself a cast, and is eliminable, do not count
7832 // this as an eliminable cast. We would prefer to eliminate those two
7834 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7840 // We can't extend or shrink something that has multiple uses: doing so would
7841 // require duplicating the instruction in general, which isn't profitable.
7842 if (!I->hasOneUse()) return false;
7844 unsigned Opc = I->getOpcode();
7846 case Instruction::Add:
7847 case Instruction::Sub:
7848 case Instruction::Mul:
7849 case Instruction::And:
7850 case Instruction::Or:
7851 case Instruction::Xor:
7852 // These operators can all arbitrarily be extended or truncated.
7853 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7855 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7858 case Instruction::Shl:
7859 // If we are truncating the result of this SHL, and if it's a shift of a
7860 // constant amount, we can always perform a SHL in a smaller type.
7861 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7862 uint32_t BitWidth = Ty->getScalarSizeInBits();
7863 if (BitWidth < OrigTy->getScalarSizeInBits() &&
7864 CI->getLimitedValue(BitWidth) < BitWidth)
7865 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7869 case Instruction::LShr:
7870 // If this is a truncate of a logical shr, we can truncate it to a smaller
7871 // lshr iff we know that the bits we would otherwise be shifting in are
7873 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7874 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7875 uint32_t BitWidth = Ty->getScalarSizeInBits();
7876 if (BitWidth < OrigBitWidth &&
7877 MaskedValueIsZero(I->getOperand(0),
7878 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7879 CI->getLimitedValue(BitWidth) < BitWidth) {
7880 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7885 case Instruction::ZExt:
7886 case Instruction::SExt:
7887 case Instruction::Trunc:
7888 // If this is the same kind of case as our original (e.g. zext+zext), we
7889 // can safely replace it. Note that replacing it does not reduce the number
7890 // of casts in the input.
7894 // sext (zext ty1), ty2 -> zext ty2
7895 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7898 case Instruction::Select: {
7899 SelectInst *SI = cast<SelectInst>(I);
7900 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7902 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7905 case Instruction::PHI: {
7906 // We can change a phi if we can change all operands.
7907 PHINode *PN = cast<PHINode>(I);
7908 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7909 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7915 // TODO: Can handle more cases here.
7922 /// EvaluateInDifferentType - Given an expression that
7923 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7924 /// evaluate the expression.
7925 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7927 if (Constant *C = dyn_cast<Constant>(V))
7928 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7930 // Otherwise, it must be an instruction.
7931 Instruction *I = cast<Instruction>(V);
7932 Instruction *Res = 0;
7933 unsigned Opc = I->getOpcode();
7935 case Instruction::Add:
7936 case Instruction::Sub:
7937 case Instruction::Mul:
7938 case Instruction::And:
7939 case Instruction::Or:
7940 case Instruction::Xor:
7941 case Instruction::AShr:
7942 case Instruction::LShr:
7943 case Instruction::Shl: {
7944 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7945 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7946 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7949 case Instruction::Trunc:
7950 case Instruction::ZExt:
7951 case Instruction::SExt:
7952 // If the source type of the cast is the type we're trying for then we can
7953 // just return the source. There's no need to insert it because it is not
7955 if (I->getOperand(0)->getType() == Ty)
7956 return I->getOperand(0);
7958 // Otherwise, must be the same type of cast, so just reinsert a new one.
7959 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7962 case Instruction::Select: {
7963 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7964 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7965 Res = SelectInst::Create(I->getOperand(0), True, False);
7968 case Instruction::PHI: {
7969 PHINode *OPN = cast<PHINode>(I);
7970 PHINode *NPN = PHINode::Create(Ty);
7971 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7972 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7973 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7979 // TODO: Can handle more cases here.
7980 assert(0 && "Unreachable!");
7985 return InsertNewInstBefore(Res, *I);
7988 /// @brief Implement the transforms common to all CastInst visitors.
7989 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7990 Value *Src = CI.getOperand(0);
7992 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7993 // eliminate it now.
7994 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7995 if (Instruction::CastOps opc =
7996 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7997 // The first cast (CSrc) is eliminable so we need to fix up or replace
7998 // the second cast (CI). CSrc will then have a good chance of being dead.
7999 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8003 // If we are casting a select then fold the cast into the select
8004 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8005 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8008 // If we are casting a PHI then fold the cast into the PHI
8009 if (isa<PHINode>(Src))
8010 if (Instruction *NV = FoldOpIntoPhi(CI))
8016 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8017 /// or not there is a sequence of GEP indices into the type that will land us at
8018 /// the specified offset. If so, fill them into NewIndices and return the
8019 /// resultant element type, otherwise return null.
8020 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8021 SmallVectorImpl<Value*> &NewIndices,
8022 const TargetData *TD) {
8023 if (!Ty->isSized()) return 0;
8025 // Start with the index over the outer type. Note that the type size
8026 // might be zero (even if the offset isn't zero) if the indexed type
8027 // is something like [0 x {int, int}]
8028 const Type *IntPtrTy = TD->getIntPtrType();
8029 int64_t FirstIdx = 0;
8030 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8031 FirstIdx = Offset/TySize;
8032 Offset -= FirstIdx*TySize;
8034 // Handle hosts where % returns negative instead of values [0..TySize).
8038 assert(Offset >= 0);
8040 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8043 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8045 // Index into the types. If we fail, set OrigBase to null.
8047 // Indexing into tail padding between struct/array elements.
8048 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8051 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8052 const StructLayout *SL = TD->getStructLayout(STy);
8053 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8054 "Offset must stay within the indexed type");
8056 unsigned Elt = SL->getElementContainingOffset(Offset);
8057 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8059 Offset -= SL->getElementOffset(Elt);
8060 Ty = STy->getElementType(Elt);
8061 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8062 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8063 assert(EltSize && "Cannot index into a zero-sized array");
8064 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8066 Ty = AT->getElementType();
8068 // Otherwise, we can't index into the middle of this atomic type, bail.
8076 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8077 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8078 Value *Src = CI.getOperand(0);
8080 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8081 // If casting the result of a getelementptr instruction with no offset, turn
8082 // this into a cast of the original pointer!
8083 if (GEP->hasAllZeroIndices()) {
8084 // Changing the cast operand is usually not a good idea but it is safe
8085 // here because the pointer operand is being replaced with another
8086 // pointer operand so the opcode doesn't need to change.
8088 CI.setOperand(0, GEP->getOperand(0));
8092 // If the GEP has a single use, and the base pointer is a bitcast, and the
8093 // GEP computes a constant offset, see if we can convert these three
8094 // instructions into fewer. This typically happens with unions and other
8095 // non-type-safe code.
8096 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8097 if (GEP->hasAllConstantIndices()) {
8098 // We are guaranteed to get a constant from EmitGEPOffset.
8099 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8100 int64_t Offset = OffsetV->getSExtValue();
8102 // Get the base pointer input of the bitcast, and the type it points to.
8103 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8104 const Type *GEPIdxTy =
8105 cast<PointerType>(OrigBase->getType())->getElementType();
8106 SmallVector<Value*, 8> NewIndices;
8107 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
8108 // If we were able to index down into an element, create the GEP
8109 // and bitcast the result. This eliminates one bitcast, potentially
8111 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8113 NewIndices.end(), "");
8114 InsertNewInstBefore(NGEP, CI);
8115 NGEP->takeName(GEP);
8117 if (isa<BitCastInst>(CI))
8118 return new BitCastInst(NGEP, CI.getType());
8119 assert(isa<PtrToIntInst>(CI));
8120 return new PtrToIntInst(NGEP, CI.getType());
8126 return commonCastTransforms(CI);
8129 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8130 /// type like i42. We don't want to introduce operations on random non-legal
8131 /// integer types where they don't already exist in the code. In the future,
8132 /// we should consider making this based off target-data, so that 32-bit targets
8133 /// won't get i64 operations etc.
8134 static bool isSafeIntegerType(const Type *Ty) {
8135 switch (Ty->getPrimitiveSizeInBits()) {
8146 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8147 /// integer types. This function implements the common transforms for all those
8149 /// @brief Implement the transforms common to CastInst with integer operands
8150 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8151 if (Instruction *Result = commonCastTransforms(CI))
8154 Value *Src = CI.getOperand(0);
8155 const Type *SrcTy = Src->getType();
8156 const Type *DestTy = CI.getType();
8157 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8158 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8160 // See if we can simplify any instructions used by the LHS whose sole
8161 // purpose is to compute bits we don't care about.
8162 if (SimplifyDemandedInstructionBits(CI))
8165 // If the source isn't an instruction or has more than one use then we
8166 // can't do anything more.
8167 Instruction *SrcI = dyn_cast<Instruction>(Src);
8168 if (!SrcI || !Src->hasOneUse())
8171 // Attempt to propagate the cast into the instruction for int->int casts.
8172 int NumCastsRemoved = 0;
8173 if (!isa<BitCastInst>(CI) &&
8174 // Only do this if the dest type is a simple type, don't convert the
8175 // expression tree to something weird like i93 unless the source is also
8177 (isSafeIntegerType(DestTy->getScalarType()) ||
8178 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8179 CanEvaluateInDifferentType(SrcI, DestTy,
8180 CI.getOpcode(), NumCastsRemoved)) {
8181 // If this cast is a truncate, evaluting in a different type always
8182 // eliminates the cast, so it is always a win. If this is a zero-extension,
8183 // we need to do an AND to maintain the clear top-part of the computation,
8184 // so we require that the input have eliminated at least one cast. If this
8185 // is a sign extension, we insert two new casts (to do the extension) so we
8186 // require that two casts have been eliminated.
8187 bool DoXForm = false;
8188 bool JustReplace = false;
8189 switch (CI.getOpcode()) {
8191 // All the others use floating point so we shouldn't actually
8192 // get here because of the check above.
8193 assert(0 && "Unknown cast type");
8194 case Instruction::Trunc:
8197 case Instruction::ZExt: {
8198 DoXForm = NumCastsRemoved >= 1;
8199 if (!DoXForm && 0) {
8200 // If it's unnecessary to issue an AND to clear the high bits, it's
8201 // always profitable to do this xform.
8202 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8203 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8204 if (MaskedValueIsZero(TryRes, Mask))
8205 return ReplaceInstUsesWith(CI, TryRes);
8207 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8208 if (TryI->use_empty())
8209 EraseInstFromFunction(*TryI);
8213 case Instruction::SExt: {
8214 DoXForm = NumCastsRemoved >= 2;
8215 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8216 // If we do not have to emit the truncate + sext pair, then it's always
8217 // profitable to do this xform.
8219 // It's not safe to eliminate the trunc + sext pair if one of the
8220 // eliminated cast is a truncate. e.g.
8221 // t2 = trunc i32 t1 to i16
8222 // t3 = sext i16 t2 to i32
8225 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8226 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8227 if (NumSignBits > (DestBitSize - SrcBitSize))
8228 return ReplaceInstUsesWith(CI, TryRes);
8230 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8231 if (TryI->use_empty())
8232 EraseInstFromFunction(*TryI);
8239 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8241 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8242 CI.getOpcode() == Instruction::SExt);
8244 // Just replace this cast with the result.
8245 return ReplaceInstUsesWith(CI, Res);
8247 assert(Res->getType() == DestTy);
8248 switch (CI.getOpcode()) {
8249 default: assert(0 && "Unknown cast type!");
8250 case Instruction::Trunc:
8251 case Instruction::BitCast:
8252 // Just replace this cast with the result.
8253 return ReplaceInstUsesWith(CI, Res);
8254 case Instruction::ZExt: {
8255 assert(SrcBitSize < DestBitSize && "Not a zext?");
8257 // If the high bits are already zero, just replace this cast with the
8259 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8260 if (MaskedValueIsZero(Res, Mask))
8261 return ReplaceInstUsesWith(CI, Res);
8263 // We need to emit an AND to clear the high bits.
8264 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8266 return BinaryOperator::CreateAnd(Res, C);
8268 case Instruction::SExt: {
8269 // If the high bits are already filled with sign bit, just replace this
8270 // cast with the result.
8271 unsigned NumSignBits = ComputeNumSignBits(Res);
8272 if (NumSignBits > (DestBitSize - SrcBitSize))
8273 return ReplaceInstUsesWith(CI, Res);
8275 // We need to emit a cast to truncate, then a cast to sext.
8276 return CastInst::Create(Instruction::SExt,
8277 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8284 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8285 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8287 switch (SrcI->getOpcode()) {
8288 case Instruction::Add:
8289 case Instruction::Mul:
8290 case Instruction::And:
8291 case Instruction::Or:
8292 case Instruction::Xor:
8293 // If we are discarding information, rewrite.
8294 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8295 // Don't insert two casts if they cannot be eliminated. We allow
8296 // two casts to be inserted if the sizes are the same. This could
8297 // only be converting signedness, which is a noop.
8298 if (DestBitSize == SrcBitSize ||
8299 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8300 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8301 Instruction::CastOps opcode = CI.getOpcode();
8302 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8303 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8304 return BinaryOperator::Create(
8305 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8309 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8310 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8311 SrcI->getOpcode() == Instruction::Xor &&
8312 Op1 == ConstantInt::getTrue() &&
8313 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8314 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8315 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
8318 case Instruction::SDiv:
8319 case Instruction::UDiv:
8320 case Instruction::SRem:
8321 case Instruction::URem:
8322 // If we are just changing the sign, rewrite.
8323 if (DestBitSize == SrcBitSize) {
8324 // Don't insert two casts if they cannot be eliminated. We allow
8325 // two casts to be inserted if the sizes are the same. This could
8326 // only be converting signedness, which is a noop.
8327 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8328 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8329 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8330 Op0, DestTy, *SrcI);
8331 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8332 Op1, DestTy, *SrcI);
8333 return BinaryOperator::Create(
8334 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8339 case Instruction::Shl:
8340 // Allow changing the sign of the source operand. Do not allow
8341 // changing the size of the shift, UNLESS the shift amount is a
8342 // constant. We must not change variable sized shifts to a smaller
8343 // size, because it is undefined to shift more bits out than exist
8345 if (DestBitSize == SrcBitSize ||
8346 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8347 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8348 Instruction::BitCast : Instruction::Trunc);
8349 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8350 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8351 return BinaryOperator::CreateShl(Op0c, Op1c);
8354 case Instruction::AShr:
8355 // If this is a signed shr, and if all bits shifted in are about to be
8356 // truncated off, turn it into an unsigned shr to allow greater
8358 if (DestBitSize < SrcBitSize &&
8359 isa<ConstantInt>(Op1)) {
8360 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8361 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8362 // Insert the new logical shift right.
8363 return BinaryOperator::CreateLShr(Op0, Op1);
8371 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8372 if (Instruction *Result = commonIntCastTransforms(CI))
8375 Value *Src = CI.getOperand(0);
8376 const Type *Ty = CI.getType();
8377 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8378 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8380 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8381 if (DestBitWidth == 1 &&
8382 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8383 Constant *One = ConstantInt::get(Src->getType(), 1);
8384 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8385 Value *Zero = Constant::getNullValue(Src->getType());
8386 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8389 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8390 ConstantInt *ShAmtV = 0;
8392 if (Src->hasOneUse() &&
8393 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8394 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8396 // Get a mask for the bits shifting in.
8397 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8398 if (MaskedValueIsZero(ShiftOp, Mask)) {
8399 if (ShAmt >= DestBitWidth) // All zeros.
8400 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8402 // Okay, we can shrink this. Truncate the input, then return a new
8404 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8405 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8406 return BinaryOperator::CreateLShr(V1, V2);
8413 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8414 /// in order to eliminate the icmp.
8415 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8417 // If we are just checking for a icmp eq of a single bit and zext'ing it
8418 // to an integer, then shift the bit to the appropriate place and then
8419 // cast to integer to avoid the comparison.
8420 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8421 const APInt &Op1CV = Op1C->getValue();
8423 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8424 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8425 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8426 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8427 if (!DoXform) return ICI;
8429 Value *In = ICI->getOperand(0);
8430 Value *Sh = ConstantInt::get(In->getType(),
8431 In->getType()->getScalarSizeInBits()-1);
8432 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8433 In->getName()+".lobit"),
8435 if (In->getType() != CI.getType())
8436 In = CastInst::CreateIntegerCast(In, CI.getType(),
8437 false/*ZExt*/, "tmp", &CI);
8439 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8440 Constant *One = ConstantInt::get(In->getType(), 1);
8441 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8442 In->getName()+".not"),
8446 return ReplaceInstUsesWith(CI, In);
8451 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8452 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8453 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8454 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8455 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8456 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8457 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8458 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8459 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8460 // This only works for EQ and NE
8461 ICI->isEquality()) {
8462 // If Op1C some other power of two, convert:
8463 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8464 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8465 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8466 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8468 APInt KnownZeroMask(~KnownZero);
8469 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8470 if (!DoXform) return ICI;
8472 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8473 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8474 // (X&4) == 2 --> false
8475 // (X&4) != 2 --> true
8476 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8477 Res = ConstantExpr::getZExt(Res, CI.getType());
8478 return ReplaceInstUsesWith(CI, Res);
8481 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8482 Value *In = ICI->getOperand(0);
8484 // Perform a logical shr by shiftamt.
8485 // Insert the shift to put the result in the low bit.
8486 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8487 ConstantInt::get(In->getType(), ShiftAmt),
8488 In->getName()+".lobit"), CI);
8491 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8492 Constant *One = ConstantInt::get(In->getType(), 1);
8493 In = BinaryOperator::CreateXor(In, One, "tmp");
8494 InsertNewInstBefore(cast<Instruction>(In), CI);
8497 if (CI.getType() == In->getType())
8498 return ReplaceInstUsesWith(CI, In);
8500 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8508 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8509 // If one of the common conversion will work ..
8510 if (Instruction *Result = commonIntCastTransforms(CI))
8513 Value *Src = CI.getOperand(0);
8515 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8516 // types and if the sizes are just right we can convert this into a logical
8517 // 'and' which will be much cheaper than the pair of casts.
8518 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8519 // Get the sizes of the types involved. We know that the intermediate type
8520 // will be smaller than A or C, but don't know the relation between A and C.
8521 Value *A = CSrc->getOperand(0);
8522 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8523 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8524 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8525 // If we're actually extending zero bits, then if
8526 // SrcSize < DstSize: zext(a & mask)
8527 // SrcSize == DstSize: a & mask
8528 // SrcSize > DstSize: trunc(a) & mask
8529 if (SrcSize < DstSize) {
8530 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8531 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8533 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8534 InsertNewInstBefore(And, CI);
8535 return new ZExtInst(And, CI.getType());
8536 } else if (SrcSize == DstSize) {
8537 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8538 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8540 } else if (SrcSize > DstSize) {
8541 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8542 InsertNewInstBefore(Trunc, CI);
8543 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8544 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Trunc->getType(),
8549 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8550 return transformZExtICmp(ICI, CI);
8552 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8553 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8554 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8555 // of the (zext icmp) will be transformed.
8556 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8557 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8558 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8559 (transformZExtICmp(LHS, CI, false) ||
8560 transformZExtICmp(RHS, CI, false))) {
8561 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8562 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8563 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8567 // zext(trunc(t) & C) -> (t & zext(C)).
8568 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8569 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8570 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8571 Value *TI0 = TI->getOperand(0);
8572 if (TI0->getType() == CI.getType())
8574 BinaryOperator::CreateAnd(TI0,
8575 ConstantExpr::getZExt(C, CI.getType()));
8578 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8579 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8580 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8581 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8582 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8583 And->getOperand(1) == C)
8584 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8585 Value *TI0 = TI->getOperand(0);
8586 if (TI0->getType() == CI.getType()) {
8587 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8588 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8589 InsertNewInstBefore(NewAnd, *And);
8590 return BinaryOperator::CreateXor(NewAnd, ZC);
8597 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8598 if (Instruction *I = commonIntCastTransforms(CI))
8601 Value *Src = CI.getOperand(0);
8603 // Canonicalize sign-extend from i1 to a select.
8604 if (Src->getType() == Type::Int1Ty)
8605 return SelectInst::Create(Src,
8606 ConstantInt::getAllOnesValue(CI.getType()),
8607 Constant::getNullValue(CI.getType()));
8609 // See if the value being truncated is already sign extended. If so, just
8610 // eliminate the trunc/sext pair.
8611 if (getOpcode(Src) == Instruction::Trunc) {
8612 Value *Op = cast<User>(Src)->getOperand(0);
8613 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8614 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8615 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8616 unsigned NumSignBits = ComputeNumSignBits(Op);
8618 if (OpBits == DestBits) {
8619 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8620 // bits, it is already ready.
8621 if (NumSignBits > DestBits-MidBits)
8622 return ReplaceInstUsesWith(CI, Op);
8623 } else if (OpBits < DestBits) {
8624 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8625 // bits, just sext from i32.
8626 if (NumSignBits > OpBits-MidBits)
8627 return new SExtInst(Op, CI.getType(), "tmp");
8629 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8630 // bits, just truncate to i32.
8631 if (NumSignBits > OpBits-MidBits)
8632 return new TruncInst(Op, CI.getType(), "tmp");
8636 // If the input is a shl/ashr pair of a same constant, then this is a sign
8637 // extension from a smaller value. If we could trust arbitrary bitwidth
8638 // integers, we could turn this into a truncate to the smaller bit and then
8639 // use a sext for the whole extension. Since we don't, look deeper and check
8640 // for a truncate. If the source and dest are the same type, eliminate the
8641 // trunc and extend and just do shifts. For example, turn:
8642 // %a = trunc i32 %i to i8
8643 // %b = shl i8 %a, 6
8644 // %c = ashr i8 %b, 6
8645 // %d = sext i8 %c to i32
8647 // %a = shl i32 %i, 30
8648 // %d = ashr i32 %a, 30
8650 ConstantInt *BA = 0, *CA = 0;
8651 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8652 m_ConstantInt(CA))) &&
8653 BA == CA && isa<TruncInst>(A)) {
8654 Value *I = cast<TruncInst>(A)->getOperand(0);
8655 if (I->getType() == CI.getType()) {
8656 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8657 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8658 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8659 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8660 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8662 return BinaryOperator::CreateAShr(I, ShAmtV);
8669 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8670 /// in the specified FP type without changing its value.
8671 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8673 APFloat F = CFP->getValueAPF();
8674 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8676 return ConstantFP::get(F);
8680 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8681 /// through it until we get the source value.
8682 static Value *LookThroughFPExtensions(Value *V) {
8683 if (Instruction *I = dyn_cast<Instruction>(V))
8684 if (I->getOpcode() == Instruction::FPExt)
8685 return LookThroughFPExtensions(I->getOperand(0));
8687 // If this value is a constant, return the constant in the smallest FP type
8688 // that can accurately represent it. This allows us to turn
8689 // (float)((double)X+2.0) into x+2.0f.
8690 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8691 if (CFP->getType() == Type::PPC_FP128Ty)
8692 return V; // No constant folding of this.
8693 // See if the value can be truncated to float and then reextended.
8694 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8696 if (CFP->getType() == Type::DoubleTy)
8697 return V; // Won't shrink.
8698 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8700 // Don't try to shrink to various long double types.
8706 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8707 if (Instruction *I = commonCastTransforms(CI))
8710 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8711 // smaller than the destination type, we can eliminate the truncate by doing
8712 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8713 // many builtins (sqrt, etc).
8714 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8715 if (OpI && OpI->hasOneUse()) {
8716 switch (OpI->getOpcode()) {
8718 case Instruction::FAdd:
8719 case Instruction::FSub:
8720 case Instruction::FMul:
8721 case Instruction::FDiv:
8722 case Instruction::FRem:
8723 const Type *SrcTy = OpI->getType();
8724 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8725 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8726 if (LHSTrunc->getType() != SrcTy &&
8727 RHSTrunc->getType() != SrcTy) {
8728 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8729 // If the source types were both smaller than the destination type of
8730 // the cast, do this xform.
8731 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8732 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8733 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8735 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8737 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8746 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8747 return commonCastTransforms(CI);
8750 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8751 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8753 return commonCastTransforms(FI);
8755 // fptoui(uitofp(X)) --> X
8756 // fptoui(sitofp(X)) --> X
8757 // This is safe if the intermediate type has enough bits in its mantissa to
8758 // accurately represent all values of X. For example, do not do this with
8759 // i64->float->i64. This is also safe for sitofp case, because any negative
8760 // 'X' value would cause an undefined result for the fptoui.
8761 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8762 OpI->getOperand(0)->getType() == FI.getType() &&
8763 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8764 OpI->getType()->getFPMantissaWidth())
8765 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8767 return commonCastTransforms(FI);
8770 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8771 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8773 return commonCastTransforms(FI);
8775 // fptosi(sitofp(X)) --> X
8776 // fptosi(uitofp(X)) --> X
8777 // This is safe if the intermediate type has enough bits in its mantissa to
8778 // accurately represent all values of X. For example, do not do this with
8779 // i64->float->i64. This is also safe for sitofp case, because any negative
8780 // 'X' value would cause an undefined result for the fptoui.
8781 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8782 OpI->getOperand(0)->getType() == FI.getType() &&
8783 (int)FI.getType()->getScalarSizeInBits() <=
8784 OpI->getType()->getFPMantissaWidth())
8785 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8787 return commonCastTransforms(FI);
8790 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8791 return commonCastTransforms(CI);
8794 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8795 return commonCastTransforms(CI);
8798 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8799 // If the destination integer type is smaller than the intptr_t type for
8800 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8801 // trunc to be exposed to other transforms. Don't do this for extending
8802 // ptrtoint's, because we don't know if the target sign or zero extends its
8804 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8805 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8806 TD->getIntPtrType(),
8808 return new TruncInst(P, CI.getType());
8811 return commonPointerCastTransforms(CI);
8814 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8815 // If the source integer type is larger than the intptr_t type for
8816 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8817 // allows the trunc to be exposed to other transforms. Don't do this for
8818 // extending inttoptr's, because we don't know if the target sign or zero
8819 // extends to pointers.
8820 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8821 TD->getPointerSizeInBits()) {
8822 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8823 TD->getIntPtrType(),
8825 return new IntToPtrInst(P, CI.getType());
8828 if (Instruction *I = commonCastTransforms(CI))
8831 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8832 if (!DestPointee->isSized()) return 0;
8834 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8837 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8838 m_ConstantInt(Cst)))) {
8839 // If the source and destination operands have the same type, see if this
8840 // is a single-index GEP.
8841 if (X->getType() == CI.getType()) {
8842 // Get the size of the pointee type.
8843 uint64_t Size = TD->getTypeAllocSize(DestPointee);
8845 // Convert the constant to intptr type.
8846 APInt Offset = Cst->getValue();
8847 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8849 // If Offset is evenly divisible by Size, we can do this xform.
8850 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8851 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8852 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8855 // TODO: Could handle other cases, e.g. where add is indexing into field of
8857 } else if (CI.getOperand(0)->hasOneUse() &&
8858 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8859 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8860 // "inttoptr+GEP" instead of "add+intptr".
8862 // Get the size of the pointee type.
8863 uint64_t Size = TD->getTypeAllocSize(DestPointee);
8865 // Convert the constant to intptr type.
8866 APInt Offset = Cst->getValue();
8867 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8869 // If Offset is evenly divisible by Size, we can do this xform.
8870 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8871 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8873 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8875 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8881 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8882 // If the operands are integer typed then apply the integer transforms,
8883 // otherwise just apply the common ones.
8884 Value *Src = CI.getOperand(0);
8885 const Type *SrcTy = Src->getType();
8886 const Type *DestTy = CI.getType();
8888 if (SrcTy->isInteger() && DestTy->isInteger()) {
8889 if (Instruction *Result = commonIntCastTransforms(CI))
8891 } else if (isa<PointerType>(SrcTy)) {
8892 if (Instruction *I = commonPointerCastTransforms(CI))
8895 if (Instruction *Result = commonCastTransforms(CI))
8900 // Get rid of casts from one type to the same type. These are useless and can
8901 // be replaced by the operand.
8902 if (DestTy == Src->getType())
8903 return ReplaceInstUsesWith(CI, Src);
8905 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8906 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8907 const Type *DstElTy = DstPTy->getElementType();
8908 const Type *SrcElTy = SrcPTy->getElementType();
8910 // If the address spaces don't match, don't eliminate the bitcast, which is
8911 // required for changing types.
8912 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8915 // If we are casting a malloc or alloca to a pointer to a type of the same
8916 // size, rewrite the allocation instruction to allocate the "right" type.
8917 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8918 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8921 // If the source and destination are pointers, and this cast is equivalent
8922 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8923 // This can enhance SROA and other transforms that want type-safe pointers.
8924 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8925 unsigned NumZeros = 0;
8926 while (SrcElTy != DstElTy &&
8927 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8928 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8929 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8933 // If we found a path from the src to dest, create the getelementptr now.
8934 if (SrcElTy == DstElTy) {
8935 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8936 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8937 ((Instruction*) NULL));
8941 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8942 if (SVI->hasOneUse()) {
8943 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8944 // a bitconvert to a vector with the same # elts.
8945 if (isa<VectorType>(DestTy) &&
8946 cast<VectorType>(DestTy)->getNumElements() ==
8947 SVI->getType()->getNumElements() &&
8948 SVI->getType()->getNumElements() ==
8949 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8951 // If either of the operands is a cast from CI.getType(), then
8952 // evaluating the shuffle in the casted destination's type will allow
8953 // us to eliminate at least one cast.
8954 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8955 Tmp->getOperand(0)->getType() == DestTy) ||
8956 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8957 Tmp->getOperand(0)->getType() == DestTy)) {
8958 Value *LHS = InsertCastBefore(Instruction::BitCast,
8959 SVI->getOperand(0), DestTy, CI);
8960 Value *RHS = InsertCastBefore(Instruction::BitCast,
8961 SVI->getOperand(1), DestTy, CI);
8962 // Return a new shuffle vector. Use the same element ID's, as we
8963 // know the vector types match #elts.
8964 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8972 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8974 /// %D = select %cond, %C, %A
8976 /// %C = select %cond, %B, 0
8979 /// Assuming that the specified instruction is an operand to the select, return
8980 /// a bitmask indicating which operands of this instruction are foldable if they
8981 /// equal the other incoming value of the select.
8983 static unsigned GetSelectFoldableOperands(Instruction *I) {
8984 switch (I->getOpcode()) {
8985 case Instruction::Add:
8986 case Instruction::Mul:
8987 case Instruction::And:
8988 case Instruction::Or:
8989 case Instruction::Xor:
8990 return 3; // Can fold through either operand.
8991 case Instruction::Sub: // Can only fold on the amount subtracted.
8992 case Instruction::Shl: // Can only fold on the shift amount.
8993 case Instruction::LShr:
8994 case Instruction::AShr:
8997 return 0; // Cannot fold
9001 /// GetSelectFoldableConstant - For the same transformation as the previous
9002 /// function, return the identity constant that goes into the select.
9003 static Constant *GetSelectFoldableConstant(Instruction *I) {
9004 switch (I->getOpcode()) {
9005 default: assert(0 && "This cannot happen!"); abort();
9006 case Instruction::Add:
9007 case Instruction::Sub:
9008 case Instruction::Or:
9009 case Instruction::Xor:
9010 case Instruction::Shl:
9011 case Instruction::LShr:
9012 case Instruction::AShr:
9013 return Constant::getNullValue(I->getType());
9014 case Instruction::And:
9015 return Constant::getAllOnesValue(I->getType());
9016 case Instruction::Mul:
9017 return ConstantInt::get(I->getType(), 1);
9021 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9022 /// have the same opcode and only one use each. Try to simplify this.
9023 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9025 if (TI->getNumOperands() == 1) {
9026 // If this is a non-volatile load or a cast from the same type,
9029 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9032 return 0; // unknown unary op.
9035 // Fold this by inserting a select from the input values.
9036 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9037 FI->getOperand(0), SI.getName()+".v");
9038 InsertNewInstBefore(NewSI, SI);
9039 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
9043 // Only handle binary operators here.
9044 if (!isa<BinaryOperator>(TI))
9047 // Figure out if the operations have any operands in common.
9048 Value *MatchOp, *OtherOpT, *OtherOpF;
9050 if (TI->getOperand(0) == FI->getOperand(0)) {
9051 MatchOp = TI->getOperand(0);
9052 OtherOpT = TI->getOperand(1);
9053 OtherOpF = FI->getOperand(1);
9054 MatchIsOpZero = true;
9055 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9056 MatchOp = TI->getOperand(1);
9057 OtherOpT = TI->getOperand(0);
9058 OtherOpF = FI->getOperand(0);
9059 MatchIsOpZero = false;
9060 } else if (!TI->isCommutative()) {
9062 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9063 MatchOp = TI->getOperand(0);
9064 OtherOpT = TI->getOperand(1);
9065 OtherOpF = FI->getOperand(0);
9066 MatchIsOpZero = true;
9067 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9068 MatchOp = TI->getOperand(1);
9069 OtherOpT = TI->getOperand(0);
9070 OtherOpF = FI->getOperand(1);
9071 MatchIsOpZero = true;
9076 // If we reach here, they do have operations in common.
9077 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9078 OtherOpF, SI.getName()+".v");
9079 InsertNewInstBefore(NewSI, SI);
9081 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9083 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9085 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9087 assert(0 && "Shouldn't get here");
9091 static bool isSelect01(Constant *C1, Constant *C2) {
9092 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9095 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9098 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9101 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9102 /// facilitate further optimization.
9103 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9105 // See the comment above GetSelectFoldableOperands for a description of the
9106 // transformation we are doing here.
9107 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9108 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9109 !isa<Constant>(FalseVal)) {
9110 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9111 unsigned OpToFold = 0;
9112 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9114 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9119 Constant *C = GetSelectFoldableConstant(TVI);
9120 Value *OOp = TVI->getOperand(2-OpToFold);
9121 // Avoid creating select between 2 constants unless it's selecting
9123 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9124 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9125 InsertNewInstBefore(NewSel, SI);
9126 NewSel->takeName(TVI);
9127 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9128 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9129 assert(0 && "Unknown instruction!!");
9136 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9137 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9138 !isa<Constant>(TrueVal)) {
9139 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9140 unsigned OpToFold = 0;
9141 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9143 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9148 Constant *C = GetSelectFoldableConstant(FVI);
9149 Value *OOp = FVI->getOperand(2-OpToFold);
9150 // Avoid creating select between 2 constants unless it's selecting
9152 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9153 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9154 InsertNewInstBefore(NewSel, SI);
9155 NewSel->takeName(FVI);
9156 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9157 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9158 assert(0 && "Unknown instruction!!");
9168 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9169 /// ICmpInst as its first operand.
9171 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9173 bool Changed = false;
9174 ICmpInst::Predicate Pred = ICI->getPredicate();
9175 Value *CmpLHS = ICI->getOperand(0);
9176 Value *CmpRHS = ICI->getOperand(1);
9177 Value *TrueVal = SI.getTrueValue();
9178 Value *FalseVal = SI.getFalseValue();
9180 // Check cases where the comparison is with a constant that
9181 // can be adjusted to fit the min/max idiom. We may edit ICI in
9182 // place here, so make sure the select is the only user.
9183 if (ICI->hasOneUse())
9184 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9187 case ICmpInst::ICMP_ULT:
9188 case ICmpInst::ICMP_SLT: {
9189 // X < MIN ? T : F --> F
9190 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9191 return ReplaceInstUsesWith(SI, FalseVal);
9192 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9193 Constant *AdjustedRHS = SubOne(CI);
9194 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9195 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9196 Pred = ICmpInst::getSwappedPredicate(Pred);
9197 CmpRHS = AdjustedRHS;
9198 std::swap(FalseVal, TrueVal);
9199 ICI->setPredicate(Pred);
9200 ICI->setOperand(1, CmpRHS);
9201 SI.setOperand(1, TrueVal);
9202 SI.setOperand(2, FalseVal);
9207 case ICmpInst::ICMP_UGT:
9208 case ICmpInst::ICMP_SGT: {
9209 // X > MAX ? T : F --> F
9210 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9211 return ReplaceInstUsesWith(SI, FalseVal);
9212 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9213 Constant *AdjustedRHS = AddOne(CI);
9214 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9215 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9216 Pred = ICmpInst::getSwappedPredicate(Pred);
9217 CmpRHS = AdjustedRHS;
9218 std::swap(FalseVal, TrueVal);
9219 ICI->setPredicate(Pred);
9220 ICI->setOperand(1, CmpRHS);
9221 SI.setOperand(1, TrueVal);
9222 SI.setOperand(2, FalseVal);
9229 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9230 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9231 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9232 if (match(TrueVal, m_ConstantInt<-1>()) &&
9233 match(FalseVal, m_ConstantInt<0>()))
9234 Pred = ICI->getPredicate();
9235 else if (match(TrueVal, m_ConstantInt<0>()) &&
9236 match(FalseVal, m_ConstantInt<-1>()))
9237 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9239 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9240 // If we are just checking for a icmp eq of a single bit and zext'ing it
9241 // to an integer, then shift the bit to the appropriate place and then
9242 // cast to integer to avoid the comparison.
9243 const APInt &Op1CV = CI->getValue();
9245 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9246 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9247 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9248 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9249 Value *In = ICI->getOperand(0);
9250 Value *Sh = ConstantInt::get(In->getType(),
9251 In->getType()->getScalarSizeInBits()-1);
9252 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9253 In->getName()+".lobit"),
9255 if (In->getType() != SI.getType())
9256 In = CastInst::CreateIntegerCast(In, SI.getType(),
9257 true/*SExt*/, "tmp", ICI);
9259 if (Pred == ICmpInst::ICMP_SGT)
9260 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9261 In->getName()+".not"), *ICI);
9263 return ReplaceInstUsesWith(SI, In);
9268 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9269 // Transform (X == Y) ? X : Y -> Y
9270 if (Pred == ICmpInst::ICMP_EQ)
9271 return ReplaceInstUsesWith(SI, FalseVal);
9272 // Transform (X != Y) ? X : Y -> X
9273 if (Pred == ICmpInst::ICMP_NE)
9274 return ReplaceInstUsesWith(SI, TrueVal);
9275 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9277 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9278 // Transform (X == Y) ? Y : X -> X
9279 if (Pred == ICmpInst::ICMP_EQ)
9280 return ReplaceInstUsesWith(SI, FalseVal);
9281 // Transform (X != Y) ? Y : X -> Y
9282 if (Pred == ICmpInst::ICMP_NE)
9283 return ReplaceInstUsesWith(SI, TrueVal);
9284 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9287 /// NOTE: if we wanted to, this is where to detect integer ABS
9289 return Changed ? &SI : 0;
9292 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9293 Value *CondVal = SI.getCondition();
9294 Value *TrueVal = SI.getTrueValue();
9295 Value *FalseVal = SI.getFalseValue();
9297 // select true, X, Y -> X
9298 // select false, X, Y -> Y
9299 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9300 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9302 // select C, X, X -> X
9303 if (TrueVal == FalseVal)
9304 return ReplaceInstUsesWith(SI, TrueVal);
9306 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9307 return ReplaceInstUsesWith(SI, FalseVal);
9308 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9309 return ReplaceInstUsesWith(SI, TrueVal);
9310 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9311 if (isa<Constant>(TrueVal))
9312 return ReplaceInstUsesWith(SI, TrueVal);
9314 return ReplaceInstUsesWith(SI, FalseVal);
9317 if (SI.getType() == Type::Int1Ty) {
9318 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9319 if (C->getZExtValue()) {
9320 // Change: A = select B, true, C --> A = or B, C
9321 return BinaryOperator::CreateOr(CondVal, FalseVal);
9323 // Change: A = select B, false, C --> A = and !B, C
9325 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9326 "not."+CondVal->getName()), SI);
9327 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9329 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9330 if (C->getZExtValue() == false) {
9331 // Change: A = select B, C, false --> A = and B, C
9332 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9334 // Change: A = select B, C, true --> A = or !B, C
9336 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9337 "not."+CondVal->getName()), SI);
9338 return BinaryOperator::CreateOr(NotCond, TrueVal);
9342 // select a, b, a -> a&b
9343 // select a, a, b -> a|b
9344 if (CondVal == TrueVal)
9345 return BinaryOperator::CreateOr(CondVal, FalseVal);
9346 else if (CondVal == FalseVal)
9347 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9350 // Selecting between two integer constants?
9351 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9352 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9353 // select C, 1, 0 -> zext C to int
9354 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9355 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9356 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9357 // select C, 0, 1 -> zext !C to int
9359 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9360 "not."+CondVal->getName()), SI);
9361 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9364 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9366 // (x <s 0) ? -1 : 0 -> ashr x, 31
9367 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9368 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9369 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9370 // The comparison constant and the result are not neccessarily the
9371 // same width. Make an all-ones value by inserting a AShr.
9372 Value *X = IC->getOperand(0);
9373 uint32_t Bits = X->getType()->getScalarSizeInBits();
9374 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
9375 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9377 InsertNewInstBefore(SRA, SI);
9379 // Then cast to the appropriate width.
9380 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9385 // If one of the constants is zero (we know they can't both be) and we
9386 // have an icmp instruction with zero, and we have an 'and' with the
9387 // non-constant value, eliminate this whole mess. This corresponds to
9388 // cases like this: ((X & 27) ? 27 : 0)
9389 if (TrueValC->isZero() || FalseValC->isZero())
9390 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9391 cast<Constant>(IC->getOperand(1))->isNullValue())
9392 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9393 if (ICA->getOpcode() == Instruction::And &&
9394 isa<ConstantInt>(ICA->getOperand(1)) &&
9395 (ICA->getOperand(1) == TrueValC ||
9396 ICA->getOperand(1) == FalseValC) &&
9397 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9398 // Okay, now we know that everything is set up, we just don't
9399 // know whether we have a icmp_ne or icmp_eq and whether the
9400 // true or false val is the zero.
9401 bool ShouldNotVal = !TrueValC->isZero();
9402 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9405 V = InsertNewInstBefore(BinaryOperator::Create(
9406 Instruction::Xor, V, ICA->getOperand(1)), SI);
9407 return ReplaceInstUsesWith(SI, V);
9412 // See if we are selecting two values based on a comparison of the two values.
9413 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9414 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9415 // Transform (X == Y) ? X : Y -> Y
9416 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9417 // This is not safe in general for floating point:
9418 // consider X== -0, Y== +0.
9419 // It becomes safe if either operand is a nonzero constant.
9420 ConstantFP *CFPt, *CFPf;
9421 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9422 !CFPt->getValueAPF().isZero()) ||
9423 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9424 !CFPf->getValueAPF().isZero()))
9425 return ReplaceInstUsesWith(SI, FalseVal);
9427 // Transform (X != Y) ? X : Y -> X
9428 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9429 return ReplaceInstUsesWith(SI, TrueVal);
9430 // NOTE: if we wanted to, this is where to detect MIN/MAX
9432 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9433 // Transform (X == Y) ? Y : X -> X
9434 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9435 // This is not safe in general for floating point:
9436 // consider X== -0, Y== +0.
9437 // It becomes safe if either operand is a nonzero constant.
9438 ConstantFP *CFPt, *CFPf;
9439 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9440 !CFPt->getValueAPF().isZero()) ||
9441 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9442 !CFPf->getValueAPF().isZero()))
9443 return ReplaceInstUsesWith(SI, FalseVal);
9445 // Transform (X != Y) ? Y : X -> Y
9446 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9447 return ReplaceInstUsesWith(SI, TrueVal);
9448 // NOTE: if we wanted to, this is where to detect MIN/MAX
9450 // NOTE: if we wanted to, this is where to detect ABS
9453 // See if we are selecting two values based on a comparison of the two values.
9454 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9455 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9458 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9459 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9460 if (TI->hasOneUse() && FI->hasOneUse()) {
9461 Instruction *AddOp = 0, *SubOp = 0;
9463 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9464 if (TI->getOpcode() == FI->getOpcode())
9465 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9468 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9469 // even legal for FP.
9470 if ((TI->getOpcode() == Instruction::Sub &&
9471 FI->getOpcode() == Instruction::Add) ||
9472 (TI->getOpcode() == Instruction::FSub &&
9473 FI->getOpcode() == Instruction::FAdd)) {
9474 AddOp = FI; SubOp = TI;
9475 } else if ((FI->getOpcode() == Instruction::Sub &&
9476 TI->getOpcode() == Instruction::Add) ||
9477 (FI->getOpcode() == Instruction::FSub &&
9478 TI->getOpcode() == Instruction::FAdd)) {
9479 AddOp = TI; SubOp = FI;
9483 Value *OtherAddOp = 0;
9484 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9485 OtherAddOp = AddOp->getOperand(1);
9486 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9487 OtherAddOp = AddOp->getOperand(0);
9491 // So at this point we know we have (Y -> OtherAddOp):
9492 // select C, (add X, Y), (sub X, Z)
9493 Value *NegVal; // Compute -Z
9494 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9495 NegVal = ConstantExpr::getNeg(C);
9497 NegVal = InsertNewInstBefore(
9498 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9501 Value *NewTrueOp = OtherAddOp;
9502 Value *NewFalseOp = NegVal;
9504 std::swap(NewTrueOp, NewFalseOp);
9505 Instruction *NewSel =
9506 SelectInst::Create(CondVal, NewTrueOp,
9507 NewFalseOp, SI.getName() + ".p");
9509 NewSel = InsertNewInstBefore(NewSel, SI);
9510 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9515 // See if we can fold the select into one of our operands.
9516 if (SI.getType()->isInteger()) {
9517 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9522 if (BinaryOperator::isNot(CondVal)) {
9523 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9524 SI.setOperand(1, FalseVal);
9525 SI.setOperand(2, TrueVal);
9532 /// EnforceKnownAlignment - If the specified pointer points to an object that
9533 /// we control, modify the object's alignment to PrefAlign. This isn't
9534 /// often possible though. If alignment is important, a more reliable approach
9535 /// is to simply align all global variables and allocation instructions to
9536 /// their preferred alignment from the beginning.
9538 static unsigned EnforceKnownAlignment(Value *V,
9539 unsigned Align, unsigned PrefAlign) {
9541 User *U = dyn_cast<User>(V);
9542 if (!U) return Align;
9544 switch (getOpcode(U)) {
9546 case Instruction::BitCast:
9547 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9548 case Instruction::GetElementPtr: {
9549 // If all indexes are zero, it is just the alignment of the base pointer.
9550 bool AllZeroOperands = true;
9551 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9552 if (!isa<Constant>(*i) ||
9553 !cast<Constant>(*i)->isNullValue()) {
9554 AllZeroOperands = false;
9558 if (AllZeroOperands) {
9559 // Treat this like a bitcast.
9560 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9566 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9567 // If there is a large requested alignment and we can, bump up the alignment
9569 if (!GV->isDeclaration()) {
9570 if (GV->getAlignment() >= PrefAlign)
9571 Align = GV->getAlignment();
9573 GV->setAlignment(PrefAlign);
9577 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9578 // If there is a requested alignment and if this is an alloca, round up. We
9579 // don't do this for malloc, because some systems can't respect the request.
9580 if (isa<AllocaInst>(AI)) {
9581 if (AI->getAlignment() >= PrefAlign)
9582 Align = AI->getAlignment();
9584 AI->setAlignment(PrefAlign);
9593 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9594 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9595 /// and it is more than the alignment of the ultimate object, see if we can
9596 /// increase the alignment of the ultimate object, making this check succeed.
9597 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9598 unsigned PrefAlign) {
9599 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9600 sizeof(PrefAlign) * CHAR_BIT;
9601 APInt Mask = APInt::getAllOnesValue(BitWidth);
9602 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9603 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9604 unsigned TrailZ = KnownZero.countTrailingOnes();
9605 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9607 if (PrefAlign > Align)
9608 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9610 // We don't need to make any adjustment.
9614 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9615 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9616 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9617 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9618 unsigned CopyAlign = MI->getAlignment();
9620 if (CopyAlign < MinAlign) {
9621 MI->setAlignment(MinAlign);
9625 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9627 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9628 if (MemOpLength == 0) return 0;
9630 // Source and destination pointer types are always "i8*" for intrinsic. See
9631 // if the size is something we can handle with a single primitive load/store.
9632 // A single load+store correctly handles overlapping memory in the memmove
9634 unsigned Size = MemOpLength->getZExtValue();
9635 if (Size == 0) return MI; // Delete this mem transfer.
9637 if (Size > 8 || (Size&(Size-1)))
9638 return 0; // If not 1/2/4/8 bytes, exit.
9640 // Use an integer load+store unless we can find something better.
9641 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9643 // Memcpy forces the use of i8* for the source and destination. That means
9644 // that if you're using memcpy to move one double around, you'll get a cast
9645 // from double* to i8*. We'd much rather use a double load+store rather than
9646 // an i64 load+store, here because this improves the odds that the source or
9647 // dest address will be promotable. See if we can find a better type than the
9648 // integer datatype.
9649 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9650 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9651 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9652 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9653 // down through these levels if so.
9654 while (!SrcETy->isSingleValueType()) {
9655 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9656 if (STy->getNumElements() == 1)
9657 SrcETy = STy->getElementType(0);
9660 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9661 if (ATy->getNumElements() == 1)
9662 SrcETy = ATy->getElementType();
9669 if (SrcETy->isSingleValueType())
9670 NewPtrTy = PointerType::getUnqual(SrcETy);
9675 // If the memcpy/memmove provides better alignment info than we can
9677 SrcAlign = std::max(SrcAlign, CopyAlign);
9678 DstAlign = std::max(DstAlign, CopyAlign);
9680 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9681 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9682 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9683 InsertNewInstBefore(L, *MI);
9684 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9686 // Set the size of the copy to 0, it will be deleted on the next iteration.
9687 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9691 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9692 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9693 if (MI->getAlignment() < Alignment) {
9694 MI->setAlignment(Alignment);
9698 // Extract the length and alignment and fill if they are constant.
9699 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9700 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9701 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9703 uint64_t Len = LenC->getZExtValue();
9704 Alignment = MI->getAlignment();
9706 // If the length is zero, this is a no-op
9707 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9709 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9710 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9711 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9713 Value *Dest = MI->getDest();
9714 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9716 // Alignment 0 is identity for alignment 1 for memset, but not store.
9717 if (Alignment == 0) Alignment = 1;
9719 // Extract the fill value and store.
9720 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9721 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9724 // Set the size of the copy to 0, it will be deleted on the next iteration.
9725 MI->setLength(Constant::getNullValue(LenC->getType()));
9733 /// visitCallInst - CallInst simplification. This mostly only handles folding
9734 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9735 /// the heavy lifting.
9737 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9738 // If the caller function is nounwind, mark the call as nounwind, even if the
9740 if (CI.getParent()->getParent()->doesNotThrow() &&
9741 !CI.doesNotThrow()) {
9742 CI.setDoesNotThrow();
9748 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9749 if (!II) return visitCallSite(&CI);
9751 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9753 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9754 bool Changed = false;
9756 // memmove/cpy/set of zero bytes is a noop.
9757 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9758 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9760 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9761 if (CI->getZExtValue() == 1) {
9762 // Replace the instruction with just byte operations. We would
9763 // transform other cases to loads/stores, but we don't know if
9764 // alignment is sufficient.
9768 // If we have a memmove and the source operation is a constant global,
9769 // then the source and dest pointers can't alias, so we can change this
9770 // into a call to memcpy.
9771 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9772 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9773 if (GVSrc->isConstant()) {
9774 Module *M = CI.getParent()->getParent()->getParent();
9775 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9777 Tys[0] = CI.getOperand(3)->getType();
9779 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9783 // memmove(x,x,size) -> noop.
9784 if (MMI->getSource() == MMI->getDest())
9785 return EraseInstFromFunction(CI);
9788 // If we can determine a pointer alignment that is bigger than currently
9789 // set, update the alignment.
9790 if (isa<MemTransferInst>(MI)) {
9791 if (Instruction *I = SimplifyMemTransfer(MI))
9793 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9794 if (Instruction *I = SimplifyMemSet(MSI))
9798 if (Changed) return II;
9801 switch (II->getIntrinsicID()) {
9803 case Intrinsic::bswap:
9804 // bswap(bswap(x)) -> x
9805 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9806 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9807 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9809 case Intrinsic::ppc_altivec_lvx:
9810 case Intrinsic::ppc_altivec_lvxl:
9811 case Intrinsic::x86_sse_loadu_ps:
9812 case Intrinsic::x86_sse2_loadu_pd:
9813 case Intrinsic::x86_sse2_loadu_dq:
9814 // Turn PPC lvx -> load if the pointer is known aligned.
9815 // Turn X86 loadups -> load if the pointer is known aligned.
9816 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9817 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9818 PointerType::getUnqual(II->getType()),
9820 return new LoadInst(Ptr);
9823 case Intrinsic::ppc_altivec_stvx:
9824 case Intrinsic::ppc_altivec_stvxl:
9825 // Turn stvx -> store if the pointer is known aligned.
9826 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9827 const Type *OpPtrTy =
9828 PointerType::getUnqual(II->getOperand(1)->getType());
9829 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9830 return new StoreInst(II->getOperand(1), Ptr);
9833 case Intrinsic::x86_sse_storeu_ps:
9834 case Intrinsic::x86_sse2_storeu_pd:
9835 case Intrinsic::x86_sse2_storeu_dq:
9836 // Turn X86 storeu -> store if the pointer is known aligned.
9837 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9838 const Type *OpPtrTy =
9839 PointerType::getUnqual(II->getOperand(2)->getType());
9840 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9841 return new StoreInst(II->getOperand(2), Ptr);
9845 case Intrinsic::x86_sse_cvttss2si: {
9846 // These intrinsics only demands the 0th element of its input vector. If
9847 // we can simplify the input based on that, do so now.
9849 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9850 APInt DemandedElts(VWidth, 1);
9851 APInt UndefElts(VWidth, 0);
9852 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9854 II->setOperand(1, V);
9860 case Intrinsic::ppc_altivec_vperm:
9861 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9862 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9863 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9865 // Check that all of the elements are integer constants or undefs.
9866 bool AllEltsOk = true;
9867 for (unsigned i = 0; i != 16; ++i) {
9868 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9869 !isa<UndefValue>(Mask->getOperand(i))) {
9876 // Cast the input vectors to byte vectors.
9877 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9878 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9879 Value *Result = UndefValue::get(Op0->getType());
9881 // Only extract each element once.
9882 Value *ExtractedElts[32];
9883 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9885 for (unsigned i = 0; i != 16; ++i) {
9886 if (isa<UndefValue>(Mask->getOperand(i)))
9888 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9889 Idx &= 31; // Match the hardware behavior.
9891 if (ExtractedElts[Idx] == 0) {
9893 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9894 InsertNewInstBefore(Elt, CI);
9895 ExtractedElts[Idx] = Elt;
9898 // Insert this value into the result vector.
9899 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9901 InsertNewInstBefore(cast<Instruction>(Result), CI);
9903 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9908 case Intrinsic::stackrestore: {
9909 // If the save is right next to the restore, remove the restore. This can
9910 // happen when variable allocas are DCE'd.
9911 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9912 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9913 BasicBlock::iterator BI = SS;
9915 return EraseInstFromFunction(CI);
9919 // Scan down this block to see if there is another stack restore in the
9920 // same block without an intervening call/alloca.
9921 BasicBlock::iterator BI = II;
9922 TerminatorInst *TI = II->getParent()->getTerminator();
9923 bool CannotRemove = false;
9924 for (++BI; &*BI != TI; ++BI) {
9925 if (isa<AllocaInst>(BI)) {
9926 CannotRemove = true;
9929 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9930 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9931 // If there is a stackrestore below this one, remove this one.
9932 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9933 return EraseInstFromFunction(CI);
9934 // Otherwise, ignore the intrinsic.
9936 // If we found a non-intrinsic call, we can't remove the stack
9938 CannotRemove = true;
9944 // If the stack restore is in a return/unwind block and if there are no
9945 // allocas or calls between the restore and the return, nuke the restore.
9946 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9947 return EraseInstFromFunction(CI);
9952 return visitCallSite(II);
9955 // InvokeInst simplification
9957 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9958 return visitCallSite(&II);
9961 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
9962 /// passed through the varargs area, we can eliminate the use of the cast.
9963 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9964 const CastInst * const CI,
9965 const TargetData * const TD,
9967 if (!CI->isLosslessCast())
9970 // The size of ByVal arguments is derived from the type, so we
9971 // can't change to a type with a different size. If the size were
9972 // passed explicitly we could avoid this check.
9973 if (!CS.paramHasAttr(ix, Attribute::ByVal))
9977 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9978 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9979 if (!SrcTy->isSized() || !DstTy->isSized())
9981 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9986 // visitCallSite - Improvements for call and invoke instructions.
9988 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9989 bool Changed = false;
9991 // If the callee is a constexpr cast of a function, attempt to move the cast
9992 // to the arguments of the call/invoke.
9993 if (transformConstExprCastCall(CS)) return 0;
9995 Value *Callee = CS.getCalledValue();
9997 if (Function *CalleeF = dyn_cast<Function>(Callee))
9998 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9999 Instruction *OldCall = CS.getInstruction();
10000 // If the call and callee calling conventions don't match, this call must
10001 // be unreachable, as the call is undefined.
10002 new StoreInst(ConstantInt::getTrue(),
10003 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
10005 if (!OldCall->use_empty())
10006 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10007 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10008 return EraseInstFromFunction(*OldCall);
10012 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10013 // This instruction is not reachable, just remove it. We insert a store to
10014 // undef so that we know that this code is not reachable, despite the fact
10015 // that we can't modify the CFG here.
10016 new StoreInst(ConstantInt::getTrue(),
10017 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
10018 CS.getInstruction());
10020 if (!CS.getInstruction()->use_empty())
10021 CS.getInstruction()->
10022 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10024 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10025 // Don't break the CFG, insert a dummy cond branch.
10026 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10027 ConstantInt::getTrue(), II);
10029 return EraseInstFromFunction(*CS.getInstruction());
10032 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10033 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10034 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10035 return transformCallThroughTrampoline(CS);
10037 const PointerType *PTy = cast<PointerType>(Callee->getType());
10038 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10039 if (FTy->isVarArg()) {
10040 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10041 // See if we can optimize any arguments passed through the varargs area of
10043 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10044 E = CS.arg_end(); I != E; ++I, ++ix) {
10045 CastInst *CI = dyn_cast<CastInst>(*I);
10046 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10047 *I = CI->getOperand(0);
10053 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10054 // Inline asm calls cannot throw - mark them 'nounwind'.
10055 CS.setDoesNotThrow();
10059 return Changed ? CS.getInstruction() : 0;
10062 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10063 // attempt to move the cast to the arguments of the call/invoke.
10065 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10066 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10067 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10068 if (CE->getOpcode() != Instruction::BitCast ||
10069 !isa<Function>(CE->getOperand(0)))
10071 Function *Callee = cast<Function>(CE->getOperand(0));
10072 Instruction *Caller = CS.getInstruction();
10073 const AttrListPtr &CallerPAL = CS.getAttributes();
10075 // Okay, this is a cast from a function to a different type. Unless doing so
10076 // would cause a type conversion of one of our arguments, change this call to
10077 // be a direct call with arguments casted to the appropriate types.
10079 const FunctionType *FT = Callee->getFunctionType();
10080 const Type *OldRetTy = Caller->getType();
10081 const Type *NewRetTy = FT->getReturnType();
10083 if (isa<StructType>(NewRetTy))
10084 return false; // TODO: Handle multiple return values.
10086 // Check to see if we are changing the return type...
10087 if (OldRetTy != NewRetTy) {
10088 if (Callee->isDeclaration() &&
10089 // Conversion is ok if changing from one pointer type to another or from
10090 // a pointer to an integer of the same size.
10091 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10092 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10093 return false; // Cannot transform this return value.
10095 if (!Caller->use_empty() &&
10096 // void -> non-void is handled specially
10097 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10098 return false; // Cannot transform this return value.
10100 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10101 Attributes RAttrs = CallerPAL.getRetAttributes();
10102 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10103 return false; // Attribute not compatible with transformed value.
10106 // If the callsite is an invoke instruction, and the return value is used by
10107 // a PHI node in a successor, we cannot change the return type of the call
10108 // because there is no place to put the cast instruction (without breaking
10109 // the critical edge). Bail out in this case.
10110 if (!Caller->use_empty())
10111 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10112 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10114 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10115 if (PN->getParent() == II->getNormalDest() ||
10116 PN->getParent() == II->getUnwindDest())
10120 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10121 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10123 CallSite::arg_iterator AI = CS.arg_begin();
10124 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10125 const Type *ParamTy = FT->getParamType(i);
10126 const Type *ActTy = (*AI)->getType();
10128 if (!CastInst::isCastable(ActTy, ParamTy))
10129 return false; // Cannot transform this parameter value.
10131 if (CallerPAL.getParamAttributes(i + 1)
10132 & Attribute::typeIncompatible(ParamTy))
10133 return false; // Attribute not compatible with transformed value.
10135 // Converting from one pointer type to another or between a pointer and an
10136 // integer of the same size is safe even if we do not have a body.
10137 bool isConvertible = ActTy == ParamTy ||
10138 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10139 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10140 if (Callee->isDeclaration() && !isConvertible) return false;
10143 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10144 Callee->isDeclaration())
10145 return false; // Do not delete arguments unless we have a function body.
10147 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10148 !CallerPAL.isEmpty())
10149 // In this case we have more arguments than the new function type, but we
10150 // won't be dropping them. Check that these extra arguments have attributes
10151 // that are compatible with being a vararg call argument.
10152 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10153 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10155 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10156 if (PAttrs & Attribute::VarArgsIncompatible)
10160 // Okay, we decided that this is a safe thing to do: go ahead and start
10161 // inserting cast instructions as necessary...
10162 std::vector<Value*> Args;
10163 Args.reserve(NumActualArgs);
10164 SmallVector<AttributeWithIndex, 8> attrVec;
10165 attrVec.reserve(NumCommonArgs);
10167 // Get any return attributes.
10168 Attributes RAttrs = CallerPAL.getRetAttributes();
10170 // If the return value is not being used, the type may not be compatible
10171 // with the existing attributes. Wipe out any problematic attributes.
10172 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10174 // Add the new return attributes.
10176 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10178 AI = CS.arg_begin();
10179 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10180 const Type *ParamTy = FT->getParamType(i);
10181 if ((*AI)->getType() == ParamTy) {
10182 Args.push_back(*AI);
10184 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10185 false, ParamTy, false);
10186 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10187 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10190 // Add any parameter attributes.
10191 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10192 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10195 // If the function takes more arguments than the call was taking, add them
10197 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10198 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10200 // If we are removing arguments to the function, emit an obnoxious warning...
10201 if (FT->getNumParams() < NumActualArgs) {
10202 if (!FT->isVarArg()) {
10203 cerr << "WARNING: While resolving call to function '"
10204 << Callee->getName() << "' arguments were dropped!\n";
10206 // Add all of the arguments in their promoted form to the arg list...
10207 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10208 const Type *PTy = getPromotedType((*AI)->getType());
10209 if (PTy != (*AI)->getType()) {
10210 // Must promote to pass through va_arg area!
10211 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10213 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10214 InsertNewInstBefore(Cast, *Caller);
10215 Args.push_back(Cast);
10217 Args.push_back(*AI);
10220 // Add any parameter attributes.
10221 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10222 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10227 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10228 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10230 if (NewRetTy == Type::VoidTy)
10231 Caller->setName(""); // Void type should not have a name.
10233 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10236 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10237 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10238 Args.begin(), Args.end(),
10239 Caller->getName(), Caller);
10240 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10241 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10243 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10244 Caller->getName(), Caller);
10245 CallInst *CI = cast<CallInst>(Caller);
10246 if (CI->isTailCall())
10247 cast<CallInst>(NC)->setTailCall();
10248 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10249 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10252 // Insert a cast of the return type as necessary.
10254 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10255 if (NV->getType() != Type::VoidTy) {
10256 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10258 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10260 // If this is an invoke instruction, we should insert it after the first
10261 // non-phi, instruction in the normal successor block.
10262 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10263 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10264 InsertNewInstBefore(NC, *I);
10266 // Otherwise, it's a call, just insert cast right after the call instr
10267 InsertNewInstBefore(NC, *Caller);
10269 AddUsersToWorkList(*Caller);
10271 NV = UndefValue::get(Caller->getType());
10275 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10276 Caller->replaceAllUsesWith(NV);
10277 Caller->eraseFromParent();
10278 RemoveFromWorkList(Caller);
10282 // transformCallThroughTrampoline - Turn a call to a function created by the
10283 // init_trampoline intrinsic into a direct call to the underlying function.
10285 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10286 Value *Callee = CS.getCalledValue();
10287 const PointerType *PTy = cast<PointerType>(Callee->getType());
10288 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10289 const AttrListPtr &Attrs = CS.getAttributes();
10291 // If the call already has the 'nest' attribute somewhere then give up -
10292 // otherwise 'nest' would occur twice after splicing in the chain.
10293 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10296 IntrinsicInst *Tramp =
10297 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10299 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10300 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10301 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10303 const AttrListPtr &NestAttrs = NestF->getAttributes();
10304 if (!NestAttrs.isEmpty()) {
10305 unsigned NestIdx = 1;
10306 const Type *NestTy = 0;
10307 Attributes NestAttr = Attribute::None;
10309 // Look for a parameter marked with the 'nest' attribute.
10310 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10311 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10312 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10313 // Record the parameter type and any other attributes.
10315 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10320 Instruction *Caller = CS.getInstruction();
10321 std::vector<Value*> NewArgs;
10322 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10324 SmallVector<AttributeWithIndex, 8> NewAttrs;
10325 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10327 // Insert the nest argument into the call argument list, which may
10328 // mean appending it. Likewise for attributes.
10330 // Add any result attributes.
10331 if (Attributes Attr = Attrs.getRetAttributes())
10332 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10336 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10338 if (Idx == NestIdx) {
10339 // Add the chain argument and attributes.
10340 Value *NestVal = Tramp->getOperand(3);
10341 if (NestVal->getType() != NestTy)
10342 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10343 NewArgs.push_back(NestVal);
10344 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10350 // Add the original argument and attributes.
10351 NewArgs.push_back(*I);
10352 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10354 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10360 // Add any function attributes.
10361 if (Attributes Attr = Attrs.getFnAttributes())
10362 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10364 // The trampoline may have been bitcast to a bogus type (FTy).
10365 // Handle this by synthesizing a new function type, equal to FTy
10366 // with the chain parameter inserted.
10368 std::vector<const Type*> NewTypes;
10369 NewTypes.reserve(FTy->getNumParams()+1);
10371 // Insert the chain's type into the list of parameter types, which may
10372 // mean appending it.
10375 FunctionType::param_iterator I = FTy->param_begin(),
10376 E = FTy->param_end();
10379 if (Idx == NestIdx)
10380 // Add the chain's type.
10381 NewTypes.push_back(NestTy);
10386 // Add the original type.
10387 NewTypes.push_back(*I);
10393 // Replace the trampoline call with a direct call. Let the generic
10394 // code sort out any function type mismatches.
10395 FunctionType *NewFTy =
10396 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10397 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10398 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10399 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10401 Instruction *NewCaller;
10402 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10403 NewCaller = InvokeInst::Create(NewCallee,
10404 II->getNormalDest(), II->getUnwindDest(),
10405 NewArgs.begin(), NewArgs.end(),
10406 Caller->getName(), Caller);
10407 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10408 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10410 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10411 Caller->getName(), Caller);
10412 if (cast<CallInst>(Caller)->isTailCall())
10413 cast<CallInst>(NewCaller)->setTailCall();
10414 cast<CallInst>(NewCaller)->
10415 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10416 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10418 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10419 Caller->replaceAllUsesWith(NewCaller);
10420 Caller->eraseFromParent();
10421 RemoveFromWorkList(Caller);
10426 // Replace the trampoline call with a direct call. Since there is no 'nest'
10427 // parameter, there is no need to adjust the argument list. Let the generic
10428 // code sort out any function type mismatches.
10429 Constant *NewCallee =
10430 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10431 CS.setCalledFunction(NewCallee);
10432 return CS.getInstruction();
10435 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10436 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10437 /// and a single binop.
10438 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10439 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10440 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10441 unsigned Opc = FirstInst->getOpcode();
10442 Value *LHSVal = FirstInst->getOperand(0);
10443 Value *RHSVal = FirstInst->getOperand(1);
10445 const Type *LHSType = LHSVal->getType();
10446 const Type *RHSType = RHSVal->getType();
10448 // Scan to see if all operands are the same opcode, all have one use, and all
10449 // kill their operands (i.e. the operands have one use).
10450 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10451 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10452 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10453 // Verify type of the LHS matches so we don't fold cmp's of different
10454 // types or GEP's with different index types.
10455 I->getOperand(0)->getType() != LHSType ||
10456 I->getOperand(1)->getType() != RHSType)
10459 // If they are CmpInst instructions, check their predicates
10460 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10461 if (cast<CmpInst>(I)->getPredicate() !=
10462 cast<CmpInst>(FirstInst)->getPredicate())
10465 // Keep track of which operand needs a phi node.
10466 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10467 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10470 // Otherwise, this is safe to transform!
10472 Value *InLHS = FirstInst->getOperand(0);
10473 Value *InRHS = FirstInst->getOperand(1);
10474 PHINode *NewLHS = 0, *NewRHS = 0;
10476 NewLHS = PHINode::Create(LHSType,
10477 FirstInst->getOperand(0)->getName() + ".pn");
10478 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10479 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10480 InsertNewInstBefore(NewLHS, PN);
10485 NewRHS = PHINode::Create(RHSType,
10486 FirstInst->getOperand(1)->getName() + ".pn");
10487 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10488 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10489 InsertNewInstBefore(NewRHS, PN);
10493 // Add all operands to the new PHIs.
10494 if (NewLHS || NewRHS) {
10495 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10496 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10498 Value *NewInLHS = InInst->getOperand(0);
10499 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10502 Value *NewInRHS = InInst->getOperand(1);
10503 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10508 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10509 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10510 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10511 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10515 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10516 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10518 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10519 FirstInst->op_end());
10520 // This is true if all GEP bases are allocas and if all indices into them are
10522 bool AllBasePointersAreAllocas = true;
10524 // Scan to see if all operands are the same opcode, all have one use, and all
10525 // kill their operands (i.e. the operands have one use).
10526 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10527 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10528 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10529 GEP->getNumOperands() != FirstInst->getNumOperands())
10532 // Keep track of whether or not all GEPs are of alloca pointers.
10533 if (AllBasePointersAreAllocas &&
10534 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10535 !GEP->hasAllConstantIndices()))
10536 AllBasePointersAreAllocas = false;
10538 // Compare the operand lists.
10539 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10540 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10543 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10544 // if one of the PHIs has a constant for the index. The index may be
10545 // substantially cheaper to compute for the constants, so making it a
10546 // variable index could pessimize the path. This also handles the case
10547 // for struct indices, which must always be constant.
10548 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10549 isa<ConstantInt>(GEP->getOperand(op)))
10552 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10554 FixedOperands[op] = 0; // Needs a PHI.
10558 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10559 // bother doing this transformation. At best, this will just save a bit of
10560 // offset calculation, but all the predecessors will have to materialize the
10561 // stack address into a register anyway. We'd actually rather *clone* the
10562 // load up into the predecessors so that we have a load of a gep of an alloca,
10563 // which can usually all be folded into the load.
10564 if (AllBasePointersAreAllocas)
10567 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10568 // that is variable.
10569 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10571 bool HasAnyPHIs = false;
10572 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10573 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10574 Value *FirstOp = FirstInst->getOperand(i);
10575 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10576 FirstOp->getName()+".pn");
10577 InsertNewInstBefore(NewPN, PN);
10579 NewPN->reserveOperandSpace(e);
10580 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10581 OperandPhis[i] = NewPN;
10582 FixedOperands[i] = NewPN;
10587 // Add all operands to the new PHIs.
10589 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10590 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10591 BasicBlock *InBB = PN.getIncomingBlock(i);
10593 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10594 if (PHINode *OpPhi = OperandPhis[op])
10595 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10599 Value *Base = FixedOperands[0];
10600 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10601 FixedOperands.end());
10605 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10606 /// sink the load out of the block that defines it. This means that it must be
10607 /// obvious the value of the load is not changed from the point of the load to
10608 /// the end of the block it is in.
10610 /// Finally, it is safe, but not profitable, to sink a load targetting a
10611 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10613 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10614 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10616 for (++BBI; BBI != E; ++BBI)
10617 if (BBI->mayWriteToMemory())
10620 // Check for non-address taken alloca. If not address-taken already, it isn't
10621 // profitable to do this xform.
10622 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10623 bool isAddressTaken = false;
10624 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10626 if (isa<LoadInst>(UI)) continue;
10627 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10628 // If storing TO the alloca, then the address isn't taken.
10629 if (SI->getOperand(1) == AI) continue;
10631 isAddressTaken = true;
10635 if (!isAddressTaken && AI->isStaticAlloca())
10639 // If this load is a load from a GEP with a constant offset from an alloca,
10640 // then we don't want to sink it. In its present form, it will be
10641 // load [constant stack offset]. Sinking it will cause us to have to
10642 // materialize the stack addresses in each predecessor in a register only to
10643 // do a shared load from register in the successor.
10644 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10645 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10646 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10653 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10654 // operator and they all are only used by the PHI, PHI together their
10655 // inputs, and do the operation once, to the result of the PHI.
10656 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10657 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10659 // Scan the instruction, looking for input operations that can be folded away.
10660 // If all input operands to the phi are the same instruction (e.g. a cast from
10661 // the same type or "+42") we can pull the operation through the PHI, reducing
10662 // code size and simplifying code.
10663 Constant *ConstantOp = 0;
10664 const Type *CastSrcTy = 0;
10665 bool isVolatile = false;
10666 if (isa<CastInst>(FirstInst)) {
10667 CastSrcTy = FirstInst->getOperand(0)->getType();
10668 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10669 // Can fold binop, compare or shift here if the RHS is a constant,
10670 // otherwise call FoldPHIArgBinOpIntoPHI.
10671 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10672 if (ConstantOp == 0)
10673 return FoldPHIArgBinOpIntoPHI(PN);
10674 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10675 isVolatile = LI->isVolatile();
10676 // We can't sink the load if the loaded value could be modified between the
10677 // load and the PHI.
10678 if (LI->getParent() != PN.getIncomingBlock(0) ||
10679 !isSafeAndProfitableToSinkLoad(LI))
10682 // If the PHI is of volatile loads and the load block has multiple
10683 // successors, sinking it would remove a load of the volatile value from
10684 // the path through the other successor.
10686 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10689 } else if (isa<GetElementPtrInst>(FirstInst)) {
10690 return FoldPHIArgGEPIntoPHI(PN);
10692 return 0; // Cannot fold this operation.
10695 // Check to see if all arguments are the same operation.
10696 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10697 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10698 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10699 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10702 if (I->getOperand(0)->getType() != CastSrcTy)
10703 return 0; // Cast operation must match.
10704 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10705 // We can't sink the load if the loaded value could be modified between
10706 // the load and the PHI.
10707 if (LI->isVolatile() != isVolatile ||
10708 LI->getParent() != PN.getIncomingBlock(i) ||
10709 !isSafeAndProfitableToSinkLoad(LI))
10712 // If the PHI is of volatile loads and the load block has multiple
10713 // successors, sinking it would remove a load of the volatile value from
10714 // the path through the other successor.
10716 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10719 } else if (I->getOperand(1) != ConstantOp) {
10724 // Okay, they are all the same operation. Create a new PHI node of the
10725 // correct type, and PHI together all of the LHS's of the instructions.
10726 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10727 PN.getName()+".in");
10728 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10730 Value *InVal = FirstInst->getOperand(0);
10731 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10733 // Add all operands to the new PHI.
10734 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10735 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10736 if (NewInVal != InVal)
10738 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10743 // The new PHI unions all of the same values together. This is really
10744 // common, so we handle it intelligently here for compile-time speed.
10748 InsertNewInstBefore(NewPN, PN);
10752 // Insert and return the new operation.
10753 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10754 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10755 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10756 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10757 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10758 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10759 PhiVal, ConstantOp);
10760 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10762 // If this was a volatile load that we are merging, make sure to loop through
10763 // and mark all the input loads as non-volatile. If we don't do this, we will
10764 // insert a new volatile load and the old ones will not be deletable.
10766 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10767 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10769 return new LoadInst(PhiVal, "", isVolatile);
10772 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10774 static bool DeadPHICycle(PHINode *PN,
10775 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10776 if (PN->use_empty()) return true;
10777 if (!PN->hasOneUse()) return false;
10779 // Remember this node, and if we find the cycle, return.
10780 if (!PotentiallyDeadPHIs.insert(PN))
10783 // Don't scan crazily complex things.
10784 if (PotentiallyDeadPHIs.size() == 16)
10787 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10788 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10793 /// PHIsEqualValue - Return true if this phi node is always equal to
10794 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10795 /// z = some value; x = phi (y, z); y = phi (x, z)
10796 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10797 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10798 // See if we already saw this PHI node.
10799 if (!ValueEqualPHIs.insert(PN))
10802 // Don't scan crazily complex things.
10803 if (ValueEqualPHIs.size() == 16)
10806 // Scan the operands to see if they are either phi nodes or are equal to
10808 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10809 Value *Op = PN->getIncomingValue(i);
10810 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10811 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10813 } else if (Op != NonPhiInVal)
10821 // PHINode simplification
10823 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10824 // If LCSSA is around, don't mess with Phi nodes
10825 if (MustPreserveLCSSA) return 0;
10827 if (Value *V = PN.hasConstantValue())
10828 return ReplaceInstUsesWith(PN, V);
10830 // If all PHI operands are the same operation, pull them through the PHI,
10831 // reducing code size.
10832 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10833 isa<Instruction>(PN.getIncomingValue(1)) &&
10834 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10835 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10836 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10837 // than themselves more than once.
10838 PN.getIncomingValue(0)->hasOneUse())
10839 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10842 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10843 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10844 // PHI)... break the cycle.
10845 if (PN.hasOneUse()) {
10846 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10847 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10848 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10849 PotentiallyDeadPHIs.insert(&PN);
10850 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10851 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10854 // If this phi has a single use, and if that use just computes a value for
10855 // the next iteration of a loop, delete the phi. This occurs with unused
10856 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10857 // common case here is good because the only other things that catch this
10858 // are induction variable analysis (sometimes) and ADCE, which is only run
10860 if (PHIUser->hasOneUse() &&
10861 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10862 PHIUser->use_back() == &PN) {
10863 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10867 // We sometimes end up with phi cycles that non-obviously end up being the
10868 // same value, for example:
10869 // z = some value; x = phi (y, z); y = phi (x, z)
10870 // where the phi nodes don't necessarily need to be in the same block. Do a
10871 // quick check to see if the PHI node only contains a single non-phi value, if
10872 // so, scan to see if the phi cycle is actually equal to that value.
10874 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10875 // Scan for the first non-phi operand.
10876 while (InValNo != NumOperandVals &&
10877 isa<PHINode>(PN.getIncomingValue(InValNo)))
10880 if (InValNo != NumOperandVals) {
10881 Value *NonPhiInVal = PN.getOperand(InValNo);
10883 // Scan the rest of the operands to see if there are any conflicts, if so
10884 // there is no need to recursively scan other phis.
10885 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10886 Value *OpVal = PN.getIncomingValue(InValNo);
10887 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10891 // If we scanned over all operands, then we have one unique value plus
10892 // phi values. Scan PHI nodes to see if they all merge in each other or
10894 if (InValNo == NumOperandVals) {
10895 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10896 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10897 return ReplaceInstUsesWith(PN, NonPhiInVal);
10904 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10905 Instruction *InsertPoint,
10906 InstCombiner *IC) {
10907 unsigned PtrSize = DTy->getScalarSizeInBits();
10908 unsigned VTySize = V->getType()->getScalarSizeInBits();
10909 // We must cast correctly to the pointer type. Ensure that we
10910 // sign extend the integer value if it is smaller as this is
10911 // used for address computation.
10912 Instruction::CastOps opcode =
10913 (VTySize < PtrSize ? Instruction::SExt :
10914 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10915 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10919 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10920 Value *PtrOp = GEP.getOperand(0);
10921 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10922 // If so, eliminate the noop.
10923 if (GEP.getNumOperands() == 1)
10924 return ReplaceInstUsesWith(GEP, PtrOp);
10926 if (isa<UndefValue>(GEP.getOperand(0)))
10927 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10929 bool HasZeroPointerIndex = false;
10930 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10931 HasZeroPointerIndex = C->isNullValue();
10933 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10934 return ReplaceInstUsesWith(GEP, PtrOp);
10936 // Eliminate unneeded casts for indices.
10937 bool MadeChange = false;
10939 gep_type_iterator GTI = gep_type_begin(GEP);
10940 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10941 i != e; ++i, ++GTI) {
10942 if (isa<SequentialType>(*GTI)) {
10943 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10944 if (CI->getOpcode() == Instruction::ZExt ||
10945 CI->getOpcode() == Instruction::SExt) {
10946 const Type *SrcTy = CI->getOperand(0)->getType();
10947 // We can eliminate a cast from i32 to i64 iff the target
10948 // is a 32-bit pointer target.
10949 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
10951 *i = CI->getOperand(0);
10955 // If we are using a wider index than needed for this platform, shrink it
10956 // to what we need. If narrower, sign-extend it to what we need.
10957 // If the incoming value needs a cast instruction,
10958 // insert it. This explicit cast can make subsequent optimizations more
10961 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10962 if (Constant *C = dyn_cast<Constant>(Op)) {
10963 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10966 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10971 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10972 if (Constant *C = dyn_cast<Constant>(Op)) {
10973 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10976 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10984 if (MadeChange) return &GEP;
10986 // Combine Indices - If the source pointer to this getelementptr instruction
10987 // is a getelementptr instruction, combine the indices of the two
10988 // getelementptr instructions into a single instruction.
10990 SmallVector<Value*, 8> SrcGEPOperands;
10991 if (User *Src = dyn_castGetElementPtr(PtrOp))
10992 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10994 if (!SrcGEPOperands.empty()) {
10995 // Note that if our source is a gep chain itself that we wait for that
10996 // chain to be resolved before we perform this transformation. This
10997 // avoids us creating a TON of code in some cases.
10999 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11000 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11001 return 0; // Wait until our source is folded to completion.
11003 SmallVector<Value*, 8> Indices;
11005 // Find out whether the last index in the source GEP is a sequential idx.
11006 bool EndsWithSequential = false;
11007 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11008 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11009 EndsWithSequential = !isa<StructType>(*I);
11011 // Can we combine the two pointer arithmetics offsets?
11012 if (EndsWithSequential) {
11013 // Replace: gep (gep %P, long B), long A, ...
11014 // With: T = long A+B; gep %P, T, ...
11016 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11017 if (SO1 == Constant::getNullValue(SO1->getType())) {
11019 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11022 // If they aren't the same type, convert both to an integer of the
11023 // target's pointer size.
11024 if (SO1->getType() != GO1->getType()) {
11025 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11026 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
11027 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11028 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
11030 unsigned PS = TD->getPointerSizeInBits();
11031 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11032 // Convert GO1 to SO1's type.
11033 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11035 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11036 // Convert SO1 to GO1's type.
11037 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11039 const Type *PT = TD->getIntPtrType();
11040 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11041 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11045 if (isa<Constant>(SO1) && isa<Constant>(GO1))
11046 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
11048 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11049 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11053 // Recycle the GEP we already have if possible.
11054 if (SrcGEPOperands.size() == 2) {
11055 GEP.setOperand(0, SrcGEPOperands[0]);
11056 GEP.setOperand(1, Sum);
11059 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11060 SrcGEPOperands.end()-1);
11061 Indices.push_back(Sum);
11062 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11064 } else if (isa<Constant>(*GEP.idx_begin()) &&
11065 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11066 SrcGEPOperands.size() != 1) {
11067 // Otherwise we can do the fold if the first index of the GEP is a zero
11068 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11069 SrcGEPOperands.end());
11070 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11073 if (!Indices.empty())
11074 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11075 Indices.end(), GEP.getName());
11077 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11078 // GEP of global variable. If all of the indices for this GEP are
11079 // constants, we can promote this to a constexpr instead of an instruction.
11081 // Scan for nonconstants...
11082 SmallVector<Constant*, 8> Indices;
11083 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11084 for (; I != E && isa<Constant>(*I); ++I)
11085 Indices.push_back(cast<Constant>(*I));
11087 if (I == E) { // If they are all constants...
11088 Constant *CE = ConstantExpr::getGetElementPtr(GV,
11089 &Indices[0],Indices.size());
11091 // Replace all uses of the GEP with the new constexpr...
11092 return ReplaceInstUsesWith(GEP, CE);
11094 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11095 if (!isa<PointerType>(X->getType())) {
11096 // Not interesting. Source pointer must be a cast from pointer.
11097 } else if (HasZeroPointerIndex) {
11098 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11099 // into : GEP [10 x i8]* X, i32 0, ...
11101 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11102 // into : GEP i8* X, ...
11104 // This occurs when the program declares an array extern like "int X[];"
11105 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11106 const PointerType *XTy = cast<PointerType>(X->getType());
11107 if (const ArrayType *CATy =
11108 dyn_cast<ArrayType>(CPTy->getElementType())) {
11109 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11110 if (CATy->getElementType() == XTy->getElementType()) {
11111 // -> GEP i8* X, ...
11112 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11113 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11115 } else if (const ArrayType *XATy =
11116 dyn_cast<ArrayType>(XTy->getElementType())) {
11117 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11118 if (CATy->getElementType() == XATy->getElementType()) {
11119 // -> GEP [10 x i8]* X, i32 0, ...
11120 // At this point, we know that the cast source type is a pointer
11121 // to an array of the same type as the destination pointer
11122 // array. Because the array type is never stepped over (there
11123 // is a leading zero) we can fold the cast into this GEP.
11124 GEP.setOperand(0, X);
11129 } else if (GEP.getNumOperands() == 2) {
11130 // Transform things like:
11131 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11132 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11133 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11134 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11135 if (isa<ArrayType>(SrcElTy) &&
11136 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11137 TD->getTypeAllocSize(ResElTy)) {
11139 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11140 Idx[1] = GEP.getOperand(1);
11141 Value *V = InsertNewInstBefore(
11142 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11143 // V and GEP are both pointer types --> BitCast
11144 return new BitCastInst(V, GEP.getType());
11147 // Transform things like:
11148 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11149 // (where tmp = 8*tmp2) into:
11150 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11152 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11153 uint64_t ArrayEltSize =
11154 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11156 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11157 // allow either a mul, shift, or constant here.
11159 ConstantInt *Scale = 0;
11160 if (ArrayEltSize == 1) {
11161 NewIdx = GEP.getOperand(1);
11162 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11163 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11164 NewIdx = ConstantInt::get(CI->getType(), 1);
11166 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11167 if (Inst->getOpcode() == Instruction::Shl &&
11168 isa<ConstantInt>(Inst->getOperand(1))) {
11169 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11170 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11171 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11173 NewIdx = Inst->getOperand(0);
11174 } else if (Inst->getOpcode() == Instruction::Mul &&
11175 isa<ConstantInt>(Inst->getOperand(1))) {
11176 Scale = cast<ConstantInt>(Inst->getOperand(1));
11177 NewIdx = Inst->getOperand(0);
11181 // If the index will be to exactly the right offset with the scale taken
11182 // out, perform the transformation. Note, we don't know whether Scale is
11183 // signed or not. We'll use unsigned version of division/modulo
11184 // operation after making sure Scale doesn't have the sign bit set.
11185 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11186 Scale->getZExtValue() % ArrayEltSize == 0) {
11187 Scale = ConstantInt::get(Scale->getType(),
11188 Scale->getZExtValue() / ArrayEltSize);
11189 if (Scale->getZExtValue() != 1) {
11190 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11192 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11193 NewIdx = InsertNewInstBefore(Sc, GEP);
11196 // Insert the new GEP instruction.
11198 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11200 Instruction *NewGEP =
11201 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11202 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11203 // The NewGEP must be pointer typed, so must the old one -> BitCast
11204 return new BitCastInst(NewGEP, GEP.getType());
11210 /// See if we can simplify:
11211 /// X = bitcast A to B*
11212 /// Y = gep X, <...constant indices...>
11213 /// into a gep of the original struct. This is important for SROA and alias
11214 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11215 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11216 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11217 // Determine how much the GEP moves the pointer. We are guaranteed to get
11218 // a constant back from EmitGEPOffset.
11219 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11220 int64_t Offset = OffsetV->getSExtValue();
11222 // If this GEP instruction doesn't move the pointer, just replace the GEP
11223 // with a bitcast of the real input to the dest type.
11225 // If the bitcast is of an allocation, and the allocation will be
11226 // converted to match the type of the cast, don't touch this.
11227 if (isa<AllocationInst>(BCI->getOperand(0))) {
11228 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11229 if (Instruction *I = visitBitCast(*BCI)) {
11232 BCI->getParent()->getInstList().insert(BCI, I);
11233 ReplaceInstUsesWith(*BCI, I);
11238 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11241 // Otherwise, if the offset is non-zero, we need to find out if there is a
11242 // field at Offset in 'A's type. If so, we can pull the cast through the
11244 SmallVector<Value*, 8> NewIndices;
11246 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11247 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11248 Instruction *NGEP =
11249 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11251 if (NGEP->getType() == GEP.getType()) return NGEP;
11252 InsertNewInstBefore(NGEP, GEP);
11253 NGEP->takeName(&GEP);
11254 return new BitCastInst(NGEP, GEP.getType());
11262 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11263 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11264 if (AI.isArrayAllocation()) { // Check C != 1
11265 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11266 const Type *NewTy =
11267 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11268 AllocationInst *New = 0;
11270 // Create and insert the replacement instruction...
11271 if (isa<MallocInst>(AI))
11272 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11274 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11275 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11278 InsertNewInstBefore(New, AI);
11280 // Scan to the end of the allocation instructions, to skip over a block of
11281 // allocas if possible...also skip interleaved debug info
11283 BasicBlock::iterator It = New;
11284 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11286 // Now that I is pointing to the first non-allocation-inst in the block,
11287 // insert our getelementptr instruction...
11289 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
11293 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11294 New->getName()+".sub", It);
11296 // Now make everything use the getelementptr instead of the original
11298 return ReplaceInstUsesWith(AI, V);
11299 } else if (isa<UndefValue>(AI.getArraySize())) {
11300 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11304 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11305 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11306 // Note that we only do this for alloca's, because malloc should allocate
11307 // and return a unique pointer, even for a zero byte allocation.
11308 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11309 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11311 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11312 if (AI.getAlignment() == 0)
11313 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11319 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11320 Value *Op = FI.getOperand(0);
11322 // free undef -> unreachable.
11323 if (isa<UndefValue>(Op)) {
11324 // Insert a new store to null because we cannot modify the CFG here.
11325 new StoreInst(ConstantInt::getTrue(),
11326 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
11327 return EraseInstFromFunction(FI);
11330 // If we have 'free null' delete the instruction. This can happen in stl code
11331 // when lots of inlining happens.
11332 if (isa<ConstantPointerNull>(Op))
11333 return EraseInstFromFunction(FI);
11335 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11336 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11337 FI.setOperand(0, CI->getOperand(0));
11341 // Change free (gep X, 0,0,0,0) into free(X)
11342 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11343 if (GEPI->hasAllZeroIndices()) {
11344 AddToWorkList(GEPI);
11345 FI.setOperand(0, GEPI->getOperand(0));
11350 // Change free(malloc) into nothing, if the malloc has a single use.
11351 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11352 if (MI->hasOneUse()) {
11353 EraseInstFromFunction(FI);
11354 return EraseInstFromFunction(*MI);
11361 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11362 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11363 const TargetData *TD) {
11364 User *CI = cast<User>(LI.getOperand(0));
11365 Value *CastOp = CI->getOperand(0);
11368 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11369 // Instead of loading constant c string, use corresponding integer value
11370 // directly if string length is small enough.
11372 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11373 unsigned len = Str.length();
11374 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11375 unsigned numBits = Ty->getPrimitiveSizeInBits();
11376 // Replace LI with immediate integer store.
11377 if ((numBits >> 3) == len + 1) {
11378 APInt StrVal(numBits, 0);
11379 APInt SingleChar(numBits, 0);
11380 if (TD->isLittleEndian()) {
11381 for (signed i = len-1; i >= 0; i--) {
11382 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11383 StrVal = (StrVal << 8) | SingleChar;
11386 for (unsigned i = 0; i < len; i++) {
11387 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11388 StrVal = (StrVal << 8) | SingleChar;
11390 // Append NULL at the end.
11392 StrVal = (StrVal << 8) | SingleChar;
11394 Value *NL = ConstantInt::get(StrVal);
11395 return IC.ReplaceInstUsesWith(LI, NL);
11401 const PointerType *DestTy = cast<PointerType>(CI->getType());
11402 const Type *DestPTy = DestTy->getElementType();
11403 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11405 // If the address spaces don't match, don't eliminate the cast.
11406 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11409 const Type *SrcPTy = SrcTy->getElementType();
11411 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11412 isa<VectorType>(DestPTy)) {
11413 // If the source is an array, the code below will not succeed. Check to
11414 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11416 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11417 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11418 if (ASrcTy->getNumElements() != 0) {
11420 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11421 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11422 SrcTy = cast<PointerType>(CastOp->getType());
11423 SrcPTy = SrcTy->getElementType();
11426 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11427 isa<VectorType>(SrcPTy)) &&
11428 // Do not allow turning this into a load of an integer, which is then
11429 // casted to a pointer, this pessimizes pointer analysis a lot.
11430 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11431 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11432 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11434 // Okay, we are casting from one integer or pointer type to another of
11435 // the same size. Instead of casting the pointer before the load, cast
11436 // the result of the loaded value.
11437 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11439 LI.isVolatile()),LI);
11440 // Now cast the result of the load.
11441 return new BitCastInst(NewLoad, LI.getType());
11448 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11449 Value *Op = LI.getOperand(0);
11451 // Attempt to improve the alignment.
11452 unsigned KnownAlign =
11453 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11455 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11456 LI.getAlignment()))
11457 LI.setAlignment(KnownAlign);
11459 // load (cast X) --> cast (load X) iff safe
11460 if (isa<CastInst>(Op))
11461 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11464 // None of the following transforms are legal for volatile loads.
11465 if (LI.isVolatile()) return 0;
11467 // Do really simple store-to-load forwarding and load CSE, to catch cases
11468 // where there are several consequtive memory accesses to the same location,
11469 // separated by a few arithmetic operations.
11470 BasicBlock::iterator BBI = &LI;
11471 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11472 return ReplaceInstUsesWith(LI, AvailableVal);
11474 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11475 const Value *GEPI0 = GEPI->getOperand(0);
11476 // TODO: Consider a target hook for valid address spaces for this xform.
11477 if (isa<ConstantPointerNull>(GEPI0) &&
11478 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11479 // Insert a new store to null instruction before the load to indicate
11480 // that this code is not reachable. We do this instead of inserting
11481 // an unreachable instruction directly because we cannot modify the
11483 new StoreInst(UndefValue::get(LI.getType()),
11484 Constant::getNullValue(Op->getType()), &LI);
11485 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11489 if (Constant *C = dyn_cast<Constant>(Op)) {
11490 // load null/undef -> undef
11491 // TODO: Consider a target hook for valid address spaces for this xform.
11492 if (isa<UndefValue>(C) || (C->isNullValue() &&
11493 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11494 // Insert a new store to null instruction before the load to indicate that
11495 // this code is not reachable. We do this instead of inserting an
11496 // unreachable instruction directly because we cannot modify the CFG.
11497 new StoreInst(UndefValue::get(LI.getType()),
11498 Constant::getNullValue(Op->getType()), &LI);
11499 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11502 // Instcombine load (constant global) into the value loaded.
11503 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11504 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11505 return ReplaceInstUsesWith(LI, GV->getInitializer());
11507 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11508 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11509 if (CE->getOpcode() == Instruction::GetElementPtr) {
11510 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11511 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11513 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11514 return ReplaceInstUsesWith(LI, V);
11515 if (CE->getOperand(0)->isNullValue()) {
11516 // Insert a new store to null instruction before the load to indicate
11517 // that this code is not reachable. We do this instead of inserting
11518 // an unreachable instruction directly because we cannot modify the
11520 new StoreInst(UndefValue::get(LI.getType()),
11521 Constant::getNullValue(Op->getType()), &LI);
11522 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11525 } else if (CE->isCast()) {
11526 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11532 // If this load comes from anywhere in a constant global, and if the global
11533 // is all undef or zero, we know what it loads.
11534 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11535 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11536 if (GV->getInitializer()->isNullValue())
11537 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11538 else if (isa<UndefValue>(GV->getInitializer()))
11539 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11543 if (Op->hasOneUse()) {
11544 // Change select and PHI nodes to select values instead of addresses: this
11545 // helps alias analysis out a lot, allows many others simplifications, and
11546 // exposes redundancy in the code.
11548 // Note that we cannot do the transformation unless we know that the
11549 // introduced loads cannot trap! Something like this is valid as long as
11550 // the condition is always false: load (select bool %C, int* null, int* %G),
11551 // but it would not be valid if we transformed it to load from null
11552 // unconditionally.
11554 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11555 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11556 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11557 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11558 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11559 SI->getOperand(1)->getName()+".val"), LI);
11560 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11561 SI->getOperand(2)->getName()+".val"), LI);
11562 return SelectInst::Create(SI->getCondition(), V1, V2);
11565 // load (select (cond, null, P)) -> load P
11566 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11567 if (C->isNullValue()) {
11568 LI.setOperand(0, SI->getOperand(2));
11572 // load (select (cond, P, null)) -> load P
11573 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11574 if (C->isNullValue()) {
11575 LI.setOperand(0, SI->getOperand(1));
11583 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11584 /// when possible. This makes it generally easy to do alias analysis and/or
11585 /// SROA/mem2reg of the memory object.
11586 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11587 User *CI = cast<User>(SI.getOperand(1));
11588 Value *CastOp = CI->getOperand(0);
11590 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11591 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11592 if (SrcTy == 0) return 0;
11594 const Type *SrcPTy = SrcTy->getElementType();
11596 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11599 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11600 /// to its first element. This allows us to handle things like:
11601 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11602 /// on 32-bit hosts.
11603 SmallVector<Value*, 4> NewGEPIndices;
11605 // If the source is an array, the code below will not succeed. Check to
11606 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11608 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11609 // Index through pointer.
11610 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11611 NewGEPIndices.push_back(Zero);
11614 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11615 if (!STy->getNumElements()) /* Struct can be empty {} */
11617 NewGEPIndices.push_back(Zero);
11618 SrcPTy = STy->getElementType(0);
11619 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11620 NewGEPIndices.push_back(Zero);
11621 SrcPTy = ATy->getElementType();
11627 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11630 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11633 // If the pointers point into different address spaces or if they point to
11634 // values with different sizes, we can't do the transformation.
11635 if (SrcTy->getAddressSpace() !=
11636 cast<PointerType>(CI->getType())->getAddressSpace() ||
11637 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11638 IC.getTargetData().getTypeSizeInBits(DestPTy))
11641 // Okay, we are casting from one integer or pointer type to another of
11642 // the same size. Instead of casting the pointer before
11643 // the store, cast the value to be stored.
11645 Value *SIOp0 = SI.getOperand(0);
11646 Instruction::CastOps opcode = Instruction::BitCast;
11647 const Type* CastSrcTy = SIOp0->getType();
11648 const Type* CastDstTy = SrcPTy;
11649 if (isa<PointerType>(CastDstTy)) {
11650 if (CastSrcTy->isInteger())
11651 opcode = Instruction::IntToPtr;
11652 } else if (isa<IntegerType>(CastDstTy)) {
11653 if (isa<PointerType>(SIOp0->getType()))
11654 opcode = Instruction::PtrToInt;
11657 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11658 // emit a GEP to index into its first field.
11659 if (!NewGEPIndices.empty()) {
11660 if (Constant *C = dyn_cast<Constant>(CastOp))
11661 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11662 NewGEPIndices.size());
11664 CastOp = IC.InsertNewInstBefore(
11665 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11666 NewGEPIndices.end()), SI);
11669 if (Constant *C = dyn_cast<Constant>(SIOp0))
11670 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11672 NewCast = IC.InsertNewInstBefore(
11673 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11675 return new StoreInst(NewCast, CastOp);
11678 /// equivalentAddressValues - Test if A and B will obviously have the same
11679 /// value. This includes recognizing that %t0 and %t1 will have the same
11680 /// value in code like this:
11681 /// %t0 = getelementptr \@a, 0, 3
11682 /// store i32 0, i32* %t0
11683 /// %t1 = getelementptr \@a, 0, 3
11684 /// %t2 = load i32* %t1
11686 static bool equivalentAddressValues(Value *A, Value *B) {
11687 // Test if the values are trivially equivalent.
11688 if (A == B) return true;
11690 // Test if the values come form identical arithmetic instructions.
11691 if (isa<BinaryOperator>(A) ||
11692 isa<CastInst>(A) ||
11694 isa<GetElementPtrInst>(A))
11695 if (Instruction *BI = dyn_cast<Instruction>(B))
11696 if (cast<Instruction>(A)->isIdenticalTo(BI))
11699 // Otherwise they may not be equivalent.
11703 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11704 // return the llvm.dbg.declare.
11705 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11706 if (!V->hasNUses(2))
11708 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11710 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11712 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11713 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11720 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11721 Value *Val = SI.getOperand(0);
11722 Value *Ptr = SI.getOperand(1);
11724 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11725 EraseInstFromFunction(SI);
11730 // If the RHS is an alloca with a single use, zapify the store, making the
11732 // If the RHS is an alloca with a two uses, the other one being a
11733 // llvm.dbg.declare, zapify the store and the declare, making the
11734 // alloca dead. We must do this to prevent declare's from affecting
11736 if (!SI.isVolatile()) {
11737 if (Ptr->hasOneUse()) {
11738 if (isa<AllocaInst>(Ptr)) {
11739 EraseInstFromFunction(SI);
11743 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11744 if (isa<AllocaInst>(GEP->getOperand(0))) {
11745 if (GEP->getOperand(0)->hasOneUse()) {
11746 EraseInstFromFunction(SI);
11750 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11751 EraseInstFromFunction(*DI);
11752 EraseInstFromFunction(SI);
11759 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11760 EraseInstFromFunction(*DI);
11761 EraseInstFromFunction(SI);
11767 // Attempt to improve the alignment.
11768 unsigned KnownAlign =
11769 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11771 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11772 SI.getAlignment()))
11773 SI.setAlignment(KnownAlign);
11775 // Do really simple DSE, to catch cases where there are several consecutive
11776 // stores to the same location, separated by a few arithmetic operations. This
11777 // situation often occurs with bitfield accesses.
11778 BasicBlock::iterator BBI = &SI;
11779 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11782 // Don't count debug info directives, lest they affect codegen,
11783 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11784 // It is necessary for correctness to skip those that feed into a
11785 // llvm.dbg.declare, as these are not present when debugging is off.
11786 if (isa<DbgInfoIntrinsic>(BBI) ||
11787 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11792 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11793 // Prev store isn't volatile, and stores to the same location?
11794 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11795 SI.getOperand(1))) {
11798 EraseInstFromFunction(*PrevSI);
11804 // If this is a load, we have to stop. However, if the loaded value is from
11805 // the pointer we're loading and is producing the pointer we're storing,
11806 // then *this* store is dead (X = load P; store X -> P).
11807 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11808 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11809 !SI.isVolatile()) {
11810 EraseInstFromFunction(SI);
11814 // Otherwise, this is a load from some other location. Stores before it
11815 // may not be dead.
11819 // Don't skip over loads or things that can modify memory.
11820 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11825 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11827 // store X, null -> turns into 'unreachable' in SimplifyCFG
11828 if (isa<ConstantPointerNull>(Ptr) &&
11829 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11830 if (!isa<UndefValue>(Val)) {
11831 SI.setOperand(0, UndefValue::get(Val->getType()));
11832 if (Instruction *U = dyn_cast<Instruction>(Val))
11833 AddToWorkList(U); // Dropped a use.
11836 return 0; // Do not modify these!
11839 // store undef, Ptr -> noop
11840 if (isa<UndefValue>(Val)) {
11841 EraseInstFromFunction(SI);
11846 // If the pointer destination is a cast, see if we can fold the cast into the
11848 if (isa<CastInst>(Ptr))
11849 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11851 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11853 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11857 // If this store is the last instruction in the basic block (possibly
11858 // excepting debug info instructions and the pointer bitcasts that feed
11859 // into them), and if the block ends with an unconditional branch, try
11860 // to move it to the successor block.
11864 } while (isa<DbgInfoIntrinsic>(BBI) ||
11865 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11866 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11867 if (BI->isUnconditional())
11868 if (SimplifyStoreAtEndOfBlock(SI))
11869 return 0; // xform done!
11874 /// SimplifyStoreAtEndOfBlock - Turn things like:
11875 /// if () { *P = v1; } else { *P = v2 }
11876 /// into a phi node with a store in the successor.
11878 /// Simplify things like:
11879 /// *P = v1; if () { *P = v2; }
11880 /// into a phi node with a store in the successor.
11882 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11883 BasicBlock *StoreBB = SI.getParent();
11885 // Check to see if the successor block has exactly two incoming edges. If
11886 // so, see if the other predecessor contains a store to the same location.
11887 // if so, insert a PHI node (if needed) and move the stores down.
11888 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11890 // Determine whether Dest has exactly two predecessors and, if so, compute
11891 // the other predecessor.
11892 pred_iterator PI = pred_begin(DestBB);
11893 BasicBlock *OtherBB = 0;
11894 if (*PI != StoreBB)
11897 if (PI == pred_end(DestBB))
11900 if (*PI != StoreBB) {
11905 if (++PI != pred_end(DestBB))
11908 // Bail out if all the relevant blocks aren't distinct (this can happen,
11909 // for example, if SI is in an infinite loop)
11910 if (StoreBB == DestBB || OtherBB == DestBB)
11913 // Verify that the other block ends in a branch and is not otherwise empty.
11914 BasicBlock::iterator BBI = OtherBB->getTerminator();
11915 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11916 if (!OtherBr || BBI == OtherBB->begin())
11919 // If the other block ends in an unconditional branch, check for the 'if then
11920 // else' case. there is an instruction before the branch.
11921 StoreInst *OtherStore = 0;
11922 if (OtherBr->isUnconditional()) {
11924 // Skip over debugging info.
11925 while (isa<DbgInfoIntrinsic>(BBI) ||
11926 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11927 if (BBI==OtherBB->begin())
11931 // If this isn't a store, or isn't a store to the same location, bail out.
11932 OtherStore = dyn_cast<StoreInst>(BBI);
11933 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11936 // Otherwise, the other block ended with a conditional branch. If one of the
11937 // destinations is StoreBB, then we have the if/then case.
11938 if (OtherBr->getSuccessor(0) != StoreBB &&
11939 OtherBr->getSuccessor(1) != StoreBB)
11942 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11943 // if/then triangle. See if there is a store to the same ptr as SI that
11944 // lives in OtherBB.
11946 // Check to see if we find the matching store.
11947 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11948 if (OtherStore->getOperand(1) != SI.getOperand(1))
11952 // If we find something that may be using or overwriting the stored
11953 // value, or if we run out of instructions, we can't do the xform.
11954 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11955 BBI == OtherBB->begin())
11959 // In order to eliminate the store in OtherBr, we have to
11960 // make sure nothing reads or overwrites the stored value in
11962 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11963 // FIXME: This should really be AA driven.
11964 if (I->mayReadFromMemory() || I->mayWriteToMemory())
11969 // Insert a PHI node now if we need it.
11970 Value *MergedVal = OtherStore->getOperand(0);
11971 if (MergedVal != SI.getOperand(0)) {
11972 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11973 PN->reserveOperandSpace(2);
11974 PN->addIncoming(SI.getOperand(0), SI.getParent());
11975 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11976 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11979 // Advance to a place where it is safe to insert the new store and
11981 BBI = DestBB->getFirstNonPHI();
11982 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11983 OtherStore->isVolatile()), *BBI);
11985 // Nuke the old stores.
11986 EraseInstFromFunction(SI);
11987 EraseInstFromFunction(*OtherStore);
11993 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11994 // Change br (not X), label True, label False to: br X, label False, True
11996 BasicBlock *TrueDest;
11997 BasicBlock *FalseDest;
11998 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11999 !isa<Constant>(X)) {
12000 // Swap Destinations and condition...
12001 BI.setCondition(X);
12002 BI.setSuccessor(0, FalseDest);
12003 BI.setSuccessor(1, TrueDest);
12007 // Cannonicalize fcmp_one -> fcmp_oeq
12008 FCmpInst::Predicate FPred; Value *Y;
12009 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
12010 TrueDest, FalseDest)))
12011 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12012 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12013 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12014 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12015 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
12016 NewSCC->takeName(I);
12017 // Swap Destinations and condition...
12018 BI.setCondition(NewSCC);
12019 BI.setSuccessor(0, FalseDest);
12020 BI.setSuccessor(1, TrueDest);
12021 RemoveFromWorkList(I);
12022 I->eraseFromParent();
12023 AddToWorkList(NewSCC);
12027 // Cannonicalize icmp_ne -> icmp_eq
12028 ICmpInst::Predicate IPred;
12029 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12030 TrueDest, FalseDest)))
12031 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12032 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12033 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12034 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12035 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12036 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
12037 NewSCC->takeName(I);
12038 // Swap Destinations and condition...
12039 BI.setCondition(NewSCC);
12040 BI.setSuccessor(0, FalseDest);
12041 BI.setSuccessor(1, TrueDest);
12042 RemoveFromWorkList(I);
12043 I->eraseFromParent();;
12044 AddToWorkList(NewSCC);
12051 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12052 Value *Cond = SI.getCondition();
12053 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12054 if (I->getOpcode() == Instruction::Add)
12055 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12056 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12057 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12058 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12060 SI.setOperand(0, I->getOperand(0));
12068 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12069 Value *Agg = EV.getAggregateOperand();
12071 if (!EV.hasIndices())
12072 return ReplaceInstUsesWith(EV, Agg);
12074 if (Constant *C = dyn_cast<Constant>(Agg)) {
12075 if (isa<UndefValue>(C))
12076 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12078 if (isa<ConstantAggregateZero>(C))
12079 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12081 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12082 // Extract the element indexed by the first index out of the constant
12083 Value *V = C->getOperand(*EV.idx_begin());
12084 if (EV.getNumIndices() > 1)
12085 // Extract the remaining indices out of the constant indexed by the
12087 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12089 return ReplaceInstUsesWith(EV, V);
12091 return 0; // Can't handle other constants
12093 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12094 // We're extracting from an insertvalue instruction, compare the indices
12095 const unsigned *exti, *exte, *insi, *inse;
12096 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12097 exte = EV.idx_end(), inse = IV->idx_end();
12098 exti != exte && insi != inse;
12100 if (*insi != *exti)
12101 // The insert and extract both reference distinctly different elements.
12102 // This means the extract is not influenced by the insert, and we can
12103 // replace the aggregate operand of the extract with the aggregate
12104 // operand of the insert. i.e., replace
12105 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12106 // %E = extractvalue { i32, { i32 } } %I, 0
12108 // %E = extractvalue { i32, { i32 } } %A, 0
12109 return ExtractValueInst::Create(IV->getAggregateOperand(),
12110 EV.idx_begin(), EV.idx_end());
12112 if (exti == exte && insi == inse)
12113 // Both iterators are at the end: Index lists are identical. Replace
12114 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12115 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12117 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12118 if (exti == exte) {
12119 // The extract list is a prefix of the insert list. i.e. replace
12120 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12121 // %E = extractvalue { i32, { i32 } } %I, 1
12123 // %X = extractvalue { i32, { i32 } } %A, 1
12124 // %E = insertvalue { i32 } %X, i32 42, 0
12125 // by switching the order of the insert and extract (though the
12126 // insertvalue should be left in, since it may have other uses).
12127 Value *NewEV = InsertNewInstBefore(
12128 ExtractValueInst::Create(IV->getAggregateOperand(),
12129 EV.idx_begin(), EV.idx_end()),
12131 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12135 // The insert list is a prefix of the extract list
12136 // We can simply remove the common indices from the extract and make it
12137 // operate on the inserted value instead of the insertvalue result.
12139 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12140 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12142 // %E extractvalue { i32 } { i32 42 }, 0
12143 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12146 // Can't simplify extracts from other values. Note that nested extracts are
12147 // already simplified implicitely by the above (extract ( extract (insert) )
12148 // will be translated into extract ( insert ( extract ) ) first and then just
12149 // the value inserted, if appropriate).
12153 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12154 /// is to leave as a vector operation.
12155 static bool CheapToScalarize(Value *V, bool isConstant) {
12156 if (isa<ConstantAggregateZero>(V))
12158 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12159 if (isConstant) return true;
12160 // If all elts are the same, we can extract.
12161 Constant *Op0 = C->getOperand(0);
12162 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12163 if (C->getOperand(i) != Op0)
12167 Instruction *I = dyn_cast<Instruction>(V);
12168 if (!I) return false;
12170 // Insert element gets simplified to the inserted element or is deleted if
12171 // this is constant idx extract element and its a constant idx insertelt.
12172 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12173 isa<ConstantInt>(I->getOperand(2)))
12175 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12177 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12178 if (BO->hasOneUse() &&
12179 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12180 CheapToScalarize(BO->getOperand(1), isConstant)))
12182 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12183 if (CI->hasOneUse() &&
12184 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12185 CheapToScalarize(CI->getOperand(1), isConstant)))
12191 /// Read and decode a shufflevector mask.
12193 /// It turns undef elements into values that are larger than the number of
12194 /// elements in the input.
12195 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12196 unsigned NElts = SVI->getType()->getNumElements();
12197 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12198 return std::vector<unsigned>(NElts, 0);
12199 if (isa<UndefValue>(SVI->getOperand(2)))
12200 return std::vector<unsigned>(NElts, 2*NElts);
12202 std::vector<unsigned> Result;
12203 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12204 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12205 if (isa<UndefValue>(*i))
12206 Result.push_back(NElts*2); // undef -> 8
12208 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12212 /// FindScalarElement - Given a vector and an element number, see if the scalar
12213 /// value is already around as a register, for example if it were inserted then
12214 /// extracted from the vector.
12215 static Value *FindScalarElement(Value *V, unsigned EltNo) {
12216 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12217 const VectorType *PTy = cast<VectorType>(V->getType());
12218 unsigned Width = PTy->getNumElements();
12219 if (EltNo >= Width) // Out of range access.
12220 return UndefValue::get(PTy->getElementType());
12222 if (isa<UndefValue>(V))
12223 return UndefValue::get(PTy->getElementType());
12224 else if (isa<ConstantAggregateZero>(V))
12225 return Constant::getNullValue(PTy->getElementType());
12226 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12227 return CP->getOperand(EltNo);
12228 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12229 // If this is an insert to a variable element, we don't know what it is.
12230 if (!isa<ConstantInt>(III->getOperand(2)))
12232 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12234 // If this is an insert to the element we are looking for, return the
12236 if (EltNo == IIElt)
12237 return III->getOperand(1);
12239 // Otherwise, the insertelement doesn't modify the value, recurse on its
12241 return FindScalarElement(III->getOperand(0), EltNo);
12242 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12243 unsigned LHSWidth =
12244 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12245 unsigned InEl = getShuffleMask(SVI)[EltNo];
12246 if (InEl < LHSWidth)
12247 return FindScalarElement(SVI->getOperand(0), InEl);
12248 else if (InEl < LHSWidth*2)
12249 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
12251 return UndefValue::get(PTy->getElementType());
12254 // Otherwise, we don't know.
12258 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12259 // If vector val is undef, replace extract with scalar undef.
12260 if (isa<UndefValue>(EI.getOperand(0)))
12261 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12263 // If vector val is constant 0, replace extract with scalar 0.
12264 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12265 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12267 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12268 // If vector val is constant with all elements the same, replace EI with
12269 // that element. When the elements are not identical, we cannot replace yet
12270 // (we do that below, but only when the index is constant).
12271 Constant *op0 = C->getOperand(0);
12272 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12273 if (C->getOperand(i) != op0) {
12278 return ReplaceInstUsesWith(EI, op0);
12281 // If extracting a specified index from the vector, see if we can recursively
12282 // find a previously computed scalar that was inserted into the vector.
12283 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12284 unsigned IndexVal = IdxC->getZExtValue();
12285 unsigned VectorWidth =
12286 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12288 // If this is extracting an invalid index, turn this into undef, to avoid
12289 // crashing the code below.
12290 if (IndexVal >= VectorWidth)
12291 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12293 // This instruction only demands the single element from the input vector.
12294 // If the input vector has a single use, simplify it based on this use
12296 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12297 APInt UndefElts(VectorWidth, 0);
12298 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12299 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12300 DemandedMask, UndefElts)) {
12301 EI.setOperand(0, V);
12306 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
12307 return ReplaceInstUsesWith(EI, Elt);
12309 // If the this extractelement is directly using a bitcast from a vector of
12310 // the same number of elements, see if we can find the source element from
12311 // it. In this case, we will end up needing to bitcast the scalars.
12312 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12313 if (const VectorType *VT =
12314 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12315 if (VT->getNumElements() == VectorWidth)
12316 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12317 return new BitCastInst(Elt, EI.getType());
12321 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12322 if (I->hasOneUse()) {
12323 // Push extractelement into predecessor operation if legal and
12324 // profitable to do so
12325 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12326 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12327 if (CheapToScalarize(BO, isConstantElt)) {
12328 ExtractElementInst *newEI0 =
12329 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12330 EI.getName()+".lhs");
12331 ExtractElementInst *newEI1 =
12332 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12333 EI.getName()+".rhs");
12334 InsertNewInstBefore(newEI0, EI);
12335 InsertNewInstBefore(newEI1, EI);
12336 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12338 } else if (isa<LoadInst>(I)) {
12340 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12341 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12342 PointerType::get(EI.getType(), AS),EI);
12343 GetElementPtrInst *GEP =
12344 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12345 InsertNewInstBefore(GEP, EI);
12346 return new LoadInst(GEP);
12349 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12350 // Extracting the inserted element?
12351 if (IE->getOperand(2) == EI.getOperand(1))
12352 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12353 // If the inserted and extracted elements are constants, they must not
12354 // be the same value, extract from the pre-inserted value instead.
12355 if (isa<Constant>(IE->getOperand(2)) &&
12356 isa<Constant>(EI.getOperand(1))) {
12357 AddUsesToWorkList(EI);
12358 EI.setOperand(0, IE->getOperand(0));
12361 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12362 // If this is extracting an element from a shufflevector, figure out where
12363 // it came from and extract from the appropriate input element instead.
12364 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12365 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12367 unsigned LHSWidth =
12368 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12370 if (SrcIdx < LHSWidth)
12371 Src = SVI->getOperand(0);
12372 else if (SrcIdx < LHSWidth*2) {
12373 SrcIdx -= LHSWidth;
12374 Src = SVI->getOperand(1);
12376 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12378 return new ExtractElementInst(Src, SrcIdx);
12385 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12386 /// elements from either LHS or RHS, return the shuffle mask and true.
12387 /// Otherwise, return false.
12388 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12389 std::vector<Constant*> &Mask) {
12390 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12391 "Invalid CollectSingleShuffleElements");
12392 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12394 if (isa<UndefValue>(V)) {
12395 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12397 } else if (V == LHS) {
12398 for (unsigned i = 0; i != NumElts; ++i)
12399 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12401 } else if (V == RHS) {
12402 for (unsigned i = 0; i != NumElts; ++i)
12403 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12405 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12406 // If this is an insert of an extract from some other vector, include it.
12407 Value *VecOp = IEI->getOperand(0);
12408 Value *ScalarOp = IEI->getOperand(1);
12409 Value *IdxOp = IEI->getOperand(2);
12411 if (!isa<ConstantInt>(IdxOp))
12413 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12415 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12416 // Okay, we can handle this if the vector we are insertinting into is
12417 // transitively ok.
12418 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12419 // If so, update the mask to reflect the inserted undef.
12420 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12423 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12424 if (isa<ConstantInt>(EI->getOperand(1)) &&
12425 EI->getOperand(0)->getType() == V->getType()) {
12426 unsigned ExtractedIdx =
12427 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12429 // This must be extracting from either LHS or RHS.
12430 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12431 // Okay, we can handle this if the vector we are insertinting into is
12432 // transitively ok.
12433 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12434 // If so, update the mask to reflect the inserted value.
12435 if (EI->getOperand(0) == LHS) {
12436 Mask[InsertedIdx % NumElts] =
12437 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12439 assert(EI->getOperand(0) == RHS);
12440 Mask[InsertedIdx % NumElts] =
12441 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12450 // TODO: Handle shufflevector here!
12455 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12456 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12457 /// that computes V and the LHS value of the shuffle.
12458 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12460 assert(isa<VectorType>(V->getType()) &&
12461 (RHS == 0 || V->getType() == RHS->getType()) &&
12462 "Invalid shuffle!");
12463 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12465 if (isa<UndefValue>(V)) {
12466 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12468 } else if (isa<ConstantAggregateZero>(V)) {
12469 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12471 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12472 // If this is an insert of an extract from some other vector, include it.
12473 Value *VecOp = IEI->getOperand(0);
12474 Value *ScalarOp = IEI->getOperand(1);
12475 Value *IdxOp = IEI->getOperand(2);
12477 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12478 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12479 EI->getOperand(0)->getType() == V->getType()) {
12480 unsigned ExtractedIdx =
12481 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12482 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12484 // Either the extracted from or inserted into vector must be RHSVec,
12485 // otherwise we'd end up with a shuffle of three inputs.
12486 if (EI->getOperand(0) == RHS || RHS == 0) {
12487 RHS = EI->getOperand(0);
12488 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12489 Mask[InsertedIdx % NumElts] =
12490 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12494 if (VecOp == RHS) {
12495 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12496 // Everything but the extracted element is replaced with the RHS.
12497 for (unsigned i = 0; i != NumElts; ++i) {
12498 if (i != InsertedIdx)
12499 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12504 // If this insertelement is a chain that comes from exactly these two
12505 // vectors, return the vector and the effective shuffle.
12506 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12507 return EI->getOperand(0);
12512 // TODO: Handle shufflevector here!
12514 // Otherwise, can't do anything fancy. Return an identity vector.
12515 for (unsigned i = 0; i != NumElts; ++i)
12516 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12520 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12521 Value *VecOp = IE.getOperand(0);
12522 Value *ScalarOp = IE.getOperand(1);
12523 Value *IdxOp = IE.getOperand(2);
12525 // Inserting an undef or into an undefined place, remove this.
12526 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12527 ReplaceInstUsesWith(IE, VecOp);
12529 // If the inserted element was extracted from some other vector, and if the
12530 // indexes are constant, try to turn this into a shufflevector operation.
12531 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12532 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12533 EI->getOperand(0)->getType() == IE.getType()) {
12534 unsigned NumVectorElts = IE.getType()->getNumElements();
12535 unsigned ExtractedIdx =
12536 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12537 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12539 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12540 return ReplaceInstUsesWith(IE, VecOp);
12542 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12543 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12545 // If we are extracting a value from a vector, then inserting it right
12546 // back into the same place, just use the input vector.
12547 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12548 return ReplaceInstUsesWith(IE, VecOp);
12550 // We could theoretically do this for ANY input. However, doing so could
12551 // turn chains of insertelement instructions into a chain of shufflevector
12552 // instructions, and right now we do not merge shufflevectors. As such,
12553 // only do this in a situation where it is clear that there is benefit.
12554 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12555 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12556 // the values of VecOp, except then one read from EIOp0.
12557 // Build a new shuffle mask.
12558 std::vector<Constant*> Mask;
12559 if (isa<UndefValue>(VecOp))
12560 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12562 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12563 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12566 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12567 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12568 ConstantVector::get(Mask));
12571 // If this insertelement isn't used by some other insertelement, turn it
12572 // (and any insertelements it points to), into one big shuffle.
12573 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12574 std::vector<Constant*> Mask;
12576 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12577 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12578 // We now have a shuffle of LHS, RHS, Mask.
12579 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12584 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12585 APInt UndefElts(VWidth, 0);
12586 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12587 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12594 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12595 Value *LHS = SVI.getOperand(0);
12596 Value *RHS = SVI.getOperand(1);
12597 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12599 bool MadeChange = false;
12601 // Undefined shuffle mask -> undefined value.
12602 if (isa<UndefValue>(SVI.getOperand(2)))
12603 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12605 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12607 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12610 APInt UndefElts(VWidth, 0);
12611 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12612 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12613 LHS = SVI.getOperand(0);
12614 RHS = SVI.getOperand(1);
12618 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12619 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12620 if (LHS == RHS || isa<UndefValue>(LHS)) {
12621 if (isa<UndefValue>(LHS) && LHS == RHS) {
12622 // shuffle(undef,undef,mask) -> undef.
12623 return ReplaceInstUsesWith(SVI, LHS);
12626 // Remap any references to RHS to use LHS.
12627 std::vector<Constant*> Elts;
12628 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12629 if (Mask[i] >= 2*e)
12630 Elts.push_back(UndefValue::get(Type::Int32Ty));
12632 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12633 (Mask[i] < e && isa<UndefValue>(LHS))) {
12634 Mask[i] = 2*e; // Turn into undef.
12635 Elts.push_back(UndefValue::get(Type::Int32Ty));
12637 Mask[i] = Mask[i] % e; // Force to LHS.
12638 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12642 SVI.setOperand(0, SVI.getOperand(1));
12643 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12644 SVI.setOperand(2, ConstantVector::get(Elts));
12645 LHS = SVI.getOperand(0);
12646 RHS = SVI.getOperand(1);
12650 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12651 bool isLHSID = true, isRHSID = true;
12653 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12654 if (Mask[i] >= e*2) continue; // Ignore undef values.
12655 // Is this an identity shuffle of the LHS value?
12656 isLHSID &= (Mask[i] == i);
12658 // Is this an identity shuffle of the RHS value?
12659 isRHSID &= (Mask[i]-e == i);
12662 // Eliminate identity shuffles.
12663 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12664 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12666 // If the LHS is a shufflevector itself, see if we can combine it with this
12667 // one without producing an unusual shuffle. Here we are really conservative:
12668 // we are absolutely afraid of producing a shuffle mask not in the input
12669 // program, because the code gen may not be smart enough to turn a merged
12670 // shuffle into two specific shuffles: it may produce worse code. As such,
12671 // we only merge two shuffles if the result is one of the two input shuffle
12672 // masks. In this case, merging the shuffles just removes one instruction,
12673 // which we know is safe. This is good for things like turning:
12674 // (splat(splat)) -> splat.
12675 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12676 if (isa<UndefValue>(RHS)) {
12677 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12679 std::vector<unsigned> NewMask;
12680 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12681 if (Mask[i] >= 2*e)
12682 NewMask.push_back(2*e);
12684 NewMask.push_back(LHSMask[Mask[i]]);
12686 // If the result mask is equal to the src shuffle or this shuffle mask, do
12687 // the replacement.
12688 if (NewMask == LHSMask || NewMask == Mask) {
12689 unsigned LHSInNElts =
12690 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12691 std::vector<Constant*> Elts;
12692 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12693 if (NewMask[i] >= LHSInNElts*2) {
12694 Elts.push_back(UndefValue::get(Type::Int32Ty));
12696 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12699 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12700 LHSSVI->getOperand(1),
12701 ConstantVector::get(Elts));
12706 return MadeChange ? &SVI : 0;
12712 /// TryToSinkInstruction - Try to move the specified instruction from its
12713 /// current block into the beginning of DestBlock, which can only happen if it's
12714 /// safe to move the instruction past all of the instructions between it and the
12715 /// end of its block.
12716 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12717 assert(I->hasOneUse() && "Invariants didn't hold!");
12719 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12720 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12723 // Do not sink alloca instructions out of the entry block.
12724 if (isa<AllocaInst>(I) && I->getParent() ==
12725 &DestBlock->getParent()->getEntryBlock())
12728 // We can only sink load instructions if there is nothing between the load and
12729 // the end of block that could change the value.
12730 if (I->mayReadFromMemory()) {
12731 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12733 if (Scan->mayWriteToMemory())
12737 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12739 CopyPrecedingStopPoint(I, InsertPos);
12740 I->moveBefore(InsertPos);
12746 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12747 /// all reachable code to the worklist.
12749 /// This has a couple of tricks to make the code faster and more powerful. In
12750 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12751 /// them to the worklist (this significantly speeds up instcombine on code where
12752 /// many instructions are dead or constant). Additionally, if we find a branch
12753 /// whose condition is a known constant, we only visit the reachable successors.
12755 static void AddReachableCodeToWorklist(BasicBlock *BB,
12756 SmallPtrSet<BasicBlock*, 64> &Visited,
12758 const TargetData *TD) {
12759 SmallVector<BasicBlock*, 256> Worklist;
12760 Worklist.push_back(BB);
12762 while (!Worklist.empty()) {
12763 BB = Worklist.back();
12764 Worklist.pop_back();
12766 // We have now visited this block! If we've already been here, ignore it.
12767 if (!Visited.insert(BB)) continue;
12769 DbgInfoIntrinsic *DBI_Prev = NULL;
12770 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12771 Instruction *Inst = BBI++;
12773 // DCE instruction if trivially dead.
12774 if (isInstructionTriviallyDead(Inst)) {
12776 DOUT << "IC: DCE: " << *Inst;
12777 Inst->eraseFromParent();
12781 // ConstantProp instruction if trivially constant.
12782 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12783 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12784 Inst->replaceAllUsesWith(C);
12786 Inst->eraseFromParent();
12790 // If there are two consecutive llvm.dbg.stoppoint calls then
12791 // it is likely that the optimizer deleted code in between these
12793 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12796 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12797 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12798 IC.RemoveFromWorkList(DBI_Prev);
12799 DBI_Prev->eraseFromParent();
12801 DBI_Prev = DBI_Next;
12806 IC.AddToWorkList(Inst);
12809 // Recursively visit successors. If this is a branch or switch on a
12810 // constant, only visit the reachable successor.
12811 TerminatorInst *TI = BB->getTerminator();
12812 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12813 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12814 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12815 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12816 Worklist.push_back(ReachableBB);
12819 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12820 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12821 // See if this is an explicit destination.
12822 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12823 if (SI->getCaseValue(i) == Cond) {
12824 BasicBlock *ReachableBB = SI->getSuccessor(i);
12825 Worklist.push_back(ReachableBB);
12829 // Otherwise it is the default destination.
12830 Worklist.push_back(SI->getSuccessor(0));
12835 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12836 Worklist.push_back(TI->getSuccessor(i));
12840 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12841 bool Changed = false;
12842 TD = &getAnalysis<TargetData>();
12844 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12845 << F.getNameStr() << "\n");
12848 // Do a depth-first traversal of the function, populate the worklist with
12849 // the reachable instructions. Ignore blocks that are not reachable. Keep
12850 // track of which blocks we visit.
12851 SmallPtrSet<BasicBlock*, 64> Visited;
12852 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12854 // Do a quick scan over the function. If we find any blocks that are
12855 // unreachable, remove any instructions inside of them. This prevents
12856 // the instcombine code from having to deal with some bad special cases.
12857 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12858 if (!Visited.count(BB)) {
12859 Instruction *Term = BB->getTerminator();
12860 while (Term != BB->begin()) { // Remove instrs bottom-up
12861 BasicBlock::iterator I = Term; --I;
12863 DOUT << "IC: DCE: " << *I;
12864 // A debug intrinsic shouldn't force another iteration if we weren't
12865 // going to do one without it.
12866 if (!isa<DbgInfoIntrinsic>(I)) {
12870 if (!I->use_empty())
12871 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12872 I->eraseFromParent();
12877 while (!Worklist.empty()) {
12878 Instruction *I = RemoveOneFromWorkList();
12879 if (I == 0) continue; // skip null values.
12881 // Check to see if we can DCE the instruction.
12882 if (isInstructionTriviallyDead(I)) {
12883 // Add operands to the worklist.
12884 if (I->getNumOperands() < 4)
12885 AddUsesToWorkList(*I);
12888 DOUT << "IC: DCE: " << *I;
12890 I->eraseFromParent();
12891 RemoveFromWorkList(I);
12896 // Instruction isn't dead, see if we can constant propagate it.
12897 if (Constant *C = ConstantFoldInstruction(I, TD)) {
12898 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12900 // Add operands to the worklist.
12901 AddUsesToWorkList(*I);
12902 ReplaceInstUsesWith(*I, C);
12905 I->eraseFromParent();
12906 RemoveFromWorkList(I);
12912 (I->getType()->getTypeID() == Type::VoidTyID ||
12913 I->isTrapping())) {
12914 // See if we can constant fold its operands.
12915 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12916 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12917 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12924 // See if we can trivially sink this instruction to a successor basic block.
12925 if (I->hasOneUse()) {
12926 BasicBlock *BB = I->getParent();
12927 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12928 if (UserParent != BB) {
12929 bool UserIsSuccessor = false;
12930 // See if the user is one of our successors.
12931 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12932 if (*SI == UserParent) {
12933 UserIsSuccessor = true;
12937 // If the user is one of our immediate successors, and if that successor
12938 // only has us as a predecessors (we'd have to split the critical edge
12939 // otherwise), we can keep going.
12940 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12941 next(pred_begin(UserParent)) == pred_end(UserParent))
12942 // Okay, the CFG is simple enough, try to sink this instruction.
12943 Changed |= TryToSinkInstruction(I, UserParent);
12947 // Now that we have an instruction, try combining it to simplify it...
12951 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12952 if (Instruction *Result = visit(*I)) {
12954 // Should we replace the old instruction with a new one?
12956 DOUT << "IC: Old = " << *I
12957 << " New = " << *Result;
12959 // Everything uses the new instruction now.
12960 I->replaceAllUsesWith(Result);
12962 // Push the new instruction and any users onto the worklist.
12963 AddToWorkList(Result);
12964 AddUsersToWorkList(*Result);
12966 // Move the name to the new instruction first.
12967 Result->takeName(I);
12969 // Insert the new instruction into the basic block...
12970 BasicBlock *InstParent = I->getParent();
12971 BasicBlock::iterator InsertPos = I;
12973 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12974 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12977 InstParent->getInstList().insert(InsertPos, Result);
12979 // Make sure that we reprocess all operands now that we reduced their
12981 AddUsesToWorkList(*I);
12983 // Instructions can end up on the worklist more than once. Make sure
12984 // we do not process an instruction that has been deleted.
12985 RemoveFromWorkList(I);
12987 // Erase the old instruction.
12988 InstParent->getInstList().erase(I);
12991 DOUT << "IC: Mod = " << OrigI
12992 << " New = " << *I;
12995 // If the instruction was modified, it's possible that it is now dead.
12996 // if so, remove it.
12997 if (isInstructionTriviallyDead(I)) {
12998 // Make sure we process all operands now that we are reducing their
13000 AddUsesToWorkList(*I);
13002 // Instructions may end up in the worklist more than once. Erase all
13003 // occurrences of this instruction.
13004 RemoveFromWorkList(I);
13005 I->eraseFromParent();
13008 AddUsersToWorkList(*I);
13015 assert(WorklistMap.empty() && "Worklist empty, but map not?");
13017 // Do an explicit clear, this shrinks the map if needed.
13018 WorklistMap.clear();
13023 bool InstCombiner::runOnFunction(Function &F) {
13024 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13026 bool EverMadeChange = false;
13028 // Iterate while there is work to do.
13029 unsigned Iteration = 0;
13030 while (DoOneIteration(F, Iteration++))
13031 EverMadeChange = true;
13032 return EverMadeChange;
13035 FunctionPass *llvm::createInstructionCombiningPass() {
13036 return new InstCombiner();