1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG. This pass is where
12 // algebraic simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/ConstantRange.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/PatternMatch.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/ADT/DenseMap.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/SmallPtrSet.h"
61 #include "llvm/ADT/Statistic.h"
62 #include "llvm/ADT/STLExtras.h"
67 using namespace llvm::PatternMatch;
69 STATISTIC(NumCombined , "Number of insts combined");
70 STATISTIC(NumConstProp, "Number of constant folds");
71 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
72 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
73 STATISTIC(NumSunkInst , "Number of instructions sunk");
76 class VISIBILITY_HIDDEN InstCombiner
77 : public FunctionPass,
78 public InstVisitor<InstCombiner, Instruction*> {
79 // Worklist of all of the instructions that need to be simplified.
80 SmallVector<Instruction*, 256> Worklist;
81 DenseMap<Instruction*, unsigned> WorklistMap;
83 bool MustPreserveLCSSA;
85 static char ID; // Pass identification, replacement for typeid
86 InstCombiner() : FunctionPass(&ID) {}
89 LLVMContext *getContext() const { return Context; }
91 /// AddToWorkList - Add the specified instruction to the worklist if it
92 /// isn't already in it.
93 void AddToWorkList(Instruction *I) {
94 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
95 Worklist.push_back(I);
98 // RemoveFromWorkList - remove I from the worklist if it exists.
99 void RemoveFromWorkList(Instruction *I) {
100 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
101 if (It == WorklistMap.end()) return; // Not in worklist.
103 // Don't bother moving everything down, just null out the slot.
104 Worklist[It->second] = 0;
106 WorklistMap.erase(It);
109 Instruction *RemoveOneFromWorkList() {
110 Instruction *I = Worklist.back();
112 WorklistMap.erase(I);
117 /// AddUsersToWorkList - When an instruction is simplified, add all users of
118 /// the instruction to the work lists because they might get more simplified
121 void AddUsersToWorkList(Value &I) {
122 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
124 AddToWorkList(cast<Instruction>(*UI));
127 /// AddUsesToWorkList - When an instruction is simplified, add operands to
128 /// the work lists because they might get more simplified now.
130 void AddUsesToWorkList(Instruction &I) {
131 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
132 if (Instruction *Op = dyn_cast<Instruction>(*i))
136 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
137 /// dead. Add all of its operands to the worklist, turning them into
138 /// undef's to reduce the number of uses of those instructions.
140 /// Return the specified operand before it is turned into an undef.
142 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
143 Value *R = I.getOperand(op);
145 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
146 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
148 // Set the operand to undef to drop the use.
149 *i = Context->getUndef(Op->getType());
156 virtual bool runOnFunction(Function &F);
158 bool DoOneIteration(Function &F, unsigned ItNum);
160 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
161 AU.addPreservedID(LCSSAID);
162 AU.setPreservesCFG();
165 TargetData *getTargetData() const { return TD; }
167 // Visitation implementation - Implement instruction combining for different
168 // instruction types. The semantics are as follows:
170 // null - No change was made
171 // I - Change was made, I is still valid, I may be dead though
172 // otherwise - Change was made, replace I with returned instruction
174 Instruction *visitAdd(BinaryOperator &I);
175 Instruction *visitFAdd(BinaryOperator &I);
176 Instruction *visitSub(BinaryOperator &I);
177 Instruction *visitFSub(BinaryOperator &I);
178 Instruction *visitMul(BinaryOperator &I);
179 Instruction *visitFMul(BinaryOperator &I);
180 Instruction *visitURem(BinaryOperator &I);
181 Instruction *visitSRem(BinaryOperator &I);
182 Instruction *visitFRem(BinaryOperator &I);
183 bool SimplifyDivRemOfSelect(BinaryOperator &I);
184 Instruction *commonRemTransforms(BinaryOperator &I);
185 Instruction *commonIRemTransforms(BinaryOperator &I);
186 Instruction *commonDivTransforms(BinaryOperator &I);
187 Instruction *commonIDivTransforms(BinaryOperator &I);
188 Instruction *visitUDiv(BinaryOperator &I);
189 Instruction *visitSDiv(BinaryOperator &I);
190 Instruction *visitFDiv(BinaryOperator &I);
191 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
192 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
193 Instruction *visitAnd(BinaryOperator &I);
194 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
195 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
196 Value *A, Value *B, Value *C);
197 Instruction *visitOr (BinaryOperator &I);
198 Instruction *visitXor(BinaryOperator &I);
199 Instruction *visitShl(BinaryOperator &I);
200 Instruction *visitAShr(BinaryOperator &I);
201 Instruction *visitLShr(BinaryOperator &I);
202 Instruction *commonShiftTransforms(BinaryOperator &I);
203 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
205 Instruction *visitFCmpInst(FCmpInst &I);
206 Instruction *visitICmpInst(ICmpInst &I);
207 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
208 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
211 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
212 ConstantInt *DivRHS);
214 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
215 ICmpInst::Predicate Cond, Instruction &I);
216 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
218 Instruction *commonCastTransforms(CastInst &CI);
219 Instruction *commonIntCastTransforms(CastInst &CI);
220 Instruction *commonPointerCastTransforms(CastInst &CI);
221 Instruction *visitTrunc(TruncInst &CI);
222 Instruction *visitZExt(ZExtInst &CI);
223 Instruction *visitSExt(SExtInst &CI);
224 Instruction *visitFPTrunc(FPTruncInst &CI);
225 Instruction *visitFPExt(CastInst &CI);
226 Instruction *visitFPToUI(FPToUIInst &FI);
227 Instruction *visitFPToSI(FPToSIInst &FI);
228 Instruction *visitUIToFP(CastInst &CI);
229 Instruction *visitSIToFP(CastInst &CI);
230 Instruction *visitPtrToInt(PtrToIntInst &CI);
231 Instruction *visitIntToPtr(IntToPtrInst &CI);
232 Instruction *visitBitCast(BitCastInst &CI);
233 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
235 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
236 Instruction *visitSelectInst(SelectInst &SI);
237 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
238 Instruction *visitCallInst(CallInst &CI);
239 Instruction *visitInvokeInst(InvokeInst &II);
240 Instruction *visitPHINode(PHINode &PN);
241 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
242 Instruction *visitAllocationInst(AllocationInst &AI);
243 Instruction *visitFreeInst(FreeInst &FI);
244 Instruction *visitLoadInst(LoadInst &LI);
245 Instruction *visitStoreInst(StoreInst &SI);
246 Instruction *visitBranchInst(BranchInst &BI);
247 Instruction *visitSwitchInst(SwitchInst &SI);
248 Instruction *visitInsertElementInst(InsertElementInst &IE);
249 Instruction *visitExtractElementInst(ExtractElementInst &EI);
250 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
251 Instruction *visitExtractValueInst(ExtractValueInst &EV);
253 // visitInstruction - Specify what to return for unhandled instructions...
254 Instruction *visitInstruction(Instruction &I) { return 0; }
257 Instruction *visitCallSite(CallSite CS);
258 bool transformConstExprCastCall(CallSite CS);
259 Instruction *transformCallThroughTrampoline(CallSite CS);
260 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
261 bool DoXform = true);
262 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
263 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
267 // InsertNewInstBefore - insert an instruction New before instruction Old
268 // in the program. Add the new instruction to the worklist.
270 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
271 assert(New && New->getParent() == 0 &&
272 "New instruction already inserted into a basic block!");
273 BasicBlock *BB = Old.getParent();
274 BB->getInstList().insert(&Old, New); // Insert inst
279 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
280 /// This also adds the cast to the worklist. Finally, this returns the
282 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
284 if (V->getType() == Ty) return V;
286 if (Constant *CV = dyn_cast<Constant>(V))
287 return Context->getConstantExprCast(opc, CV, Ty);
289 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
294 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
295 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
299 // ReplaceInstUsesWith - This method is to be used when an instruction is
300 // found to be dead, replacable with another preexisting expression. Here
301 // we add all uses of I to the worklist, replace all uses of I with the new
302 // value, then return I, so that the inst combiner will know that I was
305 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
306 AddUsersToWorkList(I); // Add all modified instrs to worklist
308 I.replaceAllUsesWith(V);
311 // If we are replacing the instruction with itself, this must be in a
312 // segment of unreachable code, so just clobber the instruction.
313 I.replaceAllUsesWith(Context->getUndef(I.getType()));
318 // EraseInstFromFunction - When dealing with an instruction that has side
319 // effects or produces a void value, we can't rely on DCE to delete the
320 // instruction. Instead, visit methods should return the value returned by
322 Instruction *EraseInstFromFunction(Instruction &I) {
323 assert(I.use_empty() && "Cannot erase instruction that is used!");
324 AddUsesToWorkList(I);
325 RemoveFromWorkList(&I);
327 return 0; // Don't do anything with FI
330 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
331 APInt &KnownOne, unsigned Depth = 0) const {
332 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335 bool MaskedValueIsZero(Value *V, const APInt &Mask,
336 unsigned Depth = 0) const {
337 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
339 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
340 return llvm::ComputeNumSignBits(Op, TD, Depth);
345 /// SimplifyCommutative - This performs a few simplifications for
346 /// commutative operators.
347 bool SimplifyCommutative(BinaryOperator &I);
349 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
350 /// most-complex to least-complex order.
351 bool SimplifyCompare(CmpInst &I);
353 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
354 /// based on the demanded bits.
355 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
356 APInt& KnownZero, APInt& KnownOne,
358 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
359 APInt& KnownZero, APInt& KnownOne,
362 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
363 /// SimplifyDemandedBits knows about. See if the instruction has any
364 /// properties that allow us to simplify its operands.
365 bool SimplifyDemandedInstructionBits(Instruction &Inst);
367 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
368 APInt& UndefElts, unsigned Depth = 0);
370 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
371 // PHI node as operand #0, see if we can fold the instruction into the PHI
372 // (which is only possible if all operands to the PHI are constants).
373 Instruction *FoldOpIntoPhi(Instruction &I);
375 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
376 // operator and they all are only used by the PHI, PHI together their
377 // inputs, and do the operation once, to the result of the PHI.
378 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
379 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
380 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
383 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
384 ConstantInt *AndRHS, BinaryOperator &TheAnd);
386 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
387 bool isSub, Instruction &I);
388 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
389 bool isSigned, bool Inside, Instruction &IB);
390 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
391 Instruction *MatchBSwap(BinaryOperator &I);
392 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
393 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
394 Instruction *SimplifyMemSet(MemSetInst *MI);
397 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
399 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
400 unsigned CastOpc, int &NumCastsRemoved);
401 unsigned GetOrEnforceKnownAlignment(Value *V,
402 unsigned PrefAlign = 0);
407 char InstCombiner::ID = 0;
408 static RegisterPass<InstCombiner>
409 X("instcombine", "Combine redundant instructions");
411 // getComplexity: Assign a complexity or rank value to LLVM Values...
412 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
413 static unsigned getComplexity(LLVMContext *Context, Value *V) {
414 if (isa<Instruction>(V)) {
415 if (BinaryOperator::isNeg(V) ||
416 BinaryOperator::isFNeg(V) ||
417 BinaryOperator::isNot(V))
421 if (isa<Argument>(V)) return 3;
422 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
425 // isOnlyUse - Return true if this instruction will be deleted if we stop using
427 static bool isOnlyUse(Value *V) {
428 return V->hasOneUse() || isa<Constant>(V);
431 // getPromotedType - Return the specified type promoted as it would be to pass
432 // though a va_arg area...
433 static const Type *getPromotedType(const Type *Ty) {
434 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
435 if (ITy->getBitWidth() < 32)
436 return Type::Int32Ty;
441 /// getBitCastOperand - If the specified operand is a CastInst, a constant
442 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
443 /// operand value, otherwise return null.
444 static Value *getBitCastOperand(Value *V) {
445 if (Operator *O = dyn_cast<Operator>(V)) {
446 if (O->getOpcode() == Instruction::BitCast)
447 return O->getOperand(0);
448 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
449 if (GEP->hasAllZeroIndices())
450 return GEP->getPointerOperand();
455 /// This function is a wrapper around CastInst::isEliminableCastPair. It
456 /// simply extracts arguments and returns what that function returns.
457 static Instruction::CastOps
458 isEliminableCastPair(
459 const CastInst *CI, ///< The first cast instruction
460 unsigned opcode, ///< The opcode of the second cast instruction
461 const Type *DstTy, ///< The target type for the second cast instruction
462 TargetData *TD ///< The target data for pointer size
465 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
466 const Type *MidTy = CI->getType(); // B from above
468 // Get the opcodes of the two Cast instructions
469 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
470 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
472 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
474 TD ? TD->getIntPtrType() : 0);
476 // We don't want to form an inttoptr or ptrtoint that converts to an integer
477 // type that differs from the pointer size.
478 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
479 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
482 return Instruction::CastOps(Res);
485 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
486 /// in any code being generated. It does not require codegen if V is simple
487 /// enough or if the cast can be folded into other casts.
488 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
489 const Type *Ty, TargetData *TD) {
490 if (V->getType() == Ty || isa<Constant>(V)) return false;
492 // If this is another cast that can be eliminated, it isn't codegen either.
493 if (const CastInst *CI = dyn_cast<CastInst>(V))
494 if (isEliminableCastPair(CI, opcode, Ty, TD))
499 // SimplifyCommutative - This performs a few simplifications for commutative
502 // 1. Order operands such that they are listed from right (least complex) to
503 // left (most complex). This puts constants before unary operators before
506 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
507 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
509 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
510 bool Changed = false;
511 if (getComplexity(Context, I.getOperand(0)) <
512 getComplexity(Context, I.getOperand(1)))
513 Changed = !I.swapOperands();
515 if (!I.isAssociative()) return Changed;
516 Instruction::BinaryOps Opcode = I.getOpcode();
517 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
518 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
519 if (isa<Constant>(I.getOperand(1))) {
520 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
521 cast<Constant>(I.getOperand(1)),
522 cast<Constant>(Op->getOperand(1)));
523 I.setOperand(0, Op->getOperand(0));
524 I.setOperand(1, Folded);
526 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
527 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
528 isOnlyUse(Op) && isOnlyUse(Op1)) {
529 Constant *C1 = cast<Constant>(Op->getOperand(1));
530 Constant *C2 = cast<Constant>(Op1->getOperand(1));
532 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
533 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
534 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
538 I.setOperand(0, New);
539 I.setOperand(1, Folded);
546 /// SimplifyCompare - For a CmpInst this function just orders the operands
547 /// so that theyare listed from right (least complex) to left (most complex).
548 /// This puts constants before unary operators before binary operators.
549 bool InstCombiner::SimplifyCompare(CmpInst &I) {
550 if (getComplexity(Context, I.getOperand(0)) >=
551 getComplexity(Context, I.getOperand(1)))
554 // Compare instructions are not associative so there's nothing else we can do.
558 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
559 // if the LHS is a constant zero (which is the 'negate' form).
561 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
562 if (BinaryOperator::isNeg(V))
563 return BinaryOperator::getNegArgument(V);
565 // Constants can be considered to be negated values if they can be folded.
566 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
567 return Context->getConstantExprNeg(C);
569 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
570 if (C->getType()->getElementType()->isInteger())
571 return Context->getConstantExprNeg(C);
576 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
577 // instruction if the LHS is a constant negative zero (which is the 'negate'
580 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
581 if (BinaryOperator::isFNeg(V))
582 return BinaryOperator::getFNegArgument(V);
584 // Constants can be considered to be negated values if they can be folded.
585 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
586 return Context->getConstantExprFNeg(C);
588 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
589 if (C->getType()->getElementType()->isFloatingPoint())
590 return Context->getConstantExprFNeg(C);
595 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
596 if (BinaryOperator::isNot(V))
597 return BinaryOperator::getNotArgument(V);
599 // Constants can be considered to be not'ed values...
600 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
601 return Context->getConstantInt(~C->getValue());
605 // dyn_castFoldableMul - If this value is a multiply that can be folded into
606 // other computations (because it has a constant operand), return the
607 // non-constant operand of the multiply, and set CST to point to the multiplier.
608 // Otherwise, return null.
610 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
611 LLVMContext *Context) {
612 if (V->hasOneUse() && V->getType()->isInteger())
613 if (Instruction *I = dyn_cast<Instruction>(V)) {
614 if (I->getOpcode() == Instruction::Mul)
615 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
616 return I->getOperand(0);
617 if (I->getOpcode() == Instruction::Shl)
618 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
619 // The multiplier is really 1 << CST.
620 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
621 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
622 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
623 return I->getOperand(0);
629 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
630 /// expression, return it.
631 static User *dyn_castGetElementPtr(Value *V) {
632 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
633 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
634 if (CE->getOpcode() == Instruction::GetElementPtr)
635 return cast<User>(V);
639 /// AddOne - Add one to a ConstantInt
640 static Constant *AddOne(Constant *C, LLVMContext *Context) {
641 return Context->getConstantExprAdd(C,
642 Context->getConstantInt(C->getType(), 1));
644 /// SubOne - Subtract one from a ConstantInt
645 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
646 return Context->getConstantExprSub(C,
647 Context->getConstantInt(C->getType(), 1));
649 /// MultiplyOverflows - True if the multiply can not be expressed in an int
651 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
652 LLVMContext *Context) {
653 uint32_t W = C1->getBitWidth();
654 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
663 APInt MulExt = LHSExt * RHSExt;
666 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
667 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
668 return MulExt.slt(Min) || MulExt.sgt(Max);
670 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
674 /// ShrinkDemandedConstant - Check to see if the specified operand of the
675 /// specified instruction is a constant integer. If so, check to see if there
676 /// are any bits set in the constant that are not demanded. If so, shrink the
677 /// constant and return true.
678 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
679 APInt Demanded, LLVMContext *Context) {
680 assert(I && "No instruction?");
681 assert(OpNo < I->getNumOperands() && "Operand index too large");
683 // If the operand is not a constant integer, nothing to do.
684 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
685 if (!OpC) return false;
687 // If there are no bits set that aren't demanded, nothing to do.
688 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
689 if ((~Demanded & OpC->getValue()) == 0)
692 // This instruction is producing bits that are not demanded. Shrink the RHS.
693 Demanded &= OpC->getValue();
694 I->setOperand(OpNo, Context->getConstantInt(Demanded));
698 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
699 // set of known zero and one bits, compute the maximum and minimum values that
700 // could have the specified known zero and known one bits, returning them in
702 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
703 const APInt& KnownOne,
704 APInt& Min, APInt& Max) {
705 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
706 KnownZero.getBitWidth() == Min.getBitWidth() &&
707 KnownZero.getBitWidth() == Max.getBitWidth() &&
708 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
709 APInt UnknownBits = ~(KnownZero|KnownOne);
711 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
712 // bit if it is unknown.
714 Max = KnownOne|UnknownBits;
716 if (UnknownBits.isNegative()) { // Sign bit is unknown
717 Min.set(Min.getBitWidth()-1);
718 Max.clear(Max.getBitWidth()-1);
722 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
723 // a set of known zero and one bits, compute the maximum and minimum values that
724 // could have the specified known zero and known one bits, returning them in
726 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
727 const APInt &KnownOne,
728 APInt &Min, APInt &Max) {
729 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
730 KnownZero.getBitWidth() == Min.getBitWidth() &&
731 KnownZero.getBitWidth() == Max.getBitWidth() &&
732 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
733 APInt UnknownBits = ~(KnownZero|KnownOne);
735 // The minimum value is when the unknown bits are all zeros.
737 // The maximum value is when the unknown bits are all ones.
738 Max = KnownOne|UnknownBits;
741 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
742 /// SimplifyDemandedBits knows about. See if the instruction has any
743 /// properties that allow us to simplify its operands.
744 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
745 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
746 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
747 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
749 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
750 KnownZero, KnownOne, 0);
751 if (V == 0) return false;
752 if (V == &Inst) return true;
753 ReplaceInstUsesWith(Inst, V);
757 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
758 /// specified instruction operand if possible, updating it in place. It returns
759 /// true if it made any change and false otherwise.
760 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
761 APInt &KnownZero, APInt &KnownOne,
763 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
764 KnownZero, KnownOne, Depth);
765 if (NewVal == 0) return false;
771 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
772 /// value based on the demanded bits. When this function is called, it is known
773 /// that only the bits set in DemandedMask of the result of V are ever used
774 /// downstream. Consequently, depending on the mask and V, it may be possible
775 /// to replace V with a constant or one of its operands. In such cases, this
776 /// function does the replacement and returns true. In all other cases, it
777 /// returns false after analyzing the expression and setting KnownOne and known
778 /// to be one in the expression. KnownZero contains all the bits that are known
779 /// to be zero in the expression. These are provided to potentially allow the
780 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
781 /// the expression. KnownOne and KnownZero always follow the invariant that
782 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
783 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
784 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
785 /// and KnownOne must all be the same.
787 /// This returns null if it did not change anything and it permits no
788 /// simplification. This returns V itself if it did some simplification of V's
789 /// operands based on the information about what bits are demanded. This returns
790 /// some other non-null value if it found out that V is equal to another value
791 /// in the context where the specified bits are demanded, but not for all users.
792 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
793 APInt &KnownZero, APInt &KnownOne,
795 assert(V != 0 && "Null pointer of Value???");
796 assert(Depth <= 6 && "Limit Search Depth");
797 uint32_t BitWidth = DemandedMask.getBitWidth();
798 const Type *VTy = V->getType();
799 assert((TD || !isa<PointerType>(VTy)) &&
800 "SimplifyDemandedBits needs to know bit widths!");
801 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
802 (!VTy->isIntOrIntVector() ||
803 VTy->getScalarSizeInBits() == BitWidth) &&
804 KnownZero.getBitWidth() == BitWidth &&
805 KnownOne.getBitWidth() == BitWidth &&
806 "Value *V, DemandedMask, KnownZero and KnownOne "
807 "must have same BitWidth");
808 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
809 // We know all of the bits for a constant!
810 KnownOne = CI->getValue() & DemandedMask;
811 KnownZero = ~KnownOne & DemandedMask;
814 if (isa<ConstantPointerNull>(V)) {
815 // We know all of the bits for a constant!
817 KnownZero = DemandedMask;
823 if (DemandedMask == 0) { // Not demanding any bits from V.
824 if (isa<UndefValue>(V))
826 return Context->getUndef(VTy);
829 if (Depth == 6) // Limit search depth.
832 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
833 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
835 Instruction *I = dyn_cast<Instruction>(V);
837 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
838 return 0; // Only analyze instructions.
841 // If there are multiple uses of this value and we aren't at the root, then
842 // we can't do any simplifications of the operands, because DemandedMask
843 // only reflects the bits demanded by *one* of the users.
844 if (Depth != 0 && !I->hasOneUse()) {
845 // Despite the fact that we can't simplify this instruction in all User's
846 // context, we can at least compute the knownzero/knownone bits, and we can
847 // do simplifications that apply to *just* the one user if we know that
848 // this instruction has a simpler value in that context.
849 if (I->getOpcode() == Instruction::And) {
850 // If either the LHS or the RHS are Zero, the result is zero.
851 ComputeMaskedBits(I->getOperand(1), DemandedMask,
852 RHSKnownZero, RHSKnownOne, Depth+1);
853 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
854 LHSKnownZero, LHSKnownOne, Depth+1);
856 // If all of the demanded bits are known 1 on one side, return the other.
857 // These bits cannot contribute to the result of the 'and' in this
859 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
860 (DemandedMask & ~LHSKnownZero))
861 return I->getOperand(0);
862 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
863 (DemandedMask & ~RHSKnownZero))
864 return I->getOperand(1);
866 // If all of the demanded bits in the inputs are known zeros, return zero.
867 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
868 return Context->getNullValue(VTy);
870 } else if (I->getOpcode() == Instruction::Or) {
871 // We can simplify (X|Y) -> X or Y in the user's context if we know that
872 // only bits from X or Y are demanded.
874 // If either the LHS or the RHS are One, the result is One.
875 ComputeMaskedBits(I->getOperand(1), DemandedMask,
876 RHSKnownZero, RHSKnownOne, Depth+1);
877 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
878 LHSKnownZero, LHSKnownOne, Depth+1);
880 // If all of the demanded bits are known zero on one side, return the
881 // other. These bits cannot contribute to the result of the 'or' in this
883 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
884 (DemandedMask & ~LHSKnownOne))
885 return I->getOperand(0);
886 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
887 (DemandedMask & ~RHSKnownOne))
888 return I->getOperand(1);
890 // If all of the potentially set bits on one side are known to be set on
891 // the other side, just use the 'other' side.
892 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
893 (DemandedMask & (~RHSKnownZero)))
894 return I->getOperand(0);
895 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
896 (DemandedMask & (~LHSKnownZero)))
897 return I->getOperand(1);
900 // Compute the KnownZero/KnownOne bits to simplify things downstream.
901 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
905 // If this is the root being simplified, allow it to have multiple uses,
906 // just set the DemandedMask to all bits so that we can try to simplify the
907 // operands. This allows visitTruncInst (for example) to simplify the
908 // operand of a trunc without duplicating all the logic below.
909 if (Depth == 0 && !V->hasOneUse())
910 DemandedMask = APInt::getAllOnesValue(BitWidth);
912 switch (I->getOpcode()) {
914 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
916 case Instruction::And:
917 // If either the LHS or the RHS are Zero, the result is zero.
918 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
919 RHSKnownZero, RHSKnownOne, Depth+1) ||
920 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
921 LHSKnownZero, LHSKnownOne, Depth+1))
923 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
924 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
926 // If all of the demanded bits are known 1 on one side, return the other.
927 // These bits cannot contribute to the result of the 'and'.
928 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
929 (DemandedMask & ~LHSKnownZero))
930 return I->getOperand(0);
931 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
932 (DemandedMask & ~RHSKnownZero))
933 return I->getOperand(1);
935 // If all of the demanded bits in the inputs are known zeros, return zero.
936 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
937 return Context->getNullValue(VTy);
939 // If the RHS is a constant, see if we can simplify it.
940 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
943 // Output known-1 bits are only known if set in both the LHS & RHS.
944 RHSKnownOne &= LHSKnownOne;
945 // Output known-0 are known to be clear if zero in either the LHS | RHS.
946 RHSKnownZero |= LHSKnownZero;
948 case Instruction::Or:
949 // If either the LHS or the RHS are One, the result is One.
950 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
951 RHSKnownZero, RHSKnownOne, Depth+1) ||
952 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
953 LHSKnownZero, LHSKnownOne, Depth+1))
955 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
956 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
958 // If all of the demanded bits are known zero on one side, return the other.
959 // These bits cannot contribute to the result of the 'or'.
960 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
961 (DemandedMask & ~LHSKnownOne))
962 return I->getOperand(0);
963 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
964 (DemandedMask & ~RHSKnownOne))
965 return I->getOperand(1);
967 // If all of the potentially set bits on one side are known to be set on
968 // the other side, just use the 'other' side.
969 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
970 (DemandedMask & (~RHSKnownZero)))
971 return I->getOperand(0);
972 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
973 (DemandedMask & (~LHSKnownZero)))
974 return I->getOperand(1);
976 // If the RHS is a constant, see if we can simplify it.
977 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
980 // Output known-0 bits are only known if clear in both the LHS & RHS.
981 RHSKnownZero &= LHSKnownZero;
982 // Output known-1 are known to be set if set in either the LHS | RHS.
983 RHSKnownOne |= LHSKnownOne;
985 case Instruction::Xor: {
986 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
987 RHSKnownZero, RHSKnownOne, Depth+1) ||
988 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
989 LHSKnownZero, LHSKnownOne, Depth+1))
991 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
992 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
994 // If all of the demanded bits are known zero on one side, return the other.
995 // These bits cannot contribute to the result of the 'xor'.
996 if ((DemandedMask & RHSKnownZero) == DemandedMask)
997 return I->getOperand(0);
998 if ((DemandedMask & LHSKnownZero) == DemandedMask)
999 return I->getOperand(1);
1001 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1002 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1003 (RHSKnownOne & LHSKnownOne);
1004 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1005 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1006 (RHSKnownOne & LHSKnownZero);
1008 // If all of the demanded bits are known to be zero on one side or the
1009 // other, turn this into an *inclusive* or.
1010 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1011 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1013 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1015 return InsertNewInstBefore(Or, *I);
1018 // If all of the demanded bits on one side are known, and all of the set
1019 // bits on that side are also known to be set on the other side, turn this
1020 // into an AND, as we know the bits will be cleared.
1021 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1022 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1024 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1025 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1027 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1028 return InsertNewInstBefore(And, *I);
1032 // If the RHS is a constant, see if we can simplify it.
1033 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1034 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1037 RHSKnownZero = KnownZeroOut;
1038 RHSKnownOne = KnownOneOut;
1041 case Instruction::Select:
1042 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1043 RHSKnownZero, RHSKnownOne, Depth+1) ||
1044 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1045 LHSKnownZero, LHSKnownOne, Depth+1))
1047 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1048 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1050 // If the operands are constants, see if we can simplify them.
1051 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1052 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1055 // Only known if known in both the LHS and RHS.
1056 RHSKnownOne &= LHSKnownOne;
1057 RHSKnownZero &= LHSKnownZero;
1059 case Instruction::Trunc: {
1060 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1061 DemandedMask.zext(truncBf);
1062 RHSKnownZero.zext(truncBf);
1063 RHSKnownOne.zext(truncBf);
1064 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1065 RHSKnownZero, RHSKnownOne, Depth+1))
1067 DemandedMask.trunc(BitWidth);
1068 RHSKnownZero.trunc(BitWidth);
1069 RHSKnownOne.trunc(BitWidth);
1070 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1073 case Instruction::BitCast:
1074 if (!I->getOperand(0)->getType()->isIntOrIntVector())
1075 return false; // vector->int or fp->int?
1077 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1078 if (const VectorType *SrcVTy =
1079 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1080 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1081 // Don't touch a bitcast between vectors of different element counts.
1084 // Don't touch a scalar-to-vector bitcast.
1086 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1087 // Don't touch a vector-to-scalar bitcast.
1090 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1091 RHSKnownZero, RHSKnownOne, Depth+1))
1093 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1095 case Instruction::ZExt: {
1096 // Compute the bits in the result that are not present in the input.
1097 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1099 DemandedMask.trunc(SrcBitWidth);
1100 RHSKnownZero.trunc(SrcBitWidth);
1101 RHSKnownOne.trunc(SrcBitWidth);
1102 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1103 RHSKnownZero, RHSKnownOne, Depth+1))
1105 DemandedMask.zext(BitWidth);
1106 RHSKnownZero.zext(BitWidth);
1107 RHSKnownOne.zext(BitWidth);
1108 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1109 // The top bits are known to be zero.
1110 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1113 case Instruction::SExt: {
1114 // Compute the bits in the result that are not present in the input.
1115 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1117 APInt InputDemandedBits = DemandedMask &
1118 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1120 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1121 // If any of the sign extended bits are demanded, we know that the sign
1123 if ((NewBits & DemandedMask) != 0)
1124 InputDemandedBits.set(SrcBitWidth-1);
1126 InputDemandedBits.trunc(SrcBitWidth);
1127 RHSKnownZero.trunc(SrcBitWidth);
1128 RHSKnownOne.trunc(SrcBitWidth);
1129 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1130 RHSKnownZero, RHSKnownOne, Depth+1))
1132 InputDemandedBits.zext(BitWidth);
1133 RHSKnownZero.zext(BitWidth);
1134 RHSKnownOne.zext(BitWidth);
1135 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1137 // If the sign bit of the input is known set or clear, then we know the
1138 // top bits of the result.
1140 // If the input sign bit is known zero, or if the NewBits are not demanded
1141 // convert this into a zero extension.
1142 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1143 // Convert to ZExt cast
1144 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1145 return InsertNewInstBefore(NewCast, *I);
1146 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1147 RHSKnownOne |= NewBits;
1151 case Instruction::Add: {
1152 // Figure out what the input bits are. If the top bits of the and result
1153 // are not demanded, then the add doesn't demand them from its input
1155 unsigned NLZ = DemandedMask.countLeadingZeros();
1157 // If there is a constant on the RHS, there are a variety of xformations
1159 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1160 // If null, this should be simplified elsewhere. Some of the xforms here
1161 // won't work if the RHS is zero.
1165 // If the top bit of the output is demanded, demand everything from the
1166 // input. Otherwise, we demand all the input bits except NLZ top bits.
1167 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1169 // Find information about known zero/one bits in the input.
1170 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1171 LHSKnownZero, LHSKnownOne, Depth+1))
1174 // If the RHS of the add has bits set that can't affect the input, reduce
1176 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
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 Context->getConstantInt(I->getType(), InputBit-ResultBit));
1399 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1400 Context->getConstantInt(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 = Context->getConstantInt(RHSKnownOne);
1418 if (isa<PointerType>(V->getType()))
1419 C = Context->getConstantExprIntToPtr(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 Context->getUndef(V->getType());
1451 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1452 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1453 Constant *Undef = Context->getUndef(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 = Context->getConstantVector(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 = Context->getNullValue(EltTy);
1481 Constant *Undef = Context->getUndef(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 Context->getConstantVector(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(Context->getUndef(Type::Int32Ty));
1604 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1605 Shuffle->getMaskValue(i)));
1607 I->setOperand(2, Context->getConstantVector(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 llvm_unreachable("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 llvm_unreachable("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,
1735 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1736 RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1737 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1739 switch (II->getIntrinsicID()) {
1740 default: llvm_unreachable("Case stmts out of sync!");
1741 case Intrinsic::x86_sse_sub_ss:
1742 case Intrinsic::x86_sse2_sub_sd:
1743 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1744 II->getName()), *II);
1746 case Intrinsic::x86_sse_mul_ss:
1747 case Intrinsic::x86_sse2_mul_sd:
1748 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1749 II->getName()), *II);
1754 InsertElementInst::Create(
1755 Context->getUndef(II->getType()), TmpV,
1756 Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
1757 InsertNewInstBefore(New, *II);
1758 AddSoonDeadInstToWorklist(*II, 0);
1763 // Output elements are undefined if both are undefined. Consider things
1764 // like undef&0. The result is known zero, not undef.
1765 UndefElts &= UndefElts2;
1771 return MadeChange ? I : 0;
1775 /// AssociativeOpt - Perform an optimization on an associative operator. This
1776 /// function is designed to check a chain of associative operators for a
1777 /// potential to apply a certain optimization. Since the optimization may be
1778 /// applicable if the expression was reassociated, this checks the chain, then
1779 /// reassociates the expression as necessary to expose the optimization
1780 /// opportunity. This makes use of a special Functor, which must define
1781 /// 'shouldApply' and 'apply' methods.
1783 template<typename Functor>
1784 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1785 LLVMContext *Context) {
1786 unsigned Opcode = Root.getOpcode();
1787 Value *LHS = Root.getOperand(0);
1789 // Quick check, see if the immediate LHS matches...
1790 if (F.shouldApply(LHS))
1791 return F.apply(Root);
1793 // Otherwise, if the LHS is not of the same opcode as the root, return.
1794 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1795 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1796 // Should we apply this transform to the RHS?
1797 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1799 // If not to the RHS, check to see if we should apply to the LHS...
1800 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1801 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1805 // If the functor wants to apply the optimization to the RHS of LHSI,
1806 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1808 // Now all of the instructions are in the current basic block, go ahead
1809 // and perform the reassociation.
1810 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1812 // First move the selected RHS to the LHS of the root...
1813 Root.setOperand(0, LHSI->getOperand(1));
1815 // Make what used to be the LHS of the root be the user of the root...
1816 Value *ExtraOperand = TmpLHSI->getOperand(1);
1817 if (&Root == TmpLHSI) {
1818 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1821 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1822 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1823 BasicBlock::iterator ARI = &Root; ++ARI;
1824 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1827 // Now propagate the ExtraOperand down the chain of instructions until we
1829 while (TmpLHSI != LHSI) {
1830 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1831 // Move the instruction to immediately before the chain we are
1832 // constructing to avoid breaking dominance properties.
1833 NextLHSI->moveBefore(ARI);
1836 Value *NextOp = NextLHSI->getOperand(1);
1837 NextLHSI->setOperand(1, ExtraOperand);
1839 ExtraOperand = NextOp;
1842 // Now that the instructions are reassociated, have the functor perform
1843 // the transformation...
1844 return F.apply(Root);
1847 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1854 // AddRHS - Implements: X + X --> X << 1
1857 LLVMContext *Context;
1858 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1859 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1860 Instruction *apply(BinaryOperator &Add) const {
1861 return BinaryOperator::CreateShl(Add.getOperand(0),
1862 Context->getConstantInt(Add.getType(), 1));
1866 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1868 struct AddMaskingAnd {
1870 LLVMContext *Context;
1871 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1872 bool shouldApply(Value *LHS) const {
1874 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1875 Context->getConstantExprAnd(C1, C2)->isNullValue();
1877 Instruction *apply(BinaryOperator &Add) const {
1878 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1884 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1886 LLVMContext *Context = IC->getContext();
1888 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1889 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1892 // Figure out if the constant is the left or the right argument.
1893 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1894 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1896 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1898 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1899 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1902 Value *Op0 = SO, *Op1 = ConstOperand;
1904 std::swap(Op0, Op1);
1906 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1907 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1908 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1909 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1910 Op0, Op1, SO->getName()+".cmp");
1912 llvm_unreachable("Unknown binary instruction type!");
1914 return IC->InsertNewInstBefore(New, I);
1917 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1918 // constant as the other operand, try to fold the binary operator into the
1919 // select arguments. This also works for Cast instructions, which obviously do
1920 // not have a second operand.
1921 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1923 // Don't modify shared select instructions
1924 if (!SI->hasOneUse()) return 0;
1925 Value *TV = SI->getOperand(1);
1926 Value *FV = SI->getOperand(2);
1928 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1929 // Bool selects with constant operands can be folded to logical ops.
1930 if (SI->getType() == Type::Int1Ty) return 0;
1932 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1933 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1935 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1942 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1943 /// node as operand #0, see if we can fold the instruction into the PHI (which
1944 /// is only possible if all operands to the PHI are constants).
1945 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1946 PHINode *PN = cast<PHINode>(I.getOperand(0));
1947 unsigned NumPHIValues = PN->getNumIncomingValues();
1948 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1950 // Check to see if all of the operands of the PHI are constants. If there is
1951 // one non-constant value, remember the BB it is. If there is more than one
1952 // or if *it* is a PHI, bail out.
1953 BasicBlock *NonConstBB = 0;
1954 for (unsigned i = 0; i != NumPHIValues; ++i)
1955 if (!isa<Constant>(PN->getIncomingValue(i))) {
1956 if (NonConstBB) return 0; // More than one non-const value.
1957 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1958 NonConstBB = PN->getIncomingBlock(i);
1960 // If the incoming non-constant value is in I's block, we have an infinite
1962 if (NonConstBB == I.getParent())
1966 // If there is exactly one non-constant value, we can insert a copy of the
1967 // operation in that block. However, if this is a critical edge, we would be
1968 // inserting the computation one some other paths (e.g. inside a loop). Only
1969 // do this if the pred block is unconditionally branching into the phi block.
1971 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1972 if (!BI || !BI->isUnconditional()) return 0;
1975 // Okay, we can do the transformation: create the new PHI node.
1976 PHINode *NewPN = PHINode::Create(I.getType(), "");
1977 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1978 InsertNewInstBefore(NewPN, *PN);
1979 NewPN->takeName(PN);
1981 // Next, add all of the operands to the PHI.
1982 if (I.getNumOperands() == 2) {
1983 Constant *C = cast<Constant>(I.getOperand(1));
1984 for (unsigned i = 0; i != NumPHIValues; ++i) {
1986 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1987 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1988 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
1990 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
1992 assert(PN->getIncomingBlock(i) == NonConstBB);
1993 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1994 InV = BinaryOperator::Create(BO->getOpcode(),
1995 PN->getIncomingValue(i), C, "phitmp",
1996 NonConstBB->getTerminator());
1997 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1998 InV = CmpInst::Create(*Context, CI->getOpcode(),
2000 PN->getIncomingValue(i), C, "phitmp",
2001 NonConstBB->getTerminator());
2003 llvm_unreachable("Unknown binop!");
2005 AddToWorkList(cast<Instruction>(InV));
2007 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2010 CastInst *CI = cast<CastInst>(&I);
2011 const Type *RetTy = CI->getType();
2012 for (unsigned i = 0; i != NumPHIValues; ++i) {
2014 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2015 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2017 assert(PN->getIncomingBlock(i) == NonConstBB);
2018 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2019 I.getType(), "phitmp",
2020 NonConstBB->getTerminator());
2021 AddToWorkList(cast<Instruction>(InV));
2023 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2026 return ReplaceInstUsesWith(I, NewPN);
2030 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2031 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2032 /// This basically requires proving that the add in the original type would not
2033 /// overflow to change the sign bit or have a carry out.
2034 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2035 // There are different heuristics we can use for this. Here are some simple
2038 // Add has the property that adding any two 2's complement numbers can only
2039 // have one carry bit which can change a sign. As such, if LHS and RHS each
2040 // have at least two sign bits, we know that the addition of the two values will
2041 // sign extend fine.
2042 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2046 // If one of the operands only has one non-zero bit, and if the other operand
2047 // has a known-zero bit in a more significant place than it (not including the
2048 // sign bit) the ripple may go up to and fill the zero, but won't change the
2049 // sign. For example, (X & ~4) + 1.
2057 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2058 bool Changed = SimplifyCommutative(I);
2059 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2061 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2062 // X + undef -> undef
2063 if (isa<UndefValue>(RHS))
2064 return ReplaceInstUsesWith(I, RHS);
2067 if (RHSC->isNullValue())
2068 return ReplaceInstUsesWith(I, LHS);
2070 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2071 // X + (signbit) --> X ^ signbit
2072 const APInt& Val = CI->getValue();
2073 uint32_t BitWidth = Val.getBitWidth();
2074 if (Val == APInt::getSignBit(BitWidth))
2075 return BinaryOperator::CreateXor(LHS, RHS);
2077 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2078 // (X & 254)+1 -> (X&254)|1
2079 if (SimplifyDemandedInstructionBits(I))
2082 // zext(bool) + C -> bool ? C + 1 : C
2083 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2084 if (ZI->getSrcTy() == Type::Int1Ty)
2085 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2088 if (isa<PHINode>(LHS))
2089 if (Instruction *NV = FoldOpIntoPhi(I))
2092 ConstantInt *XorRHS = 0;
2094 if (isa<ConstantInt>(RHSC) &&
2095 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2096 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2097 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2099 uint32_t Size = TySizeBits / 2;
2100 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2101 APInt CFF80Val(-C0080Val);
2103 if (TySizeBits > Size) {
2104 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2105 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2106 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2107 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2108 // This is a sign extend if the top bits are known zero.
2109 if (!MaskedValueIsZero(XorLHS,
2110 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2111 Size = 0; // Not a sign ext, but can't be any others either.
2116 C0080Val = APIntOps::lshr(C0080Val, Size);
2117 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2118 } while (Size >= 1);
2120 // FIXME: This shouldn't be necessary. When the backends can handle types
2121 // with funny bit widths then this switch statement should be removed. It
2122 // is just here to get the size of the "middle" type back up to something
2123 // that the back ends can handle.
2124 const Type *MiddleType = 0;
2127 case 32: MiddleType = Type::Int32Ty; break;
2128 case 16: MiddleType = Type::Int16Ty; break;
2129 case 8: MiddleType = Type::Int8Ty; break;
2132 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2133 InsertNewInstBefore(NewTrunc, I);
2134 return new SExtInst(NewTrunc, I.getType(), I.getName());
2139 if (I.getType() == Type::Int1Ty)
2140 return BinaryOperator::CreateXor(LHS, RHS);
2143 if (I.getType()->isInteger()) {
2144 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2147 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2148 if (RHSI->getOpcode() == Instruction::Sub)
2149 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2150 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2152 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2153 if (LHSI->getOpcode() == Instruction::Sub)
2154 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2155 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2160 // -A + -B --> -(A + B)
2161 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2162 if (LHS->getType()->isIntOrIntVector()) {
2163 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2164 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2165 InsertNewInstBefore(NewAdd, I);
2166 return BinaryOperator::CreateNeg(*Context, NewAdd);
2170 return BinaryOperator::CreateSub(RHS, LHSV);
2174 if (!isa<Constant>(RHS))
2175 if (Value *V = dyn_castNegVal(RHS, Context))
2176 return BinaryOperator::CreateSub(LHS, V);
2180 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2181 if (X == RHS) // X*C + X --> X * (C+1)
2182 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2184 // X*C1 + X*C2 --> X * (C1+C2)
2186 if (X == dyn_castFoldableMul(RHS, C1, Context))
2187 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2190 // X + X*C --> X * (C+1)
2191 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2192 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2194 // X + ~X --> -1 since ~X = -X-1
2195 if (dyn_castNotVal(LHS, Context) == RHS ||
2196 dyn_castNotVal(RHS, Context) == LHS)
2197 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2200 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2201 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2202 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2205 // A+B --> A|B iff A and B have no bits set in common.
2206 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2207 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2208 APInt LHSKnownOne(IT->getBitWidth(), 0);
2209 APInt LHSKnownZero(IT->getBitWidth(), 0);
2210 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2211 if (LHSKnownZero != 0) {
2212 APInt RHSKnownOne(IT->getBitWidth(), 0);
2213 APInt RHSKnownZero(IT->getBitWidth(), 0);
2214 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2216 // No bits in common -> bitwise or.
2217 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2218 return BinaryOperator::CreateOr(LHS, RHS);
2222 // W*X + Y*Z --> W * (X+Z) iff W == Y
2223 if (I.getType()->isIntOrIntVector()) {
2224 Value *W, *X, *Y, *Z;
2225 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2226 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2230 } else if (Y == X) {
2232 } else if (X == Z) {
2239 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2240 LHS->getName()), I);
2241 return BinaryOperator::CreateMul(W, NewAdd);
2246 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2248 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
2249 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2251 // (X & FF00) + xx00 -> (X+xx00) & FF00
2252 if (LHS->hasOneUse() &&
2253 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2254 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2255 if (Anded == CRHS) {
2256 // See if all bits from the first bit set in the Add RHS up are included
2257 // in the mask. First, get the rightmost bit.
2258 const APInt& AddRHSV = CRHS->getValue();
2260 // Form a mask of all bits from the lowest bit added through the top.
2261 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2263 // See if the and mask includes all of these bits.
2264 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2266 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2267 // Okay, the xform is safe. Insert the new add pronto.
2268 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2269 LHS->getName()), I);
2270 return BinaryOperator::CreateAnd(NewAdd, C2);
2275 // Try to fold constant add into select arguments.
2276 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2277 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2281 // add (select X 0 (sub n A)) A --> select X A n
2283 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2286 SI = dyn_cast<SelectInst>(RHS);
2289 if (SI && SI->hasOneUse()) {
2290 Value *TV = SI->getTrueValue();
2291 Value *FV = SI->getFalseValue();
2294 // Can we fold the add into the argument of the select?
2295 // We check both true and false select arguments for a matching subtract.
2296 if (match(FV, m_Zero(), *Context) &&
2297 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2298 // Fold the add into the true select value.
2299 return SelectInst::Create(SI->getCondition(), N, A);
2300 if (match(TV, m_Zero(), *Context) &&
2301 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2302 // Fold the add into the false select value.
2303 return SelectInst::Create(SI->getCondition(), A, N);
2307 // Check for (add (sext x), y), see if we can merge this into an
2308 // integer add followed by a sext.
2309 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2310 // (add (sext x), cst) --> (sext (add x, cst'))
2311 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2313 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2314 if (LHSConv->hasOneUse() &&
2315 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2316 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2317 // Insert the new, smaller add.
2318 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2320 InsertNewInstBefore(NewAdd, I);
2321 return new SExtInst(NewAdd, I.getType());
2325 // (add (sext x), (sext y)) --> (sext (add int x, y))
2326 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2327 // Only do this if x/y have the same type, if at last one of them has a
2328 // single use (so we don't increase the number of sexts), and if the
2329 // integer add will not overflow.
2330 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2331 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2332 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2333 RHSConv->getOperand(0))) {
2334 // Insert the new integer add.
2335 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2336 RHSConv->getOperand(0),
2338 InsertNewInstBefore(NewAdd, I);
2339 return new SExtInst(NewAdd, I.getType());
2344 return Changed ? &I : 0;
2347 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2348 bool Changed = SimplifyCommutative(I);
2349 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2351 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2353 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2354 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2355 (I.getType())->getValueAPF()))
2356 return ReplaceInstUsesWith(I, LHS);
2359 if (isa<PHINode>(LHS))
2360 if (Instruction *NV = FoldOpIntoPhi(I))
2365 // -A + -B --> -(A + B)
2366 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2367 return BinaryOperator::CreateFSub(RHS, LHSV);
2370 if (!isa<Constant>(RHS))
2371 if (Value *V = dyn_castFNegVal(RHS, Context))
2372 return BinaryOperator::CreateFSub(LHS, V);
2374 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2375 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2376 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2377 return ReplaceInstUsesWith(I, LHS);
2379 // Check for (add double (sitofp x), y), see if we can merge this into an
2380 // integer add followed by a promotion.
2381 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2382 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2383 // ... if the constant fits in the integer value. This is useful for things
2384 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2385 // requires a constant pool load, and generally allows the add to be better
2387 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2389 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2390 if (LHSConv->hasOneUse() &&
2391 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2392 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2393 // Insert the new integer add.
2394 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2396 InsertNewInstBefore(NewAdd, I);
2397 return new SIToFPInst(NewAdd, I.getType());
2401 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2402 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2403 // Only do this if x/y have the same type, if at last one of them has a
2404 // single use (so we don't increase the number of int->fp conversions),
2405 // and if the integer add will not overflow.
2406 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2407 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2408 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2409 RHSConv->getOperand(0))) {
2410 // Insert the new integer add.
2411 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2412 RHSConv->getOperand(0),
2414 InsertNewInstBefore(NewAdd, I);
2415 return new SIToFPInst(NewAdd, I.getType());
2420 return Changed ? &I : 0;
2423 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2424 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2426 if (Op0 == Op1) // sub X, X -> 0
2427 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2429 // If this is a 'B = x-(-A)', change to B = x+A...
2430 if (Value *V = dyn_castNegVal(Op1, Context))
2431 return BinaryOperator::CreateAdd(Op0, V);
2433 if (isa<UndefValue>(Op0))
2434 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2435 if (isa<UndefValue>(Op1))
2436 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2438 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2439 // Replace (-1 - A) with (~A)...
2440 if (C->isAllOnesValue())
2441 return BinaryOperator::CreateNot(*Context, Op1);
2443 // C - ~X == X + (1+C)
2445 if (match(Op1, m_Not(m_Value(X)), *Context))
2446 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2448 // -(X >>u 31) -> (X >>s 31)
2449 // -(X >>s 31) -> (X >>u 31)
2451 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2452 if (SI->getOpcode() == Instruction::LShr) {
2453 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2454 // Check to see if we are shifting out everything but the sign bit.
2455 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2456 SI->getType()->getPrimitiveSizeInBits()-1) {
2457 // Ok, the transformation is safe. Insert AShr.
2458 return BinaryOperator::Create(Instruction::AShr,
2459 SI->getOperand(0), CU, SI->getName());
2463 else if (SI->getOpcode() == Instruction::AShr) {
2464 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2465 // Check to see if we are shifting out everything but the sign bit.
2466 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2467 SI->getType()->getPrimitiveSizeInBits()-1) {
2468 // Ok, the transformation is safe. Insert LShr.
2469 return BinaryOperator::CreateLShr(
2470 SI->getOperand(0), CU, SI->getName());
2477 // Try to fold constant sub into select arguments.
2478 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2479 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2482 // C - zext(bool) -> bool ? C - 1 : C
2483 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2484 if (ZI->getSrcTy() == Type::Int1Ty)
2485 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2488 if (I.getType() == Type::Int1Ty)
2489 return BinaryOperator::CreateXor(Op0, Op1);
2491 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2492 if (Op1I->getOpcode() == Instruction::Add) {
2493 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2494 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2496 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2497 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2499 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2500 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2501 // C1-(X+C2) --> (C1-C2)-X
2502 return BinaryOperator::CreateSub(
2503 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2507 if (Op1I->hasOneUse()) {
2508 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2509 // is not used by anyone else...
2511 if (Op1I->getOpcode() == Instruction::Sub) {
2512 // Swap the two operands of the subexpr...
2513 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2514 Op1I->setOperand(0, IIOp1);
2515 Op1I->setOperand(1, IIOp0);
2517 // Create the new top level add instruction...
2518 return BinaryOperator::CreateAdd(Op0, Op1);
2521 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2523 if (Op1I->getOpcode() == Instruction::And &&
2524 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2525 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2528 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2529 OtherOp, "B.not"), I);
2530 return BinaryOperator::CreateAnd(Op0, NewNot);
2533 // 0 - (X sdiv C) -> (X sdiv -C)
2534 if (Op1I->getOpcode() == Instruction::SDiv)
2535 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2537 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2538 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2539 Context->getConstantExprNeg(DivRHS));
2541 // X - X*C --> X * (1-C)
2542 ConstantInt *C2 = 0;
2543 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2545 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2547 return BinaryOperator::CreateMul(Op0, CP1);
2552 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2553 if (Op0I->getOpcode() == Instruction::Add) {
2554 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2555 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2556 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2557 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2558 } else if (Op0I->getOpcode() == Instruction::Sub) {
2559 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2560 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2566 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2567 if (X == Op1) // X*C - X --> X * (C-1)
2568 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2570 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2571 if (X == dyn_castFoldableMul(Op1, C2, Context))
2572 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2577 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2578 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2580 // If this is a 'B = x-(-A)', change to B = x+A...
2581 if (Value *V = dyn_castFNegVal(Op1, Context))
2582 return BinaryOperator::CreateFAdd(Op0, V);
2584 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2585 if (Op1I->getOpcode() == Instruction::FAdd) {
2586 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2587 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2589 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2590 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2598 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2599 /// comparison only checks the sign bit. If it only checks the sign bit, set
2600 /// TrueIfSigned if the result of the comparison is true when the input value is
2602 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2603 bool &TrueIfSigned) {
2605 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2606 TrueIfSigned = true;
2607 return RHS->isZero();
2608 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2609 TrueIfSigned = true;
2610 return RHS->isAllOnesValue();
2611 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2612 TrueIfSigned = false;
2613 return RHS->isAllOnesValue();
2614 case ICmpInst::ICMP_UGT:
2615 // True if LHS u> RHS and RHS == high-bit-mask - 1
2616 TrueIfSigned = true;
2617 return RHS->getValue() ==
2618 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2619 case ICmpInst::ICMP_UGE:
2620 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2621 TrueIfSigned = true;
2622 return RHS->getValue().isSignBit();
2628 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2629 bool Changed = SimplifyCommutative(I);
2630 Value *Op0 = I.getOperand(0);
2632 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2633 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2635 // Simplify mul instructions with a constant RHS...
2636 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2637 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2639 // ((X << C1)*C2) == (X * (C2 << C1))
2640 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2641 if (SI->getOpcode() == Instruction::Shl)
2642 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2643 return BinaryOperator::CreateMul(SI->getOperand(0),
2644 Context->getConstantExprShl(CI, ShOp));
2647 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2648 if (CI->equalsInt(1)) // X * 1 == X
2649 return ReplaceInstUsesWith(I, Op0);
2650 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2651 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2653 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2654 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2655 return BinaryOperator::CreateShl(Op0,
2656 Context->getConstantInt(Op0->getType(), Val.logBase2()));
2658 } else if (isa<VectorType>(Op1->getType())) {
2659 if (Op1->isNullValue())
2660 return ReplaceInstUsesWith(I, Op1);
2662 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2663 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2664 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2666 // As above, vector X*splat(1.0) -> X in all defined cases.
2667 if (Constant *Splat = Op1V->getSplatValue()) {
2668 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2669 if (CI->equalsInt(1))
2670 return ReplaceInstUsesWith(I, Op0);
2675 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2676 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2677 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2678 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2679 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2681 InsertNewInstBefore(Add, I);
2682 Value *C1C2 = Context->getConstantExprMul(Op1,
2683 cast<Constant>(Op0I->getOperand(1)));
2684 return BinaryOperator::CreateAdd(Add, C1C2);
2688 // Try to fold constant mul into select arguments.
2689 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2690 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2693 if (isa<PHINode>(Op0))
2694 if (Instruction *NV = FoldOpIntoPhi(I))
2698 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2699 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2700 return BinaryOperator::CreateMul(Op0v, Op1v);
2702 // (X / Y) * Y = X - (X % Y)
2703 // (X / Y) * -Y = (X % Y) - X
2705 Value *Op1 = I.getOperand(1);
2706 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2708 (BO->getOpcode() != Instruction::UDiv &&
2709 BO->getOpcode() != Instruction::SDiv)) {
2711 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2713 Value *Neg = dyn_castNegVal(Op1, Context);
2714 if (BO && BO->hasOneUse() &&
2715 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2716 (BO->getOpcode() == Instruction::UDiv ||
2717 BO->getOpcode() == Instruction::SDiv)) {
2718 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2721 if (BO->getOpcode() == Instruction::UDiv)
2722 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2724 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2726 InsertNewInstBefore(Rem, I);
2730 return BinaryOperator::CreateSub(Op0BO, Rem);
2732 return BinaryOperator::CreateSub(Rem, Op0BO);
2736 if (I.getType() == Type::Int1Ty)
2737 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2739 // If one of the operands of the multiply is a cast from a boolean value, then
2740 // we know the bool is either zero or one, so this is a 'masking' multiply.
2741 // See if we can simplify things based on how the boolean was originally
2743 CastInst *BoolCast = 0;
2744 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2745 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2748 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2749 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2752 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2753 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2754 const Type *SCOpTy = SCIOp0->getType();
2757 // If the icmp is true iff the sign bit of X is set, then convert this
2758 // multiply into a shift/and combination.
2759 if (isa<ConstantInt>(SCIOp1) &&
2760 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2762 // Shift the X value right to turn it into "all signbits".
2763 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2764 SCOpTy->getPrimitiveSizeInBits()-1);
2766 InsertNewInstBefore(
2767 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2768 BoolCast->getOperand(0)->getName()+
2771 // If the multiply type is not the same as the source type, sign extend
2772 // or truncate to the multiply type.
2773 if (I.getType() != V->getType()) {
2774 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2775 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2776 Instruction::CastOps opcode =
2777 (SrcBits == DstBits ? Instruction::BitCast :
2778 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2779 V = InsertCastBefore(opcode, V, I.getType(), I);
2782 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2783 return BinaryOperator::CreateAnd(V, OtherOp);
2788 return Changed ? &I : 0;
2791 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2792 bool Changed = SimplifyCommutative(I);
2793 Value *Op0 = I.getOperand(0);
2795 // Simplify mul instructions with a constant RHS...
2796 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2797 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2798 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2799 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2800 if (Op1F->isExactlyValue(1.0))
2801 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2802 } else if (isa<VectorType>(Op1->getType())) {
2803 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2804 // As above, vector X*splat(1.0) -> X in all defined cases.
2805 if (Constant *Splat = Op1V->getSplatValue()) {
2806 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2807 if (F->isExactlyValue(1.0))
2808 return ReplaceInstUsesWith(I, Op0);
2813 // Try to fold constant mul into select arguments.
2814 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2815 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2818 if (isa<PHINode>(Op0))
2819 if (Instruction *NV = FoldOpIntoPhi(I))
2823 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2824 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2825 return BinaryOperator::CreateFMul(Op0v, Op1v);
2827 return Changed ? &I : 0;
2830 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2832 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2833 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2835 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2836 int NonNullOperand = -1;
2837 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2838 if (ST->isNullValue())
2840 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2841 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2842 if (ST->isNullValue())
2845 if (NonNullOperand == -1)
2848 Value *SelectCond = SI->getOperand(0);
2850 // Change the div/rem to use 'Y' instead of the select.
2851 I.setOperand(1, SI->getOperand(NonNullOperand));
2853 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2854 // problem. However, the select, or the condition of the select may have
2855 // multiple uses. Based on our knowledge that the operand must be non-zero,
2856 // propagate the known value for the select into other uses of it, and
2857 // propagate a known value of the condition into its other users.
2859 // If the select and condition only have a single use, don't bother with this,
2861 if (SI->use_empty() && SelectCond->hasOneUse())
2864 // Scan the current block backward, looking for other uses of SI.
2865 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2867 while (BBI != BBFront) {
2869 // If we found a call to a function, we can't assume it will return, so
2870 // information from below it cannot be propagated above it.
2871 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2874 // Replace uses of the select or its condition with the known values.
2875 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2878 *I = SI->getOperand(NonNullOperand);
2880 } else if (*I == SelectCond) {
2881 *I = NonNullOperand == 1 ? Context->getTrue() :
2882 Context->getFalse();
2887 // If we past the instruction, quit looking for it.
2890 if (&*BBI == SelectCond)
2893 // If we ran out of things to eliminate, break out of the loop.
2894 if (SelectCond == 0 && SI == 0)
2902 /// This function implements the transforms on div instructions that work
2903 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2904 /// used by the visitors to those instructions.
2905 /// @brief Transforms common to all three div instructions
2906 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2907 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2909 // undef / X -> 0 for integer.
2910 // undef / X -> undef for FP (the undef could be a snan).
2911 if (isa<UndefValue>(Op0)) {
2912 if (Op0->getType()->isFPOrFPVector())
2913 return ReplaceInstUsesWith(I, Op0);
2914 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2917 // X / undef -> undef
2918 if (isa<UndefValue>(Op1))
2919 return ReplaceInstUsesWith(I, Op1);
2924 /// This function implements the transforms common to both integer division
2925 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2926 /// division instructions.
2927 /// @brief Common integer divide transforms
2928 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2929 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2931 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2933 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2934 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2935 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2936 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2939 Constant *CI = Context->getConstantInt(I.getType(), 1);
2940 return ReplaceInstUsesWith(I, CI);
2943 if (Instruction *Common = commonDivTransforms(I))
2946 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2947 // This does not apply for fdiv.
2948 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2951 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2953 if (RHS->equalsInt(1))
2954 return ReplaceInstUsesWith(I, Op0);
2956 // (X / C1) / C2 -> X / (C1*C2)
2957 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2958 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2959 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2960 if (MultiplyOverflows(RHS, LHSRHS,
2961 I.getOpcode()==Instruction::SDiv, Context))
2962 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2964 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2965 Context->getConstantExprMul(RHS, LHSRHS));
2968 if (!RHS->isZero()) { // avoid X udiv 0
2969 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2970 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2972 if (isa<PHINode>(Op0))
2973 if (Instruction *NV = FoldOpIntoPhi(I))
2978 // 0 / X == 0, we don't need to preserve faults!
2979 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2980 if (LHS->equalsInt(0))
2981 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2983 // It can't be division by zero, hence it must be division by one.
2984 if (I.getType() == Type::Int1Ty)
2985 return ReplaceInstUsesWith(I, Op0);
2987 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2988 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2991 return ReplaceInstUsesWith(I, Op0);
2997 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2998 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3000 // Handle the integer div common cases
3001 if (Instruction *Common = commonIDivTransforms(I))
3004 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3005 // X udiv C^2 -> X >> C
3006 // Check to see if this is an unsigned division with an exact power of 2,
3007 // if so, convert to a right shift.
3008 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3009 return BinaryOperator::CreateLShr(Op0,
3010 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3012 // X udiv C, where C >= signbit
3013 if (C->getValue().isNegative()) {
3014 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3015 ICmpInst::ICMP_ULT, Op0, C),
3017 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3018 Context->getConstantInt(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 = Context->getConstantInt(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 = Context->getConstantInt(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 = Context->getConstantInt(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(*Context, 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(Op0, Mask)) {
3085 if (MaskedValueIsZero(Op1, Mask)) {
3086 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3087 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3089 ConstantInt *ShiftedInt;
3090 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3091 ShiftedInt->getValue().isPowerOf2()) {
3092 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3093 // Safe because the only negative value (1 << Y) can take on is
3094 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3095 // the sign bit set.
3096 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3104 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3105 return commonDivTransforms(I);
3108 /// This function implements the transforms on rem instructions that work
3109 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3110 /// is used by the visitors to those instructions.
3111 /// @brief Transforms common to all three rem instructions
3112 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3113 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3115 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3116 if (I.getType()->isFPOrFPVector())
3117 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3118 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3120 if (isa<UndefValue>(Op1))
3121 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3123 // Handle cases involving: rem X, (select Cond, Y, Z)
3124 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3130 /// This function implements the transforms common to both integer remainder
3131 /// instructions (urem and srem). It is called by the visitors to those integer
3132 /// remainder instructions.
3133 /// @brief Common integer remainder transforms
3134 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3135 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3137 if (Instruction *common = commonRemTransforms(I))
3140 // 0 % X == 0 for integer, we don't need to preserve faults!
3141 if (Constant *LHS = dyn_cast<Constant>(Op0))
3142 if (LHS->isNullValue())
3143 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3145 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3146 // X % 0 == undef, we don't need to preserve faults!
3147 if (RHS->equalsInt(0))
3148 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3150 if (RHS->equalsInt(1)) // X % 1 == 0
3151 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3153 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3154 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3155 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3157 } else if (isa<PHINode>(Op0I)) {
3158 if (Instruction *NV = FoldOpIntoPhi(I))
3162 // See if we can fold away this rem instruction.
3163 if (SimplifyDemandedInstructionBits(I))
3171 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3172 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3174 if (Instruction *common = commonIRemTransforms(I))
3177 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3178 // X urem C^2 -> X and C
3179 // Check to see if this is an unsigned remainder with an exact power of 2,
3180 // if so, convert to a bitwise and.
3181 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3182 if (C->getValue().isPowerOf2())
3183 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3186 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3187 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3188 if (RHSI->getOpcode() == Instruction::Shl &&
3189 isa<ConstantInt>(RHSI->getOperand(0))) {
3190 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3191 Constant *N1 = Context->getAllOnesValue(I.getType());
3192 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3194 return BinaryOperator::CreateAnd(Op0, Add);
3199 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3200 // where C1&C2 are powers of two.
3201 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3202 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3203 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3204 // STO == 0 and SFO == 0 handled above.
3205 if ((STO->getValue().isPowerOf2()) &&
3206 (SFO->getValue().isPowerOf2())) {
3207 Value *TrueAnd = InsertNewInstBefore(
3208 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3209 SI->getName()+".t"), I);
3210 Value *FalseAnd = InsertNewInstBefore(
3211 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3212 SI->getName()+".f"), I);
3213 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3221 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3222 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3224 // Handle the integer rem common cases
3225 if (Instruction *common = commonIRemTransforms(I))
3228 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3229 if (!isa<Constant>(RHSNeg) ||
3230 (isa<ConstantInt>(RHSNeg) &&
3231 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3233 AddUsesToWorkList(I);
3234 I.setOperand(1, RHSNeg);
3238 // If the sign bits of both operands are zero (i.e. we can prove they are
3239 // unsigned inputs), turn this into a urem.
3240 if (I.getType()->isInteger()) {
3241 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3242 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3243 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3244 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3248 // If it's a constant vector, flip any negative values positive.
3249 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3250 unsigned VWidth = RHSV->getNumOperands();
3252 bool hasNegative = false;
3253 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3254 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3255 if (RHS->getValue().isNegative())
3259 std::vector<Constant *> Elts(VWidth);
3260 for (unsigned i = 0; i != VWidth; ++i) {
3261 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3262 if (RHS->getValue().isNegative())
3263 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3269 Constant *NewRHSV = Context->getConstantVector(Elts);
3270 if (NewRHSV != RHSV) {
3271 AddUsesToWorkList(I);
3272 I.setOperand(1, NewRHSV);
3281 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3282 return commonRemTransforms(I);
3285 // isOneBitSet - Return true if there is exactly one bit set in the specified
3287 static bool isOneBitSet(const ConstantInt *CI) {
3288 return CI->getValue().isPowerOf2();
3291 // isHighOnes - Return true if the constant is of the form 1+0+.
3292 // This is the same as lowones(~X).
3293 static bool isHighOnes(const ConstantInt *CI) {
3294 return (~CI->getValue() + 1).isPowerOf2();
3297 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3298 /// are carefully arranged to allow folding of expressions such as:
3300 /// (A < B) | (A > B) --> (A != B)
3302 /// Note that this is only valid if the first and second predicates have the
3303 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3305 /// Three bits are used to represent the condition, as follows:
3310 /// <=> Value Definition
3311 /// 000 0 Always false
3318 /// 111 7 Always true
3320 static unsigned getICmpCode(const ICmpInst *ICI) {
3321 switch (ICI->getPredicate()) {
3323 case ICmpInst::ICMP_UGT: return 1; // 001
3324 case ICmpInst::ICMP_SGT: return 1; // 001
3325 case ICmpInst::ICMP_EQ: return 2; // 010
3326 case ICmpInst::ICMP_UGE: return 3; // 011
3327 case ICmpInst::ICMP_SGE: return 3; // 011
3328 case ICmpInst::ICMP_ULT: return 4; // 100
3329 case ICmpInst::ICMP_SLT: return 4; // 100
3330 case ICmpInst::ICMP_NE: return 5; // 101
3331 case ICmpInst::ICMP_ULE: return 6; // 110
3332 case ICmpInst::ICMP_SLE: return 6; // 110
3335 llvm_unreachable("Invalid ICmp predicate!");
3340 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3341 /// predicate into a three bit mask. It also returns whether it is an ordered
3342 /// predicate by reference.
3343 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3346 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3347 case FCmpInst::FCMP_UNO: return 0; // 000
3348 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3349 case FCmpInst::FCMP_UGT: return 1; // 001
3350 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3351 case FCmpInst::FCMP_UEQ: return 2; // 010
3352 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3353 case FCmpInst::FCMP_UGE: return 3; // 011
3354 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3355 case FCmpInst::FCMP_ULT: return 4; // 100
3356 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3357 case FCmpInst::FCMP_UNE: return 5; // 101
3358 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3359 case FCmpInst::FCMP_ULE: return 6; // 110
3362 // Not expecting FCMP_FALSE and FCMP_TRUE;
3363 llvm_unreachable("Unexpected FCmp predicate!");
3368 /// getICmpValue - This is the complement of getICmpCode, which turns an
3369 /// opcode and two operands into either a constant true or false, or a brand
3370 /// new ICmp instruction. The sign is passed in to determine which kind
3371 /// of predicate to use in the new icmp instruction.
3372 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3373 LLVMContext *Context) {
3375 default: llvm_unreachable("Illegal ICmp code!");
3376 case 0: return Context->getFalse();
3379 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3381 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3382 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
3385 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3387 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3390 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3392 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3393 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
3396 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3398 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3399 case 7: return Context->getTrue();
3403 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3404 /// opcode and two operands into either a FCmp instruction. isordered is passed
3405 /// in to determine which kind of predicate to use in the new fcmp instruction.
3406 static Value *getFCmpValue(bool isordered, unsigned code,
3407 Value *LHS, Value *RHS, LLVMContext *Context) {
3409 default: llvm_unreachable("Illegal FCmp code!");
3412 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3414 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3417 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3419 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3422 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3424 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3427 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3429 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3432 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3434 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3437 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3439 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3442 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3444 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3445 case 7: return Context->getTrue();
3449 /// PredicatesFoldable - Return true if both predicates match sign or if at
3450 /// least one of them is an equality comparison (which is signless).
3451 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3452 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3453 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3454 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3458 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3459 struct FoldICmpLogical {
3462 ICmpInst::Predicate pred;
3463 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3464 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3465 pred(ICI->getPredicate()) {}
3466 bool shouldApply(Value *V) const {
3467 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3468 if (PredicatesFoldable(pred, ICI->getPredicate()))
3469 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3470 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3473 Instruction *apply(Instruction &Log) const {
3474 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3475 if (ICI->getOperand(0) != LHS) {
3476 assert(ICI->getOperand(1) == LHS);
3477 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3480 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3481 unsigned LHSCode = getICmpCode(ICI);
3482 unsigned RHSCode = getICmpCode(RHSICI);
3484 switch (Log.getOpcode()) {
3485 case Instruction::And: Code = LHSCode & RHSCode; break;
3486 case Instruction::Or: Code = LHSCode | RHSCode; break;
3487 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3488 default: llvm_unreachable("Illegal logical opcode!"); return 0;
3491 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3492 ICmpInst::isSignedPredicate(ICI->getPredicate());
3494 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3495 if (Instruction *I = dyn_cast<Instruction>(RV))
3497 // Otherwise, it's a constant boolean value...
3498 return IC.ReplaceInstUsesWith(Log, RV);
3501 } // end anonymous namespace
3503 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3504 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3505 // guaranteed to be a binary operator.
3506 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3508 ConstantInt *AndRHS,
3509 BinaryOperator &TheAnd) {
3510 Value *X = Op->getOperand(0);
3511 Constant *Together = 0;
3513 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3515 switch (Op->getOpcode()) {
3516 case Instruction::Xor:
3517 if (Op->hasOneUse()) {
3518 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3519 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3520 InsertNewInstBefore(And, TheAnd);
3522 return BinaryOperator::CreateXor(And, Together);
3525 case Instruction::Or:
3526 if (Together == AndRHS) // (X | C) & C --> C
3527 return ReplaceInstUsesWith(TheAnd, AndRHS);
3529 if (Op->hasOneUse() && Together != OpRHS) {
3530 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3531 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3532 InsertNewInstBefore(Or, TheAnd);
3534 return BinaryOperator::CreateAnd(Or, AndRHS);
3537 case Instruction::Add:
3538 if (Op->hasOneUse()) {
3539 // Adding a one to a single bit bit-field should be turned into an XOR
3540 // of the bit. First thing to check is to see if this AND is with a
3541 // single bit constant.
3542 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3544 // If there is only one bit set...
3545 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3546 // Ok, at this point, we know that we are masking the result of the
3547 // ADD down to exactly one bit. If the constant we are adding has
3548 // no bits set below this bit, then we can eliminate the ADD.
3549 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3551 // Check to see if any bits below the one bit set in AndRHSV are set.
3552 if ((AddRHS & (AndRHSV-1)) == 0) {
3553 // If not, the only thing that can effect the output of the AND is
3554 // the bit specified by AndRHSV. If that bit is set, the effect of
3555 // the XOR is to toggle the bit. If it is clear, then the ADD has
3557 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3558 TheAnd.setOperand(0, X);
3561 // Pull the XOR out of the AND.
3562 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3563 InsertNewInstBefore(NewAnd, TheAnd);
3564 NewAnd->takeName(Op);
3565 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3572 case Instruction::Shl: {
3573 // We know that the AND will not produce any of the bits shifted in, so if
3574 // the anded constant includes them, clear them now!
3576 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3577 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3578 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3579 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3581 if (CI->getValue() == ShlMask) {
3582 // Masking out bits that the shift already masks
3583 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3584 } else if (CI != AndRHS) { // Reducing bits set in and.
3585 TheAnd.setOperand(1, CI);
3590 case Instruction::LShr:
3592 // We know that the AND will not produce any of the bits shifted in, so if
3593 // the anded constant includes them, clear them now! This only applies to
3594 // unsigned shifts, because a signed shr may bring in set bits!
3596 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3597 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3598 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3599 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3601 if (CI->getValue() == ShrMask) {
3602 // Masking out bits that the shift already masks.
3603 return ReplaceInstUsesWith(TheAnd, Op);
3604 } else if (CI != AndRHS) {
3605 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3610 case Instruction::AShr:
3612 // See if this is shifting in some sign extension, then masking it out
3614 if (Op->hasOneUse()) {
3615 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3616 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3617 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3618 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3619 if (C == AndRHS) { // Masking out bits shifted in.
3620 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3621 // Make the argument unsigned.
3622 Value *ShVal = Op->getOperand(0);
3623 ShVal = InsertNewInstBefore(
3624 BinaryOperator::CreateLShr(ShVal, OpRHS,
3625 Op->getName()), TheAnd);
3626 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3635 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3636 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3637 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3638 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3639 /// insert new instructions.
3640 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3641 bool isSigned, bool Inside,
3643 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
3644 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3645 "Lo is not <= Hi in range emission code!");
3648 if (Lo == Hi) // Trivially false.
3649 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3651 // V >= Min && V < Hi --> V < Hi
3652 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3653 ICmpInst::Predicate pred = (isSigned ?
3654 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3655 return new ICmpInst(*Context, pred, V, Hi);
3658 // Emit V-Lo <u Hi-Lo
3659 Constant *NegLo = Context->getConstantExprNeg(Lo);
3660 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3661 InsertNewInstBefore(Add, IB);
3662 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3663 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3666 if (Lo == Hi) // Trivially true.
3667 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3669 // V < Min || V >= Hi -> V > Hi-1
3670 Hi = SubOne(cast<ConstantInt>(Hi), Context);
3671 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3672 ICmpInst::Predicate pred = (isSigned ?
3673 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3674 return new ICmpInst(*Context, pred, V, Hi);
3677 // Emit V-Lo >u Hi-1-Lo
3678 // Note that Hi has already had one subtracted from it, above.
3679 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3680 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3681 InsertNewInstBefore(Add, IB);
3682 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3683 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3686 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3687 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3688 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3689 // not, since all 1s are not contiguous.
3690 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3691 const APInt& V = Val->getValue();
3692 uint32_t BitWidth = Val->getType()->getBitWidth();
3693 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3695 // look for the first zero bit after the run of ones
3696 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3697 // look for the first non-zero bit
3698 ME = V.getActiveBits();
3702 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3703 /// where isSub determines whether the operator is a sub. If we can fold one of
3704 /// the following xforms:
3706 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3707 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3708 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3710 /// return (A +/- B).
3712 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3713 ConstantInt *Mask, bool isSub,
3715 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3716 if (!LHSI || LHSI->getNumOperands() != 2 ||
3717 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3719 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3721 switch (LHSI->getOpcode()) {
3723 case Instruction::And:
3724 if (Context->getConstantExprAnd(N, Mask) == Mask) {
3725 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3726 if ((Mask->getValue().countLeadingZeros() +
3727 Mask->getValue().countPopulation()) ==
3728 Mask->getValue().getBitWidth())
3731 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3732 // part, we don't need any explicit masks to take them out of A. If that
3733 // is all N is, ignore it.
3734 uint32_t MB = 0, ME = 0;
3735 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3736 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3737 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3738 if (MaskedValueIsZero(RHS, Mask))
3743 case Instruction::Or:
3744 case Instruction::Xor:
3745 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3746 if ((Mask->getValue().countLeadingZeros() +
3747 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3748 && Context->getConstantExprAnd(N, Mask)->isNullValue())
3755 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3757 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3758 return InsertNewInstBefore(New, I);
3761 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3762 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3763 ICmpInst *LHS, ICmpInst *RHS) {
3765 ConstantInt *LHSCst, *RHSCst;
3766 ICmpInst::Predicate LHSCC, RHSCC;
3768 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3769 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3770 m_ConstantInt(LHSCst)), *Context) ||
3771 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3772 m_ConstantInt(RHSCst)), *Context))
3775 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3776 // where C is a power of 2
3777 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3778 LHSCst->getValue().isPowerOf2()) {
3779 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3780 InsertNewInstBefore(NewOr, I);
3781 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3784 // From here on, we only handle:
3785 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3786 if (Val != Val2) return 0;
3788 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3789 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3790 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3791 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3792 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3795 // We can't fold (ugt x, C) & (sgt x, C2).
3796 if (!PredicatesFoldable(LHSCC, RHSCC))
3799 // Ensure that the larger constant is on the RHS.
3801 if (ICmpInst::isSignedPredicate(LHSCC) ||
3802 (ICmpInst::isEquality(LHSCC) &&
3803 ICmpInst::isSignedPredicate(RHSCC)))
3804 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3806 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3809 std::swap(LHS, RHS);
3810 std::swap(LHSCst, RHSCst);
3811 std::swap(LHSCC, RHSCC);
3814 // At this point, we know we have have two icmp instructions
3815 // comparing a value against two constants and and'ing the result
3816 // together. Because of the above check, we know that we only have
3817 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3818 // (from the FoldICmpLogical check above), that the two constants
3819 // are not equal and that the larger constant is on the RHS
3820 assert(LHSCst != RHSCst && "Compares not folded above?");
3823 default: llvm_unreachable("Unknown integer condition code!");
3824 case ICmpInst::ICMP_EQ:
3826 default: llvm_unreachable("Unknown integer condition code!");
3827 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3828 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3829 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3830 return ReplaceInstUsesWith(I, Context->getFalse());
3831 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3832 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3833 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3834 return ReplaceInstUsesWith(I, LHS);
3836 case ICmpInst::ICMP_NE:
3838 default: llvm_unreachable("Unknown integer condition code!");
3839 case ICmpInst::ICMP_ULT:
3840 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3841 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3842 break; // (X != 13 & X u< 15) -> no change
3843 case ICmpInst::ICMP_SLT:
3844 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3845 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3846 break; // (X != 13 & X s< 15) -> no change
3847 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3848 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3849 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3850 return ReplaceInstUsesWith(I, RHS);
3851 case ICmpInst::ICMP_NE:
3852 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3853 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3854 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3855 Val->getName()+".off");
3856 InsertNewInstBefore(Add, I);
3857 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3858 Context->getConstantInt(Add->getType(), 1));
3860 break; // (X != 13 & X != 15) -> no change
3863 case ICmpInst::ICMP_ULT:
3865 default: llvm_unreachable("Unknown integer condition code!");
3866 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3867 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3868 return ReplaceInstUsesWith(I, Context->getFalse());
3869 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3871 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3872 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3873 return ReplaceInstUsesWith(I, LHS);
3874 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3878 case ICmpInst::ICMP_SLT:
3880 default: llvm_unreachable("Unknown integer condition code!");
3881 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3882 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3883 return ReplaceInstUsesWith(I, Context->getFalse());
3884 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3886 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3887 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3888 return ReplaceInstUsesWith(I, LHS);
3889 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3893 case ICmpInst::ICMP_UGT:
3895 default: llvm_unreachable("Unknown integer condition code!");
3896 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3897 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3898 return ReplaceInstUsesWith(I, RHS);
3899 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3901 case ICmpInst::ICMP_NE:
3902 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3903 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3904 break; // (X u> 13 & X != 15) -> no change
3905 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3906 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3907 RHSCst, false, true, I);
3908 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3912 case ICmpInst::ICMP_SGT:
3914 default: llvm_unreachable("Unknown integer condition code!");
3915 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3916 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3917 return ReplaceInstUsesWith(I, RHS);
3918 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3920 case ICmpInst::ICMP_NE:
3921 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3922 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3923 break; // (X s> 13 & X != 15) -> no change
3924 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3925 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3926 RHSCst, true, true, I);
3927 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3936 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3939 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3940 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3941 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3942 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3943 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3944 // If either of the constants are nans, then the whole thing returns
3946 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3947 return ReplaceInstUsesWith(I, Context->getFalse());
3948 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3949 LHS->getOperand(0), RHS->getOperand(0));
3954 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3955 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3956 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3959 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3960 // Swap RHS operands to match LHS.
3961 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3962 std::swap(Op1LHS, Op1RHS);
3965 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3966 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3968 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3970 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3971 return ReplaceInstUsesWith(I, Context->getFalse());
3972 if (Op0CC == FCmpInst::FCMP_TRUE)
3973 return ReplaceInstUsesWith(I, RHS);
3974 if (Op1CC == FCmpInst::FCMP_TRUE)
3975 return ReplaceInstUsesWith(I, LHS);
3979 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3980 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3982 std::swap(LHS, RHS);
3983 std::swap(Op0Pred, Op1Pred);
3984 std::swap(Op0Ordered, Op1Ordered);
3987 // uno && ueq -> uno && (uno || eq) -> ueq
3988 // ord && olt -> ord && (ord && lt) -> olt
3989 if (Op0Ordered == Op1Ordered)
3990 return ReplaceInstUsesWith(I, RHS);
3992 // uno && oeq -> uno && (ord && eq) -> false
3993 // uno && ord -> false
3995 return ReplaceInstUsesWith(I, Context->getFalse());
3996 // ord && ueq -> ord && (uno || eq) -> oeq
3997 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3998 Op0LHS, Op0RHS, Context));
4006 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4007 bool Changed = SimplifyCommutative(I);
4008 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4010 if (isa<UndefValue>(Op1)) // X & undef -> 0
4011 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4015 return ReplaceInstUsesWith(I, Op1);
4017 // See if we can simplify any instructions used by the instruction whose sole
4018 // purpose is to compute bits we don't care about.
4019 if (SimplifyDemandedInstructionBits(I))
4021 if (isa<VectorType>(I.getType())) {
4022 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4023 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4024 return ReplaceInstUsesWith(I, I.getOperand(0));
4025 } else if (isa<ConstantAggregateZero>(Op1)) {
4026 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4030 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4031 const APInt& AndRHSMask = AndRHS->getValue();
4032 APInt NotAndRHS(~AndRHSMask);
4034 // Optimize a variety of ((val OP C1) & C2) combinations...
4035 if (isa<BinaryOperator>(Op0)) {
4036 Instruction *Op0I = cast<Instruction>(Op0);
4037 Value *Op0LHS = Op0I->getOperand(0);
4038 Value *Op0RHS = Op0I->getOperand(1);
4039 switch (Op0I->getOpcode()) {
4040 case Instruction::Xor:
4041 case Instruction::Or:
4042 // If the mask is only needed on one incoming arm, push it up.
4043 if (Op0I->hasOneUse()) {
4044 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4045 // Not masking anything out for the LHS, move to RHS.
4046 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4047 Op0RHS->getName()+".masked");
4048 InsertNewInstBefore(NewRHS, I);
4049 return BinaryOperator::Create(
4050 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4052 if (!isa<Constant>(Op0RHS) &&
4053 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4054 // Not masking anything out for the RHS, move to LHS.
4055 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4056 Op0LHS->getName()+".masked");
4057 InsertNewInstBefore(NewLHS, I);
4058 return BinaryOperator::Create(
4059 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4064 case Instruction::Add:
4065 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4066 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4067 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4068 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4069 return BinaryOperator::CreateAnd(V, AndRHS);
4070 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4071 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4074 case Instruction::Sub:
4075 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4076 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4077 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4078 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4079 return BinaryOperator::CreateAnd(V, AndRHS);
4081 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4082 // has 1's for all bits that the subtraction with A might affect.
4083 if (Op0I->hasOneUse()) {
4084 uint32_t BitWidth = AndRHSMask.getBitWidth();
4085 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4086 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4088 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4089 if (!(A && A->isZero()) && // avoid infinite recursion.
4090 MaskedValueIsZero(Op0LHS, Mask)) {
4091 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4092 InsertNewInstBefore(NewNeg, I);
4093 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4098 case Instruction::Shl:
4099 case Instruction::LShr:
4100 // (1 << x) & 1 --> zext(x == 0)
4101 // (1 >> x) & 1 --> zext(x == 0)
4102 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4103 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4104 Op0RHS, Context->getNullValue(I.getType()));
4105 InsertNewInstBefore(NewICmp, I);
4106 return new ZExtInst(NewICmp, I.getType());
4111 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4112 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4114 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4115 // If this is an integer truncation or change from signed-to-unsigned, and
4116 // if the source is an and/or with immediate, transform it. This
4117 // frequently occurs for bitfield accesses.
4118 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4119 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4120 CastOp->getNumOperands() == 2)
4121 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4122 if (CastOp->getOpcode() == Instruction::And) {
4123 // Change: and (cast (and X, C1) to T), C2
4124 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4125 // This will fold the two constants together, which may allow
4126 // other simplifications.
4127 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4128 CastOp->getOperand(0), I.getType(),
4129 CastOp->getName()+".shrunk");
4130 NewCast = InsertNewInstBefore(NewCast, I);
4131 // trunc_or_bitcast(C1)&C2
4133 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4134 C3 = Context->getConstantExprAnd(C3, AndRHS);
4135 return BinaryOperator::CreateAnd(NewCast, C3);
4136 } else if (CastOp->getOpcode() == Instruction::Or) {
4137 // Change: and (cast (or X, C1) to T), C2
4138 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4140 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4141 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4143 return ReplaceInstUsesWith(I, AndRHS);
4149 // Try to fold constant and into select arguments.
4150 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4151 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4153 if (isa<PHINode>(Op0))
4154 if (Instruction *NV = FoldOpIntoPhi(I))
4158 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4159 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4161 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4162 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4164 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4165 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4166 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4167 I.getName()+".demorgan");
4168 InsertNewInstBefore(Or, I);
4169 return BinaryOperator::CreateNot(*Context, Or);
4173 Value *A = 0, *B = 0, *C = 0, *D = 0;
4174 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4175 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4176 return ReplaceInstUsesWith(I, Op1);
4178 // (A|B) & ~(A&B) -> A^B
4179 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4180 if ((A == C && B == D) || (A == D && B == C))
4181 return BinaryOperator::CreateXor(A, B);
4185 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4186 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4187 return ReplaceInstUsesWith(I, Op0);
4189 // ~(A&B) & (A|B) -> A^B
4190 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4191 if ((A == C && B == D) || (A == D && B == C))
4192 return BinaryOperator::CreateXor(A, B);
4196 if (Op0->hasOneUse() &&
4197 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4198 if (A == Op1) { // (A^B)&A -> A&(A^B)
4199 I.swapOperands(); // Simplify below
4200 std::swap(Op0, Op1);
4201 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4202 cast<BinaryOperator>(Op0)->swapOperands();
4203 I.swapOperands(); // Simplify below
4204 std::swap(Op0, Op1);
4208 if (Op1->hasOneUse() &&
4209 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4210 if (B == Op0) { // B&(A^B) -> B&(B^A)
4211 cast<BinaryOperator>(Op1)->swapOperands();
4214 if (A == Op0) { // A&(A^B) -> A & ~B
4215 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4216 InsertNewInstBefore(NotB, I);
4217 return BinaryOperator::CreateAnd(A, NotB);
4221 // (A&((~A)|B)) -> A&B
4222 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4223 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4224 return BinaryOperator::CreateAnd(A, Op1);
4225 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4226 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4227 return BinaryOperator::CreateAnd(A, Op0);
4230 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4231 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4232 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4235 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4236 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4240 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4241 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4242 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4243 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4244 const Type *SrcTy = Op0C->getOperand(0)->getType();
4245 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4246 // Only do this if the casts both really cause code to be generated.
4247 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4249 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4251 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4252 Op1C->getOperand(0),
4254 InsertNewInstBefore(NewOp, I);
4255 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4259 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4260 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4261 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4262 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4263 SI0->getOperand(1) == SI1->getOperand(1) &&
4264 (SI0->hasOneUse() || SI1->hasOneUse())) {
4265 Instruction *NewOp =
4266 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4268 SI0->getName()), I);
4269 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4270 SI1->getOperand(1));
4274 // If and'ing two fcmp, try combine them into one.
4275 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4276 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4277 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4281 return Changed ? &I : 0;
4284 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4285 /// capable of providing pieces of a bswap. The subexpression provides pieces
4286 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4287 /// the expression came from the corresponding "byte swapped" byte in some other
4288 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4289 /// we know that the expression deposits the low byte of %X into the high byte
4290 /// of the bswap result and that all other bytes are zero. This expression is
4291 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4294 /// This function returns true if the match was unsuccessful and false if so.
4295 /// On entry to the function the "OverallLeftShift" is a signed integer value
4296 /// indicating the number of bytes that the subexpression is later shifted. For
4297 /// example, if the expression is later right shifted by 16 bits, the
4298 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4299 /// byte of ByteValues is actually being set.
4301 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4302 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4303 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4304 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4305 /// always in the local (OverallLeftShift) coordinate space.
4307 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4308 SmallVector<Value*, 8> &ByteValues) {
4309 if (Instruction *I = dyn_cast<Instruction>(V)) {
4310 // If this is an or instruction, it may be an inner node of the bswap.
4311 if (I->getOpcode() == Instruction::Or) {
4312 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4314 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4318 // If this is a logical shift by a constant multiple of 8, recurse with
4319 // OverallLeftShift and ByteMask adjusted.
4320 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4322 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4323 // Ensure the shift amount is defined and of a byte value.
4324 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4327 unsigned ByteShift = ShAmt >> 3;
4328 if (I->getOpcode() == Instruction::Shl) {
4329 // X << 2 -> collect(X, +2)
4330 OverallLeftShift += ByteShift;
4331 ByteMask >>= ByteShift;
4333 // X >>u 2 -> collect(X, -2)
4334 OverallLeftShift -= ByteShift;
4335 ByteMask <<= ByteShift;
4336 ByteMask &= (~0U >> (32-ByteValues.size()));
4339 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4340 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4342 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4346 // If this is a logical 'and' with a mask that clears bytes, clear the
4347 // corresponding bytes in ByteMask.
4348 if (I->getOpcode() == Instruction::And &&
4349 isa<ConstantInt>(I->getOperand(1))) {
4350 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4351 unsigned NumBytes = ByteValues.size();
4352 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4353 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4355 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4356 // If this byte is masked out by a later operation, we don't care what
4358 if ((ByteMask & (1 << i)) == 0)
4361 // If the AndMask is all zeros for this byte, clear the bit.
4362 APInt MaskB = AndMask & Byte;
4364 ByteMask &= ~(1U << i);
4368 // If the AndMask is not all ones for this byte, it's not a bytezap.
4372 // Otherwise, this byte is kept.
4375 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4380 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4381 // the input value to the bswap. Some observations: 1) if more than one byte
4382 // is demanded from this input, then it could not be successfully assembled
4383 // into a byteswap. At least one of the two bytes would not be aligned with
4384 // their ultimate destination.
4385 if (!isPowerOf2_32(ByteMask)) return true;
4386 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4388 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4389 // is demanded, it needs to go into byte 0 of the result. This means that the
4390 // byte needs to be shifted until it lands in the right byte bucket. The
4391 // shift amount depends on the position: if the byte is coming from the high
4392 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4393 // low part, it must be shifted left.
4394 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4395 if (InputByteNo < ByteValues.size()/2) {
4396 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4399 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4403 // If the destination byte value is already defined, the values are or'd
4404 // together, which isn't a bswap (unless it's an or of the same bits).
4405 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4407 ByteValues[DestByteNo] = V;
4411 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4412 /// If so, insert the new bswap intrinsic and return it.
4413 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4414 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4415 if (!ITy || ITy->getBitWidth() % 16 ||
4416 // ByteMask only allows up to 32-byte values.
4417 ITy->getBitWidth() > 32*8)
4418 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4420 /// ByteValues - For each byte of the result, we keep track of which value
4421 /// defines each byte.
4422 SmallVector<Value*, 8> ByteValues;
4423 ByteValues.resize(ITy->getBitWidth()/8);
4425 // Try to find all the pieces corresponding to the bswap.
4426 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4427 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4430 // Check to see if all of the bytes come from the same value.
4431 Value *V = ByteValues[0];
4432 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4434 // Check to make sure that all of the bytes come from the same value.
4435 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4436 if (ByteValues[i] != V)
4438 const Type *Tys[] = { ITy };
4439 Module *M = I.getParent()->getParent()->getParent();
4440 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4441 return CallInst::Create(F, V);
4444 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4445 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4446 /// we can simplify this expression to "cond ? C : D or B".
4447 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4449 LLVMContext *Context) {
4450 // If A is not a select of -1/0, this cannot match.
4452 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4455 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4456 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4457 return SelectInst::Create(Cond, C, B);
4458 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4459 return SelectInst::Create(Cond, C, B);
4460 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4461 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4462 return SelectInst::Create(Cond, C, D);
4463 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4464 return SelectInst::Create(Cond, C, D);
4468 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4469 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4470 ICmpInst *LHS, ICmpInst *RHS) {
4472 ConstantInt *LHSCst, *RHSCst;
4473 ICmpInst::Predicate LHSCC, RHSCC;
4475 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4476 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4477 m_ConstantInt(LHSCst)), *Context) ||
4478 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4479 m_ConstantInt(RHSCst)), *Context))
4482 // From here on, we only handle:
4483 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4484 if (Val != Val2) return 0;
4486 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4487 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4488 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4489 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4490 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4493 // We can't fold (ugt x, C) | (sgt x, C2).
4494 if (!PredicatesFoldable(LHSCC, RHSCC))
4497 // Ensure that the larger constant is on the RHS.
4499 if (ICmpInst::isSignedPredicate(LHSCC) ||
4500 (ICmpInst::isEquality(LHSCC) &&
4501 ICmpInst::isSignedPredicate(RHSCC)))
4502 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4504 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4507 std::swap(LHS, RHS);
4508 std::swap(LHSCst, RHSCst);
4509 std::swap(LHSCC, RHSCC);
4512 // At this point, we know we have have two icmp instructions
4513 // comparing a value against two constants and or'ing the result
4514 // together. Because of the above check, we know that we only have
4515 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4516 // FoldICmpLogical check above), that the two constants are not
4518 assert(LHSCst != RHSCst && "Compares not folded above?");
4521 default: llvm_unreachable("Unknown integer condition code!");
4522 case ICmpInst::ICMP_EQ:
4524 default: llvm_unreachable("Unknown integer condition code!");
4525 case ICmpInst::ICMP_EQ:
4526 if (LHSCst == SubOne(RHSCst, Context)) {
4527 // (X == 13 | X == 14) -> X-13 <u 2
4528 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4529 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4530 Val->getName()+".off");
4531 InsertNewInstBefore(Add, I);
4532 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4533 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4535 break; // (X == 13 | X == 15) -> no change
4536 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4537 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4539 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4540 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4541 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4542 return ReplaceInstUsesWith(I, RHS);
4545 case ICmpInst::ICMP_NE:
4547 default: llvm_unreachable("Unknown integer condition code!");
4548 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4549 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4550 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4551 return ReplaceInstUsesWith(I, LHS);
4552 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4553 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4554 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4555 return ReplaceInstUsesWith(I, Context->getTrue());
4558 case ICmpInst::ICMP_ULT:
4560 default: llvm_unreachable("Unknown integer condition code!");
4561 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4563 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4564 // If RHSCst is [us]MAXINT, it is always false. Not handling
4565 // this can cause overflow.
4566 if (RHSCst->isMaxValue(false))
4567 return ReplaceInstUsesWith(I, LHS);
4568 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4570 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4572 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4573 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4574 return ReplaceInstUsesWith(I, RHS);
4575 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4579 case ICmpInst::ICMP_SLT:
4581 default: llvm_unreachable("Unknown integer condition code!");
4582 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4584 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4585 // If RHSCst is [us]MAXINT, it is always false. Not handling
4586 // this can cause overflow.
4587 if (RHSCst->isMaxValue(true))
4588 return ReplaceInstUsesWith(I, LHS);
4589 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4591 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4593 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4594 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4595 return ReplaceInstUsesWith(I, RHS);
4596 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4600 case ICmpInst::ICMP_UGT:
4602 default: llvm_unreachable("Unknown integer condition code!");
4603 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4604 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4605 return ReplaceInstUsesWith(I, LHS);
4606 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4608 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4609 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4610 return ReplaceInstUsesWith(I, Context->getTrue());
4611 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4615 case ICmpInst::ICMP_SGT:
4617 default: llvm_unreachable("Unknown integer condition code!");
4618 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4619 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4620 return ReplaceInstUsesWith(I, LHS);
4621 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4623 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4624 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4625 return ReplaceInstUsesWith(I, Context->getTrue());
4626 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4634 /// FoldOrWithConstants - This helper function folds:
4636 /// ((A | B) & C1) | (B & C2)
4642 /// when the XOR of the two constants is "all ones" (-1).
4643 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4644 Value *A, Value *B, Value *C) {
4645 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4649 ConstantInt *CI2 = 0;
4650 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4652 APInt Xor = CI1->getValue() ^ CI2->getValue();
4653 if (!Xor.isAllOnesValue()) return 0;
4655 if (V1 == A || V1 == B) {
4656 Instruction *NewOp =
4657 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4658 return BinaryOperator::CreateOr(NewOp, V1);
4664 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4665 bool Changed = SimplifyCommutative(I);
4666 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4668 if (isa<UndefValue>(Op1)) // X | undef -> -1
4669 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4673 return ReplaceInstUsesWith(I, Op0);
4675 // See if we can simplify any instructions used by the instruction whose sole
4676 // purpose is to compute bits we don't care about.
4677 if (SimplifyDemandedInstructionBits(I))
4679 if (isa<VectorType>(I.getType())) {
4680 if (isa<ConstantAggregateZero>(Op1)) {
4681 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4682 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4683 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4684 return ReplaceInstUsesWith(I, I.getOperand(1));
4689 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4690 ConstantInt *C1 = 0; Value *X = 0;
4691 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4692 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4694 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4695 InsertNewInstBefore(Or, I);
4697 return BinaryOperator::CreateAnd(Or,
4698 Context->getConstantInt(RHS->getValue() | C1->getValue()));
4701 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4702 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4704 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4705 InsertNewInstBefore(Or, I);
4707 return BinaryOperator::CreateXor(Or,
4708 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4711 // Try to fold constant and into select arguments.
4712 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4713 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4715 if (isa<PHINode>(Op0))
4716 if (Instruction *NV = FoldOpIntoPhi(I))
4720 Value *A = 0, *B = 0;
4721 ConstantInt *C1 = 0, *C2 = 0;
4723 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4724 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4725 return ReplaceInstUsesWith(I, Op1);
4726 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4727 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4728 return ReplaceInstUsesWith(I, Op0);
4730 // (A | B) | C and A | (B | C) -> bswap if possible.
4731 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4732 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4733 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4734 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4735 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4736 if (Instruction *BSwap = MatchBSwap(I))
4740 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4741 if (Op0->hasOneUse() &&
4742 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4743 MaskedValueIsZero(Op1, C1->getValue())) {
4744 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4745 InsertNewInstBefore(NOr, I);
4747 return BinaryOperator::CreateXor(NOr, C1);
4750 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4751 if (Op1->hasOneUse() &&
4752 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4753 MaskedValueIsZero(Op0, C1->getValue())) {
4754 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4755 InsertNewInstBefore(NOr, I);
4757 return BinaryOperator::CreateXor(NOr, C1);
4761 Value *C = 0, *D = 0;
4762 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4763 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4764 Value *V1 = 0, *V2 = 0, *V3 = 0;
4765 C1 = dyn_cast<ConstantInt>(C);
4766 C2 = dyn_cast<ConstantInt>(D);
4767 if (C1 && C2) { // (A & C1)|(B & C2)
4768 // If we have: ((V + N) & C1) | (V & C2)
4769 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4770 // replace with V+N.
4771 if (C1->getValue() == ~C2->getValue()) {
4772 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4773 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4774 // Add commutes, try both ways.
4775 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4776 return ReplaceInstUsesWith(I, A);
4777 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4778 return ReplaceInstUsesWith(I, A);
4780 // Or commutes, try both ways.
4781 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4782 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4783 // Add commutes, try both ways.
4784 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4785 return ReplaceInstUsesWith(I, B);
4786 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4787 return ReplaceInstUsesWith(I, B);
4790 V1 = 0; V2 = 0; V3 = 0;
4793 // Check to see if we have any common things being and'ed. If so, find the
4794 // terms for V1 & (V2|V3).
4795 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4796 if (A == B) // (A & C)|(A & D) == A & (C|D)
4797 V1 = A, V2 = C, V3 = D;
4798 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4799 V1 = A, V2 = B, V3 = C;
4800 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4801 V1 = C, V2 = A, V3 = D;
4802 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4803 V1 = C, V2 = A, V3 = B;
4807 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4808 return BinaryOperator::CreateAnd(V1, Or);
4812 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4813 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4815 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4817 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4819 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4822 // ((A&~B)|(~A&B)) -> A^B
4823 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4824 match(B, m_Not(m_Specific(A)), *Context)))
4825 return BinaryOperator::CreateXor(A, D);
4826 // ((~B&A)|(~A&B)) -> A^B
4827 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4828 match(B, m_Not(m_Specific(C)), *Context)))
4829 return BinaryOperator::CreateXor(C, D);
4830 // ((A&~B)|(B&~A)) -> A^B
4831 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4832 match(D, m_Not(m_Specific(A)), *Context)))
4833 return BinaryOperator::CreateXor(A, B);
4834 // ((~B&A)|(B&~A)) -> A^B
4835 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4836 match(D, m_Not(m_Specific(C)), *Context)))
4837 return BinaryOperator::CreateXor(C, B);
4840 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4841 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4842 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4843 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4844 SI0->getOperand(1) == SI1->getOperand(1) &&
4845 (SI0->hasOneUse() || SI1->hasOneUse())) {
4846 Instruction *NewOp =
4847 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4849 SI0->getName()), I);
4850 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4851 SI1->getOperand(1));
4855 // ((A|B)&1)|(B&-2) -> (A&1) | B
4856 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4857 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4858 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4859 if (Ret) return Ret;
4861 // (B&-2)|((A|B)&1) -> (A&1) | B
4862 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4863 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4864 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4865 if (Ret) return Ret;
4868 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
4869 if (A == Op1) // ~A | A == -1
4870 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4874 // Note, A is still live here!
4875 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
4877 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4879 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4880 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4881 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4882 I.getName()+".demorgan"), I);
4883 return BinaryOperator::CreateNot(*Context, And);
4887 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4888 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4889 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4892 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4893 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4897 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4898 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4899 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4900 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4901 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4902 !isa<ICmpInst>(Op1C->getOperand(0))) {
4903 const Type *SrcTy = Op0C->getOperand(0)->getType();
4904 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4905 // Only do this if the casts both really cause code to be
4907 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4909 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4911 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4912 Op1C->getOperand(0),
4914 InsertNewInstBefore(NewOp, I);
4915 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4922 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4923 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4924 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4925 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4926 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4927 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4928 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4929 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4930 // If either of the constants are nans, then the whole thing returns
4932 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4933 return ReplaceInstUsesWith(I, Context->getTrue());
4935 // Otherwise, no need to compare the two constants, compare the
4937 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4938 LHS->getOperand(0), RHS->getOperand(0));
4941 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4942 FCmpInst::Predicate Op0CC, Op1CC;
4943 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4944 m_Value(Op0RHS)), *Context) &&
4945 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4946 m_Value(Op1RHS)), *Context)) {
4947 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4948 // Swap RHS operands to match LHS.
4949 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4950 std::swap(Op1LHS, Op1RHS);
4952 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4953 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4955 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4957 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4958 Op1CC == FCmpInst::FCMP_TRUE)
4959 return ReplaceInstUsesWith(I, Context->getTrue());
4960 else if (Op0CC == FCmpInst::FCMP_FALSE)
4961 return ReplaceInstUsesWith(I, Op1);
4962 else if (Op1CC == FCmpInst::FCMP_FALSE)
4963 return ReplaceInstUsesWith(I, Op0);
4966 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4967 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4968 if (Op0Ordered == Op1Ordered) {
4969 // If both are ordered or unordered, return a new fcmp with
4970 // or'ed predicates.
4971 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4972 Op0LHS, Op0RHS, Context);
4973 if (Instruction *I = dyn_cast<Instruction>(RV))
4975 // Otherwise, it's a constant boolean value...
4976 return ReplaceInstUsesWith(I, RV);
4984 return Changed ? &I : 0;
4989 // XorSelf - Implements: X ^ X --> 0
4992 XorSelf(Value *rhs) : RHS(rhs) {}
4993 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4994 Instruction *apply(BinaryOperator &Xor) const {
5001 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5002 bool Changed = SimplifyCommutative(I);
5003 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5005 if (isa<UndefValue>(Op1)) {
5006 if (isa<UndefValue>(Op0))
5007 // Handle undef ^ undef -> 0 special case. This is a common
5009 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5010 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
5013 // xor X, X = 0, even if X is nested in a sequence of Xor's.
5014 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5015 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5016 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5019 // See if we can simplify any instructions used by the instruction whose sole
5020 // purpose is to compute bits we don't care about.
5021 if (SimplifyDemandedInstructionBits(I))
5023 if (isa<VectorType>(I.getType()))
5024 if (isa<ConstantAggregateZero>(Op1))
5025 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
5027 // Is this a ~ operation?
5028 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5029 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5030 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5031 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5032 if (Op0I->getOpcode() == Instruction::And ||
5033 Op0I->getOpcode() == Instruction::Or) {
5034 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5035 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5037 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5038 Op0I->getOperand(1)->getName()+".not");
5039 InsertNewInstBefore(NotY, I);
5040 if (Op0I->getOpcode() == Instruction::And)
5041 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5043 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5050 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5051 if (RHS == Context->getTrue() && Op0->hasOneUse()) {
5052 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5053 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5054 return new ICmpInst(*Context, ICI->getInversePredicate(),
5055 ICI->getOperand(0), ICI->getOperand(1));
5057 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5058 return new FCmpInst(*Context, FCI->getInversePredicate(),
5059 FCI->getOperand(0), FCI->getOperand(1));
5062 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5063 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5064 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5065 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5066 Instruction::CastOps Opcode = Op0C->getOpcode();
5067 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5068 if (RHS == Context->getConstantExprCast(Opcode,
5070 Op0C->getDestTy())) {
5071 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5073 CI->getOpcode(), CI->getInversePredicate(),
5074 CI->getOperand(0), CI->getOperand(1)), I);
5075 NewCI->takeName(CI);
5076 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5083 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5084 // ~(c-X) == X-c-1 == X+(-c-1)
5085 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5086 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5087 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5088 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5089 Context->getConstantInt(I.getType(), 1));
5090 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5093 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5094 if (Op0I->getOpcode() == Instruction::Add) {
5095 // ~(X-c) --> (-c-1)-X
5096 if (RHS->isAllOnesValue()) {
5097 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5098 return BinaryOperator::CreateSub(
5099 Context->getConstantExprSub(NegOp0CI,
5100 Context->getConstantInt(I.getType(), 1)),
5101 Op0I->getOperand(0));
5102 } else if (RHS->getValue().isSignBit()) {
5103 // (X + C) ^ signbit -> (X + C + signbit)
5105 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5106 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5109 } else if (Op0I->getOpcode() == Instruction::Or) {
5110 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5111 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5112 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5113 // Anything in both C1 and C2 is known to be zero, remove it from
5115 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5116 NewRHS = Context->getConstantExprAnd(NewRHS,
5117 Context->getConstantExprNot(CommonBits));
5118 AddToWorkList(Op0I);
5119 I.setOperand(0, Op0I->getOperand(0));
5120 I.setOperand(1, NewRHS);
5127 // Try to fold constant and into select arguments.
5128 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5129 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5131 if (isa<PHINode>(Op0))
5132 if (Instruction *NV = FoldOpIntoPhi(I))
5136 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
5138 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5140 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
5142 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5145 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5148 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5149 if (A == Op0) { // B^(B|A) == (A|B)^B
5150 Op1I->swapOperands();
5152 std::swap(Op0, Op1);
5153 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5154 I.swapOperands(); // Simplified below.
5155 std::swap(Op0, Op1);
5157 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5158 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5159 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5160 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5161 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5163 if (A == Op0) { // A^(A&B) -> A^(B&A)
5164 Op1I->swapOperands();
5167 if (B == Op0) { // A^(B&A) -> (B&A)^A
5168 I.swapOperands(); // Simplified below.
5169 std::swap(Op0, Op1);
5174 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5177 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5178 Op0I->hasOneUse()) {
5179 if (A == Op1) // (B|A)^B == (A|B)^B
5181 if (B == Op1) { // (A|B)^B == A & ~B
5183 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5185 return BinaryOperator::CreateAnd(A, NotB);
5187 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5188 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5189 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5190 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5191 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5193 if (A == Op1) // (A&B)^A -> (B&A)^A
5195 if (B == Op1 && // (B&A)^A == ~B & A
5196 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5198 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5199 return BinaryOperator::CreateAnd(N, Op1);
5204 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5205 if (Op0I && Op1I && Op0I->isShift() &&
5206 Op0I->getOpcode() == Op1I->getOpcode() &&
5207 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5208 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5209 Instruction *NewOp =
5210 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5211 Op1I->getOperand(0),
5212 Op0I->getName()), I);
5213 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5214 Op1I->getOperand(1));
5218 Value *A, *B, *C, *D;
5219 // (A & B)^(A | B) -> A ^ B
5220 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5221 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5222 if ((A == C && B == D) || (A == D && B == C))
5223 return BinaryOperator::CreateXor(A, B);
5225 // (A | B)^(A & B) -> A ^ B
5226 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5227 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5228 if ((A == C && B == D) || (A == D && B == C))
5229 return BinaryOperator::CreateXor(A, B);
5233 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5234 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5235 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5236 // (X & Y)^(X & Y) -> (Y^Z) & X
5237 Value *X = 0, *Y = 0, *Z = 0;
5239 X = A, Y = B, Z = D;
5241 X = A, Y = B, Z = C;
5243 X = B, Y = A, Z = D;
5245 X = B, Y = A, Z = C;
5248 Instruction *NewOp =
5249 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5250 return BinaryOperator::CreateAnd(NewOp, X);
5255 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5256 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5257 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5260 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5261 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5262 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5263 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5264 const Type *SrcTy = Op0C->getOperand(0)->getType();
5265 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5266 // Only do this if the casts both really cause code to be generated.
5267 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5269 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5271 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5272 Op1C->getOperand(0),
5274 InsertNewInstBefore(NewOp, I);
5275 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5280 return Changed ? &I : 0;
5283 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5284 LLVMContext *Context) {
5285 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5288 static bool HasAddOverflow(ConstantInt *Result,
5289 ConstantInt *In1, ConstantInt *In2,
5292 if (In2->getValue().isNegative())
5293 return Result->getValue().sgt(In1->getValue());
5295 return Result->getValue().slt(In1->getValue());
5297 return Result->getValue().ult(In1->getValue());
5300 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5301 /// overflowed for this type.
5302 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5303 Constant *In2, LLVMContext *Context,
5304 bool IsSigned = false) {
5305 Result = Context->getConstantExprAdd(In1, In2);
5307 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5308 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5309 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5310 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5311 ExtractElement(In1, Idx, Context),
5312 ExtractElement(In2, Idx, Context),
5319 return HasAddOverflow(cast<ConstantInt>(Result),
5320 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5324 static bool HasSubOverflow(ConstantInt *Result,
5325 ConstantInt *In1, ConstantInt *In2,
5328 if (In2->getValue().isNegative())
5329 return Result->getValue().slt(In1->getValue());
5331 return Result->getValue().sgt(In1->getValue());
5333 return Result->getValue().ugt(In1->getValue());
5336 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5337 /// overflowed for this type.
5338 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5339 Constant *In2, LLVMContext *Context,
5340 bool IsSigned = false) {
5341 Result = Context->getConstantExprSub(In1, In2);
5343 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5344 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5345 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5346 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5347 ExtractElement(In1, Idx, Context),
5348 ExtractElement(In2, Idx, Context),
5355 return HasSubOverflow(cast<ConstantInt>(Result),
5356 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5360 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5361 /// code necessary to compute the offset from the base pointer (without adding
5362 /// in the base pointer). Return the result as a signed integer of intptr size.
5363 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5364 TargetData &TD = *IC.getTargetData();
5365 gep_type_iterator GTI = gep_type_begin(GEP);
5366 const Type *IntPtrTy = TD.getIntPtrType();
5367 LLVMContext *Context = IC.getContext();
5368 Value *Result = Context->getNullValue(IntPtrTy);
5370 // Build a mask for high order bits.
5371 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5372 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5374 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5377 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5378 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5379 if (OpC->isZero()) continue;
5381 // Handle a struct index, which adds its field offset to the pointer.
5382 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5383 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5385 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5387 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5389 Result = IC.InsertNewInstBefore(
5390 BinaryOperator::CreateAdd(Result,
5391 Context->getConstantInt(IntPtrTy, Size),
5392 GEP->getName()+".offs"), I);
5396 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5398 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5399 Scale = Context->getConstantExprMul(OC, Scale);
5400 if (Constant *RC = dyn_cast<Constant>(Result))
5401 Result = Context->getConstantExprAdd(RC, Scale);
5403 // Emit an add instruction.
5404 Result = IC.InsertNewInstBefore(
5405 BinaryOperator::CreateAdd(Result, Scale,
5406 GEP->getName()+".offs"), I);
5410 // Convert to correct type.
5411 if (Op->getType() != IntPtrTy) {
5412 if (Constant *OpC = dyn_cast<Constant>(Op))
5413 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5415 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5417 Op->getName()+".c"), I);
5420 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5421 if (Constant *OpC = dyn_cast<Constant>(Op))
5422 Op = Context->getConstantExprMul(OpC, Scale);
5423 else // We'll let instcombine(mul) convert this to a shl if possible.
5424 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5425 GEP->getName()+".idx"), I);
5428 // Emit an add instruction.
5429 if (isa<Constant>(Op) && isa<Constant>(Result))
5430 Result = Context->getConstantExprAdd(cast<Constant>(Op),
5431 cast<Constant>(Result));
5433 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5434 GEP->getName()+".offs"), I);
5440 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5441 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5442 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5443 /// be complex, and scales are involved. The above expression would also be
5444 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5445 /// This later form is less amenable to optimization though, and we are allowed
5446 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5448 /// If we can't emit an optimized form for this expression, this returns null.
5450 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5452 TargetData &TD = *IC.getTargetData();
5453 gep_type_iterator GTI = gep_type_begin(GEP);
5455 // Check to see if this gep only has a single variable index. If so, and if
5456 // any constant indices are a multiple of its scale, then we can compute this
5457 // in terms of the scale of the variable index. For example, if the GEP
5458 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5459 // because the expression will cross zero at the same point.
5460 unsigned i, e = GEP->getNumOperands();
5462 for (i = 1; i != e; ++i, ++GTI) {
5463 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5464 // Compute the aggregate offset of constant indices.
5465 if (CI->isZero()) continue;
5467 // Handle a struct index, which adds its field offset to the pointer.
5468 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5469 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5471 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5472 Offset += Size*CI->getSExtValue();
5475 // Found our variable index.
5480 // If there are no variable indices, we must have a constant offset, just
5481 // evaluate it the general way.
5482 if (i == e) return 0;
5484 Value *VariableIdx = GEP->getOperand(i);
5485 // Determine the scale factor of the variable element. For example, this is
5486 // 4 if the variable index is into an array of i32.
5487 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5489 // Verify that there are no other variable indices. If so, emit the hard way.
5490 for (++i, ++GTI; i != e; ++i, ++GTI) {
5491 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5494 // Compute the aggregate offset of constant indices.
5495 if (CI->isZero()) continue;
5497 // Handle a struct index, which adds its field offset to the pointer.
5498 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5499 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5501 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5502 Offset += Size*CI->getSExtValue();
5506 // Okay, we know we have a single variable index, which must be a
5507 // pointer/array/vector index. If there is no offset, life is simple, return
5509 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5511 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5512 // we don't need to bother extending: the extension won't affect where the
5513 // computation crosses zero.
5514 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5515 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5516 VariableIdx->getNameStart(), &I);
5520 // Otherwise, there is an index. The computation we will do will be modulo
5521 // the pointer size, so get it.
5522 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5524 Offset &= PtrSizeMask;
5525 VariableScale &= PtrSizeMask;
5527 // To do this transformation, any constant index must be a multiple of the
5528 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5529 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5530 // multiple of the variable scale.
5531 int64_t NewOffs = Offset / (int64_t)VariableScale;
5532 if (Offset != NewOffs*(int64_t)VariableScale)
5535 // Okay, we can do this evaluation. Start by converting the index to intptr.
5536 const Type *IntPtrTy = TD.getIntPtrType();
5537 if (VariableIdx->getType() != IntPtrTy)
5538 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5540 VariableIdx->getNameStart(), &I);
5541 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5542 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5546 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5547 /// else. At this point we know that the GEP is on the LHS of the comparison.
5548 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5549 ICmpInst::Predicate Cond,
5551 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5553 // Look through bitcasts.
5554 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5555 RHS = BCI->getOperand(0);
5557 Value *PtrBase = GEPLHS->getOperand(0);
5558 if (TD && PtrBase == RHS) {
5559 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5560 // This transformation (ignoring the base and scales) is valid because we
5561 // know pointers can't overflow. See if we can output an optimized form.
5562 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5564 // If not, synthesize the offset the hard way.
5566 Offset = EmitGEPOffset(GEPLHS, I, *this);
5567 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5568 Context->getNullValue(Offset->getType()));
5569 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5570 // If the base pointers are different, but the indices are the same, just
5571 // compare the base pointer.
5572 if (PtrBase != GEPRHS->getOperand(0)) {
5573 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5574 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5575 GEPRHS->getOperand(0)->getType();
5577 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5578 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5579 IndicesTheSame = false;
5583 // If all indices are the same, just compare the base pointers.
5585 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
5586 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5588 // Otherwise, the base pointers are different and the indices are
5589 // different, bail out.
5593 // If one of the GEPs has all zero indices, recurse.
5594 bool AllZeros = true;
5595 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5596 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5597 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5602 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5603 ICmpInst::getSwappedPredicate(Cond), I);
5605 // If the other GEP has all zero indices, recurse.
5607 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5608 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5609 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5614 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5616 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5617 // If the GEPs only differ by one index, compare it.
5618 unsigned NumDifferences = 0; // Keep track of # differences.
5619 unsigned DiffOperand = 0; // The operand that differs.
5620 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5621 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5622 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5623 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5624 // Irreconcilable differences.
5628 if (NumDifferences++) break;
5633 if (NumDifferences == 0) // SAME GEP?
5634 return ReplaceInstUsesWith(I, // No comparison is needed here.
5635 Context->getConstantInt(Type::Int1Ty,
5636 ICmpInst::isTrueWhenEqual(Cond)));
5638 else if (NumDifferences == 1) {
5639 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5640 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5641 // Make sure we do a signed comparison here.
5642 return new ICmpInst(*Context,
5643 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5647 // Only lower this if the icmp is the only user of the GEP or if we expect
5648 // the result to fold to a constant!
5650 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5651 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5652 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5653 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5654 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5655 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5661 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5663 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5666 if (!isa<ConstantFP>(RHSC)) return 0;
5667 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5669 // Get the width of the mantissa. We don't want to hack on conversions that
5670 // might lose information from the integer, e.g. "i64 -> float"
5671 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5672 if (MantissaWidth == -1) return 0; // Unknown.
5674 // Check to see that the input is converted from an integer type that is small
5675 // enough that preserves all bits. TODO: check here for "known" sign bits.
5676 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5677 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5679 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5680 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5684 // If the conversion would lose info, don't hack on this.
5685 if ((int)InputSize > MantissaWidth)
5688 // Otherwise, we can potentially simplify the comparison. We know that it
5689 // will always come through as an integer value and we know the constant is
5690 // not a NAN (it would have been previously simplified).
5691 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5693 ICmpInst::Predicate Pred;
5694 switch (I.getPredicate()) {
5695 default: llvm_unreachable("Unexpected predicate!");
5696 case FCmpInst::FCMP_UEQ:
5697 case FCmpInst::FCMP_OEQ:
5698 Pred = ICmpInst::ICMP_EQ;
5700 case FCmpInst::FCMP_UGT:
5701 case FCmpInst::FCMP_OGT:
5702 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5704 case FCmpInst::FCMP_UGE:
5705 case FCmpInst::FCMP_OGE:
5706 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5708 case FCmpInst::FCMP_ULT:
5709 case FCmpInst::FCMP_OLT:
5710 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5712 case FCmpInst::FCMP_ULE:
5713 case FCmpInst::FCMP_OLE:
5714 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5716 case FCmpInst::FCMP_UNE:
5717 case FCmpInst::FCMP_ONE:
5718 Pred = ICmpInst::ICMP_NE;
5720 case FCmpInst::FCMP_ORD:
5721 return ReplaceInstUsesWith(I, Context->getTrue());
5722 case FCmpInst::FCMP_UNO:
5723 return ReplaceInstUsesWith(I, Context->getFalse());
5726 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5728 // Now we know that the APFloat is a normal number, zero or inf.
5730 // See if the FP constant is too large for the integer. For example,
5731 // comparing an i8 to 300.0.
5732 unsigned IntWidth = IntTy->getScalarSizeInBits();
5735 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5736 // and large values.
5737 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5738 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5739 APFloat::rmNearestTiesToEven);
5740 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5741 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5742 Pred == ICmpInst::ICMP_SLE)
5743 return ReplaceInstUsesWith(I, Context->getTrue());
5744 return ReplaceInstUsesWith(I, Context->getFalse());
5747 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5748 // +INF and large values.
5749 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5750 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5751 APFloat::rmNearestTiesToEven);
5752 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5753 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5754 Pred == ICmpInst::ICMP_ULE)
5755 return ReplaceInstUsesWith(I, Context->getTrue());
5756 return ReplaceInstUsesWith(I, Context->getFalse());
5761 // See if the RHS value is < SignedMin.
5762 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5763 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5764 APFloat::rmNearestTiesToEven);
5765 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5766 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5767 Pred == ICmpInst::ICMP_SGE)
5768 return ReplaceInstUsesWith(I, Context->getTrue());
5769 return ReplaceInstUsesWith(I, Context->getFalse());
5773 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5774 // [0, UMAX], but it may still be fractional. See if it is fractional by
5775 // casting the FP value to the integer value and back, checking for equality.
5776 // Don't do this for zero, because -0.0 is not fractional.
5777 Constant *RHSInt = LHSUnsigned
5778 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5779 : Context->getConstantExprFPToSI(RHSC, IntTy);
5780 if (!RHS.isZero()) {
5781 bool Equal = LHSUnsigned
5782 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5783 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5785 // If we had a comparison against a fractional value, we have to adjust
5786 // the compare predicate and sometimes the value. RHSC is rounded towards
5787 // zero at this point.
5789 default: llvm_unreachable("Unexpected integer comparison!");
5790 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5791 return ReplaceInstUsesWith(I, Context->getTrue());
5792 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5793 return ReplaceInstUsesWith(I, Context->getFalse());
5794 case ICmpInst::ICMP_ULE:
5795 // (float)int <= 4.4 --> int <= 4
5796 // (float)int <= -4.4 --> false
5797 if (RHS.isNegative())
5798 return ReplaceInstUsesWith(I, Context->getFalse());
5800 case ICmpInst::ICMP_SLE:
5801 // (float)int <= 4.4 --> int <= 4
5802 // (float)int <= -4.4 --> int < -4
5803 if (RHS.isNegative())
5804 Pred = ICmpInst::ICMP_SLT;
5806 case ICmpInst::ICMP_ULT:
5807 // (float)int < -4.4 --> false
5808 // (float)int < 4.4 --> int <= 4
5809 if (RHS.isNegative())
5810 return ReplaceInstUsesWith(I, Context->getFalse());
5811 Pred = ICmpInst::ICMP_ULE;
5813 case ICmpInst::ICMP_SLT:
5814 // (float)int < -4.4 --> int < -4
5815 // (float)int < 4.4 --> int <= 4
5816 if (!RHS.isNegative())
5817 Pred = ICmpInst::ICMP_SLE;
5819 case ICmpInst::ICMP_UGT:
5820 // (float)int > 4.4 --> int > 4
5821 // (float)int > -4.4 --> true
5822 if (RHS.isNegative())
5823 return ReplaceInstUsesWith(I, Context->getTrue());
5825 case ICmpInst::ICMP_SGT:
5826 // (float)int > 4.4 --> int > 4
5827 // (float)int > -4.4 --> int >= -4
5828 if (RHS.isNegative())
5829 Pred = ICmpInst::ICMP_SGE;
5831 case ICmpInst::ICMP_UGE:
5832 // (float)int >= -4.4 --> true
5833 // (float)int >= 4.4 --> int > 4
5834 if (!RHS.isNegative())
5835 return ReplaceInstUsesWith(I, Context->getTrue());
5836 Pred = ICmpInst::ICMP_UGT;
5838 case ICmpInst::ICMP_SGE:
5839 // (float)int >= -4.4 --> int >= -4
5840 // (float)int >= 4.4 --> int > 4
5841 if (!RHS.isNegative())
5842 Pred = ICmpInst::ICMP_SGT;
5848 // Lower this FP comparison into an appropriate integer version of the
5850 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5853 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5854 bool Changed = SimplifyCompare(I);
5855 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5857 // Fold trivial predicates.
5858 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5859 return ReplaceInstUsesWith(I, Context->getFalse());
5860 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5861 return ReplaceInstUsesWith(I, Context->getTrue());
5863 // Simplify 'fcmp pred X, X'
5865 switch (I.getPredicate()) {
5866 default: llvm_unreachable("Unknown predicate!");
5867 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5868 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5869 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5870 return ReplaceInstUsesWith(I, Context->getTrue());
5871 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5872 case FCmpInst::FCMP_OLT: // True if ordered and less than
5873 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5874 return ReplaceInstUsesWith(I, Context->getFalse());
5876 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5877 case FCmpInst::FCMP_ULT: // True if unordered or less than
5878 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5879 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5880 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5881 I.setPredicate(FCmpInst::FCMP_UNO);
5882 I.setOperand(1, Context->getNullValue(Op0->getType()));
5885 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5886 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5887 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5888 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5889 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5890 I.setPredicate(FCmpInst::FCMP_ORD);
5891 I.setOperand(1, Context->getNullValue(Op0->getType()));
5896 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5897 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5899 // Handle fcmp with constant RHS
5900 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5901 // If the constant is a nan, see if we can fold the comparison based on it.
5902 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5903 if (CFP->getValueAPF().isNaN()) {
5904 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5905 return ReplaceInstUsesWith(I, Context->getFalse());
5906 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5907 "Comparison must be either ordered or unordered!");
5908 // True if unordered.
5909 return ReplaceInstUsesWith(I, Context->getTrue());
5913 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5914 switch (LHSI->getOpcode()) {
5915 case Instruction::PHI:
5916 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5917 // block. If in the same block, we're encouraging jump threading. If
5918 // not, we are just pessimizing the code by making an i1 phi.
5919 if (LHSI->getParent() == I.getParent())
5920 if (Instruction *NV = FoldOpIntoPhi(I))
5923 case Instruction::SIToFP:
5924 case Instruction::UIToFP:
5925 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5928 case Instruction::Select:
5929 // If either operand of the select is a constant, we can fold the
5930 // comparison into the select arms, which will cause one to be
5931 // constant folded and the select turned into a bitwise or.
5932 Value *Op1 = 0, *Op2 = 0;
5933 if (LHSI->hasOneUse()) {
5934 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5935 // Fold the known value into the constant operand.
5936 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5937 // Insert a new FCmp of the other select operand.
5938 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5939 LHSI->getOperand(2), RHSC,
5941 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5942 // Fold the known value into the constant operand.
5943 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5944 // Insert a new FCmp of the other select operand.
5945 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5946 LHSI->getOperand(1), RHSC,
5952 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5957 return Changed ? &I : 0;
5960 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5961 bool Changed = SimplifyCompare(I);
5962 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5963 const Type *Ty = Op0->getType();
5967 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
5968 I.isTrueWhenEqual()));
5970 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5971 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5973 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5974 // addresses never equal each other! We already know that Op0 != Op1.
5975 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5976 isa<ConstantPointerNull>(Op0)) &&
5977 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5978 isa<ConstantPointerNull>(Op1)))
5979 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
5980 !I.isTrueWhenEqual()));
5982 // icmp's with boolean values can always be turned into bitwise operations
5983 if (Ty == Type::Int1Ty) {
5984 switch (I.getPredicate()) {
5985 default: llvm_unreachable("Invalid icmp instruction!");
5986 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5987 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5988 InsertNewInstBefore(Xor, I);
5989 return BinaryOperator::CreateNot(*Context, Xor);
5991 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5992 return BinaryOperator::CreateXor(Op0, Op1);
5994 case ICmpInst::ICMP_UGT:
5995 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5997 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5998 Instruction *Not = BinaryOperator::CreateNot(*Context,
5999 Op0, I.getName()+"tmp");
6000 InsertNewInstBefore(Not, I);
6001 return BinaryOperator::CreateAnd(Not, Op1);
6003 case ICmpInst::ICMP_SGT:
6004 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
6006 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
6007 Instruction *Not = BinaryOperator::CreateNot(*Context,
6008 Op1, I.getName()+"tmp");
6009 InsertNewInstBefore(Not, I);
6010 return BinaryOperator::CreateAnd(Not, Op0);
6012 case ICmpInst::ICMP_UGE:
6013 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6015 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
6016 Instruction *Not = BinaryOperator::CreateNot(*Context,
6017 Op0, I.getName()+"tmp");
6018 InsertNewInstBefore(Not, I);
6019 return BinaryOperator::CreateOr(Not, Op1);
6021 case ICmpInst::ICMP_SGE:
6022 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6024 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
6025 Instruction *Not = BinaryOperator::CreateNot(*Context,
6026 Op1, I.getName()+"tmp");
6027 InsertNewInstBefore(Not, I);
6028 return BinaryOperator::CreateOr(Not, Op0);
6033 unsigned BitWidth = 0;
6035 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6036 else if (Ty->isIntOrIntVector())
6037 BitWidth = Ty->getScalarSizeInBits();
6039 bool isSignBit = false;
6041 // See if we are doing a comparison with a constant.
6042 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6043 Value *A = 0, *B = 0;
6045 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6046 if (I.isEquality() && CI->isNullValue() &&
6047 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6048 // (icmp cond A B) if cond is equality
6049 return new ICmpInst(*Context, I.getPredicate(), A, B);
6052 // If we have an icmp le or icmp ge instruction, turn it into the
6053 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6054 // them being folded in the code below.
6055 switch (I.getPredicate()) {
6057 case ICmpInst::ICMP_ULE:
6058 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
6059 return ReplaceInstUsesWith(I, Context->getTrue());
6060 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6061 AddOne(CI, Context));
6062 case ICmpInst::ICMP_SLE:
6063 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
6064 return ReplaceInstUsesWith(I, Context->getTrue());
6065 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6066 AddOne(CI, Context));
6067 case ICmpInst::ICMP_UGE:
6068 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6069 return ReplaceInstUsesWith(I, Context->getTrue());
6070 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6071 SubOne(CI, Context));
6072 case ICmpInst::ICMP_SGE:
6073 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6074 return ReplaceInstUsesWith(I, Context->getTrue());
6075 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6076 SubOne(CI, Context));
6079 // If this comparison is a normal comparison, it demands all
6080 // bits, if it is a sign bit comparison, it only demands the sign bit.
6082 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6085 // See if we can fold the comparison based on range information we can get
6086 // by checking whether bits are known to be zero or one in the input.
6087 if (BitWidth != 0) {
6088 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6089 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6091 if (SimplifyDemandedBits(I.getOperandUse(0),
6092 isSignBit ? APInt::getSignBit(BitWidth)
6093 : APInt::getAllOnesValue(BitWidth),
6094 Op0KnownZero, Op0KnownOne, 0))
6096 if (SimplifyDemandedBits(I.getOperandUse(1),
6097 APInt::getAllOnesValue(BitWidth),
6098 Op1KnownZero, Op1KnownOne, 0))
6101 // Given the known and unknown bits, compute a range that the LHS could be
6102 // in. Compute the Min, Max and RHS values based on the known bits. For the
6103 // EQ and NE we use unsigned values.
6104 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6105 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6106 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6107 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6109 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6112 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6114 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6118 // If Min and Max are known to be the same, then SimplifyDemandedBits
6119 // figured out that the LHS is a constant. Just constant fold this now so
6120 // that code below can assume that Min != Max.
6121 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6122 return new ICmpInst(*Context, I.getPredicate(),
6123 Context->getConstantInt(Op0Min), Op1);
6124 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6125 return new ICmpInst(*Context, I.getPredicate(), Op0,
6126 Context->getConstantInt(Op1Min));
6128 // Based on the range information we know about the LHS, see if we can
6129 // simplify this comparison. For example, (x&4) < 8 is always true.
6130 switch (I.getPredicate()) {
6131 default: llvm_unreachable("Unknown icmp opcode!");
6132 case ICmpInst::ICMP_EQ:
6133 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6134 return ReplaceInstUsesWith(I, Context->getFalse());
6136 case ICmpInst::ICMP_NE:
6137 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6138 return ReplaceInstUsesWith(I, Context->getTrue());
6140 case ICmpInst::ICMP_ULT:
6141 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6142 return ReplaceInstUsesWith(I, Context->getTrue());
6143 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6144 return ReplaceInstUsesWith(I, Context->getFalse());
6145 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6146 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6147 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6148 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6149 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6150 SubOne(CI, Context));
6152 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6153 if (CI->isMinValue(true))
6154 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6155 Context->getAllOnesValue(Op0->getType()));
6158 case ICmpInst::ICMP_UGT:
6159 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6160 return ReplaceInstUsesWith(I, Context->getTrue());
6161 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6162 return ReplaceInstUsesWith(I, Context->getFalse());
6164 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6165 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6166 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6167 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6168 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6169 AddOne(CI, Context));
6171 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6172 if (CI->isMaxValue(true))
6173 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6174 Context->getNullValue(Op0->getType()));
6177 case ICmpInst::ICMP_SLT:
6178 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6179 return ReplaceInstUsesWith(I, Context->getTrue());
6180 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6181 return ReplaceInstUsesWith(I, Context->getFalse());
6182 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6183 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6184 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6185 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6186 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6187 SubOne(CI, Context));
6190 case ICmpInst::ICMP_SGT:
6191 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6192 return ReplaceInstUsesWith(I, Context->getTrue());
6193 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6194 return ReplaceInstUsesWith(I, Context->getFalse());
6196 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6197 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6198 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6199 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6200 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6201 AddOne(CI, Context));
6204 case ICmpInst::ICMP_SGE:
6205 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6206 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6207 return ReplaceInstUsesWith(I, Context->getTrue());
6208 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6209 return ReplaceInstUsesWith(I, Context->getFalse());
6211 case ICmpInst::ICMP_SLE:
6212 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6213 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6214 return ReplaceInstUsesWith(I, Context->getTrue());
6215 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6216 return ReplaceInstUsesWith(I, Context->getFalse());
6218 case ICmpInst::ICMP_UGE:
6219 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6220 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6221 return ReplaceInstUsesWith(I, Context->getTrue());
6222 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6223 return ReplaceInstUsesWith(I, Context->getFalse());
6225 case ICmpInst::ICMP_ULE:
6226 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6227 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6228 return ReplaceInstUsesWith(I, Context->getTrue());
6229 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6230 return ReplaceInstUsesWith(I, Context->getFalse());
6234 // Turn a signed comparison into an unsigned one if both operands
6235 // are known to have the same sign.
6236 if (I.isSignedPredicate() &&
6237 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6238 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6239 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6242 // Test if the ICmpInst instruction is used exclusively by a select as
6243 // part of a minimum or maximum operation. If so, refrain from doing
6244 // any other folding. This helps out other analyses which understand
6245 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6246 // and CodeGen. And in this case, at least one of the comparison
6247 // operands has at least one user besides the compare (the select),
6248 // which would often largely negate the benefit of folding anyway.
6250 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6251 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6252 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6255 // See if we are doing a comparison between a constant and an instruction that
6256 // can be folded into the comparison.
6257 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6258 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6259 // instruction, see if that instruction also has constants so that the
6260 // instruction can be folded into the icmp
6261 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6262 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6266 // Handle icmp with constant (but not simple integer constant) RHS
6267 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6268 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6269 switch (LHSI->getOpcode()) {
6270 case Instruction::GetElementPtr:
6271 if (RHSC->isNullValue()) {
6272 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6273 bool isAllZeros = true;
6274 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6275 if (!isa<Constant>(LHSI->getOperand(i)) ||
6276 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6281 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6282 Context->getNullValue(LHSI->getOperand(0)->getType()));
6286 case Instruction::PHI:
6287 // Only fold icmp into the PHI if the phi and fcmp are in the same
6288 // block. If in the same block, we're encouraging jump threading. If
6289 // not, we are just pessimizing the code by making an i1 phi.
6290 if (LHSI->getParent() == I.getParent())
6291 if (Instruction *NV = FoldOpIntoPhi(I))
6294 case Instruction::Select: {
6295 // If either operand of the select is a constant, we can fold the
6296 // comparison into the select arms, which will cause one to be
6297 // constant folded and the select turned into a bitwise or.
6298 Value *Op1 = 0, *Op2 = 0;
6299 if (LHSI->hasOneUse()) {
6300 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6301 // Fold the known value into the constant operand.
6302 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6303 // Insert a new ICmp of the other select operand.
6304 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6305 LHSI->getOperand(2), RHSC,
6307 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6308 // Fold the known value into the constant operand.
6309 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6310 // Insert a new ICmp of the other select operand.
6311 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6312 LHSI->getOperand(1), RHSC,
6318 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6321 case Instruction::Malloc:
6322 // If we have (malloc != null), and if the malloc has a single use, we
6323 // can assume it is successful and remove the malloc.
6324 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6325 AddToWorkList(LHSI);
6326 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6327 !I.isTrueWhenEqual()));
6333 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6334 if (User *GEP = dyn_castGetElementPtr(Op0))
6335 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6337 if (User *GEP = dyn_castGetElementPtr(Op1))
6338 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6339 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6342 // Test to see if the operands of the icmp are casted versions of other
6343 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6345 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6346 if (isa<PointerType>(Op0->getType()) &&
6347 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6348 // We keep moving the cast from the left operand over to the right
6349 // operand, where it can often be eliminated completely.
6350 Op0 = CI->getOperand(0);
6352 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6353 // so eliminate it as well.
6354 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6355 Op1 = CI2->getOperand(0);
6357 // If Op1 is a constant, we can fold the cast into the constant.
6358 if (Op0->getType() != Op1->getType()) {
6359 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6360 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6362 // Otherwise, cast the RHS right before the icmp
6363 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6366 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6370 if (isa<CastInst>(Op0)) {
6371 // Handle the special case of: icmp (cast bool to X), <cst>
6372 // This comes up when you have code like
6375 // For generality, we handle any zero-extension of any operand comparison
6376 // with a constant or another cast from the same type.
6377 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6378 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6382 // See if it's the same type of instruction on the left and right.
6383 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6384 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6385 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6386 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6387 switch (Op0I->getOpcode()) {
6389 case Instruction::Add:
6390 case Instruction::Sub:
6391 case Instruction::Xor:
6392 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6393 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6394 Op1I->getOperand(0));
6395 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6396 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6397 if (CI->getValue().isSignBit()) {
6398 ICmpInst::Predicate Pred = I.isSignedPredicate()
6399 ? I.getUnsignedPredicate()
6400 : I.getSignedPredicate();
6401 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6402 Op1I->getOperand(0));
6405 if (CI->getValue().isMaxSignedValue()) {
6406 ICmpInst::Predicate Pred = I.isSignedPredicate()
6407 ? I.getUnsignedPredicate()
6408 : I.getSignedPredicate();
6409 Pred = I.getSwappedPredicate(Pred);
6410 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6411 Op1I->getOperand(0));
6415 case Instruction::Mul:
6416 if (!I.isEquality())
6419 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6420 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6421 // Mask = -1 >> count-trailing-zeros(Cst).
6422 if (!CI->isZero() && !CI->isOne()) {
6423 const APInt &AP = CI->getValue();
6424 ConstantInt *Mask = Context->getConstantInt(
6425 APInt::getLowBitsSet(AP.getBitWidth(),
6427 AP.countTrailingZeros()));
6428 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6430 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6432 InsertNewInstBefore(And1, I);
6433 InsertNewInstBefore(And2, I);
6434 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6443 // ~x < ~y --> y < x
6445 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6446 match(Op1, m_Not(m_Value(B)), *Context))
6447 return new ICmpInst(*Context, I.getPredicate(), B, A);
6450 if (I.isEquality()) {
6451 Value *A, *B, *C, *D;
6453 // -x == -y --> x == y
6454 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6455 match(Op1, m_Neg(m_Value(B)), *Context))
6456 return new ICmpInst(*Context, I.getPredicate(), A, B);
6458 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6459 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6460 Value *OtherVal = A == Op1 ? B : A;
6461 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6462 Context->getNullValue(A->getType()));
6465 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6466 // A^c1 == C^c2 --> A == C^(c1^c2)
6467 ConstantInt *C1, *C2;
6468 if (match(B, m_ConstantInt(C1), *Context) &&
6469 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6471 Context->getConstantInt(C1->getValue() ^ C2->getValue());
6472 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6473 return new ICmpInst(*Context, I.getPredicate(), A,
6474 InsertNewInstBefore(Xor, I));
6477 // A^B == A^D -> B == D
6478 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6479 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6480 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6481 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6485 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6486 (A == Op0 || B == Op0)) {
6487 // A == (A^B) -> B == 0
6488 Value *OtherVal = A == Op0 ? B : A;
6489 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6490 Context->getNullValue(A->getType()));
6493 // (A-B) == A -> B == 0
6494 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6495 return new ICmpInst(*Context, I.getPredicate(), B,
6496 Context->getNullValue(B->getType()));
6498 // A == (A-B) -> B == 0
6499 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6500 return new ICmpInst(*Context, I.getPredicate(), B,
6501 Context->getNullValue(B->getType()));
6503 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6504 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6505 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6506 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6507 Value *X = 0, *Y = 0, *Z = 0;
6510 X = B; Y = D; Z = A;
6511 } else if (A == D) {
6512 X = B; Y = C; Z = A;
6513 } else if (B == C) {
6514 X = A; Y = D; Z = B;
6515 } else if (B == D) {
6516 X = A; Y = C; Z = B;
6519 if (X) { // Build (X^Y) & Z
6520 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6521 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6522 I.setOperand(0, Op1);
6523 I.setOperand(1, Context->getNullValue(Op1->getType()));
6528 return Changed ? &I : 0;
6532 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6533 /// and CmpRHS are both known to be integer constants.
6534 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6535 ConstantInt *DivRHS) {
6536 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6537 const APInt &CmpRHSV = CmpRHS->getValue();
6539 // FIXME: If the operand types don't match the type of the divide
6540 // then don't attempt this transform. The code below doesn't have the
6541 // logic to deal with a signed divide and an unsigned compare (and
6542 // vice versa). This is because (x /s C1) <s C2 produces different
6543 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6544 // (x /u C1) <u C2. Simply casting the operands and result won't
6545 // work. :( The if statement below tests that condition and bails
6547 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6548 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6550 if (DivRHS->isZero())
6551 return 0; // The ProdOV computation fails on divide by zero.
6552 if (DivIsSigned && DivRHS->isAllOnesValue())
6553 return 0; // The overflow computation also screws up here
6554 if (DivRHS->isOne())
6555 return 0; // Not worth bothering, and eliminates some funny cases
6558 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6559 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6560 // C2 (CI). By solving for X we can turn this into a range check
6561 // instead of computing a divide.
6562 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6564 // Determine if the product overflows by seeing if the product is
6565 // not equal to the divide. Make sure we do the same kind of divide
6566 // as in the LHS instruction that we're folding.
6567 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6568 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6570 // Get the ICmp opcode
6571 ICmpInst::Predicate Pred = ICI.getPredicate();
6573 // Figure out the interval that is being checked. For example, a comparison
6574 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6575 // Compute this interval based on the constants involved and the signedness of
6576 // the compare/divide. This computes a half-open interval, keeping track of
6577 // whether either value in the interval overflows. After analysis each
6578 // overflow variable is set to 0 if it's corresponding bound variable is valid
6579 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6580 int LoOverflow = 0, HiOverflow = 0;
6581 Constant *LoBound = 0, *HiBound = 0;
6583 if (!DivIsSigned) { // udiv
6584 // e.g. X/5 op 3 --> [15, 20)
6586 HiOverflow = LoOverflow = ProdOV;
6588 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6589 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6590 if (CmpRHSV == 0) { // (X / pos) op 0
6591 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6592 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6595 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6596 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6597 HiOverflow = LoOverflow = ProdOV;
6599 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6600 } else { // (X / pos) op neg
6601 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6602 HiBound = AddOne(Prod, Context);
6603 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6605 ConstantInt* DivNeg =
6606 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6607 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6611 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6612 if (CmpRHSV == 0) { // (X / neg) op 0
6613 // e.g. X/-5 op 0 --> [-4, 5)
6614 LoBound = AddOne(DivRHS, Context);
6615 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6616 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6617 HiOverflow = 1; // [INTMIN+1, overflow)
6618 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6620 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6621 // e.g. X/-5 op 3 --> [-19, -14)
6622 HiBound = AddOne(Prod, Context);
6623 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6625 LoOverflow = AddWithOverflow(LoBound, HiBound,
6626 DivRHS, Context, true) ? -1 : 0;
6627 } else { // (X / neg) op neg
6628 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6629 LoOverflow = HiOverflow = ProdOV;
6631 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6634 // Dividing by a negative swaps the condition. LT <-> GT
6635 Pred = ICmpInst::getSwappedPredicate(Pred);
6638 Value *X = DivI->getOperand(0);
6640 default: llvm_unreachable("Unhandled icmp opcode!");
6641 case ICmpInst::ICMP_EQ:
6642 if (LoOverflow && HiOverflow)
6643 return ReplaceInstUsesWith(ICI, Context->getFalse());
6644 else if (HiOverflow)
6645 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
6646 ICmpInst::ICMP_UGE, X, LoBound);
6647 else if (LoOverflow)
6648 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
6649 ICmpInst::ICMP_ULT, X, HiBound);
6651 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6652 case ICmpInst::ICMP_NE:
6653 if (LoOverflow && HiOverflow)
6654 return ReplaceInstUsesWith(ICI, Context->getTrue());
6655 else if (HiOverflow)
6656 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
6657 ICmpInst::ICMP_ULT, X, LoBound);
6658 else if (LoOverflow)
6659 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
6660 ICmpInst::ICMP_UGE, X, HiBound);
6662 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6663 case ICmpInst::ICMP_ULT:
6664 case ICmpInst::ICMP_SLT:
6665 if (LoOverflow == +1) // Low bound is greater than input range.
6666 return ReplaceInstUsesWith(ICI, Context->getTrue());
6667 if (LoOverflow == -1) // Low bound is less than input range.
6668 return ReplaceInstUsesWith(ICI, Context->getFalse());
6669 return new ICmpInst(*Context, Pred, X, LoBound);
6670 case ICmpInst::ICMP_UGT:
6671 case ICmpInst::ICMP_SGT:
6672 if (HiOverflow == +1) // High bound greater than input range.
6673 return ReplaceInstUsesWith(ICI, Context->getFalse());
6674 else if (HiOverflow == -1) // High bound less than input range.
6675 return ReplaceInstUsesWith(ICI, Context->getTrue());
6676 if (Pred == ICmpInst::ICMP_UGT)
6677 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6679 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6684 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6686 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6689 const APInt &RHSV = RHS->getValue();
6691 switch (LHSI->getOpcode()) {
6692 case Instruction::Trunc:
6693 if (ICI.isEquality() && LHSI->hasOneUse()) {
6694 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6695 // of the high bits truncated out of x are known.
6696 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6697 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6698 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6699 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6700 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6702 // If all the high bits are known, we can do this xform.
6703 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6704 // Pull in the high bits from known-ones set.
6705 APInt NewRHS(RHS->getValue());
6706 NewRHS.zext(SrcBits);
6708 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6709 Context->getConstantInt(NewRHS));
6714 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6715 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6716 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6718 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6719 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6720 Value *CompareVal = LHSI->getOperand(0);
6722 // If the sign bit of the XorCST is not set, there is no change to
6723 // the operation, just stop using the Xor.
6724 if (!XorCST->getValue().isNegative()) {
6725 ICI.setOperand(0, CompareVal);
6726 AddToWorkList(LHSI);
6730 // Was the old condition true if the operand is positive?
6731 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6733 // If so, the new one isn't.
6734 isTrueIfPositive ^= true;
6736 if (isTrueIfPositive)
6737 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6738 SubOne(RHS, Context));
6740 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6741 AddOne(RHS, Context));
6744 if (LHSI->hasOneUse()) {
6745 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6746 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6747 const APInt &SignBit = XorCST->getValue();
6748 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6749 ? ICI.getUnsignedPredicate()
6750 : ICI.getSignedPredicate();
6751 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6752 Context->getConstantInt(RHSV ^ SignBit));
6755 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6756 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6757 const APInt &NotSignBit = XorCST->getValue();
6758 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6759 ? ICI.getUnsignedPredicate()
6760 : ICI.getSignedPredicate();
6761 Pred = ICI.getSwappedPredicate(Pred);
6762 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6763 Context->getConstantInt(RHSV ^ NotSignBit));
6768 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6769 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6770 LHSI->getOperand(0)->hasOneUse()) {
6771 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6773 // If the LHS is an AND of a truncating cast, we can widen the
6774 // and/compare to be the input width without changing the value
6775 // produced, eliminating a cast.
6776 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6777 // We can do this transformation if either the AND constant does not
6778 // have its sign bit set or if it is an equality comparison.
6779 // Extending a relational comparison when we're checking the sign
6780 // bit would not work.
6781 if (Cast->hasOneUse() &&
6782 (ICI.isEquality() ||
6783 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6785 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6786 APInt NewCST = AndCST->getValue();
6787 NewCST.zext(BitWidth);
6789 NewCI.zext(BitWidth);
6790 Instruction *NewAnd =
6791 BinaryOperator::CreateAnd(Cast->getOperand(0),
6792 Context->getConstantInt(NewCST),LHSI->getName());
6793 InsertNewInstBefore(NewAnd, ICI);
6794 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6795 Context->getConstantInt(NewCI));
6799 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6800 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6801 // happens a LOT in code produced by the C front-end, for bitfield
6803 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6804 if (Shift && !Shift->isShift())
6808 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6809 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6810 const Type *AndTy = AndCST->getType(); // Type of the and.
6812 // We can fold this as long as we can't shift unknown bits
6813 // into the mask. This can only happen with signed shift
6814 // rights, as they sign-extend.
6816 bool CanFold = Shift->isLogicalShift();
6818 // To test for the bad case of the signed shr, see if any
6819 // of the bits shifted in could be tested after the mask.
6820 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6821 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6823 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6824 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6825 AndCST->getValue()) == 0)
6831 if (Shift->getOpcode() == Instruction::Shl)
6832 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6834 NewCst = Context->getConstantExprShl(RHS, ShAmt);
6836 // Check to see if we are shifting out any of the bits being
6838 if (Context->getConstantExpr(Shift->getOpcode(),
6839 NewCst, ShAmt) != RHS) {
6840 // If we shifted bits out, the fold is not going to work out.
6841 // As a special case, check to see if this means that the
6842 // result is always true or false now.
6843 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6844 return ReplaceInstUsesWith(ICI, Context->getFalse());
6845 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6846 return ReplaceInstUsesWith(ICI, Context->getTrue());
6848 ICI.setOperand(1, NewCst);
6849 Constant *NewAndCST;
6850 if (Shift->getOpcode() == Instruction::Shl)
6851 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6853 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6854 LHSI->setOperand(1, NewAndCST);
6855 LHSI->setOperand(0, Shift->getOperand(0));
6856 AddToWorkList(Shift); // Shift is dead.
6857 AddUsesToWorkList(ICI);
6863 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6864 // preferable because it allows the C<<Y expression to be hoisted out
6865 // of a loop if Y is invariant and X is not.
6866 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6867 ICI.isEquality() && !Shift->isArithmeticShift() &&
6868 !isa<Constant>(Shift->getOperand(0))) {
6871 if (Shift->getOpcode() == Instruction::LShr) {
6872 NS = BinaryOperator::CreateShl(AndCST,
6873 Shift->getOperand(1), "tmp");
6875 // Insert a logical shift.
6876 NS = BinaryOperator::CreateLShr(AndCST,
6877 Shift->getOperand(1), "tmp");
6879 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6881 // Compute X & (C << Y).
6882 Instruction *NewAnd =
6883 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6884 InsertNewInstBefore(NewAnd, ICI);
6886 ICI.setOperand(0, NewAnd);
6892 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6893 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6896 uint32_t TypeBits = RHSV.getBitWidth();
6898 // Check that the shift amount is in range. If not, don't perform
6899 // undefined shifts. When the shift is visited it will be
6901 if (ShAmt->uge(TypeBits))
6904 if (ICI.isEquality()) {
6905 // If we are comparing against bits always shifted out, the
6906 // comparison cannot succeed.
6908 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6910 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6911 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6912 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6913 return ReplaceInstUsesWith(ICI, Cst);
6916 if (LHSI->hasOneUse()) {
6917 // Otherwise strength reduce the shift into an and.
6918 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6920 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6921 TypeBits-ShAmtVal));
6924 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6925 Mask, LHSI->getName()+".mask");
6926 Value *And = InsertNewInstBefore(AndI, ICI);
6927 return new ICmpInst(*Context, ICI.getPredicate(), And,
6928 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6932 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6933 bool TrueIfSigned = false;
6934 if (LHSI->hasOneUse() &&
6935 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6936 // (X << 31) <s 0 --> (X&1) != 0
6937 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6938 (TypeBits-ShAmt->getZExtValue()-1));
6940 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6941 Mask, LHSI->getName()+".mask");
6942 Value *And = InsertNewInstBefore(AndI, ICI);
6944 return new ICmpInst(*Context,
6945 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6946 And, Context->getNullValue(And->getType()));
6951 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6952 case Instruction::AShr: {
6953 // Only handle equality comparisons of shift-by-constant.
6954 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6955 if (!ShAmt || !ICI.isEquality()) break;
6957 // Check that the shift amount is in range. If not, don't perform
6958 // undefined shifts. When the shift is visited it will be
6960 uint32_t TypeBits = RHSV.getBitWidth();
6961 if (ShAmt->uge(TypeBits))
6964 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6966 // If we are comparing against bits always shifted out, the
6967 // comparison cannot succeed.
6968 APInt Comp = RHSV << ShAmtVal;
6969 if (LHSI->getOpcode() == Instruction::LShr)
6970 Comp = Comp.lshr(ShAmtVal);
6972 Comp = Comp.ashr(ShAmtVal);
6974 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6975 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6976 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6977 return ReplaceInstUsesWith(ICI, Cst);
6980 // Otherwise, check to see if the bits shifted out are known to be zero.
6981 // If so, we can compare against the unshifted value:
6982 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6983 if (LHSI->hasOneUse() &&
6984 MaskedValueIsZero(LHSI->getOperand(0),
6985 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6986 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6987 Context->getConstantExprShl(RHS, ShAmt));
6990 if (LHSI->hasOneUse()) {
6991 // Otherwise strength reduce the shift into an and.
6992 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6993 Constant *Mask = Context->getConstantInt(Val);
6996 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6997 Mask, LHSI->getName()+".mask");
6998 Value *And = InsertNewInstBefore(AndI, ICI);
6999 return new ICmpInst(*Context, ICI.getPredicate(), And,
7000 Context->getConstantExprShl(RHS, ShAmt));
7005 case Instruction::SDiv:
7006 case Instruction::UDiv:
7007 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7008 // Fold this div into the comparison, producing a range check.
7009 // Determine, based on the divide type, what the range is being
7010 // checked. If there is an overflow on the low or high side, remember
7011 // it, otherwise compute the range [low, hi) bounding the new value.
7012 // See: InsertRangeTest above for the kinds of replacements possible.
7013 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7014 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7019 case Instruction::Add:
7020 // Fold: icmp pred (add, X, C1), C2
7022 if (!ICI.isEquality()) {
7023 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7025 const APInt &LHSV = LHSC->getValue();
7027 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7030 if (ICI.isSignedPredicate()) {
7031 if (CR.getLower().isSignBit()) {
7032 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7033 Context->getConstantInt(CR.getUpper()));
7034 } else if (CR.getUpper().isSignBit()) {
7035 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7036 Context->getConstantInt(CR.getLower()));
7039 if (CR.getLower().isMinValue()) {
7040 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7041 Context->getConstantInt(CR.getUpper()));
7042 } else if (CR.getUpper().isMinValue()) {
7043 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7044 Context->getConstantInt(CR.getLower()));
7051 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7052 if (ICI.isEquality()) {
7053 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7055 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7056 // the second operand is a constant, simplify a bit.
7057 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7058 switch (BO->getOpcode()) {
7059 case Instruction::SRem:
7060 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7061 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7062 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7063 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7064 Instruction *NewRem =
7065 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7067 InsertNewInstBefore(NewRem, ICI);
7068 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
7069 Context->getNullValue(BO->getType()));
7073 case Instruction::Add:
7074 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7075 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7076 if (BO->hasOneUse())
7077 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7078 Context->getConstantExprSub(RHS, BOp1C));
7079 } else if (RHSV == 0) {
7080 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7081 // efficiently invertible, or if the add has just this one use.
7082 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7084 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7085 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7086 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7087 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7088 else if (BO->hasOneUse()) {
7089 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7090 InsertNewInstBefore(Neg, ICI);
7092 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7096 case Instruction::Xor:
7097 // For the xor case, we can xor two constants together, eliminating
7098 // the explicit xor.
7099 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7100 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7101 Context->getConstantExprXor(RHS, BOC));
7104 case Instruction::Sub:
7105 // Replace (([sub|xor] A, B) != 0) with (A != B)
7107 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7111 case Instruction::Or:
7112 // If bits are being or'd in that are not present in the constant we
7113 // are comparing against, then the comparison could never succeed!
7114 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7115 Constant *NotCI = Context->getConstantExprNot(RHS);
7116 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7117 return ReplaceInstUsesWith(ICI,
7118 Context->getConstantInt(Type::Int1Ty,
7123 case Instruction::And:
7124 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7125 // If bits are being compared against that are and'd out, then the
7126 // comparison can never succeed!
7127 if ((RHSV & ~BOC->getValue()) != 0)
7128 return ReplaceInstUsesWith(ICI,
7129 Context->getConstantInt(Type::Int1Ty,
7132 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7133 if (RHS == BOC && RHSV.isPowerOf2())
7134 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7135 ICmpInst::ICMP_NE, LHSI,
7136 Context->getNullValue(RHS->getType()));
7138 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7139 if (BOC->getValue().isSignBit()) {
7140 Value *X = BO->getOperand(0);
7141 Constant *Zero = Context->getNullValue(X->getType());
7142 ICmpInst::Predicate pred = isICMP_NE ?
7143 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7144 return new ICmpInst(*Context, pred, X, Zero);
7147 // ((X & ~7) == 0) --> X < 8
7148 if (RHSV == 0 && isHighOnes(BOC)) {
7149 Value *X = BO->getOperand(0);
7150 Constant *NegX = Context->getConstantExprNeg(BOC);
7151 ICmpInst::Predicate pred = isICMP_NE ?
7152 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7153 return new ICmpInst(*Context, pred, X, NegX);
7158 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7159 // Handle icmp {eq|ne} <intrinsic>, intcst.
7160 if (II->getIntrinsicID() == Intrinsic::bswap) {
7162 ICI.setOperand(0, II->getOperand(1));
7163 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7171 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7172 /// We only handle extending casts so far.
7174 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7175 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7176 Value *LHSCIOp = LHSCI->getOperand(0);
7177 const Type *SrcTy = LHSCIOp->getType();
7178 const Type *DestTy = LHSCI->getType();
7181 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7182 // integer type is the same size as the pointer type.
7183 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7184 TD->getPointerSizeInBits() ==
7185 cast<IntegerType>(DestTy)->getBitWidth()) {
7187 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7188 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7189 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7190 RHSOp = RHSC->getOperand(0);
7191 // If the pointer types don't match, insert a bitcast.
7192 if (LHSCIOp->getType() != RHSOp->getType())
7193 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7197 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7200 // The code below only handles extension cast instructions, so far.
7202 if (LHSCI->getOpcode() != Instruction::ZExt &&
7203 LHSCI->getOpcode() != Instruction::SExt)
7206 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7207 bool isSignedCmp = ICI.isSignedPredicate();
7209 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7210 // Not an extension from the same type?
7211 RHSCIOp = CI->getOperand(0);
7212 if (RHSCIOp->getType() != LHSCIOp->getType())
7215 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7216 // and the other is a zext), then we can't handle this.
7217 if (CI->getOpcode() != LHSCI->getOpcode())
7220 // Deal with equality cases early.
7221 if (ICI.isEquality())
7222 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7224 // A signed comparison of sign extended values simplifies into a
7225 // signed comparison.
7226 if (isSignedCmp && isSignedExt)
7227 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7229 // The other three cases all fold into an unsigned comparison.
7230 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7233 // If we aren't dealing with a constant on the RHS, exit early
7234 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7238 // Compute the constant that would happen if we truncated to SrcTy then
7239 // reextended to DestTy.
7240 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7241 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7244 // If the re-extended constant didn't change...
7246 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7247 // For example, we might have:
7248 // %A = sext i16 %X to i32
7249 // %B = icmp ugt i32 %A, 1330
7250 // It is incorrect to transform this into
7251 // %B = icmp ugt i16 %X, 1330
7252 // because %A may have negative value.
7254 // However, we allow this when the compare is EQ/NE, because they are
7256 if (isSignedExt == isSignedCmp || ICI.isEquality())
7257 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7261 // The re-extended constant changed so the constant cannot be represented
7262 // in the shorter type. Consequently, we cannot emit a simple comparison.
7264 // First, handle some easy cases. We know the result cannot be equal at this
7265 // point so handle the ICI.isEquality() cases
7266 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7267 return ReplaceInstUsesWith(ICI, Context->getFalse());
7268 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7269 return ReplaceInstUsesWith(ICI, Context->getTrue());
7271 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7272 // should have been folded away previously and not enter in here.
7275 // We're performing a signed comparison.
7276 if (cast<ConstantInt>(CI)->getValue().isNegative())
7277 Result = Context->getFalse(); // X < (small) --> false
7279 Result = Context->getTrue(); // X < (large) --> true
7281 // We're performing an unsigned comparison.
7283 // We're performing an unsigned comp with a sign extended value.
7284 // This is true if the input is >= 0. [aka >s -1]
7285 Constant *NegOne = Context->getAllOnesValue(SrcTy);
7286 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7287 LHSCIOp, NegOne, ICI.getName()), ICI);
7289 // Unsigned extend & unsigned compare -> always true.
7290 Result = Context->getTrue();
7294 // Finally, return the value computed.
7295 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7296 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7297 return ReplaceInstUsesWith(ICI, Result);
7299 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7300 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7301 "ICmp should be folded!");
7302 if (Constant *CI = dyn_cast<Constant>(Result))
7303 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7304 return BinaryOperator::CreateNot(*Context, Result);
7307 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7308 return commonShiftTransforms(I);
7311 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7312 return commonShiftTransforms(I);
7315 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7316 if (Instruction *R = commonShiftTransforms(I))
7319 Value *Op0 = I.getOperand(0);
7321 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7322 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7323 if (CSI->isAllOnesValue())
7324 return ReplaceInstUsesWith(I, CSI);
7326 // See if we can turn a signed shr into an unsigned shr.
7327 if (MaskedValueIsZero(Op0,
7328 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7329 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7331 // Arithmetic shifting an all-sign-bit value is a no-op.
7332 unsigned NumSignBits = ComputeNumSignBits(Op0);
7333 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7334 return ReplaceInstUsesWith(I, Op0);
7339 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7340 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7341 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7343 // shl X, 0 == X and shr X, 0 == X
7344 // shl 0, X == 0 and shr 0, X == 0
7345 if (Op1 == Context->getNullValue(Op1->getType()) ||
7346 Op0 == Context->getNullValue(Op0->getType()))
7347 return ReplaceInstUsesWith(I, Op0);
7349 if (isa<UndefValue>(Op0)) {
7350 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7351 return ReplaceInstUsesWith(I, Op0);
7352 else // undef << X -> 0, undef >>u X -> 0
7353 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7355 if (isa<UndefValue>(Op1)) {
7356 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7357 return ReplaceInstUsesWith(I, Op0);
7358 else // X << undef, X >>u undef -> 0
7359 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7362 // See if we can fold away this shift.
7363 if (SimplifyDemandedInstructionBits(I))
7366 // Try to fold constant and into select arguments.
7367 if (isa<Constant>(Op0))
7368 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7369 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7372 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7373 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7378 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7379 BinaryOperator &I) {
7380 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7382 // See if we can simplify any instructions used by the instruction whose sole
7383 // purpose is to compute bits we don't care about.
7384 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7386 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7389 if (Op1->uge(TypeBits)) {
7390 if (I.getOpcode() != Instruction::AShr)
7391 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7393 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7398 // ((X*C1) << C2) == (X * (C1 << C2))
7399 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7400 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7401 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7402 return BinaryOperator::CreateMul(BO->getOperand(0),
7403 Context->getConstantExprShl(BOOp, Op1));
7405 // Try to fold constant and into select arguments.
7406 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7407 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7409 if (isa<PHINode>(Op0))
7410 if (Instruction *NV = FoldOpIntoPhi(I))
7413 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7414 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7415 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7416 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7417 // place. Don't try to do this transformation in this case. Also, we
7418 // require that the input operand is a shift-by-constant so that we have
7419 // confidence that the shifts will get folded together. We could do this
7420 // xform in more cases, but it is unlikely to be profitable.
7421 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7422 isa<ConstantInt>(TrOp->getOperand(1))) {
7423 // Okay, we'll do this xform. Make the shift of shift.
7424 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7425 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7427 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7429 // For logical shifts, the truncation has the effect of making the high
7430 // part of the register be zeros. Emulate this by inserting an AND to
7431 // clear the top bits as needed. This 'and' will usually be zapped by
7432 // other xforms later if dead.
7433 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7434 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7435 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7437 // The mask we constructed says what the trunc would do if occurring
7438 // between the shifts. We want to know the effect *after* the second
7439 // shift. We know that it is a logical shift by a constant, so adjust the
7440 // mask as appropriate.
7441 if (I.getOpcode() == Instruction::Shl)
7442 MaskV <<= Op1->getZExtValue();
7444 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7445 MaskV = MaskV.lshr(Op1->getZExtValue());
7449 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7451 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7453 // Return the value truncated to the interesting size.
7454 return new TruncInst(And, I.getType());
7458 if (Op0->hasOneUse()) {
7459 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7460 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7463 switch (Op0BO->getOpcode()) {
7465 case Instruction::Add:
7466 case Instruction::And:
7467 case Instruction::Or:
7468 case Instruction::Xor: {
7469 // These operators commute.
7470 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7471 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7472 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7473 m_Specific(Op1)), *Context)){
7474 Instruction *YS = BinaryOperator::CreateShl(
7475 Op0BO->getOperand(0), Op1,
7477 InsertNewInstBefore(YS, I); // (Y << C)
7479 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7480 Op0BO->getOperand(1)->getName());
7481 InsertNewInstBefore(X, I); // (X + (Y << C))
7482 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7483 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7484 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7487 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7488 Value *Op0BOOp1 = Op0BO->getOperand(1);
7489 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7491 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7492 m_ConstantInt(CC)), *Context) &&
7493 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7494 Instruction *YS = BinaryOperator::CreateShl(
7495 Op0BO->getOperand(0), Op1,
7497 InsertNewInstBefore(YS, I); // (Y << C)
7499 BinaryOperator::CreateAnd(V1,
7500 Context->getConstantExprShl(CC, Op1),
7501 V1->getName()+".mask");
7502 InsertNewInstBefore(XM, I); // X & (CC << C)
7504 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7509 case Instruction::Sub: {
7510 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7511 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7512 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7513 m_Specific(Op1)), *Context)){
7514 Instruction *YS = BinaryOperator::CreateShl(
7515 Op0BO->getOperand(1), Op1,
7517 InsertNewInstBefore(YS, I); // (Y << C)
7519 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7520 Op0BO->getOperand(0)->getName());
7521 InsertNewInstBefore(X, I); // (X + (Y << C))
7522 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7523 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7524 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7527 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7528 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7529 match(Op0BO->getOperand(0),
7530 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7531 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7532 cast<BinaryOperator>(Op0BO->getOperand(0))
7533 ->getOperand(0)->hasOneUse()) {
7534 Instruction *YS = BinaryOperator::CreateShl(
7535 Op0BO->getOperand(1), Op1,
7537 InsertNewInstBefore(YS, I); // (Y << C)
7539 BinaryOperator::CreateAnd(V1,
7540 Context->getConstantExprShl(CC, Op1),
7541 V1->getName()+".mask");
7542 InsertNewInstBefore(XM, I); // X & (CC << C)
7544 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7552 // If the operand is an bitwise operator with a constant RHS, and the
7553 // shift is the only use, we can pull it out of the shift.
7554 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7555 bool isValid = true; // Valid only for And, Or, Xor
7556 bool highBitSet = false; // Transform if high bit of constant set?
7558 switch (Op0BO->getOpcode()) {
7559 default: isValid = false; break; // Do not perform transform!
7560 case Instruction::Add:
7561 isValid = isLeftShift;
7563 case Instruction::Or:
7564 case Instruction::Xor:
7567 case Instruction::And:
7572 // If this is a signed shift right, and the high bit is modified
7573 // by the logical operation, do not perform the transformation.
7574 // The highBitSet boolean indicates the value of the high bit of
7575 // the constant which would cause it to be modified for this
7578 if (isValid && I.getOpcode() == Instruction::AShr)
7579 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7582 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7584 Instruction *NewShift =
7585 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7586 InsertNewInstBefore(NewShift, I);
7587 NewShift->takeName(Op0BO);
7589 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7596 // Find out if this is a shift of a shift by a constant.
7597 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7598 if (ShiftOp && !ShiftOp->isShift())
7601 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7602 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7603 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7604 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7605 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7606 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7607 Value *X = ShiftOp->getOperand(0);
7609 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7611 const IntegerType *Ty = cast<IntegerType>(I.getType());
7613 // Check for (X << c1) << c2 and (X >> c1) >> c2
7614 if (I.getOpcode() == ShiftOp->getOpcode()) {
7615 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7617 if (AmtSum >= TypeBits) {
7618 if (I.getOpcode() != Instruction::AShr)
7619 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7620 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7623 return BinaryOperator::Create(I.getOpcode(), X,
7624 Context->getConstantInt(Ty, AmtSum));
7625 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7626 I.getOpcode() == Instruction::AShr) {
7627 if (AmtSum >= TypeBits)
7628 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7630 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7631 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7632 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7633 I.getOpcode() == Instruction::LShr) {
7634 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7635 if (AmtSum >= TypeBits)
7636 AmtSum = TypeBits-1;
7638 Instruction *Shift =
7639 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7640 InsertNewInstBefore(Shift, I);
7642 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7643 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7646 // Okay, if we get here, one shift must be left, and the other shift must be
7647 // right. See if the amounts are equal.
7648 if (ShiftAmt1 == ShiftAmt2) {
7649 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7650 if (I.getOpcode() == Instruction::Shl) {
7651 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7652 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7654 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7655 if (I.getOpcode() == Instruction::LShr) {
7656 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7657 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7659 // We can simplify ((X << C) >>s C) into a trunc + sext.
7660 // NOTE: we could do this for any C, but that would make 'unusual' integer
7661 // types. For now, just stick to ones well-supported by the code
7663 const Type *SExtType = 0;
7664 switch (Ty->getBitWidth() - ShiftAmt1) {
7671 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7676 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7677 InsertNewInstBefore(NewTrunc, I);
7678 return new SExtInst(NewTrunc, Ty);
7680 // Otherwise, we can't handle it yet.
7681 } else if (ShiftAmt1 < ShiftAmt2) {
7682 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7684 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7685 if (I.getOpcode() == Instruction::Shl) {
7686 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7687 ShiftOp->getOpcode() == Instruction::AShr);
7688 Instruction *Shift =
7689 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7690 InsertNewInstBefore(Shift, I);
7692 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7693 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7696 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7697 if (I.getOpcode() == Instruction::LShr) {
7698 assert(ShiftOp->getOpcode() == Instruction::Shl);
7699 Instruction *Shift =
7700 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7701 InsertNewInstBefore(Shift, I);
7703 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7704 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7707 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7709 assert(ShiftAmt2 < ShiftAmt1);
7710 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7712 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7713 if (I.getOpcode() == Instruction::Shl) {
7714 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7715 ShiftOp->getOpcode() == Instruction::AShr);
7716 Instruction *Shift =
7717 BinaryOperator::Create(ShiftOp->getOpcode(), X,
7718 Context->getConstantInt(Ty, ShiftDiff));
7719 InsertNewInstBefore(Shift, I);
7721 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7722 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7725 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7726 if (I.getOpcode() == Instruction::LShr) {
7727 assert(ShiftOp->getOpcode() == Instruction::Shl);
7728 Instruction *Shift =
7729 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7730 InsertNewInstBefore(Shift, I);
7732 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7733 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7736 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7743 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7744 /// expression. If so, decompose it, returning some value X, such that Val is
7747 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7748 int &Offset, LLVMContext *Context) {
7749 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7750 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7751 Offset = CI->getZExtValue();
7753 return Context->getConstantInt(Type::Int32Ty, 0);
7754 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7755 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7756 if (I->getOpcode() == Instruction::Shl) {
7757 // This is a value scaled by '1 << the shift amt'.
7758 Scale = 1U << RHS->getZExtValue();
7760 return I->getOperand(0);
7761 } else if (I->getOpcode() == Instruction::Mul) {
7762 // This value is scaled by 'RHS'.
7763 Scale = RHS->getZExtValue();
7765 return I->getOperand(0);
7766 } else if (I->getOpcode() == Instruction::Add) {
7767 // We have X+C. Check to see if we really have (X*C2)+C1,
7768 // where C1 is divisible by C2.
7771 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7773 Offset += RHS->getZExtValue();
7780 // Otherwise, we can't look past this.
7787 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7788 /// try to eliminate the cast by moving the type information into the alloc.
7789 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7790 AllocationInst &AI) {
7791 const PointerType *PTy = cast<PointerType>(CI.getType());
7793 // Remove any uses of AI that are dead.
7794 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7796 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7797 Instruction *User = cast<Instruction>(*UI++);
7798 if (isInstructionTriviallyDead(User)) {
7799 while (UI != E && *UI == User)
7800 ++UI; // If this instruction uses AI more than once, don't break UI.
7803 DOUT << "IC: DCE: " << *User;
7804 EraseInstFromFunction(*User);
7808 // This requires TargetData to get the alloca alignment and size information.
7811 // Get the type really allocated and the type casted to.
7812 const Type *AllocElTy = AI.getAllocatedType();
7813 const Type *CastElTy = PTy->getElementType();
7814 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7816 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7817 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7818 if (CastElTyAlign < AllocElTyAlign) return 0;
7820 // If the allocation has multiple uses, only promote it if we are strictly
7821 // increasing the alignment of the resultant allocation. If we keep it the
7822 // same, we open the door to infinite loops of various kinds. (A reference
7823 // from a dbg.declare doesn't count as a use for this purpose.)
7824 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7825 CastElTyAlign == AllocElTyAlign) return 0;
7827 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7828 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7829 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7831 // See if we can satisfy the modulus by pulling a scale out of the array
7833 unsigned ArraySizeScale;
7835 Value *NumElements = // See if the array size is a decomposable linear expr.
7836 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7837 ArrayOffset, Context);
7839 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7841 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7842 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7844 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7849 // If the allocation size is constant, form a constant mul expression
7850 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7851 if (isa<ConstantInt>(NumElements))
7852 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7853 cast<ConstantInt>(Amt));
7854 // otherwise multiply the amount and the number of elements
7856 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7857 Amt = InsertNewInstBefore(Tmp, AI);
7861 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7862 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7863 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7864 Amt = InsertNewInstBefore(Tmp, AI);
7867 AllocationInst *New;
7868 if (isa<MallocInst>(AI))
7869 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7871 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7872 InsertNewInstBefore(New, AI);
7875 // If the allocation has one real use plus a dbg.declare, just remove the
7877 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7878 EraseInstFromFunction(*DI);
7880 // If the allocation has multiple real uses, insert a cast and change all
7881 // things that used it to use the new cast. This will also hack on CI, but it
7883 else if (!AI.hasOneUse()) {
7884 AddUsesToWorkList(AI);
7885 // New is the allocation instruction, pointer typed. AI is the original
7886 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7887 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7888 InsertNewInstBefore(NewCast, AI);
7889 AI.replaceAllUsesWith(NewCast);
7891 return ReplaceInstUsesWith(CI, New);
7894 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7895 /// and return it as type Ty without inserting any new casts and without
7896 /// changing the computed value. This is used by code that tries to decide
7897 /// whether promoting or shrinking integer operations to wider or smaller types
7898 /// will allow us to eliminate a truncate or extend.
7900 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7901 /// extension operation if Ty is larger.
7903 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7904 /// should return true if trunc(V) can be computed by computing V in the smaller
7905 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7906 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7907 /// efficiently truncated.
7909 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7910 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7911 /// the final result.
7912 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7914 int &NumCastsRemoved){
7915 // We can always evaluate constants in another type.
7916 if (isa<Constant>(V))
7919 Instruction *I = dyn_cast<Instruction>(V);
7920 if (!I) return false;
7922 const Type *OrigTy = V->getType();
7924 // If this is an extension or truncate, we can often eliminate it.
7925 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7926 // If this is a cast from the destination type, we can trivially eliminate
7927 // it, and this will remove a cast overall.
7928 if (I->getOperand(0)->getType() == Ty) {
7929 // If the first operand is itself a cast, and is eliminable, do not count
7930 // this as an eliminable cast. We would prefer to eliminate those two
7932 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7938 // We can't extend or shrink something that has multiple uses: doing so would
7939 // require duplicating the instruction in general, which isn't profitable.
7940 if (!I->hasOneUse()) return false;
7942 unsigned Opc = I->getOpcode();
7944 case Instruction::Add:
7945 case Instruction::Sub:
7946 case Instruction::Mul:
7947 case Instruction::And:
7948 case Instruction::Or:
7949 case Instruction::Xor:
7950 // These operators can all arbitrarily be extended or truncated.
7951 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7953 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7956 case Instruction::UDiv:
7957 case Instruction::URem: {
7958 // UDiv and URem can be truncated if all the truncated bits are zero.
7959 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7960 uint32_t BitWidth = Ty->getScalarSizeInBits();
7961 if (BitWidth < OrigBitWidth) {
7962 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7963 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7964 MaskedValueIsZero(I->getOperand(1), Mask)) {
7965 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7967 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7973 case Instruction::Shl:
7974 // If we are truncating the result of this SHL, and if it's a shift of a
7975 // constant amount, we can always perform a SHL in a smaller type.
7976 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7977 uint32_t BitWidth = Ty->getScalarSizeInBits();
7978 if (BitWidth < OrigTy->getScalarSizeInBits() &&
7979 CI->getLimitedValue(BitWidth) < BitWidth)
7980 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7984 case Instruction::LShr:
7985 // If this is a truncate of a logical shr, we can truncate it to a smaller
7986 // lshr iff we know that the bits we would otherwise be shifting in are
7988 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7989 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7990 uint32_t BitWidth = Ty->getScalarSizeInBits();
7991 if (BitWidth < OrigBitWidth &&
7992 MaskedValueIsZero(I->getOperand(0),
7993 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7994 CI->getLimitedValue(BitWidth) < BitWidth) {
7995 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8000 case Instruction::ZExt:
8001 case Instruction::SExt:
8002 case Instruction::Trunc:
8003 // If this is the same kind of case as our original (e.g. zext+zext), we
8004 // can safely replace it. Note that replacing it does not reduce the number
8005 // of casts in the input.
8009 // sext (zext ty1), ty2 -> zext ty2
8010 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8013 case Instruction::Select: {
8014 SelectInst *SI = cast<SelectInst>(I);
8015 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8017 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8020 case Instruction::PHI: {
8021 // We can change a phi if we can change all operands.
8022 PHINode *PN = cast<PHINode>(I);
8023 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8024 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8030 // TODO: Can handle more cases here.
8037 /// EvaluateInDifferentType - Given an expression that
8038 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8039 /// evaluate the expression.
8040 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8042 if (Constant *C = dyn_cast<Constant>(V))
8043 return Context->getConstantExprIntegerCast(C, Ty,
8044 isSigned /*Sext or ZExt*/);
8046 // Otherwise, it must be an instruction.
8047 Instruction *I = cast<Instruction>(V);
8048 Instruction *Res = 0;
8049 unsigned Opc = I->getOpcode();
8051 case Instruction::Add:
8052 case Instruction::Sub:
8053 case Instruction::Mul:
8054 case Instruction::And:
8055 case Instruction::Or:
8056 case Instruction::Xor:
8057 case Instruction::AShr:
8058 case Instruction::LShr:
8059 case Instruction::Shl:
8060 case Instruction::UDiv:
8061 case Instruction::URem: {
8062 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8063 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8064 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8067 case Instruction::Trunc:
8068 case Instruction::ZExt:
8069 case Instruction::SExt:
8070 // If the source type of the cast is the type we're trying for then we can
8071 // just return the source. There's no need to insert it because it is not
8073 if (I->getOperand(0)->getType() == Ty)
8074 return I->getOperand(0);
8076 // Otherwise, must be the same type of cast, so just reinsert a new one.
8077 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8080 case Instruction::Select: {
8081 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8082 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8083 Res = SelectInst::Create(I->getOperand(0), True, False);
8086 case Instruction::PHI: {
8087 PHINode *OPN = cast<PHINode>(I);
8088 PHINode *NPN = PHINode::Create(Ty);
8089 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8090 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8091 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8097 // TODO: Can handle more cases here.
8098 llvm_unreachable("Unreachable!");
8103 return InsertNewInstBefore(Res, *I);
8106 /// @brief Implement the transforms common to all CastInst visitors.
8107 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8108 Value *Src = CI.getOperand(0);
8110 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8111 // eliminate it now.
8112 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8113 if (Instruction::CastOps opc =
8114 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8115 // The first cast (CSrc) is eliminable so we need to fix up or replace
8116 // the second cast (CI). CSrc will then have a good chance of being dead.
8117 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8121 // If we are casting a select then fold the cast into the select
8122 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8123 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8126 // If we are casting a PHI then fold the cast into the PHI
8127 if (isa<PHINode>(Src))
8128 if (Instruction *NV = FoldOpIntoPhi(CI))
8134 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8135 /// or not there is a sequence of GEP indices into the type that will land us at
8136 /// the specified offset. If so, fill them into NewIndices and return the
8137 /// resultant element type, otherwise return null.
8138 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8139 SmallVectorImpl<Value*> &NewIndices,
8140 const TargetData *TD,
8141 LLVMContext *Context) {
8143 if (!Ty->isSized()) return 0;
8145 // Start with the index over the outer type. Note that the type size
8146 // might be zero (even if the offset isn't zero) if the indexed type
8147 // is something like [0 x {int, int}]
8148 const Type *IntPtrTy = TD->getIntPtrType();
8149 int64_t FirstIdx = 0;
8150 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8151 FirstIdx = Offset/TySize;
8152 Offset -= FirstIdx*TySize;
8154 // Handle hosts where % returns negative instead of values [0..TySize).
8158 assert(Offset >= 0);
8160 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8163 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8165 // Index into the types. If we fail, set OrigBase to null.
8167 // Indexing into tail padding between struct/array elements.
8168 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8171 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8172 const StructLayout *SL = TD->getStructLayout(STy);
8173 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8174 "Offset must stay within the indexed type");
8176 unsigned Elt = SL->getElementContainingOffset(Offset);
8177 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8179 Offset -= SL->getElementOffset(Elt);
8180 Ty = STy->getElementType(Elt);
8181 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8182 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8183 assert(EltSize && "Cannot index into a zero-sized array");
8184 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8186 Ty = AT->getElementType();
8188 // Otherwise, we can't index into the middle of this atomic type, bail.
8196 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8197 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8198 Value *Src = CI.getOperand(0);
8200 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8201 // If casting the result of a getelementptr instruction with no offset, turn
8202 // this into a cast of the original pointer!
8203 if (GEP->hasAllZeroIndices()) {
8204 // Changing the cast operand is usually not a good idea but it is safe
8205 // here because the pointer operand is being replaced with another
8206 // pointer operand so the opcode doesn't need to change.
8208 CI.setOperand(0, GEP->getOperand(0));
8212 // If the GEP has a single use, and the base pointer is a bitcast, and the
8213 // GEP computes a constant offset, see if we can convert these three
8214 // instructions into fewer. This typically happens with unions and other
8215 // non-type-safe code.
8216 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8217 if (GEP->hasAllConstantIndices()) {
8218 // We are guaranteed to get a constant from EmitGEPOffset.
8219 ConstantInt *OffsetV =
8220 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8221 int64_t Offset = OffsetV->getSExtValue();
8223 // Get the base pointer input of the bitcast, and the type it points to.
8224 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8225 const Type *GEPIdxTy =
8226 cast<PointerType>(OrigBase->getType())->getElementType();
8227 SmallVector<Value*, 8> NewIndices;
8228 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8229 // If we were able to index down into an element, create the GEP
8230 // and bitcast the result. This eliminates one bitcast, potentially
8232 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8234 NewIndices.end(), "");
8235 InsertNewInstBefore(NGEP, CI);
8236 NGEP->takeName(GEP);
8238 if (isa<BitCastInst>(CI))
8239 return new BitCastInst(NGEP, CI.getType());
8240 assert(isa<PtrToIntInst>(CI));
8241 return new PtrToIntInst(NGEP, CI.getType());
8247 return commonCastTransforms(CI);
8250 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8251 /// type like i42. We don't want to introduce operations on random non-legal
8252 /// integer types where they don't already exist in the code. In the future,
8253 /// we should consider making this based off target-data, so that 32-bit targets
8254 /// won't get i64 operations etc.
8255 static bool isSafeIntegerType(const Type *Ty) {
8256 switch (Ty->getPrimitiveSizeInBits()) {
8267 /// commonIntCastTransforms - This function implements the common transforms
8268 /// for trunc, zext, and sext.
8269 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8270 if (Instruction *Result = commonCastTransforms(CI))
8273 Value *Src = CI.getOperand(0);
8274 const Type *SrcTy = Src->getType();
8275 const Type *DestTy = CI.getType();
8276 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8277 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8279 // See if we can simplify any instructions used by the LHS whose sole
8280 // purpose is to compute bits we don't care about.
8281 if (SimplifyDemandedInstructionBits(CI))
8284 // If the source isn't an instruction or has more than one use then we
8285 // can't do anything more.
8286 Instruction *SrcI = dyn_cast<Instruction>(Src);
8287 if (!SrcI || !Src->hasOneUse())
8290 // Attempt to propagate the cast into the instruction for int->int casts.
8291 int NumCastsRemoved = 0;
8292 // Only do this if the dest type is a simple type, don't convert the
8293 // expression tree to something weird like i93 unless the source is also
8295 if ((isSafeIntegerType(DestTy->getScalarType()) ||
8296 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8297 CanEvaluateInDifferentType(SrcI, DestTy,
8298 CI.getOpcode(), NumCastsRemoved)) {
8299 // If this cast is a truncate, evaluting in a different type always
8300 // eliminates the cast, so it is always a win. If this is a zero-extension,
8301 // we need to do an AND to maintain the clear top-part of the computation,
8302 // so we require that the input have eliminated at least one cast. If this
8303 // is a sign extension, we insert two new casts (to do the extension) so we
8304 // require that two casts have been eliminated.
8305 bool DoXForm = false;
8306 bool JustReplace = false;
8307 switch (CI.getOpcode()) {
8309 // All the others use floating point so we shouldn't actually
8310 // get here because of the check above.
8311 llvm_unreachable("Unknown cast type");
8312 case Instruction::Trunc:
8315 case Instruction::ZExt: {
8316 DoXForm = NumCastsRemoved >= 1;
8317 if (!DoXForm && 0) {
8318 // If it's unnecessary to issue an AND to clear the high bits, it's
8319 // always profitable to do this xform.
8320 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8321 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8322 if (MaskedValueIsZero(TryRes, Mask))
8323 return ReplaceInstUsesWith(CI, TryRes);
8325 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8326 if (TryI->use_empty())
8327 EraseInstFromFunction(*TryI);
8331 case Instruction::SExt: {
8332 DoXForm = NumCastsRemoved >= 2;
8333 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8334 // If we do not have to emit the truncate + sext pair, then it's always
8335 // profitable to do this xform.
8337 // It's not safe to eliminate the trunc + sext pair if one of the
8338 // eliminated cast is a truncate. e.g.
8339 // t2 = trunc i32 t1 to i16
8340 // t3 = sext i16 t2 to i32
8343 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8344 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8345 if (NumSignBits > (DestBitSize - SrcBitSize))
8346 return ReplaceInstUsesWith(CI, TryRes);
8348 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8349 if (TryI->use_empty())
8350 EraseInstFromFunction(*TryI);
8357 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8359 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8360 CI.getOpcode() == Instruction::SExt);
8362 // Just replace this cast with the result.
8363 return ReplaceInstUsesWith(CI, Res);
8365 assert(Res->getType() == DestTy);
8366 switch (CI.getOpcode()) {
8367 default: llvm_unreachable("Unknown cast type!");
8368 case Instruction::Trunc:
8369 // Just replace this cast with the result.
8370 return ReplaceInstUsesWith(CI, Res);
8371 case Instruction::ZExt: {
8372 assert(SrcBitSize < DestBitSize && "Not a zext?");
8374 // If the high bits are already zero, just replace this cast with the
8376 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8377 if (MaskedValueIsZero(Res, Mask))
8378 return ReplaceInstUsesWith(CI, Res);
8380 // We need to emit an AND to clear the high bits.
8381 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8383 return BinaryOperator::CreateAnd(Res, C);
8385 case Instruction::SExt: {
8386 // If the high bits are already filled with sign bit, just replace this
8387 // cast with the result.
8388 unsigned NumSignBits = ComputeNumSignBits(Res);
8389 if (NumSignBits > (DestBitSize - SrcBitSize))
8390 return ReplaceInstUsesWith(CI, Res);
8392 // We need to emit a cast to truncate, then a cast to sext.
8393 return CastInst::Create(Instruction::SExt,
8394 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8401 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8402 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8404 switch (SrcI->getOpcode()) {
8405 case Instruction::Add:
8406 case Instruction::Mul:
8407 case Instruction::And:
8408 case Instruction::Or:
8409 case Instruction::Xor:
8410 // If we are discarding information, rewrite.
8411 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8412 // Don't insert two casts unless at least one can be eliminated.
8413 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8414 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8415 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8416 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8417 return BinaryOperator::Create(
8418 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8422 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8423 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8424 SrcI->getOpcode() == Instruction::Xor &&
8425 Op1 == Context->getTrue() &&
8426 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8427 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8428 return BinaryOperator::CreateXor(New,
8429 Context->getConstantInt(CI.getType(), 1));
8433 case Instruction::Shl: {
8434 // Canonicalize trunc inside shl, if we can.
8435 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8436 if (CI && DestBitSize < SrcBitSize &&
8437 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8438 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8439 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8440 return BinaryOperator::CreateShl(Op0c, Op1c);
8448 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8449 if (Instruction *Result = commonIntCastTransforms(CI))
8452 Value *Src = CI.getOperand(0);
8453 const Type *Ty = CI.getType();
8454 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8455 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8457 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8458 if (DestBitWidth == 1) {
8459 Constant *One = Context->getConstantInt(Src->getType(), 1);
8460 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8461 Value *Zero = Context->getNullValue(Src->getType());
8462 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8465 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8466 ConstantInt *ShAmtV = 0;
8468 if (Src->hasOneUse() &&
8469 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8470 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8472 // Get a mask for the bits shifting in.
8473 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8474 if (MaskedValueIsZero(ShiftOp, Mask)) {
8475 if (ShAmt >= DestBitWidth) // All zeros.
8476 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8478 // Okay, we can shrink this. Truncate the input, then return a new
8480 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8481 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8482 return BinaryOperator::CreateLShr(V1, V2);
8489 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8490 /// in order to eliminate the icmp.
8491 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8493 // If we are just checking for a icmp eq of a single bit and zext'ing it
8494 // to an integer, then shift the bit to the appropriate place and then
8495 // cast to integer to avoid the comparison.
8496 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8497 const APInt &Op1CV = Op1C->getValue();
8499 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8500 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8501 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8502 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8503 if (!DoXform) return ICI;
8505 Value *In = ICI->getOperand(0);
8506 Value *Sh = Context->getConstantInt(In->getType(),
8507 In->getType()->getScalarSizeInBits()-1);
8508 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8509 In->getName()+".lobit"),
8511 if (In->getType() != CI.getType())
8512 In = CastInst::CreateIntegerCast(In, CI.getType(),
8513 false/*ZExt*/, "tmp", &CI);
8515 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8516 Constant *One = Context->getConstantInt(In->getType(), 1);
8517 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8518 In->getName()+".not"),
8522 return ReplaceInstUsesWith(CI, In);
8527 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8528 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8529 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8530 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8531 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8532 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8533 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8534 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8535 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8536 // This only works for EQ and NE
8537 ICI->isEquality()) {
8538 // If Op1C some other power of two, convert:
8539 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8540 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8541 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8542 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8544 APInt KnownZeroMask(~KnownZero);
8545 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8546 if (!DoXform) return ICI;
8548 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8549 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8550 // (X&4) == 2 --> false
8551 // (X&4) != 2 --> true
8552 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8553 Res = Context->getConstantExprZExt(Res, CI.getType());
8554 return ReplaceInstUsesWith(CI, Res);
8557 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8558 Value *In = ICI->getOperand(0);
8560 // Perform a logical shr by shiftamt.
8561 // Insert the shift to put the result in the low bit.
8562 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8563 Context->getConstantInt(In->getType(), ShiftAmt),
8564 In->getName()+".lobit"), CI);
8567 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8568 Constant *One = Context->getConstantInt(In->getType(), 1);
8569 In = BinaryOperator::CreateXor(In, One, "tmp");
8570 InsertNewInstBefore(cast<Instruction>(In), CI);
8573 if (CI.getType() == In->getType())
8574 return ReplaceInstUsesWith(CI, In);
8576 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8584 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8585 // If one of the common conversion will work ..
8586 if (Instruction *Result = commonIntCastTransforms(CI))
8589 Value *Src = CI.getOperand(0);
8591 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8592 // types and if the sizes are just right we can convert this into a logical
8593 // 'and' which will be much cheaper than the pair of casts.
8594 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8595 // Get the sizes of the types involved. We know that the intermediate type
8596 // will be smaller than A or C, but don't know the relation between A and C.
8597 Value *A = CSrc->getOperand(0);
8598 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8599 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8600 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8601 // If we're actually extending zero bits, then if
8602 // SrcSize < DstSize: zext(a & mask)
8603 // SrcSize == DstSize: a & mask
8604 // SrcSize > DstSize: trunc(a) & mask
8605 if (SrcSize < DstSize) {
8606 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8607 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8609 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8610 InsertNewInstBefore(And, CI);
8611 return new ZExtInst(And, CI.getType());
8612 } else if (SrcSize == DstSize) {
8613 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8614 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8616 } else if (SrcSize > DstSize) {
8617 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8618 InsertNewInstBefore(Trunc, CI);
8619 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8620 return BinaryOperator::CreateAnd(Trunc,
8621 Context->getConstantInt(Trunc->getType(),
8626 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8627 return transformZExtICmp(ICI, CI);
8629 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8630 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8631 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8632 // of the (zext icmp) will be transformed.
8633 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8634 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8635 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8636 (transformZExtICmp(LHS, CI, false) ||
8637 transformZExtICmp(RHS, CI, false))) {
8638 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8639 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8640 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8644 // zext(trunc(t) & C) -> (t & zext(C)).
8645 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8646 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8647 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8648 Value *TI0 = TI->getOperand(0);
8649 if (TI0->getType() == CI.getType())
8651 BinaryOperator::CreateAnd(TI0,
8652 Context->getConstantExprZExt(C, CI.getType()));
8655 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8656 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8657 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8658 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8659 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8660 And->getOperand(1) == C)
8661 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8662 Value *TI0 = TI->getOperand(0);
8663 if (TI0->getType() == CI.getType()) {
8664 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8665 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8666 InsertNewInstBefore(NewAnd, *And);
8667 return BinaryOperator::CreateXor(NewAnd, ZC);
8674 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8675 if (Instruction *I = commonIntCastTransforms(CI))
8678 Value *Src = CI.getOperand(0);
8680 // Canonicalize sign-extend from i1 to a select.
8681 if (Src->getType() == Type::Int1Ty)
8682 return SelectInst::Create(Src,
8683 Context->getAllOnesValue(CI.getType()),
8684 Context->getNullValue(CI.getType()));
8686 // See if the value being truncated is already sign extended. If so, just
8687 // eliminate the trunc/sext pair.
8688 if (Operator::getOpcode(Src) == Instruction::Trunc) {
8689 Value *Op = cast<User>(Src)->getOperand(0);
8690 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8691 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8692 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8693 unsigned NumSignBits = ComputeNumSignBits(Op);
8695 if (OpBits == DestBits) {
8696 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8697 // bits, it is already ready.
8698 if (NumSignBits > DestBits-MidBits)
8699 return ReplaceInstUsesWith(CI, Op);
8700 } else if (OpBits < DestBits) {
8701 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8702 // bits, just sext from i32.
8703 if (NumSignBits > OpBits-MidBits)
8704 return new SExtInst(Op, CI.getType(), "tmp");
8706 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8707 // bits, just truncate to i32.
8708 if (NumSignBits > OpBits-MidBits)
8709 return new TruncInst(Op, CI.getType(), "tmp");
8713 // If the input is a shl/ashr pair of a same constant, then this is a sign
8714 // extension from a smaller value. If we could trust arbitrary bitwidth
8715 // integers, we could turn this into a truncate to the smaller bit and then
8716 // use a sext for the whole extension. Since we don't, look deeper and check
8717 // for a truncate. If the source and dest are the same type, eliminate the
8718 // trunc and extend and just do shifts. For example, turn:
8719 // %a = trunc i32 %i to i8
8720 // %b = shl i8 %a, 6
8721 // %c = ashr i8 %b, 6
8722 // %d = sext i8 %c to i32
8724 // %a = shl i32 %i, 30
8725 // %d = ashr i32 %a, 30
8727 ConstantInt *BA = 0, *CA = 0;
8728 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8729 m_ConstantInt(CA)), *Context) &&
8730 BA == CA && isa<TruncInst>(A)) {
8731 Value *I = cast<TruncInst>(A)->getOperand(0);
8732 if (I->getType() == CI.getType()) {
8733 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8734 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8735 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8736 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8737 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8739 return BinaryOperator::CreateAShr(I, ShAmtV);
8746 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8747 /// in the specified FP type without changing its value.
8748 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8749 LLVMContext *Context) {
8751 APFloat F = CFP->getValueAPF();
8752 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8754 return Context->getConstantFP(F);
8758 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8759 /// through it until we get the source value.
8760 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8761 if (Instruction *I = dyn_cast<Instruction>(V))
8762 if (I->getOpcode() == Instruction::FPExt)
8763 return LookThroughFPExtensions(I->getOperand(0), Context);
8765 // If this value is a constant, return the constant in the smallest FP type
8766 // that can accurately represent it. This allows us to turn
8767 // (float)((double)X+2.0) into x+2.0f.
8768 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8769 if (CFP->getType() == Type::PPC_FP128Ty)
8770 return V; // No constant folding of this.
8771 // See if the value can be truncated to float and then reextended.
8772 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8774 if (CFP->getType() == Type::DoubleTy)
8775 return V; // Won't shrink.
8776 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8778 // Don't try to shrink to various long double types.
8784 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8785 if (Instruction *I = commonCastTransforms(CI))
8788 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8789 // smaller than the destination type, we can eliminate the truncate by doing
8790 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8791 // many builtins (sqrt, etc).
8792 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8793 if (OpI && OpI->hasOneUse()) {
8794 switch (OpI->getOpcode()) {
8796 case Instruction::FAdd:
8797 case Instruction::FSub:
8798 case Instruction::FMul:
8799 case Instruction::FDiv:
8800 case Instruction::FRem:
8801 const Type *SrcTy = OpI->getType();
8802 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8803 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8804 if (LHSTrunc->getType() != SrcTy &&
8805 RHSTrunc->getType() != SrcTy) {
8806 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8807 // If the source types were both smaller than the destination type of
8808 // the cast, do this xform.
8809 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8810 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8811 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8813 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8815 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8824 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8825 return commonCastTransforms(CI);
8828 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8829 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8831 return commonCastTransforms(FI);
8833 // fptoui(uitofp(X)) --> X
8834 // fptoui(sitofp(X)) --> X
8835 // This is safe if the intermediate type has enough bits in its mantissa to
8836 // accurately represent all values of X. For example, do not do this with
8837 // i64->float->i64. This is also safe for sitofp case, because any negative
8838 // 'X' value would cause an undefined result for the fptoui.
8839 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8840 OpI->getOperand(0)->getType() == FI.getType() &&
8841 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8842 OpI->getType()->getFPMantissaWidth())
8843 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8845 return commonCastTransforms(FI);
8848 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8849 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8851 return commonCastTransforms(FI);
8853 // fptosi(sitofp(X)) --> X
8854 // fptosi(uitofp(X)) --> X
8855 // This is safe if the intermediate type has enough bits in its mantissa to
8856 // accurately represent all values of X. For example, do not do this with
8857 // i64->float->i64. This is also safe for sitofp case, because any negative
8858 // 'X' value would cause an undefined result for the fptoui.
8859 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8860 OpI->getOperand(0)->getType() == FI.getType() &&
8861 (int)FI.getType()->getScalarSizeInBits() <=
8862 OpI->getType()->getFPMantissaWidth())
8863 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8865 return commonCastTransforms(FI);
8868 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8869 return commonCastTransforms(CI);
8872 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8873 return commonCastTransforms(CI);
8876 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8877 // If the destination integer type is smaller than the intptr_t type for
8878 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8879 // trunc to be exposed to other transforms. Don't do this for extending
8880 // ptrtoint's, because we don't know if the target sign or zero extends its
8883 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8884 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8885 TD->getIntPtrType(),
8887 return new TruncInst(P, CI.getType());
8890 return commonPointerCastTransforms(CI);
8893 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8894 // If the source integer type is larger than the intptr_t type for
8895 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8896 // allows the trunc to be exposed to other transforms. Don't do this for
8897 // extending inttoptr's, because we don't know if the target sign or zero
8898 // extends to pointers.
8900 CI.getOperand(0)->getType()->getScalarSizeInBits() >
8901 TD->getPointerSizeInBits()) {
8902 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8903 TD->getIntPtrType(),
8905 return new IntToPtrInst(P, CI.getType());
8908 if (Instruction *I = commonCastTransforms(CI))
8914 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8915 // If the operands are integer typed then apply the integer transforms,
8916 // otherwise just apply the common ones.
8917 Value *Src = CI.getOperand(0);
8918 const Type *SrcTy = Src->getType();
8919 const Type *DestTy = CI.getType();
8921 if (isa<PointerType>(SrcTy)) {
8922 if (Instruction *I = commonPointerCastTransforms(CI))
8925 if (Instruction *Result = commonCastTransforms(CI))
8930 // Get rid of casts from one type to the same type. These are useless and can
8931 // be replaced by the operand.
8932 if (DestTy == Src->getType())
8933 return ReplaceInstUsesWith(CI, Src);
8935 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8936 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8937 const Type *DstElTy = DstPTy->getElementType();
8938 const Type *SrcElTy = SrcPTy->getElementType();
8940 // If the address spaces don't match, don't eliminate the bitcast, which is
8941 // required for changing types.
8942 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8945 // If we are casting a malloc or alloca to a pointer to a type of the same
8946 // size, rewrite the allocation instruction to allocate the "right" type.
8947 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8948 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8951 // If the source and destination are pointers, and this cast is equivalent
8952 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8953 // This can enhance SROA and other transforms that want type-safe pointers.
8954 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
8955 unsigned NumZeros = 0;
8956 while (SrcElTy != DstElTy &&
8957 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8958 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8959 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8963 // If we found a path from the src to dest, create the getelementptr now.
8964 if (SrcElTy == DstElTy) {
8965 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8966 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8967 ((Instruction*) NULL));
8971 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8972 if (DestVTy->getNumElements() == 1) {
8973 if (!isa<VectorType>(SrcTy)) {
8974 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8975 DestVTy->getElementType(), CI);
8976 return InsertElementInst::Create(Context->getUndef(DestTy), Elem,
8977 Context->getNullValue(Type::Int32Ty));
8979 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8983 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8984 if (SrcVTy->getNumElements() == 1) {
8985 if (!isa<VectorType>(DestTy)) {
8987 new ExtractElementInst(Src, Context->getNullValue(Type::Int32Ty));
8988 InsertNewInstBefore(Elem, CI);
8989 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8994 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8995 if (SVI->hasOneUse()) {
8996 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8997 // a bitconvert to a vector with the same # elts.
8998 if (isa<VectorType>(DestTy) &&
8999 cast<VectorType>(DestTy)->getNumElements() ==
9000 SVI->getType()->getNumElements() &&
9001 SVI->getType()->getNumElements() ==
9002 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9004 // If either of the operands is a cast from CI.getType(), then
9005 // evaluating the shuffle in the casted destination's type will allow
9006 // us to eliminate at least one cast.
9007 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9008 Tmp->getOperand(0)->getType() == DestTy) ||
9009 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9010 Tmp->getOperand(0)->getType() == DestTy)) {
9011 Value *LHS = InsertCastBefore(Instruction::BitCast,
9012 SVI->getOperand(0), DestTy, CI);
9013 Value *RHS = InsertCastBefore(Instruction::BitCast,
9014 SVI->getOperand(1), DestTy, CI);
9015 // Return a new shuffle vector. Use the same element ID's, as we
9016 // know the vector types match #elts.
9017 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9025 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9027 /// %D = select %cond, %C, %A
9029 /// %C = select %cond, %B, 0
9032 /// Assuming that the specified instruction is an operand to the select, return
9033 /// a bitmask indicating which operands of this instruction are foldable if they
9034 /// equal the other incoming value of the select.
9036 static unsigned GetSelectFoldableOperands(Instruction *I) {
9037 switch (I->getOpcode()) {
9038 case Instruction::Add:
9039 case Instruction::Mul:
9040 case Instruction::And:
9041 case Instruction::Or:
9042 case Instruction::Xor:
9043 return 3; // Can fold through either operand.
9044 case Instruction::Sub: // Can only fold on the amount subtracted.
9045 case Instruction::Shl: // Can only fold on the shift amount.
9046 case Instruction::LShr:
9047 case Instruction::AShr:
9050 return 0; // Cannot fold
9054 /// GetSelectFoldableConstant - For the same transformation as the previous
9055 /// function, return the identity constant that goes into the select.
9056 static Constant *GetSelectFoldableConstant(Instruction *I,
9057 LLVMContext *Context) {
9058 switch (I->getOpcode()) {
9059 default: llvm_unreachable("This cannot happen!");
9060 case Instruction::Add:
9061 case Instruction::Sub:
9062 case Instruction::Or:
9063 case Instruction::Xor:
9064 case Instruction::Shl:
9065 case Instruction::LShr:
9066 case Instruction::AShr:
9067 return Context->getNullValue(I->getType());
9068 case Instruction::And:
9069 return Context->getAllOnesValue(I->getType());
9070 case Instruction::Mul:
9071 return Context->getConstantInt(I->getType(), 1);
9075 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9076 /// have the same opcode and only one use each. Try to simplify this.
9077 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9079 if (TI->getNumOperands() == 1) {
9080 // If this is a non-volatile load or a cast from the same type,
9083 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9086 return 0; // unknown unary op.
9089 // Fold this by inserting a select from the input values.
9090 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9091 FI->getOperand(0), SI.getName()+".v");
9092 InsertNewInstBefore(NewSI, SI);
9093 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
9097 // Only handle binary operators here.
9098 if (!isa<BinaryOperator>(TI))
9101 // Figure out if the operations have any operands in common.
9102 Value *MatchOp, *OtherOpT, *OtherOpF;
9104 if (TI->getOperand(0) == FI->getOperand(0)) {
9105 MatchOp = TI->getOperand(0);
9106 OtherOpT = TI->getOperand(1);
9107 OtherOpF = FI->getOperand(1);
9108 MatchIsOpZero = true;
9109 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9110 MatchOp = TI->getOperand(1);
9111 OtherOpT = TI->getOperand(0);
9112 OtherOpF = FI->getOperand(0);
9113 MatchIsOpZero = false;
9114 } else if (!TI->isCommutative()) {
9116 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9117 MatchOp = TI->getOperand(0);
9118 OtherOpT = TI->getOperand(1);
9119 OtherOpF = FI->getOperand(0);
9120 MatchIsOpZero = true;
9121 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9122 MatchOp = TI->getOperand(1);
9123 OtherOpT = TI->getOperand(0);
9124 OtherOpF = FI->getOperand(1);
9125 MatchIsOpZero = true;
9130 // If we reach here, they do have operations in common.
9131 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9132 OtherOpF, SI.getName()+".v");
9133 InsertNewInstBefore(NewSI, SI);
9135 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9137 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9139 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9141 llvm_unreachable("Shouldn't get here");
9145 static bool isSelect01(Constant *C1, Constant *C2) {
9146 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9149 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9152 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9155 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9156 /// facilitate further optimization.
9157 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9159 // See the comment above GetSelectFoldableOperands for a description of the
9160 // transformation we are doing here.
9161 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9162 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9163 !isa<Constant>(FalseVal)) {
9164 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9165 unsigned OpToFold = 0;
9166 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9168 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9173 Constant *C = GetSelectFoldableConstant(TVI, Context);
9174 Value *OOp = TVI->getOperand(2-OpToFold);
9175 // Avoid creating select between 2 constants unless it's selecting
9177 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9178 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9179 InsertNewInstBefore(NewSel, SI);
9180 NewSel->takeName(TVI);
9181 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9182 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9183 llvm_unreachable("Unknown instruction!!");
9190 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9191 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9192 !isa<Constant>(TrueVal)) {
9193 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9194 unsigned OpToFold = 0;
9195 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9197 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9202 Constant *C = GetSelectFoldableConstant(FVI, Context);
9203 Value *OOp = FVI->getOperand(2-OpToFold);
9204 // Avoid creating select between 2 constants unless it's selecting
9206 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9207 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9208 InsertNewInstBefore(NewSel, SI);
9209 NewSel->takeName(FVI);
9210 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9211 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9212 llvm_unreachable("Unknown instruction!!");
9222 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9223 /// ICmpInst as its first operand.
9225 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9227 bool Changed = false;
9228 ICmpInst::Predicate Pred = ICI->getPredicate();
9229 Value *CmpLHS = ICI->getOperand(0);
9230 Value *CmpRHS = ICI->getOperand(1);
9231 Value *TrueVal = SI.getTrueValue();
9232 Value *FalseVal = SI.getFalseValue();
9234 // Check cases where the comparison is with a constant that
9235 // can be adjusted to fit the min/max idiom. We may edit ICI in
9236 // place here, so make sure the select is the only user.
9237 if (ICI->hasOneUse())
9238 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9241 case ICmpInst::ICMP_ULT:
9242 case ICmpInst::ICMP_SLT: {
9243 // X < MIN ? T : F --> F
9244 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9245 return ReplaceInstUsesWith(SI, FalseVal);
9246 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9247 Constant *AdjustedRHS = SubOne(CI, Context);
9248 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9249 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9250 Pred = ICmpInst::getSwappedPredicate(Pred);
9251 CmpRHS = AdjustedRHS;
9252 std::swap(FalseVal, TrueVal);
9253 ICI->setPredicate(Pred);
9254 ICI->setOperand(1, CmpRHS);
9255 SI.setOperand(1, TrueVal);
9256 SI.setOperand(2, FalseVal);
9261 case ICmpInst::ICMP_UGT:
9262 case ICmpInst::ICMP_SGT: {
9263 // X > MAX ? T : F --> F
9264 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9265 return ReplaceInstUsesWith(SI, FalseVal);
9266 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9267 Constant *AdjustedRHS = AddOne(CI, Context);
9268 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9269 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9270 Pred = ICmpInst::getSwappedPredicate(Pred);
9271 CmpRHS = AdjustedRHS;
9272 std::swap(FalseVal, TrueVal);
9273 ICI->setPredicate(Pred);
9274 ICI->setOperand(1, CmpRHS);
9275 SI.setOperand(1, TrueVal);
9276 SI.setOperand(2, FalseVal);
9283 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9284 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9285 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9286 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9287 match(FalseVal, m_ConstantInt<0>(), *Context))
9288 Pred = ICI->getPredicate();
9289 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9290 match(FalseVal, m_ConstantInt<-1>(), *Context))
9291 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9293 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9294 // If we are just checking for a icmp eq of a single bit and zext'ing it
9295 // to an integer, then shift the bit to the appropriate place and then
9296 // cast to integer to avoid the comparison.
9297 const APInt &Op1CV = CI->getValue();
9299 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9300 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9301 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9302 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9303 Value *In = ICI->getOperand(0);
9304 Value *Sh = Context->getConstantInt(In->getType(),
9305 In->getType()->getScalarSizeInBits()-1);
9306 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9307 In->getName()+".lobit"),
9309 if (In->getType() != SI.getType())
9310 In = CastInst::CreateIntegerCast(In, SI.getType(),
9311 true/*SExt*/, "tmp", ICI);
9313 if (Pred == ICmpInst::ICMP_SGT)
9314 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9315 In->getName()+".not"), *ICI);
9317 return ReplaceInstUsesWith(SI, In);
9322 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9323 // Transform (X == Y) ? X : Y -> Y
9324 if (Pred == ICmpInst::ICMP_EQ)
9325 return ReplaceInstUsesWith(SI, FalseVal);
9326 // Transform (X != Y) ? X : Y -> X
9327 if (Pred == ICmpInst::ICMP_NE)
9328 return ReplaceInstUsesWith(SI, TrueVal);
9329 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9331 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9332 // Transform (X == Y) ? Y : X -> X
9333 if (Pred == ICmpInst::ICMP_EQ)
9334 return ReplaceInstUsesWith(SI, FalseVal);
9335 // Transform (X != Y) ? Y : X -> Y
9336 if (Pred == ICmpInst::ICMP_NE)
9337 return ReplaceInstUsesWith(SI, TrueVal);
9338 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9341 /// NOTE: if we wanted to, this is where to detect integer ABS
9343 return Changed ? &SI : 0;
9346 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9347 Value *CondVal = SI.getCondition();
9348 Value *TrueVal = SI.getTrueValue();
9349 Value *FalseVal = SI.getFalseValue();
9351 // select true, X, Y -> X
9352 // select false, X, Y -> Y
9353 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9354 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9356 // select C, X, X -> X
9357 if (TrueVal == FalseVal)
9358 return ReplaceInstUsesWith(SI, TrueVal);
9360 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9361 return ReplaceInstUsesWith(SI, FalseVal);
9362 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9363 return ReplaceInstUsesWith(SI, TrueVal);
9364 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9365 if (isa<Constant>(TrueVal))
9366 return ReplaceInstUsesWith(SI, TrueVal);
9368 return ReplaceInstUsesWith(SI, FalseVal);
9371 if (SI.getType() == Type::Int1Ty) {
9372 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9373 if (C->getZExtValue()) {
9374 // Change: A = select B, true, C --> A = or B, C
9375 return BinaryOperator::CreateOr(CondVal, FalseVal);
9377 // Change: A = select B, false, C --> A = and !B, C
9379 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9380 "not."+CondVal->getName()), SI);
9381 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9383 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9384 if (C->getZExtValue() == false) {
9385 // Change: A = select B, C, false --> A = and B, C
9386 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9388 // Change: A = select B, C, true --> A = or !B, C
9390 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9391 "not."+CondVal->getName()), SI);
9392 return BinaryOperator::CreateOr(NotCond, TrueVal);
9396 // select a, b, a -> a&b
9397 // select a, a, b -> a|b
9398 if (CondVal == TrueVal)
9399 return BinaryOperator::CreateOr(CondVal, FalseVal);
9400 else if (CondVal == FalseVal)
9401 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9404 // Selecting between two integer constants?
9405 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9406 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9407 // select C, 1, 0 -> zext C to int
9408 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9409 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9410 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9411 // select C, 0, 1 -> zext !C to int
9413 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9414 "not."+CondVal->getName()), SI);
9415 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9418 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9419 // If one of the constants is zero (we know they can't both be) and we
9420 // have an icmp instruction with zero, and we have an 'and' with the
9421 // non-constant value, eliminate this whole mess. This corresponds to
9422 // cases like this: ((X & 27) ? 27 : 0)
9423 if (TrueValC->isZero() || FalseValC->isZero())
9424 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9425 cast<Constant>(IC->getOperand(1))->isNullValue())
9426 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9427 if (ICA->getOpcode() == Instruction::And &&
9428 isa<ConstantInt>(ICA->getOperand(1)) &&
9429 (ICA->getOperand(1) == TrueValC ||
9430 ICA->getOperand(1) == FalseValC) &&
9431 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9432 // Okay, now we know that everything is set up, we just don't
9433 // know whether we have a icmp_ne or icmp_eq and whether the
9434 // true or false val is the zero.
9435 bool ShouldNotVal = !TrueValC->isZero();
9436 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9439 V = InsertNewInstBefore(BinaryOperator::Create(
9440 Instruction::Xor, V, ICA->getOperand(1)), SI);
9441 return ReplaceInstUsesWith(SI, V);
9446 // See if we are selecting two values based on a comparison of the two values.
9447 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9448 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9449 // Transform (X == Y) ? X : Y -> Y
9450 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9451 // This is not safe in general for floating point:
9452 // consider X== -0, Y== +0.
9453 // It becomes safe if either operand is a nonzero constant.
9454 ConstantFP *CFPt, *CFPf;
9455 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9456 !CFPt->getValueAPF().isZero()) ||
9457 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9458 !CFPf->getValueAPF().isZero()))
9459 return ReplaceInstUsesWith(SI, FalseVal);
9461 // Transform (X != Y) ? X : Y -> X
9462 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9463 return ReplaceInstUsesWith(SI, TrueVal);
9464 // NOTE: if we wanted to, this is where to detect MIN/MAX
9466 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9467 // Transform (X == Y) ? Y : X -> X
9468 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9469 // This is not safe in general for floating point:
9470 // consider X== -0, Y== +0.
9471 // It becomes safe if either operand is a nonzero constant.
9472 ConstantFP *CFPt, *CFPf;
9473 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9474 !CFPt->getValueAPF().isZero()) ||
9475 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9476 !CFPf->getValueAPF().isZero()))
9477 return ReplaceInstUsesWith(SI, FalseVal);
9479 // Transform (X != Y) ? Y : X -> Y
9480 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9481 return ReplaceInstUsesWith(SI, TrueVal);
9482 // NOTE: if we wanted to, this is where to detect MIN/MAX
9484 // NOTE: if we wanted to, this is where to detect ABS
9487 // See if we are selecting two values based on a comparison of the two values.
9488 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9489 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9492 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9493 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9494 if (TI->hasOneUse() && FI->hasOneUse()) {
9495 Instruction *AddOp = 0, *SubOp = 0;
9497 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9498 if (TI->getOpcode() == FI->getOpcode())
9499 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9502 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9503 // even legal for FP.
9504 if ((TI->getOpcode() == Instruction::Sub &&
9505 FI->getOpcode() == Instruction::Add) ||
9506 (TI->getOpcode() == Instruction::FSub &&
9507 FI->getOpcode() == Instruction::FAdd)) {
9508 AddOp = FI; SubOp = TI;
9509 } else if ((FI->getOpcode() == Instruction::Sub &&
9510 TI->getOpcode() == Instruction::Add) ||
9511 (FI->getOpcode() == Instruction::FSub &&
9512 TI->getOpcode() == Instruction::FAdd)) {
9513 AddOp = TI; SubOp = FI;
9517 Value *OtherAddOp = 0;
9518 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9519 OtherAddOp = AddOp->getOperand(1);
9520 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9521 OtherAddOp = AddOp->getOperand(0);
9525 // So at this point we know we have (Y -> OtherAddOp):
9526 // select C, (add X, Y), (sub X, Z)
9527 Value *NegVal; // Compute -Z
9528 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9529 NegVal = Context->getConstantExprNeg(C);
9531 NegVal = InsertNewInstBefore(
9532 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9536 Value *NewTrueOp = OtherAddOp;
9537 Value *NewFalseOp = NegVal;
9539 std::swap(NewTrueOp, NewFalseOp);
9540 Instruction *NewSel =
9541 SelectInst::Create(CondVal, NewTrueOp,
9542 NewFalseOp, SI.getName() + ".p");
9544 NewSel = InsertNewInstBefore(NewSel, SI);
9545 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9550 // See if we can fold the select into one of our operands.
9551 if (SI.getType()->isInteger()) {
9552 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9557 if (BinaryOperator::isNot(CondVal)) {
9558 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9559 SI.setOperand(1, FalseVal);
9560 SI.setOperand(2, TrueVal);
9567 /// EnforceKnownAlignment - If the specified pointer points to an object that
9568 /// we control, modify the object's alignment to PrefAlign. This isn't
9569 /// often possible though. If alignment is important, a more reliable approach
9570 /// is to simply align all global variables and allocation instructions to
9571 /// their preferred alignment from the beginning.
9573 static unsigned EnforceKnownAlignment(Value *V,
9574 unsigned Align, unsigned PrefAlign) {
9576 User *U = dyn_cast<User>(V);
9577 if (!U) return Align;
9579 switch (Operator::getOpcode(U)) {
9581 case Instruction::BitCast:
9582 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9583 case Instruction::GetElementPtr: {
9584 // If all indexes are zero, it is just the alignment of the base pointer.
9585 bool AllZeroOperands = true;
9586 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9587 if (!isa<Constant>(*i) ||
9588 !cast<Constant>(*i)->isNullValue()) {
9589 AllZeroOperands = false;
9593 if (AllZeroOperands) {
9594 // Treat this like a bitcast.
9595 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9601 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9602 // If there is a large requested alignment and we can, bump up the alignment
9604 if (!GV->isDeclaration()) {
9605 if (GV->getAlignment() >= PrefAlign)
9606 Align = GV->getAlignment();
9608 GV->setAlignment(PrefAlign);
9612 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9613 // If there is a requested alignment and if this is an alloca, round up. We
9614 // don't do this for malloc, because some systems can't respect the request.
9615 if (isa<AllocaInst>(AI)) {
9616 if (AI->getAlignment() >= PrefAlign)
9617 Align = AI->getAlignment();
9619 AI->setAlignment(PrefAlign);
9628 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9629 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9630 /// and it is more than the alignment of the ultimate object, see if we can
9631 /// increase the alignment of the ultimate object, making this check succeed.
9632 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9633 unsigned PrefAlign) {
9634 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9635 sizeof(PrefAlign) * CHAR_BIT;
9636 APInt Mask = APInt::getAllOnesValue(BitWidth);
9637 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9638 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9639 unsigned TrailZ = KnownZero.countTrailingOnes();
9640 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9642 if (PrefAlign > Align)
9643 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9645 // We don't need to make any adjustment.
9649 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9650 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9651 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9652 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9653 unsigned CopyAlign = MI->getAlignment();
9655 if (CopyAlign < MinAlign) {
9656 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9661 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9663 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9664 if (MemOpLength == 0) return 0;
9666 // Source and destination pointer types are always "i8*" for intrinsic. See
9667 // if the size is something we can handle with a single primitive load/store.
9668 // A single load+store correctly handles overlapping memory in the memmove
9670 unsigned Size = MemOpLength->getZExtValue();
9671 if (Size == 0) return MI; // Delete this mem transfer.
9673 if (Size > 8 || (Size&(Size-1)))
9674 return 0; // If not 1/2/4/8 bytes, exit.
9676 // Use an integer load+store unless we can find something better.
9678 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9680 // Memcpy forces the use of i8* for the source and destination. That means
9681 // that if you're using memcpy to move one double around, you'll get a cast
9682 // from double* to i8*. We'd much rather use a double load+store rather than
9683 // an i64 load+store, here because this improves the odds that the source or
9684 // dest address will be promotable. See if we can find a better type than the
9685 // integer datatype.
9686 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9687 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9688 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9689 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9690 // down through these levels if so.
9691 while (!SrcETy->isSingleValueType()) {
9692 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9693 if (STy->getNumElements() == 1)
9694 SrcETy = STy->getElementType(0);
9697 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9698 if (ATy->getNumElements() == 1)
9699 SrcETy = ATy->getElementType();
9706 if (SrcETy->isSingleValueType())
9707 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9712 // If the memcpy/memmove provides better alignment info than we can
9714 SrcAlign = std::max(SrcAlign, CopyAlign);
9715 DstAlign = std::max(DstAlign, CopyAlign);
9717 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9718 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9719 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9720 InsertNewInstBefore(L, *MI);
9721 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9723 // Set the size of the copy to 0, it will be deleted on the next iteration.
9724 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9728 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9729 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9730 if (MI->getAlignment() < Alignment) {
9731 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9736 // Extract the length and alignment and fill if they are constant.
9737 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9738 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9739 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9741 uint64_t Len = LenC->getZExtValue();
9742 Alignment = MI->getAlignment();
9744 // If the length is zero, this is a no-op
9745 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9747 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9748 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9749 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
9751 Value *Dest = MI->getDest();
9752 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9754 // Alignment 0 is identity for alignment 1 for memset, but not store.
9755 if (Alignment == 0) Alignment = 1;
9757 // Extract the fill value and store.
9758 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9759 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9760 Dest, false, Alignment), *MI);
9762 // Set the size of the copy to 0, it will be deleted on the next iteration.
9763 MI->setLength(Context->getNullValue(LenC->getType()));
9771 /// visitCallInst - CallInst simplification. This mostly only handles folding
9772 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9773 /// the heavy lifting.
9775 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9776 // If the caller function is nounwind, mark the call as nounwind, even if the
9778 if (CI.getParent()->getParent()->doesNotThrow() &&
9779 !CI.doesNotThrow()) {
9780 CI.setDoesNotThrow();
9786 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9787 if (!II) return visitCallSite(&CI);
9789 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9791 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9792 bool Changed = false;
9794 // memmove/cpy/set of zero bytes is a noop.
9795 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9796 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9798 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9799 if (CI->getZExtValue() == 1) {
9800 // Replace the instruction with just byte operations. We would
9801 // transform other cases to loads/stores, but we don't know if
9802 // alignment is sufficient.
9806 // If we have a memmove and the source operation is a constant global,
9807 // then the source and dest pointers can't alias, so we can change this
9808 // into a call to memcpy.
9809 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9810 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9811 if (GVSrc->isConstant()) {
9812 Module *M = CI.getParent()->getParent()->getParent();
9813 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9815 Tys[0] = CI.getOperand(3)->getType();
9817 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9821 // memmove(x,x,size) -> noop.
9822 if (MMI->getSource() == MMI->getDest())
9823 return EraseInstFromFunction(CI);
9826 // If we can determine a pointer alignment that is bigger than currently
9827 // set, update the alignment.
9828 if (isa<MemTransferInst>(MI)) {
9829 if (Instruction *I = SimplifyMemTransfer(MI))
9831 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9832 if (Instruction *I = SimplifyMemSet(MSI))
9836 if (Changed) return II;
9839 switch (II->getIntrinsicID()) {
9841 case Intrinsic::bswap:
9842 // bswap(bswap(x)) -> x
9843 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9844 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9845 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9847 case Intrinsic::ppc_altivec_lvx:
9848 case Intrinsic::ppc_altivec_lvxl:
9849 case Intrinsic::x86_sse_loadu_ps:
9850 case Intrinsic::x86_sse2_loadu_pd:
9851 case Intrinsic::x86_sse2_loadu_dq:
9852 // Turn PPC lvx -> load if the pointer is known aligned.
9853 // Turn X86 loadups -> load if the pointer is known aligned.
9854 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9855 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9856 Context->getPointerTypeUnqual(II->getType()),
9858 return new LoadInst(Ptr);
9861 case Intrinsic::ppc_altivec_stvx:
9862 case Intrinsic::ppc_altivec_stvxl:
9863 // Turn stvx -> store if the pointer is known aligned.
9864 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9865 const Type *OpPtrTy =
9866 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9867 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9868 return new StoreInst(II->getOperand(1), Ptr);
9871 case Intrinsic::x86_sse_storeu_ps:
9872 case Intrinsic::x86_sse2_storeu_pd:
9873 case Intrinsic::x86_sse2_storeu_dq:
9874 // Turn X86 storeu -> store if the pointer is known aligned.
9875 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9876 const Type *OpPtrTy =
9877 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9878 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9879 return new StoreInst(II->getOperand(2), Ptr);
9883 case Intrinsic::x86_sse_cvttss2si: {
9884 // These intrinsics only demands the 0th element of its input vector. If
9885 // we can simplify the input based on that, do so now.
9887 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9888 APInt DemandedElts(VWidth, 1);
9889 APInt UndefElts(VWidth, 0);
9890 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9892 II->setOperand(1, V);
9898 case Intrinsic::ppc_altivec_vperm:
9899 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9900 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9901 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9903 // Check that all of the elements are integer constants or undefs.
9904 bool AllEltsOk = true;
9905 for (unsigned i = 0; i != 16; ++i) {
9906 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9907 !isa<UndefValue>(Mask->getOperand(i))) {
9914 // Cast the input vectors to byte vectors.
9915 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9916 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9917 Value *Result = Context->getUndef(Op0->getType());
9919 // Only extract each element once.
9920 Value *ExtractedElts[32];
9921 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9923 for (unsigned i = 0; i != 16; ++i) {
9924 if (isa<UndefValue>(Mask->getOperand(i)))
9926 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9927 Idx &= 31; // Match the hardware behavior.
9929 if (ExtractedElts[Idx] == 0) {
9931 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
9932 Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
9933 InsertNewInstBefore(Elt, CI);
9934 ExtractedElts[Idx] = Elt;
9937 // Insert this value into the result vector.
9938 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9939 Context->getConstantInt(Type::Int32Ty, i, false),
9941 InsertNewInstBefore(cast<Instruction>(Result), CI);
9943 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9948 case Intrinsic::stackrestore: {
9949 // If the save is right next to the restore, remove the restore. This can
9950 // happen when variable allocas are DCE'd.
9951 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9952 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9953 BasicBlock::iterator BI = SS;
9955 return EraseInstFromFunction(CI);
9959 // Scan down this block to see if there is another stack restore in the
9960 // same block without an intervening call/alloca.
9961 BasicBlock::iterator BI = II;
9962 TerminatorInst *TI = II->getParent()->getTerminator();
9963 bool CannotRemove = false;
9964 for (++BI; &*BI != TI; ++BI) {
9965 if (isa<AllocaInst>(BI)) {
9966 CannotRemove = true;
9969 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9970 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9971 // If there is a stackrestore below this one, remove this one.
9972 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9973 return EraseInstFromFunction(CI);
9974 // Otherwise, ignore the intrinsic.
9976 // If we found a non-intrinsic call, we can't remove the stack
9978 CannotRemove = true;
9984 // If the stack restore is in a return/unwind block and if there are no
9985 // allocas or calls between the restore and the return, nuke the restore.
9986 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9987 return EraseInstFromFunction(CI);
9992 return visitCallSite(II);
9995 // InvokeInst simplification
9997 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9998 return visitCallSite(&II);
10001 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
10002 /// passed through the varargs area, we can eliminate the use of the cast.
10003 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10004 const CastInst * const CI,
10005 const TargetData * const TD,
10007 if (!CI->isLosslessCast())
10010 // The size of ByVal arguments is derived from the type, so we
10011 // can't change to a type with a different size. If the size were
10012 // passed explicitly we could avoid this check.
10013 if (!CS.paramHasAttr(ix, Attribute::ByVal))
10016 const Type* SrcTy =
10017 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10018 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10019 if (!SrcTy->isSized() || !DstTy->isSized())
10021 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10026 // visitCallSite - Improvements for call and invoke instructions.
10028 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10029 bool Changed = false;
10031 // If the callee is a constexpr cast of a function, attempt to move the cast
10032 // to the arguments of the call/invoke.
10033 if (transformConstExprCastCall(CS)) return 0;
10035 Value *Callee = CS.getCalledValue();
10037 if (Function *CalleeF = dyn_cast<Function>(Callee))
10038 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10039 Instruction *OldCall = CS.getInstruction();
10040 // If the call and callee calling conventions don't match, this call must
10041 // be unreachable, as the call is undefined.
10042 new StoreInst(Context->getTrue(),
10043 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10045 if (!OldCall->use_empty())
10046 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10047 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10048 return EraseInstFromFunction(*OldCall);
10052 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10053 // This instruction is not reachable, just remove it. We insert a store to
10054 // undef so that we know that this code is not reachable, despite the fact
10055 // that we can't modify the CFG here.
10056 new StoreInst(Context->getTrue(),
10057 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10058 CS.getInstruction());
10060 if (!CS.getInstruction()->use_empty())
10061 CS.getInstruction()->
10062 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10064 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10065 // Don't break the CFG, insert a dummy cond branch.
10066 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10067 Context->getTrue(), II);
10069 return EraseInstFromFunction(*CS.getInstruction());
10072 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10073 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10074 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10075 return transformCallThroughTrampoline(CS);
10077 const PointerType *PTy = cast<PointerType>(Callee->getType());
10078 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10079 if (FTy->isVarArg()) {
10080 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10081 // See if we can optimize any arguments passed through the varargs area of
10083 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10084 E = CS.arg_end(); I != E; ++I, ++ix) {
10085 CastInst *CI = dyn_cast<CastInst>(*I);
10086 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10087 *I = CI->getOperand(0);
10093 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10094 // Inline asm calls cannot throw - mark them 'nounwind'.
10095 CS.setDoesNotThrow();
10099 return Changed ? CS.getInstruction() : 0;
10102 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10103 // attempt to move the cast to the arguments of the call/invoke.
10105 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10106 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10107 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10108 if (CE->getOpcode() != Instruction::BitCast ||
10109 !isa<Function>(CE->getOperand(0)))
10111 Function *Callee = cast<Function>(CE->getOperand(0));
10112 Instruction *Caller = CS.getInstruction();
10113 const AttrListPtr &CallerPAL = CS.getAttributes();
10115 // Okay, this is a cast from a function to a different type. Unless doing so
10116 // would cause a type conversion of one of our arguments, change this call to
10117 // be a direct call with arguments casted to the appropriate types.
10119 const FunctionType *FT = Callee->getFunctionType();
10120 const Type *OldRetTy = Caller->getType();
10121 const Type *NewRetTy = FT->getReturnType();
10123 if (isa<StructType>(NewRetTy))
10124 return false; // TODO: Handle multiple return values.
10126 // Check to see if we are changing the return type...
10127 if (OldRetTy != NewRetTy) {
10128 if (Callee->isDeclaration() &&
10129 // Conversion is ok if changing from one pointer type to another or from
10130 // a pointer to an integer of the same size.
10131 !((isa<PointerType>(OldRetTy) || !TD ||
10132 OldRetTy == TD->getIntPtrType()) &&
10133 (isa<PointerType>(NewRetTy) || !TD ||
10134 NewRetTy == TD->getIntPtrType())))
10135 return false; // Cannot transform this return value.
10137 if (!Caller->use_empty() &&
10138 // void -> non-void is handled specially
10139 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10140 return false; // Cannot transform this return value.
10142 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10143 Attributes RAttrs = CallerPAL.getRetAttributes();
10144 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10145 return false; // Attribute not compatible with transformed value.
10148 // If the callsite is an invoke instruction, and the return value is used by
10149 // a PHI node in a successor, we cannot change the return type of the call
10150 // because there is no place to put the cast instruction (without breaking
10151 // the critical edge). Bail out in this case.
10152 if (!Caller->use_empty())
10153 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10154 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10156 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10157 if (PN->getParent() == II->getNormalDest() ||
10158 PN->getParent() == II->getUnwindDest())
10162 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10163 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10165 CallSite::arg_iterator AI = CS.arg_begin();
10166 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10167 const Type *ParamTy = FT->getParamType(i);
10168 const Type *ActTy = (*AI)->getType();
10170 if (!CastInst::isCastable(ActTy, ParamTy))
10171 return false; // Cannot transform this parameter value.
10173 if (CallerPAL.getParamAttributes(i + 1)
10174 & Attribute::typeIncompatible(ParamTy))
10175 return false; // Attribute not compatible with transformed value.
10177 // Converting from one pointer type to another or between a pointer and an
10178 // integer of the same size is safe even if we do not have a body.
10179 bool isConvertible = ActTy == ParamTy ||
10180 (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10181 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
10182 if (Callee->isDeclaration() && !isConvertible) return false;
10185 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10186 Callee->isDeclaration())
10187 return false; // Do not delete arguments unless we have a function body.
10189 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10190 !CallerPAL.isEmpty())
10191 // In this case we have more arguments than the new function type, but we
10192 // won't be dropping them. Check that these extra arguments have attributes
10193 // that are compatible with being a vararg call argument.
10194 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10195 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10197 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10198 if (PAttrs & Attribute::VarArgsIncompatible)
10202 // Okay, we decided that this is a safe thing to do: go ahead and start
10203 // inserting cast instructions as necessary...
10204 std::vector<Value*> Args;
10205 Args.reserve(NumActualArgs);
10206 SmallVector<AttributeWithIndex, 8> attrVec;
10207 attrVec.reserve(NumCommonArgs);
10209 // Get any return attributes.
10210 Attributes RAttrs = CallerPAL.getRetAttributes();
10212 // If the return value is not being used, the type may not be compatible
10213 // with the existing attributes. Wipe out any problematic attributes.
10214 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10216 // Add the new return attributes.
10218 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10220 AI = CS.arg_begin();
10221 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10222 const Type *ParamTy = FT->getParamType(i);
10223 if ((*AI)->getType() == ParamTy) {
10224 Args.push_back(*AI);
10226 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10227 false, ParamTy, false);
10228 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10229 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10232 // Add any parameter attributes.
10233 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10234 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10237 // If the function takes more arguments than the call was taking, add them
10239 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10240 Args.push_back(Context->getNullValue(FT->getParamType(i)));
10242 // If we are removing arguments to the function, emit an obnoxious warning...
10243 if (FT->getNumParams() < NumActualArgs) {
10244 if (!FT->isVarArg()) {
10245 cerr << "WARNING: While resolving call to function '"
10246 << Callee->getName() << "' arguments were dropped!\n";
10248 // Add all of the arguments in their promoted form to the arg list...
10249 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10250 const Type *PTy = getPromotedType((*AI)->getType());
10251 if (PTy != (*AI)->getType()) {
10252 // Must promote to pass through va_arg area!
10253 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10255 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10256 InsertNewInstBefore(Cast, *Caller);
10257 Args.push_back(Cast);
10259 Args.push_back(*AI);
10262 // Add any parameter attributes.
10263 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10264 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10269 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10270 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10272 if (NewRetTy == Type::VoidTy)
10273 Caller->setName(""); // Void type should not have a name.
10275 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10278 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10279 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10280 Args.begin(), Args.end(),
10281 Caller->getName(), Caller);
10282 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10283 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10285 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10286 Caller->getName(), Caller);
10287 CallInst *CI = cast<CallInst>(Caller);
10288 if (CI->isTailCall())
10289 cast<CallInst>(NC)->setTailCall();
10290 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10291 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10294 // Insert a cast of the return type as necessary.
10296 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10297 if (NV->getType() != Type::VoidTy) {
10298 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10300 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10302 // If this is an invoke instruction, we should insert it after the first
10303 // non-phi, instruction in the normal successor block.
10304 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10305 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10306 InsertNewInstBefore(NC, *I);
10308 // Otherwise, it's a call, just insert cast right after the call instr
10309 InsertNewInstBefore(NC, *Caller);
10311 AddUsersToWorkList(*Caller);
10313 NV = Context->getUndef(Caller->getType());
10317 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10318 Caller->replaceAllUsesWith(NV);
10319 Caller->eraseFromParent();
10320 RemoveFromWorkList(Caller);
10324 // transformCallThroughTrampoline - Turn a call to a function created by the
10325 // init_trampoline intrinsic into a direct call to the underlying function.
10327 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10328 Value *Callee = CS.getCalledValue();
10329 const PointerType *PTy = cast<PointerType>(Callee->getType());
10330 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10331 const AttrListPtr &Attrs = CS.getAttributes();
10333 // If the call already has the 'nest' attribute somewhere then give up -
10334 // otherwise 'nest' would occur twice after splicing in the chain.
10335 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10338 IntrinsicInst *Tramp =
10339 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10341 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10342 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10343 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10345 const AttrListPtr &NestAttrs = NestF->getAttributes();
10346 if (!NestAttrs.isEmpty()) {
10347 unsigned NestIdx = 1;
10348 const Type *NestTy = 0;
10349 Attributes NestAttr = Attribute::None;
10351 // Look for a parameter marked with the 'nest' attribute.
10352 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10353 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10354 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10355 // Record the parameter type and any other attributes.
10357 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10362 Instruction *Caller = CS.getInstruction();
10363 std::vector<Value*> NewArgs;
10364 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10366 SmallVector<AttributeWithIndex, 8> NewAttrs;
10367 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10369 // Insert the nest argument into the call argument list, which may
10370 // mean appending it. Likewise for attributes.
10372 // Add any result attributes.
10373 if (Attributes Attr = Attrs.getRetAttributes())
10374 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10378 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10380 if (Idx == NestIdx) {
10381 // Add the chain argument and attributes.
10382 Value *NestVal = Tramp->getOperand(3);
10383 if (NestVal->getType() != NestTy)
10384 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10385 NewArgs.push_back(NestVal);
10386 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10392 // Add the original argument and attributes.
10393 NewArgs.push_back(*I);
10394 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10396 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10402 // Add any function attributes.
10403 if (Attributes Attr = Attrs.getFnAttributes())
10404 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10406 // The trampoline may have been bitcast to a bogus type (FTy).
10407 // Handle this by synthesizing a new function type, equal to FTy
10408 // with the chain parameter inserted.
10410 std::vector<const Type*> NewTypes;
10411 NewTypes.reserve(FTy->getNumParams()+1);
10413 // Insert the chain's type into the list of parameter types, which may
10414 // mean appending it.
10417 FunctionType::param_iterator I = FTy->param_begin(),
10418 E = FTy->param_end();
10421 if (Idx == NestIdx)
10422 // Add the chain's type.
10423 NewTypes.push_back(NestTy);
10428 // Add the original type.
10429 NewTypes.push_back(*I);
10435 // Replace the trampoline call with a direct call. Let the generic
10436 // code sort out any function type mismatches.
10437 FunctionType *NewFTy =
10438 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10440 Constant *NewCallee =
10441 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10442 NestF : Context->getConstantExprBitCast(NestF,
10443 Context->getPointerTypeUnqual(NewFTy));
10444 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10446 Instruction *NewCaller;
10447 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10448 NewCaller = InvokeInst::Create(NewCallee,
10449 II->getNormalDest(), II->getUnwindDest(),
10450 NewArgs.begin(), NewArgs.end(),
10451 Caller->getName(), Caller);
10452 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10453 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10455 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10456 Caller->getName(), Caller);
10457 if (cast<CallInst>(Caller)->isTailCall())
10458 cast<CallInst>(NewCaller)->setTailCall();
10459 cast<CallInst>(NewCaller)->
10460 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10461 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10463 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10464 Caller->replaceAllUsesWith(NewCaller);
10465 Caller->eraseFromParent();
10466 RemoveFromWorkList(Caller);
10471 // Replace the trampoline call with a direct call. Since there is no 'nest'
10472 // parameter, there is no need to adjust the argument list. Let the generic
10473 // code sort out any function type mismatches.
10474 Constant *NewCallee =
10475 NestF->getType() == PTy ? NestF :
10476 Context->getConstantExprBitCast(NestF, PTy);
10477 CS.setCalledFunction(NewCallee);
10478 return CS.getInstruction();
10481 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10482 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10483 /// and a single binop.
10484 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10485 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10486 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10487 unsigned Opc = FirstInst->getOpcode();
10488 Value *LHSVal = FirstInst->getOperand(0);
10489 Value *RHSVal = FirstInst->getOperand(1);
10491 const Type *LHSType = LHSVal->getType();
10492 const Type *RHSType = RHSVal->getType();
10494 // Scan to see if all operands are the same opcode, all have one use, and all
10495 // kill their operands (i.e. the operands have one use).
10496 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10497 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10498 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10499 // Verify type of the LHS matches so we don't fold cmp's of different
10500 // types or GEP's with different index types.
10501 I->getOperand(0)->getType() != LHSType ||
10502 I->getOperand(1)->getType() != RHSType)
10505 // If they are CmpInst instructions, check their predicates
10506 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10507 if (cast<CmpInst>(I)->getPredicate() !=
10508 cast<CmpInst>(FirstInst)->getPredicate())
10511 // Keep track of which operand needs a phi node.
10512 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10513 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10516 // Otherwise, this is safe to transform!
10518 Value *InLHS = FirstInst->getOperand(0);
10519 Value *InRHS = FirstInst->getOperand(1);
10520 PHINode *NewLHS = 0, *NewRHS = 0;
10522 NewLHS = PHINode::Create(LHSType,
10523 FirstInst->getOperand(0)->getName() + ".pn");
10524 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10525 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10526 InsertNewInstBefore(NewLHS, PN);
10531 NewRHS = PHINode::Create(RHSType,
10532 FirstInst->getOperand(1)->getName() + ".pn");
10533 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10534 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10535 InsertNewInstBefore(NewRHS, PN);
10539 // Add all operands to the new PHIs.
10540 if (NewLHS || NewRHS) {
10541 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10542 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10544 Value *NewInLHS = InInst->getOperand(0);
10545 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10548 Value *NewInRHS = InInst->getOperand(1);
10549 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10554 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10555 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10556 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10557 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10561 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10562 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10564 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10565 FirstInst->op_end());
10566 // This is true if all GEP bases are allocas and if all indices into them are
10568 bool AllBasePointersAreAllocas = true;
10570 // Scan to see if all operands are the same opcode, all have one use, and all
10571 // kill their operands (i.e. the operands have one use).
10572 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10573 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10574 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10575 GEP->getNumOperands() != FirstInst->getNumOperands())
10578 // Keep track of whether or not all GEPs are of alloca pointers.
10579 if (AllBasePointersAreAllocas &&
10580 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10581 !GEP->hasAllConstantIndices()))
10582 AllBasePointersAreAllocas = false;
10584 // Compare the operand lists.
10585 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10586 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10589 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10590 // if one of the PHIs has a constant for the index. The index may be
10591 // substantially cheaper to compute for the constants, so making it a
10592 // variable index could pessimize the path. This also handles the case
10593 // for struct indices, which must always be constant.
10594 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10595 isa<ConstantInt>(GEP->getOperand(op)))
10598 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10600 FixedOperands[op] = 0; // Needs a PHI.
10604 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10605 // bother doing this transformation. At best, this will just save a bit of
10606 // offset calculation, but all the predecessors will have to materialize the
10607 // stack address into a register anyway. We'd actually rather *clone* the
10608 // load up into the predecessors so that we have a load of a gep of an alloca,
10609 // which can usually all be folded into the load.
10610 if (AllBasePointersAreAllocas)
10613 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10614 // that is variable.
10615 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10617 bool HasAnyPHIs = false;
10618 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10619 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10620 Value *FirstOp = FirstInst->getOperand(i);
10621 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10622 FirstOp->getName()+".pn");
10623 InsertNewInstBefore(NewPN, PN);
10625 NewPN->reserveOperandSpace(e);
10626 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10627 OperandPhis[i] = NewPN;
10628 FixedOperands[i] = NewPN;
10633 // Add all operands to the new PHIs.
10635 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10636 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10637 BasicBlock *InBB = PN.getIncomingBlock(i);
10639 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10640 if (PHINode *OpPhi = OperandPhis[op])
10641 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10645 Value *Base = FixedOperands[0];
10646 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10647 FixedOperands.end());
10651 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10652 /// sink the load out of the block that defines it. This means that it must be
10653 /// obvious the value of the load is not changed from the point of the load to
10654 /// the end of the block it is in.
10656 /// Finally, it is safe, but not profitable, to sink a load targetting a
10657 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10659 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10660 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10662 for (++BBI; BBI != E; ++BBI)
10663 if (BBI->mayWriteToMemory())
10666 // Check for non-address taken alloca. If not address-taken already, it isn't
10667 // profitable to do this xform.
10668 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10669 bool isAddressTaken = false;
10670 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10672 if (isa<LoadInst>(UI)) continue;
10673 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10674 // If storing TO the alloca, then the address isn't taken.
10675 if (SI->getOperand(1) == AI) continue;
10677 isAddressTaken = true;
10681 if (!isAddressTaken && AI->isStaticAlloca())
10685 // If this load is a load from a GEP with a constant offset from an alloca,
10686 // then we don't want to sink it. In its present form, it will be
10687 // load [constant stack offset]. Sinking it will cause us to have to
10688 // materialize the stack addresses in each predecessor in a register only to
10689 // do a shared load from register in the successor.
10690 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10691 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10692 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10699 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10700 // operator and they all are only used by the PHI, PHI together their
10701 // inputs, and do the operation once, to the result of the PHI.
10702 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10703 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10705 // Scan the instruction, looking for input operations that can be folded away.
10706 // If all input operands to the phi are the same instruction (e.g. a cast from
10707 // the same type or "+42") we can pull the operation through the PHI, reducing
10708 // code size and simplifying code.
10709 Constant *ConstantOp = 0;
10710 const Type *CastSrcTy = 0;
10711 bool isVolatile = false;
10712 if (isa<CastInst>(FirstInst)) {
10713 CastSrcTy = FirstInst->getOperand(0)->getType();
10714 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10715 // Can fold binop, compare or shift here if the RHS is a constant,
10716 // otherwise call FoldPHIArgBinOpIntoPHI.
10717 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10718 if (ConstantOp == 0)
10719 return FoldPHIArgBinOpIntoPHI(PN);
10720 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10721 isVolatile = LI->isVolatile();
10722 // We can't sink the load if the loaded value could be modified between the
10723 // load and the PHI.
10724 if (LI->getParent() != PN.getIncomingBlock(0) ||
10725 !isSafeAndProfitableToSinkLoad(LI))
10728 // If the PHI is of volatile loads and the load block has multiple
10729 // successors, sinking it would remove a load of the volatile value from
10730 // the path through the other successor.
10732 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10735 } else if (isa<GetElementPtrInst>(FirstInst)) {
10736 return FoldPHIArgGEPIntoPHI(PN);
10738 return 0; // Cannot fold this operation.
10741 // Check to see if all arguments are the same operation.
10742 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10743 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10744 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10745 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10748 if (I->getOperand(0)->getType() != CastSrcTy)
10749 return 0; // Cast operation must match.
10750 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10751 // We can't sink the load if the loaded value could be modified between
10752 // the load and the PHI.
10753 if (LI->isVolatile() != isVolatile ||
10754 LI->getParent() != PN.getIncomingBlock(i) ||
10755 !isSafeAndProfitableToSinkLoad(LI))
10758 // If the PHI is of volatile loads and the load block has multiple
10759 // successors, sinking it would remove a load of the volatile value from
10760 // the path through the other successor.
10762 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10765 } else if (I->getOperand(1) != ConstantOp) {
10770 // Okay, they are all the same operation. Create a new PHI node of the
10771 // correct type, and PHI together all of the LHS's of the instructions.
10772 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10773 PN.getName()+".in");
10774 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10776 Value *InVal = FirstInst->getOperand(0);
10777 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10779 // Add all operands to the new PHI.
10780 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10781 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10782 if (NewInVal != InVal)
10784 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10789 // The new PHI unions all of the same values together. This is really
10790 // common, so we handle it intelligently here for compile-time speed.
10794 InsertNewInstBefore(NewPN, PN);
10798 // Insert and return the new operation.
10799 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10800 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10801 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10802 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10803 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10804 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10805 PhiVal, ConstantOp);
10806 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10808 // If this was a volatile load that we are merging, make sure to loop through
10809 // and mark all the input loads as non-volatile. If we don't do this, we will
10810 // insert a new volatile load and the old ones will not be deletable.
10812 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10813 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10815 return new LoadInst(PhiVal, "", isVolatile);
10818 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10820 static bool DeadPHICycle(PHINode *PN,
10821 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10822 if (PN->use_empty()) return true;
10823 if (!PN->hasOneUse()) return false;
10825 // Remember this node, and if we find the cycle, return.
10826 if (!PotentiallyDeadPHIs.insert(PN))
10829 // Don't scan crazily complex things.
10830 if (PotentiallyDeadPHIs.size() == 16)
10833 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10834 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10839 /// PHIsEqualValue - Return true if this phi node is always equal to
10840 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10841 /// z = some value; x = phi (y, z); y = phi (x, z)
10842 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10843 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10844 // See if we already saw this PHI node.
10845 if (!ValueEqualPHIs.insert(PN))
10848 // Don't scan crazily complex things.
10849 if (ValueEqualPHIs.size() == 16)
10852 // Scan the operands to see if they are either phi nodes or are equal to
10854 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10855 Value *Op = PN->getIncomingValue(i);
10856 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10857 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10859 } else if (Op != NonPhiInVal)
10867 // PHINode simplification
10869 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10870 // If LCSSA is around, don't mess with Phi nodes
10871 if (MustPreserveLCSSA) return 0;
10873 if (Value *V = PN.hasConstantValue())
10874 return ReplaceInstUsesWith(PN, V);
10876 // If all PHI operands are the same operation, pull them through the PHI,
10877 // reducing code size.
10878 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10879 isa<Instruction>(PN.getIncomingValue(1)) &&
10880 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10881 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10882 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10883 // than themselves more than once.
10884 PN.getIncomingValue(0)->hasOneUse())
10885 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10888 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10889 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10890 // PHI)... break the cycle.
10891 if (PN.hasOneUse()) {
10892 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10893 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10894 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10895 PotentiallyDeadPHIs.insert(&PN);
10896 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10897 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10900 // If this phi has a single use, and if that use just computes a value for
10901 // the next iteration of a loop, delete the phi. This occurs with unused
10902 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10903 // common case here is good because the only other things that catch this
10904 // are induction variable analysis (sometimes) and ADCE, which is only run
10906 if (PHIUser->hasOneUse() &&
10907 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10908 PHIUser->use_back() == &PN) {
10909 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10913 // We sometimes end up with phi cycles that non-obviously end up being the
10914 // same value, for example:
10915 // z = some value; x = phi (y, z); y = phi (x, z)
10916 // where the phi nodes don't necessarily need to be in the same block. Do a
10917 // quick check to see if the PHI node only contains a single non-phi value, if
10918 // so, scan to see if the phi cycle is actually equal to that value.
10920 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10921 // Scan for the first non-phi operand.
10922 while (InValNo != NumOperandVals &&
10923 isa<PHINode>(PN.getIncomingValue(InValNo)))
10926 if (InValNo != NumOperandVals) {
10927 Value *NonPhiInVal = PN.getOperand(InValNo);
10929 // Scan the rest of the operands to see if there are any conflicts, if so
10930 // there is no need to recursively scan other phis.
10931 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10932 Value *OpVal = PN.getIncomingValue(InValNo);
10933 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10937 // If we scanned over all operands, then we have one unique value plus
10938 // phi values. Scan PHI nodes to see if they all merge in each other or
10940 if (InValNo == NumOperandVals) {
10941 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10942 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10943 return ReplaceInstUsesWith(PN, NonPhiInVal);
10950 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10951 Instruction *InsertPoint,
10952 InstCombiner *IC) {
10953 unsigned PtrSize = DTy->getScalarSizeInBits();
10954 unsigned VTySize = V->getType()->getScalarSizeInBits();
10955 // We must cast correctly to the pointer type. Ensure that we
10956 // sign extend the integer value if it is smaller as this is
10957 // used for address computation.
10958 Instruction::CastOps opcode =
10959 (VTySize < PtrSize ? Instruction::SExt :
10960 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10961 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10965 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10966 Value *PtrOp = GEP.getOperand(0);
10967 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10968 // If so, eliminate the noop.
10969 if (GEP.getNumOperands() == 1)
10970 return ReplaceInstUsesWith(GEP, PtrOp);
10972 if (isa<UndefValue>(GEP.getOperand(0)))
10973 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
10975 bool HasZeroPointerIndex = false;
10976 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10977 HasZeroPointerIndex = C->isNullValue();
10979 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10980 return ReplaceInstUsesWith(GEP, PtrOp);
10982 // Eliminate unneeded casts for indices.
10983 bool MadeChange = false;
10985 gep_type_iterator GTI = gep_type_begin(GEP);
10986 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10987 i != e; ++i, ++GTI) {
10988 if (TD && isa<SequentialType>(*GTI)) {
10989 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10990 if (CI->getOpcode() == Instruction::ZExt ||
10991 CI->getOpcode() == Instruction::SExt) {
10992 const Type *SrcTy = CI->getOperand(0)->getType();
10993 // We can eliminate a cast from i32 to i64 iff the target
10994 // is a 32-bit pointer target.
10995 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
10997 *i = CI->getOperand(0);
11001 // If we are using a wider index than needed for this platform, shrink it
11002 // to what we need. If narrower, sign-extend it to what we need.
11003 // If the incoming value needs a cast instruction,
11004 // insert it. This explicit cast can make subsequent optimizations more
11007 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11008 if (Constant *C = dyn_cast<Constant>(Op)) {
11009 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11012 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11017 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11018 if (Constant *C = dyn_cast<Constant>(Op)) {
11019 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11022 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11030 if (MadeChange) return &GEP;
11032 // Combine Indices - If the source pointer to this getelementptr instruction
11033 // is a getelementptr instruction, combine the indices of the two
11034 // getelementptr instructions into a single instruction.
11036 SmallVector<Value*, 8> SrcGEPOperands;
11037 if (User *Src = dyn_castGetElementPtr(PtrOp))
11038 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11040 if (!SrcGEPOperands.empty()) {
11041 // Note that if our source is a gep chain itself that we wait for that
11042 // chain to be resolved before we perform this transformation. This
11043 // avoids us creating a TON of code in some cases.
11045 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11046 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11047 return 0; // Wait until our source is folded to completion.
11049 SmallVector<Value*, 8> Indices;
11051 // Find out whether the last index in the source GEP is a sequential idx.
11052 bool EndsWithSequential = false;
11053 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11054 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11055 EndsWithSequential = !isa<StructType>(*I);
11057 // Can we combine the two pointer arithmetics offsets?
11058 if (EndsWithSequential) {
11059 // Replace: gep (gep %P, long B), long A, ...
11060 // With: T = long A+B; gep %P, T, ...
11062 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11063 if (SO1 == Context->getNullValue(SO1->getType())) {
11065 } else if (GO1 == Context->getNullValue(GO1->getType())) {
11068 // If they aren't the same type, convert both to an integer of the
11069 // target's pointer size.
11070 if (SO1->getType() != GO1->getType()) {
11071 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11073 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11074 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11076 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11078 unsigned PS = TD->getPointerSizeInBits();
11079 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11080 // Convert GO1 to SO1's type.
11081 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11083 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11084 // Convert SO1 to GO1's type.
11085 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11087 const Type *PT = TD->getIntPtrType();
11088 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11089 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11093 if (isa<Constant>(SO1) && isa<Constant>(GO1))
11094 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11095 cast<Constant>(GO1));
11097 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11098 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11102 // Recycle the GEP we already have if possible.
11103 if (SrcGEPOperands.size() == 2) {
11104 GEP.setOperand(0, SrcGEPOperands[0]);
11105 GEP.setOperand(1, Sum);
11108 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11109 SrcGEPOperands.end()-1);
11110 Indices.push_back(Sum);
11111 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11113 } else if (isa<Constant>(*GEP.idx_begin()) &&
11114 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11115 SrcGEPOperands.size() != 1) {
11116 // Otherwise we can do the fold if the first index of the GEP is a zero
11117 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11118 SrcGEPOperands.end());
11119 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11122 if (!Indices.empty())
11123 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11124 Indices.end(), GEP.getName());
11126 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11127 // GEP of global variable. If all of the indices for this GEP are
11128 // constants, we can promote this to a constexpr instead of an instruction.
11130 // Scan for nonconstants...
11131 SmallVector<Constant*, 8> Indices;
11132 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11133 for (; I != E && isa<Constant>(*I); ++I)
11134 Indices.push_back(cast<Constant>(*I));
11136 if (I == E) { // If they are all constants...
11137 Constant *CE = Context->getConstantExprGetElementPtr(GV,
11138 &Indices[0],Indices.size());
11140 // Replace all uses of the GEP with the new constexpr...
11141 return ReplaceInstUsesWith(GEP, CE);
11143 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11144 if (!isa<PointerType>(X->getType())) {
11145 // Not interesting. Source pointer must be a cast from pointer.
11146 } else if (HasZeroPointerIndex) {
11147 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11148 // into : GEP [10 x i8]* X, i32 0, ...
11150 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11151 // into : GEP i8* X, ...
11153 // This occurs when the program declares an array extern like "int X[];"
11154 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11155 const PointerType *XTy = cast<PointerType>(X->getType());
11156 if (const ArrayType *CATy =
11157 dyn_cast<ArrayType>(CPTy->getElementType())) {
11158 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11159 if (CATy->getElementType() == XTy->getElementType()) {
11160 // -> GEP i8* X, ...
11161 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11162 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11164 } else if (const ArrayType *XATy =
11165 dyn_cast<ArrayType>(XTy->getElementType())) {
11166 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11167 if (CATy->getElementType() == XATy->getElementType()) {
11168 // -> GEP [10 x i8]* X, i32 0, ...
11169 // At this point, we know that the cast source type is a pointer
11170 // to an array of the same type as the destination pointer
11171 // array. Because the array type is never stepped over (there
11172 // is a leading zero) we can fold the cast into this GEP.
11173 GEP.setOperand(0, X);
11178 } else if (GEP.getNumOperands() == 2) {
11179 // Transform things like:
11180 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11181 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11182 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11183 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11184 if (TD && isa<ArrayType>(SrcElTy) &&
11185 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11186 TD->getTypeAllocSize(ResElTy)) {
11188 Idx[0] = Context->getNullValue(Type::Int32Ty);
11189 Idx[1] = GEP.getOperand(1);
11190 Value *V = InsertNewInstBefore(
11191 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11192 // V and GEP are both pointer types --> BitCast
11193 return new BitCastInst(V, GEP.getType());
11196 // Transform things like:
11197 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11198 // (where tmp = 8*tmp2) into:
11199 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11201 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11202 uint64_t ArrayEltSize =
11203 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11205 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11206 // allow either a mul, shift, or constant here.
11208 ConstantInt *Scale = 0;
11209 if (ArrayEltSize == 1) {
11210 NewIdx = GEP.getOperand(1);
11212 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11213 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11214 NewIdx = Context->getConstantInt(CI->getType(), 1);
11216 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11217 if (Inst->getOpcode() == Instruction::Shl &&
11218 isa<ConstantInt>(Inst->getOperand(1))) {
11219 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11220 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11221 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11223 NewIdx = Inst->getOperand(0);
11224 } else if (Inst->getOpcode() == Instruction::Mul &&
11225 isa<ConstantInt>(Inst->getOperand(1))) {
11226 Scale = cast<ConstantInt>(Inst->getOperand(1));
11227 NewIdx = Inst->getOperand(0);
11231 // If the index will be to exactly the right offset with the scale taken
11232 // out, perform the transformation. Note, we don't know whether Scale is
11233 // signed or not. We'll use unsigned version of division/modulo
11234 // operation after making sure Scale doesn't have the sign bit set.
11235 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11236 Scale->getZExtValue() % ArrayEltSize == 0) {
11237 Scale = Context->getConstantInt(Scale->getType(),
11238 Scale->getZExtValue() / ArrayEltSize);
11239 if (Scale->getZExtValue() != 1) {
11241 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11243 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11244 NewIdx = InsertNewInstBefore(Sc, GEP);
11247 // Insert the new GEP instruction.
11249 Idx[0] = Context->getNullValue(Type::Int32Ty);
11251 Instruction *NewGEP =
11252 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11253 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11254 // The NewGEP must be pointer typed, so must the old one -> BitCast
11255 return new BitCastInst(NewGEP, GEP.getType());
11261 /// See if we can simplify:
11262 /// X = bitcast A to B*
11263 /// Y = gep X, <...constant indices...>
11264 /// into a gep of the original struct. This is important for SROA and alias
11265 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11266 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11268 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11269 // Determine how much the GEP moves the pointer. We are guaranteed to get
11270 // a constant back from EmitGEPOffset.
11271 ConstantInt *OffsetV =
11272 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11273 int64_t Offset = OffsetV->getSExtValue();
11275 // If this GEP instruction doesn't move the pointer, just replace the GEP
11276 // with a bitcast of the real input to the dest type.
11278 // If the bitcast is of an allocation, and the allocation will be
11279 // converted to match the type of the cast, don't touch this.
11280 if (isa<AllocationInst>(BCI->getOperand(0))) {
11281 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11282 if (Instruction *I = visitBitCast(*BCI)) {
11285 BCI->getParent()->getInstList().insert(BCI, I);
11286 ReplaceInstUsesWith(*BCI, I);
11291 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11294 // Otherwise, if the offset is non-zero, we need to find out if there is a
11295 // field at Offset in 'A's type. If so, we can pull the cast through the
11297 SmallVector<Value*, 8> NewIndices;
11299 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11300 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11301 Instruction *NGEP =
11302 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11304 if (NGEP->getType() == GEP.getType()) return NGEP;
11305 InsertNewInstBefore(NGEP, GEP);
11306 NGEP->takeName(&GEP);
11307 return new BitCastInst(NGEP, GEP.getType());
11315 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11316 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11317 if (AI.isArrayAllocation()) { // Check C != 1
11318 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11319 const Type *NewTy =
11320 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11321 AllocationInst *New = 0;
11323 // Create and insert the replacement instruction...
11324 if (isa<MallocInst>(AI))
11325 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11327 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11328 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11331 InsertNewInstBefore(New, AI);
11333 // Scan to the end of the allocation instructions, to skip over a block of
11334 // allocas if possible...also skip interleaved debug info
11336 BasicBlock::iterator It = New;
11337 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11339 // Now that I is pointing to the first non-allocation-inst in the block,
11340 // insert our getelementptr instruction...
11342 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11346 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11347 New->getName()+".sub", It);
11349 // Now make everything use the getelementptr instead of the original
11351 return ReplaceInstUsesWith(AI, V);
11352 } else if (isa<UndefValue>(AI.getArraySize())) {
11353 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11357 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11358 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11359 // Note that we only do this for alloca's, because malloc should allocate
11360 // and return a unique pointer, even for a zero byte allocation.
11361 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11362 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11364 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11365 if (AI.getAlignment() == 0)
11366 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11372 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11373 Value *Op = FI.getOperand(0);
11375 // free undef -> unreachable.
11376 if (isa<UndefValue>(Op)) {
11377 // Insert a new store to null because we cannot modify the CFG here.
11378 new StoreInst(Context->getTrue(),
11379 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11380 return EraseInstFromFunction(FI);
11383 // If we have 'free null' delete the instruction. This can happen in stl code
11384 // when lots of inlining happens.
11385 if (isa<ConstantPointerNull>(Op))
11386 return EraseInstFromFunction(FI);
11388 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11389 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11390 FI.setOperand(0, CI->getOperand(0));
11394 // Change free (gep X, 0,0,0,0) into free(X)
11395 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11396 if (GEPI->hasAllZeroIndices()) {
11397 AddToWorkList(GEPI);
11398 FI.setOperand(0, GEPI->getOperand(0));
11403 // Change free(malloc) into nothing, if the malloc has a single use.
11404 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11405 if (MI->hasOneUse()) {
11406 EraseInstFromFunction(FI);
11407 return EraseInstFromFunction(*MI);
11414 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11415 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11416 const TargetData *TD) {
11417 User *CI = cast<User>(LI.getOperand(0));
11418 Value *CastOp = CI->getOperand(0);
11419 LLVMContext *Context = IC.getContext();
11422 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11423 // Instead of loading constant c string, use corresponding integer value
11424 // directly if string length is small enough.
11426 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11427 unsigned len = Str.length();
11428 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11429 unsigned numBits = Ty->getPrimitiveSizeInBits();
11430 // Replace LI with immediate integer store.
11431 if ((numBits >> 3) == len + 1) {
11432 APInt StrVal(numBits, 0);
11433 APInt SingleChar(numBits, 0);
11434 if (TD->isLittleEndian()) {
11435 for (signed i = len-1; i >= 0; i--) {
11436 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11437 StrVal = (StrVal << 8) | SingleChar;
11440 for (unsigned i = 0; i < len; i++) {
11441 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11442 StrVal = (StrVal << 8) | SingleChar;
11444 // Append NULL at the end.
11446 StrVal = (StrVal << 8) | SingleChar;
11448 Value *NL = Context->getConstantInt(StrVal);
11449 return IC.ReplaceInstUsesWith(LI, NL);
11455 const PointerType *DestTy = cast<PointerType>(CI->getType());
11456 const Type *DestPTy = DestTy->getElementType();
11457 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11459 // If the address spaces don't match, don't eliminate the cast.
11460 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11463 const Type *SrcPTy = SrcTy->getElementType();
11465 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11466 isa<VectorType>(DestPTy)) {
11467 // If the source is an array, the code below will not succeed. Check to
11468 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11470 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11471 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11472 if (ASrcTy->getNumElements() != 0) {
11474 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11475 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11476 SrcTy = cast<PointerType>(CastOp->getType());
11477 SrcPTy = SrcTy->getElementType();
11480 if (IC.getTargetData() &&
11481 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11482 isa<VectorType>(SrcPTy)) &&
11483 // Do not allow turning this into a load of an integer, which is then
11484 // casted to a pointer, this pessimizes pointer analysis a lot.
11485 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11486 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11487 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11489 // Okay, we are casting from one integer or pointer type to another of
11490 // the same size. Instead of casting the pointer before the load, cast
11491 // the result of the loaded value.
11492 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11494 LI.isVolatile()),LI);
11495 // Now cast the result of the load.
11496 return new BitCastInst(NewLoad, LI.getType());
11503 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11504 Value *Op = LI.getOperand(0);
11506 // Attempt to improve the alignment.
11508 unsigned KnownAlign =
11509 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11511 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11512 LI.getAlignment()))
11513 LI.setAlignment(KnownAlign);
11516 // load (cast X) --> cast (load X) iff safe
11517 if (isa<CastInst>(Op))
11518 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11521 // None of the following transforms are legal for volatile loads.
11522 if (LI.isVolatile()) return 0;
11524 // Do really simple store-to-load forwarding and load CSE, to catch cases
11525 // where there are several consequtive memory accesses to the same location,
11526 // separated by a few arithmetic operations.
11527 BasicBlock::iterator BBI = &LI;
11528 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11529 return ReplaceInstUsesWith(LI, AvailableVal);
11531 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11532 const Value *GEPI0 = GEPI->getOperand(0);
11533 // TODO: Consider a target hook for valid address spaces for this xform.
11534 if (isa<ConstantPointerNull>(GEPI0) &&
11535 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11536 // Insert a new store to null instruction before the load to indicate
11537 // that this code is not reachable. We do this instead of inserting
11538 // an unreachable instruction directly because we cannot modify the
11540 new StoreInst(Context->getUndef(LI.getType()),
11541 Context->getNullValue(Op->getType()), &LI);
11542 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11546 if (Constant *C = dyn_cast<Constant>(Op)) {
11547 // load null/undef -> undef
11548 // TODO: Consider a target hook for valid address spaces for this xform.
11549 if (isa<UndefValue>(C) || (C->isNullValue() &&
11550 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11551 // Insert a new store to null instruction before the load to indicate that
11552 // this code is not reachable. We do this instead of inserting an
11553 // unreachable instruction directly because we cannot modify the CFG.
11554 new StoreInst(Context->getUndef(LI.getType()),
11555 Context->getNullValue(Op->getType()), &LI);
11556 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11559 // Instcombine load (constant global) into the value loaded.
11560 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11561 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11562 return ReplaceInstUsesWith(LI, GV->getInitializer());
11564 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11565 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11566 if (CE->getOpcode() == Instruction::GetElementPtr) {
11567 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11568 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11570 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11572 return ReplaceInstUsesWith(LI, V);
11573 if (CE->getOperand(0)->isNullValue()) {
11574 // Insert a new store to null instruction before the load to indicate
11575 // that this code is not reachable. We do this instead of inserting
11576 // an unreachable instruction directly because we cannot modify the
11578 new StoreInst(Context->getUndef(LI.getType()),
11579 Context->getNullValue(Op->getType()), &LI);
11580 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11583 } else if (CE->isCast()) {
11584 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11590 // If this load comes from anywhere in a constant global, and if the global
11591 // is all undef or zero, we know what it loads.
11592 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11593 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11594 if (GV->getInitializer()->isNullValue())
11595 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11596 else if (isa<UndefValue>(GV->getInitializer()))
11597 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11601 if (Op->hasOneUse()) {
11602 // Change select and PHI nodes to select values instead of addresses: this
11603 // helps alias analysis out a lot, allows many others simplifications, and
11604 // exposes redundancy in the code.
11606 // Note that we cannot do the transformation unless we know that the
11607 // introduced loads cannot trap! Something like this is valid as long as
11608 // the condition is always false: load (select bool %C, int* null, int* %G),
11609 // but it would not be valid if we transformed it to load from null
11610 // unconditionally.
11612 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11613 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11614 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11615 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11616 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11617 SI->getOperand(1)->getName()+".val"), LI);
11618 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11619 SI->getOperand(2)->getName()+".val"), LI);
11620 return SelectInst::Create(SI->getCondition(), V1, V2);
11623 // load (select (cond, null, P)) -> load P
11624 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11625 if (C->isNullValue()) {
11626 LI.setOperand(0, SI->getOperand(2));
11630 // load (select (cond, P, null)) -> load P
11631 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11632 if (C->isNullValue()) {
11633 LI.setOperand(0, SI->getOperand(1));
11641 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11642 /// when possible. This makes it generally easy to do alias analysis and/or
11643 /// SROA/mem2reg of the memory object.
11644 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11645 User *CI = cast<User>(SI.getOperand(1));
11646 Value *CastOp = CI->getOperand(0);
11647 LLVMContext *Context = IC.getContext();
11649 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11650 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11651 if (SrcTy == 0) return 0;
11653 const Type *SrcPTy = SrcTy->getElementType();
11655 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11658 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11659 /// to its first element. This allows us to handle things like:
11660 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11661 /// on 32-bit hosts.
11662 SmallVector<Value*, 4> NewGEPIndices;
11664 // If the source is an array, the code below will not succeed. Check to
11665 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11667 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11668 // Index through pointer.
11669 Constant *Zero = Context->getNullValue(Type::Int32Ty);
11670 NewGEPIndices.push_back(Zero);
11673 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11674 if (!STy->getNumElements()) /* Struct can be empty {} */
11676 NewGEPIndices.push_back(Zero);
11677 SrcPTy = STy->getElementType(0);
11678 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11679 NewGEPIndices.push_back(Zero);
11680 SrcPTy = ATy->getElementType();
11686 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11689 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11692 // If the pointers point into different address spaces or if they point to
11693 // values with different sizes, we can't do the transformation.
11694 if (!IC.getTargetData() ||
11695 SrcTy->getAddressSpace() !=
11696 cast<PointerType>(CI->getType())->getAddressSpace() ||
11697 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11698 IC.getTargetData()->getTypeSizeInBits(DestPTy))
11701 // Okay, we are casting from one integer or pointer type to another of
11702 // the same size. Instead of casting the pointer before
11703 // the store, cast the value to be stored.
11705 Value *SIOp0 = SI.getOperand(0);
11706 Instruction::CastOps opcode = Instruction::BitCast;
11707 const Type* CastSrcTy = SIOp0->getType();
11708 const Type* CastDstTy = SrcPTy;
11709 if (isa<PointerType>(CastDstTy)) {
11710 if (CastSrcTy->isInteger())
11711 opcode = Instruction::IntToPtr;
11712 } else if (isa<IntegerType>(CastDstTy)) {
11713 if (isa<PointerType>(SIOp0->getType()))
11714 opcode = Instruction::PtrToInt;
11717 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11718 // emit a GEP to index into its first field.
11719 if (!NewGEPIndices.empty()) {
11720 if (Constant *C = dyn_cast<Constant>(CastOp))
11721 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
11722 NewGEPIndices.size());
11724 CastOp = IC.InsertNewInstBefore(
11725 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11726 NewGEPIndices.end()), SI);
11729 if (Constant *C = dyn_cast<Constant>(SIOp0))
11730 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11732 NewCast = IC.InsertNewInstBefore(
11733 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11735 return new StoreInst(NewCast, CastOp);
11738 /// equivalentAddressValues - Test if A and B will obviously have the same
11739 /// value. This includes recognizing that %t0 and %t1 will have the same
11740 /// value in code like this:
11741 /// %t0 = getelementptr \@a, 0, 3
11742 /// store i32 0, i32* %t0
11743 /// %t1 = getelementptr \@a, 0, 3
11744 /// %t2 = load i32* %t1
11746 static bool equivalentAddressValues(Value *A, Value *B) {
11747 // Test if the values are trivially equivalent.
11748 if (A == B) return true;
11750 // Test if the values come form identical arithmetic instructions.
11751 if (isa<BinaryOperator>(A) ||
11752 isa<CastInst>(A) ||
11754 isa<GetElementPtrInst>(A))
11755 if (Instruction *BI = dyn_cast<Instruction>(B))
11756 if (cast<Instruction>(A)->isIdenticalTo(BI))
11759 // Otherwise they may not be equivalent.
11763 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11764 // return the llvm.dbg.declare.
11765 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11766 if (!V->hasNUses(2))
11768 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11770 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11772 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11773 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11780 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11781 Value *Val = SI.getOperand(0);
11782 Value *Ptr = SI.getOperand(1);
11784 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11785 EraseInstFromFunction(SI);
11790 // If the RHS is an alloca with a single use, zapify the store, making the
11792 // If the RHS is an alloca with a two uses, the other one being a
11793 // llvm.dbg.declare, zapify the store and the declare, making the
11794 // alloca dead. We must do this to prevent declare's from affecting
11796 if (!SI.isVolatile()) {
11797 if (Ptr->hasOneUse()) {
11798 if (isa<AllocaInst>(Ptr)) {
11799 EraseInstFromFunction(SI);
11803 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11804 if (isa<AllocaInst>(GEP->getOperand(0))) {
11805 if (GEP->getOperand(0)->hasOneUse()) {
11806 EraseInstFromFunction(SI);
11810 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11811 EraseInstFromFunction(*DI);
11812 EraseInstFromFunction(SI);
11819 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11820 EraseInstFromFunction(*DI);
11821 EraseInstFromFunction(SI);
11827 // Attempt to improve the alignment.
11829 unsigned KnownAlign =
11830 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11832 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11833 SI.getAlignment()))
11834 SI.setAlignment(KnownAlign);
11837 // Do really simple DSE, to catch cases where there are several consecutive
11838 // stores to the same location, separated by a few arithmetic operations. This
11839 // situation often occurs with bitfield accesses.
11840 BasicBlock::iterator BBI = &SI;
11841 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11844 // Don't count debug info directives, lest they affect codegen,
11845 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11846 // It is necessary for correctness to skip those that feed into a
11847 // llvm.dbg.declare, as these are not present when debugging is off.
11848 if (isa<DbgInfoIntrinsic>(BBI) ||
11849 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11854 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11855 // Prev store isn't volatile, and stores to the same location?
11856 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11857 SI.getOperand(1))) {
11860 EraseInstFromFunction(*PrevSI);
11866 // If this is a load, we have to stop. However, if the loaded value is from
11867 // the pointer we're loading and is producing the pointer we're storing,
11868 // then *this* store is dead (X = load P; store X -> P).
11869 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11870 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11871 !SI.isVolatile()) {
11872 EraseInstFromFunction(SI);
11876 // Otherwise, this is a load from some other location. Stores before it
11877 // may not be dead.
11881 // Don't skip over loads or things that can modify memory.
11882 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11887 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11889 // store X, null -> turns into 'unreachable' in SimplifyCFG
11890 if (isa<ConstantPointerNull>(Ptr) &&
11891 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11892 if (!isa<UndefValue>(Val)) {
11893 SI.setOperand(0, Context->getUndef(Val->getType()));
11894 if (Instruction *U = dyn_cast<Instruction>(Val))
11895 AddToWorkList(U); // Dropped a use.
11898 return 0; // Do not modify these!
11901 // store undef, Ptr -> noop
11902 if (isa<UndefValue>(Val)) {
11903 EraseInstFromFunction(SI);
11908 // If the pointer destination is a cast, see if we can fold the cast into the
11910 if (isa<CastInst>(Ptr))
11911 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11913 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11915 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11919 // If this store is the last instruction in the basic block (possibly
11920 // excepting debug info instructions and the pointer bitcasts that feed
11921 // into them), and if the block ends with an unconditional branch, try
11922 // to move it to the successor block.
11926 } while (isa<DbgInfoIntrinsic>(BBI) ||
11927 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11928 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11929 if (BI->isUnconditional())
11930 if (SimplifyStoreAtEndOfBlock(SI))
11931 return 0; // xform done!
11936 /// SimplifyStoreAtEndOfBlock - Turn things like:
11937 /// if () { *P = v1; } else { *P = v2 }
11938 /// into a phi node with a store in the successor.
11940 /// Simplify things like:
11941 /// *P = v1; if () { *P = v2; }
11942 /// into a phi node with a store in the successor.
11944 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11945 BasicBlock *StoreBB = SI.getParent();
11947 // Check to see if the successor block has exactly two incoming edges. If
11948 // so, see if the other predecessor contains a store to the same location.
11949 // if so, insert a PHI node (if needed) and move the stores down.
11950 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11952 // Determine whether Dest has exactly two predecessors and, if so, compute
11953 // the other predecessor.
11954 pred_iterator PI = pred_begin(DestBB);
11955 BasicBlock *OtherBB = 0;
11956 if (*PI != StoreBB)
11959 if (PI == pred_end(DestBB))
11962 if (*PI != StoreBB) {
11967 if (++PI != pred_end(DestBB))
11970 // Bail out if all the relevant blocks aren't distinct (this can happen,
11971 // for example, if SI is in an infinite loop)
11972 if (StoreBB == DestBB || OtherBB == DestBB)
11975 // Verify that the other block ends in a branch and is not otherwise empty.
11976 BasicBlock::iterator BBI = OtherBB->getTerminator();
11977 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11978 if (!OtherBr || BBI == OtherBB->begin())
11981 // If the other block ends in an unconditional branch, check for the 'if then
11982 // else' case. there is an instruction before the branch.
11983 StoreInst *OtherStore = 0;
11984 if (OtherBr->isUnconditional()) {
11986 // Skip over debugging info.
11987 while (isa<DbgInfoIntrinsic>(BBI) ||
11988 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11989 if (BBI==OtherBB->begin())
11993 // If this isn't a store, or isn't a store to the same location, bail out.
11994 OtherStore = dyn_cast<StoreInst>(BBI);
11995 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11998 // Otherwise, the other block ended with a conditional branch. If one of the
11999 // destinations is StoreBB, then we have the if/then case.
12000 if (OtherBr->getSuccessor(0) != StoreBB &&
12001 OtherBr->getSuccessor(1) != StoreBB)
12004 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12005 // if/then triangle. See if there is a store to the same ptr as SI that
12006 // lives in OtherBB.
12008 // Check to see if we find the matching store.
12009 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12010 if (OtherStore->getOperand(1) != SI.getOperand(1))
12014 // If we find something that may be using or overwriting the stored
12015 // value, or if we run out of instructions, we can't do the xform.
12016 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12017 BBI == OtherBB->begin())
12021 // In order to eliminate the store in OtherBr, we have to
12022 // make sure nothing reads or overwrites the stored value in
12024 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12025 // FIXME: This should really be AA driven.
12026 if (I->mayReadFromMemory() || I->mayWriteToMemory())
12031 // Insert a PHI node now if we need it.
12032 Value *MergedVal = OtherStore->getOperand(0);
12033 if (MergedVal != SI.getOperand(0)) {
12034 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12035 PN->reserveOperandSpace(2);
12036 PN->addIncoming(SI.getOperand(0), SI.getParent());
12037 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12038 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12041 // Advance to a place where it is safe to insert the new store and
12043 BBI = DestBB->getFirstNonPHI();
12044 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12045 OtherStore->isVolatile()), *BBI);
12047 // Nuke the old stores.
12048 EraseInstFromFunction(SI);
12049 EraseInstFromFunction(*OtherStore);
12055 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12056 // Change br (not X), label True, label False to: br X, label False, True
12058 BasicBlock *TrueDest;
12059 BasicBlock *FalseDest;
12060 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12061 !isa<Constant>(X)) {
12062 // Swap Destinations and condition...
12063 BI.setCondition(X);
12064 BI.setSuccessor(0, FalseDest);
12065 BI.setSuccessor(1, TrueDest);
12069 // Cannonicalize fcmp_one -> fcmp_oeq
12070 FCmpInst::Predicate FPred; Value *Y;
12071 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
12072 TrueDest, FalseDest), *Context))
12073 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12074 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12075 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12076 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12077 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12078 NewSCC->takeName(I);
12079 // Swap Destinations and condition...
12080 BI.setCondition(NewSCC);
12081 BI.setSuccessor(0, FalseDest);
12082 BI.setSuccessor(1, TrueDest);
12083 RemoveFromWorkList(I);
12084 I->eraseFromParent();
12085 AddToWorkList(NewSCC);
12089 // Cannonicalize icmp_ne -> icmp_eq
12090 ICmpInst::Predicate IPred;
12091 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12092 TrueDest, FalseDest), *Context))
12093 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12094 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12095 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12096 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12097 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12098 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12099 NewSCC->takeName(I);
12100 // Swap Destinations and condition...
12101 BI.setCondition(NewSCC);
12102 BI.setSuccessor(0, FalseDest);
12103 BI.setSuccessor(1, TrueDest);
12104 RemoveFromWorkList(I);
12105 I->eraseFromParent();;
12106 AddToWorkList(NewSCC);
12113 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12114 Value *Cond = SI.getCondition();
12115 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12116 if (I->getOpcode() == Instruction::Add)
12117 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12118 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12119 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12121 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12123 SI.setOperand(0, I->getOperand(0));
12131 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12132 Value *Agg = EV.getAggregateOperand();
12134 if (!EV.hasIndices())
12135 return ReplaceInstUsesWith(EV, Agg);
12137 if (Constant *C = dyn_cast<Constant>(Agg)) {
12138 if (isa<UndefValue>(C))
12139 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12141 if (isa<ConstantAggregateZero>(C))
12142 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12144 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12145 // Extract the element indexed by the first index out of the constant
12146 Value *V = C->getOperand(*EV.idx_begin());
12147 if (EV.getNumIndices() > 1)
12148 // Extract the remaining indices out of the constant indexed by the
12150 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12152 return ReplaceInstUsesWith(EV, V);
12154 return 0; // Can't handle other constants
12156 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12157 // We're extracting from an insertvalue instruction, compare the indices
12158 const unsigned *exti, *exte, *insi, *inse;
12159 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12160 exte = EV.idx_end(), inse = IV->idx_end();
12161 exti != exte && insi != inse;
12163 if (*insi != *exti)
12164 // The insert and extract both reference distinctly different elements.
12165 // This means the extract is not influenced by the insert, and we can
12166 // replace the aggregate operand of the extract with the aggregate
12167 // operand of the insert. i.e., replace
12168 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12169 // %E = extractvalue { i32, { i32 } } %I, 0
12171 // %E = extractvalue { i32, { i32 } } %A, 0
12172 return ExtractValueInst::Create(IV->getAggregateOperand(),
12173 EV.idx_begin(), EV.idx_end());
12175 if (exti == exte && insi == inse)
12176 // Both iterators are at the end: Index lists are identical. Replace
12177 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12178 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12180 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12181 if (exti == exte) {
12182 // The extract list is a prefix of the insert list. i.e. replace
12183 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12184 // %E = extractvalue { i32, { i32 } } %I, 1
12186 // %X = extractvalue { i32, { i32 } } %A, 1
12187 // %E = insertvalue { i32 } %X, i32 42, 0
12188 // by switching the order of the insert and extract (though the
12189 // insertvalue should be left in, since it may have other uses).
12190 Value *NewEV = InsertNewInstBefore(
12191 ExtractValueInst::Create(IV->getAggregateOperand(),
12192 EV.idx_begin(), EV.idx_end()),
12194 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12198 // The insert list is a prefix of the extract list
12199 // We can simply remove the common indices from the extract and make it
12200 // operate on the inserted value instead of the insertvalue result.
12202 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12203 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12205 // %E extractvalue { i32 } { i32 42 }, 0
12206 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12209 // Can't simplify extracts from other values. Note that nested extracts are
12210 // already simplified implicitely by the above (extract ( extract (insert) )
12211 // will be translated into extract ( insert ( extract ) ) first and then just
12212 // the value inserted, if appropriate).
12216 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12217 /// is to leave as a vector operation.
12218 static bool CheapToScalarize(Value *V, bool isConstant) {
12219 if (isa<ConstantAggregateZero>(V))
12221 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12222 if (isConstant) return true;
12223 // If all elts are the same, we can extract.
12224 Constant *Op0 = C->getOperand(0);
12225 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12226 if (C->getOperand(i) != Op0)
12230 Instruction *I = dyn_cast<Instruction>(V);
12231 if (!I) return false;
12233 // Insert element gets simplified to the inserted element or is deleted if
12234 // this is constant idx extract element and its a constant idx insertelt.
12235 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12236 isa<ConstantInt>(I->getOperand(2)))
12238 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12240 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12241 if (BO->hasOneUse() &&
12242 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12243 CheapToScalarize(BO->getOperand(1), isConstant)))
12245 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12246 if (CI->hasOneUse() &&
12247 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12248 CheapToScalarize(CI->getOperand(1), isConstant)))
12254 /// Read and decode a shufflevector mask.
12256 /// It turns undef elements into values that are larger than the number of
12257 /// elements in the input.
12258 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12259 unsigned NElts = SVI->getType()->getNumElements();
12260 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12261 return std::vector<unsigned>(NElts, 0);
12262 if (isa<UndefValue>(SVI->getOperand(2)))
12263 return std::vector<unsigned>(NElts, 2*NElts);
12265 std::vector<unsigned> Result;
12266 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12267 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12268 if (isa<UndefValue>(*i))
12269 Result.push_back(NElts*2); // undef -> 8
12271 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12275 /// FindScalarElement - Given a vector and an element number, see if the scalar
12276 /// value is already around as a register, for example if it were inserted then
12277 /// extracted from the vector.
12278 static Value *FindScalarElement(Value *V, unsigned EltNo,
12279 LLVMContext *Context) {
12280 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12281 const VectorType *PTy = cast<VectorType>(V->getType());
12282 unsigned Width = PTy->getNumElements();
12283 if (EltNo >= Width) // Out of range access.
12284 return Context->getUndef(PTy->getElementType());
12286 if (isa<UndefValue>(V))
12287 return Context->getUndef(PTy->getElementType());
12288 else if (isa<ConstantAggregateZero>(V))
12289 return Context->getNullValue(PTy->getElementType());
12290 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12291 return CP->getOperand(EltNo);
12292 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12293 // If this is an insert to a variable element, we don't know what it is.
12294 if (!isa<ConstantInt>(III->getOperand(2)))
12296 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12298 // If this is an insert to the element we are looking for, return the
12300 if (EltNo == IIElt)
12301 return III->getOperand(1);
12303 // Otherwise, the insertelement doesn't modify the value, recurse on its
12305 return FindScalarElement(III->getOperand(0), EltNo, Context);
12306 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12307 unsigned LHSWidth =
12308 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12309 unsigned InEl = getShuffleMask(SVI)[EltNo];
12310 if (InEl < LHSWidth)
12311 return FindScalarElement(SVI->getOperand(0), InEl, Context);
12312 else if (InEl < LHSWidth*2)
12313 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12315 return Context->getUndef(PTy->getElementType());
12318 // Otherwise, we don't know.
12322 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12323 // If vector val is undef, replace extract with scalar undef.
12324 if (isa<UndefValue>(EI.getOperand(0)))
12325 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12327 // If vector val is constant 0, replace extract with scalar 0.
12328 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12329 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12331 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12332 // If vector val is constant with all elements the same, replace EI with
12333 // that element. When the elements are not identical, we cannot replace yet
12334 // (we do that below, but only when the index is constant).
12335 Constant *op0 = C->getOperand(0);
12336 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12337 if (C->getOperand(i) != op0) {
12342 return ReplaceInstUsesWith(EI, op0);
12345 // If extracting a specified index from the vector, see if we can recursively
12346 // find a previously computed scalar that was inserted into the vector.
12347 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12348 unsigned IndexVal = IdxC->getZExtValue();
12349 unsigned VectorWidth =
12350 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12352 // If this is extracting an invalid index, turn this into undef, to avoid
12353 // crashing the code below.
12354 if (IndexVal >= VectorWidth)
12355 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12357 // This instruction only demands the single element from the input vector.
12358 // If the input vector has a single use, simplify it based on this use
12360 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12361 APInt UndefElts(VectorWidth, 0);
12362 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12363 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12364 DemandedMask, UndefElts)) {
12365 EI.setOperand(0, V);
12370 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12371 return ReplaceInstUsesWith(EI, Elt);
12373 // If the this extractelement is directly using a bitcast from a vector of
12374 // the same number of elements, see if we can find the source element from
12375 // it. In this case, we will end up needing to bitcast the scalars.
12376 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12377 if (const VectorType *VT =
12378 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12379 if (VT->getNumElements() == VectorWidth)
12380 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12381 IndexVal, Context))
12382 return new BitCastInst(Elt, EI.getType());
12386 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12387 if (I->hasOneUse()) {
12388 // Push extractelement into predecessor operation if legal and
12389 // profitable to do so
12390 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12391 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12392 if (CheapToScalarize(BO, isConstantElt)) {
12393 ExtractElementInst *newEI0 =
12394 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12395 EI.getName()+".lhs");
12396 ExtractElementInst *newEI1 =
12397 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12398 EI.getName()+".rhs");
12399 InsertNewInstBefore(newEI0, EI);
12400 InsertNewInstBefore(newEI1, EI);
12401 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12403 } else if (isa<LoadInst>(I)) {
12405 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12406 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12407 Context->getPointerType(EI.getType(), AS),EI);
12408 GetElementPtrInst *GEP =
12409 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12410 InsertNewInstBefore(GEP, EI);
12411 return new LoadInst(GEP);
12414 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12415 // Extracting the inserted element?
12416 if (IE->getOperand(2) == EI.getOperand(1))
12417 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12418 // If the inserted and extracted elements are constants, they must not
12419 // be the same value, extract from the pre-inserted value instead.
12420 if (isa<Constant>(IE->getOperand(2)) &&
12421 isa<Constant>(EI.getOperand(1))) {
12422 AddUsesToWorkList(EI);
12423 EI.setOperand(0, IE->getOperand(0));
12426 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12427 // If this is extracting an element from a shufflevector, figure out where
12428 // it came from and extract from the appropriate input element instead.
12429 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12430 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12432 unsigned LHSWidth =
12433 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12435 if (SrcIdx < LHSWidth)
12436 Src = SVI->getOperand(0);
12437 else if (SrcIdx < LHSWidth*2) {
12438 SrcIdx -= LHSWidth;
12439 Src = SVI->getOperand(1);
12441 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12443 return new ExtractElementInst(Src,
12444 Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
12447 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12452 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12453 /// elements from either LHS or RHS, return the shuffle mask and true.
12454 /// Otherwise, return false.
12455 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12456 std::vector<Constant*> &Mask,
12457 LLVMContext *Context) {
12458 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12459 "Invalid CollectSingleShuffleElements");
12460 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12462 if (isa<UndefValue>(V)) {
12463 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12465 } else if (V == LHS) {
12466 for (unsigned i = 0; i != NumElts; ++i)
12467 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12469 } else if (V == RHS) {
12470 for (unsigned i = 0; i != NumElts; ++i)
12471 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12473 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12474 // If this is an insert of an extract from some other vector, include it.
12475 Value *VecOp = IEI->getOperand(0);
12476 Value *ScalarOp = IEI->getOperand(1);
12477 Value *IdxOp = IEI->getOperand(2);
12479 if (!isa<ConstantInt>(IdxOp))
12481 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12483 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12484 // Okay, we can handle this if the vector we are insertinting into is
12485 // transitively ok.
12486 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12487 // If so, update the mask to reflect the inserted undef.
12488 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12491 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12492 if (isa<ConstantInt>(EI->getOperand(1)) &&
12493 EI->getOperand(0)->getType() == V->getType()) {
12494 unsigned ExtractedIdx =
12495 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12497 // This must be extracting from either LHS or RHS.
12498 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12499 // Okay, we can handle this if the vector we are insertinting into is
12500 // transitively ok.
12501 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12502 // If so, update the mask to reflect the inserted value.
12503 if (EI->getOperand(0) == LHS) {
12504 Mask[InsertedIdx % NumElts] =
12505 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12507 assert(EI->getOperand(0) == RHS);
12508 Mask[InsertedIdx % NumElts] =
12509 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12518 // TODO: Handle shufflevector here!
12523 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12524 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12525 /// that computes V and the LHS value of the shuffle.
12526 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12527 Value *&RHS, LLVMContext *Context) {
12528 assert(isa<VectorType>(V->getType()) &&
12529 (RHS == 0 || V->getType() == RHS->getType()) &&
12530 "Invalid shuffle!");
12531 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12533 if (isa<UndefValue>(V)) {
12534 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12536 } else if (isa<ConstantAggregateZero>(V)) {
12537 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12539 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12540 // If this is an insert of an extract from some other vector, include it.
12541 Value *VecOp = IEI->getOperand(0);
12542 Value *ScalarOp = IEI->getOperand(1);
12543 Value *IdxOp = IEI->getOperand(2);
12545 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12546 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12547 EI->getOperand(0)->getType() == V->getType()) {
12548 unsigned ExtractedIdx =
12549 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12550 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12552 // Either the extracted from or inserted into vector must be RHSVec,
12553 // otherwise we'd end up with a shuffle of three inputs.
12554 if (EI->getOperand(0) == RHS || RHS == 0) {
12555 RHS = EI->getOperand(0);
12556 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12557 Mask[InsertedIdx % NumElts] =
12558 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12562 if (VecOp == RHS) {
12563 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12565 // Everything but the extracted element is replaced with the RHS.
12566 for (unsigned i = 0; i != NumElts; ++i) {
12567 if (i != InsertedIdx)
12568 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12573 // If this insertelement is a chain that comes from exactly these two
12574 // vectors, return the vector and the effective shuffle.
12575 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12577 return EI->getOperand(0);
12582 // TODO: Handle shufflevector here!
12584 // Otherwise, can't do anything fancy. Return an identity vector.
12585 for (unsigned i = 0; i != NumElts; ++i)
12586 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12590 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12591 Value *VecOp = IE.getOperand(0);
12592 Value *ScalarOp = IE.getOperand(1);
12593 Value *IdxOp = IE.getOperand(2);
12595 // Inserting an undef or into an undefined place, remove this.
12596 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12597 ReplaceInstUsesWith(IE, VecOp);
12599 // If the inserted element was extracted from some other vector, and if the
12600 // indexes are constant, try to turn this into a shufflevector operation.
12601 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12602 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12603 EI->getOperand(0)->getType() == IE.getType()) {
12604 unsigned NumVectorElts = IE.getType()->getNumElements();
12605 unsigned ExtractedIdx =
12606 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12607 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12609 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12610 return ReplaceInstUsesWith(IE, VecOp);
12612 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12613 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12615 // If we are extracting a value from a vector, then inserting it right
12616 // back into the same place, just use the input vector.
12617 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12618 return ReplaceInstUsesWith(IE, VecOp);
12620 // We could theoretically do this for ANY input. However, doing so could
12621 // turn chains of insertelement instructions into a chain of shufflevector
12622 // instructions, and right now we do not merge shufflevectors. As such,
12623 // only do this in a situation where it is clear that there is benefit.
12624 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12625 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12626 // the values of VecOp, except then one read from EIOp0.
12627 // Build a new shuffle mask.
12628 std::vector<Constant*> Mask;
12629 if (isa<UndefValue>(VecOp))
12630 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12632 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12633 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12636 Mask[InsertedIdx] =
12637 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12638 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12639 Context->getConstantVector(Mask));
12642 // If this insertelement isn't used by some other insertelement, turn it
12643 // (and any insertelements it points to), into one big shuffle.
12644 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12645 std::vector<Constant*> Mask;
12647 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12648 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12649 // We now have a shuffle of LHS, RHS, Mask.
12650 return new ShuffleVectorInst(LHS, RHS,
12651 Context->getConstantVector(Mask));
12656 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12657 APInt UndefElts(VWidth, 0);
12658 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12659 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12666 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12667 Value *LHS = SVI.getOperand(0);
12668 Value *RHS = SVI.getOperand(1);
12669 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12671 bool MadeChange = false;
12673 // Undefined shuffle mask -> undefined value.
12674 if (isa<UndefValue>(SVI.getOperand(2)))
12675 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12677 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12679 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12682 APInt UndefElts(VWidth, 0);
12683 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12684 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12685 LHS = SVI.getOperand(0);
12686 RHS = SVI.getOperand(1);
12690 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12691 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12692 if (LHS == RHS || isa<UndefValue>(LHS)) {
12693 if (isa<UndefValue>(LHS) && LHS == RHS) {
12694 // shuffle(undef,undef,mask) -> undef.
12695 return ReplaceInstUsesWith(SVI, LHS);
12698 // Remap any references to RHS to use LHS.
12699 std::vector<Constant*> Elts;
12700 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12701 if (Mask[i] >= 2*e)
12702 Elts.push_back(Context->getUndef(Type::Int32Ty));
12704 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12705 (Mask[i] < e && isa<UndefValue>(LHS))) {
12706 Mask[i] = 2*e; // Turn into undef.
12707 Elts.push_back(Context->getUndef(Type::Int32Ty));
12709 Mask[i] = Mask[i] % e; // Force to LHS.
12710 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12714 SVI.setOperand(0, SVI.getOperand(1));
12715 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12716 SVI.setOperand(2, Context->getConstantVector(Elts));
12717 LHS = SVI.getOperand(0);
12718 RHS = SVI.getOperand(1);
12722 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12723 bool isLHSID = true, isRHSID = true;
12725 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12726 if (Mask[i] >= e*2) continue; // Ignore undef values.
12727 // Is this an identity shuffle of the LHS value?
12728 isLHSID &= (Mask[i] == i);
12730 // Is this an identity shuffle of the RHS value?
12731 isRHSID &= (Mask[i]-e == i);
12734 // Eliminate identity shuffles.
12735 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12736 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12738 // If the LHS is a shufflevector itself, see if we can combine it with this
12739 // one without producing an unusual shuffle. Here we are really conservative:
12740 // we are absolutely afraid of producing a shuffle mask not in the input
12741 // program, because the code gen may not be smart enough to turn a merged
12742 // shuffle into two specific shuffles: it may produce worse code. As such,
12743 // we only merge two shuffles if the result is one of the two input shuffle
12744 // masks. In this case, merging the shuffles just removes one instruction,
12745 // which we know is safe. This is good for things like turning:
12746 // (splat(splat)) -> splat.
12747 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12748 if (isa<UndefValue>(RHS)) {
12749 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12751 std::vector<unsigned> NewMask;
12752 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12753 if (Mask[i] >= 2*e)
12754 NewMask.push_back(2*e);
12756 NewMask.push_back(LHSMask[Mask[i]]);
12758 // If the result mask is equal to the src shuffle or this shuffle mask, do
12759 // the replacement.
12760 if (NewMask == LHSMask || NewMask == Mask) {
12761 unsigned LHSInNElts =
12762 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12763 std::vector<Constant*> Elts;
12764 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12765 if (NewMask[i] >= LHSInNElts*2) {
12766 Elts.push_back(Context->getUndef(Type::Int32Ty));
12768 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12771 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12772 LHSSVI->getOperand(1),
12773 Context->getConstantVector(Elts));
12778 return MadeChange ? &SVI : 0;
12784 /// TryToSinkInstruction - Try to move the specified instruction from its
12785 /// current block into the beginning of DestBlock, which can only happen if it's
12786 /// safe to move the instruction past all of the instructions between it and the
12787 /// end of its block.
12788 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12789 assert(I->hasOneUse() && "Invariants didn't hold!");
12791 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12792 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12795 // Do not sink alloca instructions out of the entry block.
12796 if (isa<AllocaInst>(I) && I->getParent() ==
12797 &DestBlock->getParent()->getEntryBlock())
12800 // We can only sink load instructions if there is nothing between the load and
12801 // the end of block that could change the value.
12802 if (I->mayReadFromMemory()) {
12803 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12805 if (Scan->mayWriteToMemory())
12809 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12811 CopyPrecedingStopPoint(I, InsertPos);
12812 I->moveBefore(InsertPos);
12818 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12819 /// all reachable code to the worklist.
12821 /// This has a couple of tricks to make the code faster and more powerful. In
12822 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12823 /// them to the worklist (this significantly speeds up instcombine on code where
12824 /// many instructions are dead or constant). Additionally, if we find a branch
12825 /// whose condition is a known constant, we only visit the reachable successors.
12827 static void AddReachableCodeToWorklist(BasicBlock *BB,
12828 SmallPtrSet<BasicBlock*, 64> &Visited,
12830 const TargetData *TD) {
12831 SmallVector<BasicBlock*, 256> Worklist;
12832 Worklist.push_back(BB);
12834 while (!Worklist.empty()) {
12835 BB = Worklist.back();
12836 Worklist.pop_back();
12838 // We have now visited this block! If we've already been here, ignore it.
12839 if (!Visited.insert(BB)) continue;
12841 DbgInfoIntrinsic *DBI_Prev = NULL;
12842 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12843 Instruction *Inst = BBI++;
12845 // DCE instruction if trivially dead.
12846 if (isInstructionTriviallyDead(Inst)) {
12848 DOUT << "IC: DCE: " << *Inst;
12849 Inst->eraseFromParent();
12853 // ConstantProp instruction if trivially constant.
12854 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12855 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12856 Inst->replaceAllUsesWith(C);
12858 Inst->eraseFromParent();
12862 // If there are two consecutive llvm.dbg.stoppoint calls then
12863 // it is likely that the optimizer deleted code in between these
12865 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12868 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12869 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12870 IC.RemoveFromWorkList(DBI_Prev);
12871 DBI_Prev->eraseFromParent();
12873 DBI_Prev = DBI_Next;
12878 IC.AddToWorkList(Inst);
12881 // Recursively visit successors. If this is a branch or switch on a
12882 // constant, only visit the reachable successor.
12883 TerminatorInst *TI = BB->getTerminator();
12884 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12885 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12886 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12887 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12888 Worklist.push_back(ReachableBB);
12891 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12892 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12893 // See if this is an explicit destination.
12894 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12895 if (SI->getCaseValue(i) == Cond) {
12896 BasicBlock *ReachableBB = SI->getSuccessor(i);
12897 Worklist.push_back(ReachableBB);
12901 // Otherwise it is the default destination.
12902 Worklist.push_back(SI->getSuccessor(0));
12907 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12908 Worklist.push_back(TI->getSuccessor(i));
12912 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12913 bool Changed = false;
12914 TD = getAnalysisIfAvailable<TargetData>();
12916 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12917 << F.getNameStr() << "\n");
12920 // Do a depth-first traversal of the function, populate the worklist with
12921 // the reachable instructions. Ignore blocks that are not reachable. Keep
12922 // track of which blocks we visit.
12923 SmallPtrSet<BasicBlock*, 64> Visited;
12924 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12926 // Do a quick scan over the function. If we find any blocks that are
12927 // unreachable, remove any instructions inside of them. This prevents
12928 // the instcombine code from having to deal with some bad special cases.
12929 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12930 if (!Visited.count(BB)) {
12931 Instruction *Term = BB->getTerminator();
12932 while (Term != BB->begin()) { // Remove instrs bottom-up
12933 BasicBlock::iterator I = Term; --I;
12935 DOUT << "IC: DCE: " << *I;
12936 // A debug intrinsic shouldn't force another iteration if we weren't
12937 // going to do one without it.
12938 if (!isa<DbgInfoIntrinsic>(I)) {
12942 if (!I->use_empty())
12943 I->replaceAllUsesWith(Context->getUndef(I->getType()));
12944 I->eraseFromParent();
12949 while (!Worklist.empty()) {
12950 Instruction *I = RemoveOneFromWorkList();
12951 if (I == 0) continue; // skip null values.
12953 // Check to see if we can DCE the instruction.
12954 if (isInstructionTriviallyDead(I)) {
12955 // Add operands to the worklist.
12956 if (I->getNumOperands() < 4)
12957 AddUsesToWorkList(*I);
12960 DOUT << "IC: DCE: " << *I;
12962 I->eraseFromParent();
12963 RemoveFromWorkList(I);
12968 // Instruction isn't dead, see if we can constant propagate it.
12969 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12970 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12972 // Add operands to the worklist.
12973 AddUsesToWorkList(*I);
12974 ReplaceInstUsesWith(*I, C);
12977 I->eraseFromParent();
12978 RemoveFromWorkList(I);
12984 // See if we can constant fold its operands.
12985 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12986 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12987 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12988 F.getContext(), TD))
12995 // See if we can trivially sink this instruction to a successor basic block.
12996 if (I->hasOneUse()) {
12997 BasicBlock *BB = I->getParent();
12998 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12999 if (UserParent != BB) {
13000 bool UserIsSuccessor = false;
13001 // See if the user is one of our successors.
13002 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13003 if (*SI == UserParent) {
13004 UserIsSuccessor = true;
13008 // If the user is one of our immediate successors, and if that successor
13009 // only has us as a predecessors (we'd have to split the critical edge
13010 // otherwise), we can keep going.
13011 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13012 next(pred_begin(UserParent)) == pred_end(UserParent))
13013 // Okay, the CFG is simple enough, try to sink this instruction.
13014 Changed |= TryToSinkInstruction(I, UserParent);
13018 // Now that we have an instruction, try combining it to simplify it...
13022 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13023 if (Instruction *Result = visit(*I)) {
13025 // Should we replace the old instruction with a new one?
13027 DOUT << "IC: Old = " << *I
13028 << " New = " << *Result;
13030 // Everything uses the new instruction now.
13031 I->replaceAllUsesWith(Result);
13033 // Push the new instruction and any users onto the worklist.
13034 AddToWorkList(Result);
13035 AddUsersToWorkList(*Result);
13037 // Move the name to the new instruction first.
13038 Result->takeName(I);
13040 // Insert the new instruction into the basic block...
13041 BasicBlock *InstParent = I->getParent();
13042 BasicBlock::iterator InsertPos = I;
13044 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13045 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13048 InstParent->getInstList().insert(InsertPos, Result);
13050 // Make sure that we reprocess all operands now that we reduced their
13052 AddUsesToWorkList(*I);
13054 // Instructions can end up on the worklist more than once. Make sure
13055 // we do not process an instruction that has been deleted.
13056 RemoveFromWorkList(I);
13058 // Erase the old instruction.
13059 InstParent->getInstList().erase(I);
13062 DOUT << "IC: Mod = " << OrigI
13063 << " New = " << *I;
13066 // If the instruction was modified, it's possible that it is now dead.
13067 // if so, remove it.
13068 if (isInstructionTriviallyDead(I)) {
13069 // Make sure we process all operands now that we are reducing their
13071 AddUsesToWorkList(*I);
13073 // Instructions may end up in the worklist more than once. Erase all
13074 // occurrences of this instruction.
13075 RemoveFromWorkList(I);
13076 I->eraseFromParent();
13079 AddUsersToWorkList(*I);
13086 assert(WorklistMap.empty() && "Worklist empty, but map not?");
13088 // Do an explicit clear, this shrinks the map if needed.
13089 WorklistMap.clear();
13094 bool InstCombiner::runOnFunction(Function &F) {
13095 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13096 Context = &F.getContext();
13098 bool EverMadeChange = false;
13100 // Iterate while there is work to do.
13101 unsigned Iteration = 0;
13102 while (DoOneIteration(F, Iteration++))
13103 EverMadeChange = true;
13104 return EverMadeChange;
13107 FunctionPass *llvm::createInstructionCombiningPass() {
13108 return new InstCombiner();