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 *visitAnd(BinaryOperator &I);
193 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
194 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
195 Value *A, Value *B, Value *C);
196 Instruction *visitOr (BinaryOperator &I);
197 Instruction *visitXor(BinaryOperator &I);
198 Instruction *visitShl(BinaryOperator &I);
199 Instruction *visitAShr(BinaryOperator &I);
200 Instruction *visitLShr(BinaryOperator &I);
201 Instruction *commonShiftTransforms(BinaryOperator &I);
202 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
204 Instruction *visitFCmpInst(FCmpInst &I);
205 Instruction *visitICmpInst(ICmpInst &I);
206 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
207 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
210 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
211 ConstantInt *DivRHS);
213 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
214 ICmpInst::Predicate Cond, Instruction &I);
215 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
217 Instruction *commonCastTransforms(CastInst &CI);
218 Instruction *commonIntCastTransforms(CastInst &CI);
219 Instruction *commonPointerCastTransforms(CastInst &CI);
220 Instruction *visitTrunc(TruncInst &CI);
221 Instruction *visitZExt(ZExtInst &CI);
222 Instruction *visitSExt(SExtInst &CI);
223 Instruction *visitFPTrunc(FPTruncInst &CI);
224 Instruction *visitFPExt(CastInst &CI);
225 Instruction *visitFPToUI(FPToUIInst &FI);
226 Instruction *visitFPToSI(FPToSIInst &FI);
227 Instruction *visitUIToFP(CastInst &CI);
228 Instruction *visitSIToFP(CastInst &CI);
229 Instruction *visitPtrToInt(PtrToIntInst &CI);
230 Instruction *visitIntToPtr(IntToPtrInst &CI);
231 Instruction *visitBitCast(BitCastInst &CI);
232 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
234 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
235 Instruction *visitSelectInst(SelectInst &SI);
236 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
237 Instruction *visitCallInst(CallInst &CI);
238 Instruction *visitInvokeInst(InvokeInst &II);
239 Instruction *visitPHINode(PHINode &PN);
240 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
241 Instruction *visitAllocationInst(AllocationInst &AI);
242 Instruction *visitFreeInst(FreeInst &FI);
243 Instruction *visitLoadInst(LoadInst &LI);
244 Instruction *visitStoreInst(StoreInst &SI);
245 Instruction *visitBranchInst(BranchInst &BI);
246 Instruction *visitSwitchInst(SwitchInst &SI);
247 Instruction *visitInsertElementInst(InsertElementInst &IE);
248 Instruction *visitExtractElementInst(ExtractElementInst &EI);
249 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
250 Instruction *visitExtractValueInst(ExtractValueInst &EV);
252 // visitInstruction - Specify what to return for unhandled instructions...
253 Instruction *visitInstruction(Instruction &I) { return 0; }
256 Instruction *visitCallSite(CallSite CS);
257 bool transformConstExprCastCall(CallSite CS);
258 Instruction *transformCallThroughTrampoline(CallSite CS);
259 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
260 bool DoXform = true);
261 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
262 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
266 // InsertNewInstBefore - insert an instruction New before instruction Old
267 // in the program. Add the new instruction to the worklist.
269 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
270 assert(New && New->getParent() == 0 &&
271 "New instruction already inserted into a basic block!");
272 BasicBlock *BB = Old.getParent();
273 BB->getInstList().insert(&Old, New); // Insert inst
278 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
279 /// This also adds the cast to the worklist. Finally, this returns the
281 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
283 if (V->getType() == Ty) return V;
285 if (Constant *CV = dyn_cast<Constant>(V))
286 return Context->getConstantExprCast(opc, CV, Ty);
288 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
293 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
294 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
298 // ReplaceInstUsesWith - This method is to be used when an instruction is
299 // found to be dead, replacable with another preexisting expression. Here
300 // we add all uses of I to the worklist, replace all uses of I with the new
301 // value, then return I, so that the inst combiner will know that I was
304 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
305 AddUsersToWorkList(I); // Add all modified instrs to worklist
307 I.replaceAllUsesWith(V);
310 // If we are replacing the instruction with itself, this must be in a
311 // segment of unreachable code, so just clobber the instruction.
312 I.replaceAllUsesWith(Context->getUndef(I.getType()));
317 // EraseInstFromFunction - When dealing with an instruction that has side
318 // effects or produces a void value, we can't rely on DCE to delete the
319 // instruction. Instead, visit methods should return the value returned by
321 Instruction *EraseInstFromFunction(Instruction &I) {
322 assert(I.use_empty() && "Cannot erase instruction that is used!");
323 AddUsesToWorkList(I);
324 RemoveFromWorkList(&I);
326 return 0; // Don't do anything with FI
329 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330 APInt &KnownOne, unsigned Depth = 0) const {
331 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
334 bool MaskedValueIsZero(Value *V, const APInt &Mask,
335 unsigned Depth = 0) const {
336 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
338 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339 return llvm::ComputeNumSignBits(Op, TD, Depth);
344 /// SimplifyCommutative - This performs a few simplifications for
345 /// commutative operators.
346 bool SimplifyCommutative(BinaryOperator &I);
348 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
349 /// most-complex to least-complex order.
350 bool SimplifyCompare(CmpInst &I);
352 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
353 /// based on the demanded bits.
354 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
355 APInt& KnownZero, APInt& KnownOne,
357 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
358 APInt& KnownZero, APInt& KnownOne,
361 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
362 /// SimplifyDemandedBits knows about. See if the instruction has any
363 /// properties that allow us to simplify its operands.
364 bool SimplifyDemandedInstructionBits(Instruction &Inst);
366 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
367 APInt& UndefElts, unsigned Depth = 0);
369 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370 // PHI node as operand #0, see if we can fold the instruction into the PHI
371 // (which is only possible if all operands to the PHI are constants).
372 Instruction *FoldOpIntoPhi(Instruction &I);
374 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375 // operator and they all are only used by the PHI, PHI together their
376 // inputs, and do the operation once, to the result of the PHI.
377 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
378 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
379 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
382 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
383 ConstantInt *AndRHS, BinaryOperator &TheAnd);
385 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
386 bool isSub, Instruction &I);
387 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
388 bool isSigned, bool Inside, Instruction &IB);
389 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
390 Instruction *MatchBSwap(BinaryOperator &I);
391 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
392 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
393 Instruction *SimplifyMemSet(MemSetInst *MI);
396 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
398 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
399 unsigned CastOpc, int &NumCastsRemoved);
400 unsigned GetOrEnforceKnownAlignment(Value *V,
401 unsigned PrefAlign = 0);
406 char InstCombiner::ID = 0;
407 static RegisterPass<InstCombiner>
408 X("instcombine", "Combine redundant instructions");
410 // getComplexity: Assign a complexity or rank value to LLVM Values...
411 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
412 static unsigned getComplexity(LLVMContext *Context, Value *V) {
413 if (isa<Instruction>(V)) {
414 if (BinaryOperator::isNeg(V) ||
415 BinaryOperator::isFNeg(V) ||
416 BinaryOperator::isNot(V))
420 if (isa<Argument>(V)) return 3;
421 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
424 // isOnlyUse - Return true if this instruction will be deleted if we stop using
426 static bool isOnlyUse(Value *V) {
427 return V->hasOneUse() || isa<Constant>(V);
430 // getPromotedType - Return the specified type promoted as it would be to pass
431 // though a va_arg area...
432 static const Type *getPromotedType(const Type *Ty) {
433 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
434 if (ITy->getBitWidth() < 32)
435 return Type::Int32Ty;
440 /// getBitCastOperand - If the specified operand is a CastInst, a constant
441 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
442 /// operand value, otherwise return null.
443 static Value *getBitCastOperand(Value *V) {
444 if (Operator *O = dyn_cast<Operator>(V)) {
445 if (O->getOpcode() == Instruction::BitCast)
446 return O->getOperand(0);
447 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
448 if (GEP->hasAllZeroIndices())
449 return GEP->getPointerOperand();
454 /// This function is a wrapper around CastInst::isEliminableCastPair. It
455 /// simply extracts arguments and returns what that function returns.
456 static Instruction::CastOps
457 isEliminableCastPair(
458 const CastInst *CI, ///< The first cast instruction
459 unsigned opcode, ///< The opcode of the second cast instruction
460 const Type *DstTy, ///< The target type for the second cast instruction
461 TargetData *TD ///< The target data for pointer size
464 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
465 const Type *MidTy = CI->getType(); // B from above
467 // Get the opcodes of the two Cast instructions
468 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
469 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
471 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
473 TD ? TD->getIntPtrType() : 0);
475 // We don't want to form an inttoptr or ptrtoint that converts to an integer
476 // type that differs from the pointer size.
477 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
478 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
481 return Instruction::CastOps(Res);
484 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
485 /// in any code being generated. It does not require codegen if V is simple
486 /// enough or if the cast can be folded into other casts.
487 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
488 const Type *Ty, TargetData *TD) {
489 if (V->getType() == Ty || isa<Constant>(V)) return false;
491 // If this is another cast that can be eliminated, it isn't codegen either.
492 if (const CastInst *CI = dyn_cast<CastInst>(V))
493 if (isEliminableCastPair(CI, opcode, Ty, TD))
498 // SimplifyCommutative - This performs a few simplifications for commutative
501 // 1. Order operands such that they are listed from right (least complex) to
502 // left (most complex). This puts constants before unary operators before
505 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
506 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
508 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
509 bool Changed = false;
510 if (getComplexity(Context, I.getOperand(0)) <
511 getComplexity(Context, I.getOperand(1)))
512 Changed = !I.swapOperands();
514 if (!I.isAssociative()) return Changed;
515 Instruction::BinaryOps Opcode = I.getOpcode();
516 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
517 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
518 if (isa<Constant>(I.getOperand(1))) {
519 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
520 cast<Constant>(I.getOperand(1)),
521 cast<Constant>(Op->getOperand(1)));
522 I.setOperand(0, Op->getOperand(0));
523 I.setOperand(1, Folded);
525 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
526 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
527 isOnlyUse(Op) && isOnlyUse(Op1)) {
528 Constant *C1 = cast<Constant>(Op->getOperand(1));
529 Constant *C2 = cast<Constant>(Op1->getOperand(1));
531 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
532 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
533 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
537 I.setOperand(0, New);
538 I.setOperand(1, Folded);
545 /// SimplifyCompare - For a CmpInst this function just orders the operands
546 /// so that theyare listed from right (least complex) to left (most complex).
547 /// This puts constants before unary operators before binary operators.
548 bool InstCombiner::SimplifyCompare(CmpInst &I) {
549 if (getComplexity(Context, I.getOperand(0)) >=
550 getComplexity(Context, I.getOperand(1)))
553 // Compare instructions are not associative so there's nothing else we can do.
557 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
558 // if the LHS is a constant zero (which is the 'negate' form).
560 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
561 if (BinaryOperator::isNeg(V))
562 return BinaryOperator::getNegArgument(V);
564 // Constants can be considered to be negated values if they can be folded.
565 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
566 return Context->getConstantExprNeg(C);
568 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
569 if (C->getType()->getElementType()->isInteger())
570 return Context->getConstantExprNeg(C);
575 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
576 // instruction if the LHS is a constant negative zero (which is the 'negate'
579 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
580 if (BinaryOperator::isFNeg(V))
581 return BinaryOperator::getFNegArgument(V);
583 // Constants can be considered to be negated values if they can be folded.
584 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
585 return Context->getConstantExprFNeg(C);
587 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
588 if (C->getType()->getElementType()->isFloatingPoint())
589 return Context->getConstantExprFNeg(C);
594 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
595 if (BinaryOperator::isNot(V))
596 return BinaryOperator::getNotArgument(V);
598 // Constants can be considered to be not'ed values...
599 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
600 return Context->getConstantInt(~C->getValue());
604 // dyn_castFoldableMul - If this value is a multiply that can be folded into
605 // other computations (because it has a constant operand), return the
606 // non-constant operand of the multiply, and set CST to point to the multiplier.
607 // Otherwise, return null.
609 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
610 LLVMContext *Context) {
611 if (V->hasOneUse() && V->getType()->isInteger())
612 if (Instruction *I = dyn_cast<Instruction>(V)) {
613 if (I->getOpcode() == Instruction::Mul)
614 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
615 return I->getOperand(0);
616 if (I->getOpcode() == Instruction::Shl)
617 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
618 // The multiplier is really 1 << CST.
619 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
620 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
621 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
622 return I->getOperand(0);
628 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
629 /// expression, return it.
630 static User *dyn_castGetElementPtr(Value *V) {
631 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
632 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
633 if (CE->getOpcode() == Instruction::GetElementPtr)
634 return cast<User>(V);
638 /// AddOne - Add one to a ConstantInt
639 static Constant *AddOne(Constant *C, LLVMContext *Context) {
640 return Context->getConstantExprAdd(C,
641 Context->getConstantInt(C->getType(), 1));
643 /// SubOne - Subtract one from a ConstantInt
644 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
645 return Context->getConstantExprSub(C,
646 Context->getConstantInt(C->getType(), 1));
648 /// MultiplyOverflows - True if the multiply can not be expressed in an int
650 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
651 LLVMContext *Context) {
652 uint32_t W = C1->getBitWidth();
653 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
662 APInt MulExt = LHSExt * RHSExt;
665 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
666 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
667 return MulExt.slt(Min) || MulExt.sgt(Max);
669 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
673 /// ShrinkDemandedConstant - Check to see if the specified operand of the
674 /// specified instruction is a constant integer. If so, check to see if there
675 /// are any bits set in the constant that are not demanded. If so, shrink the
676 /// constant and return true.
677 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
678 APInt Demanded, LLVMContext *Context) {
679 assert(I && "No instruction?");
680 assert(OpNo < I->getNumOperands() && "Operand index too large");
682 // If the operand is not a constant integer, nothing to do.
683 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
684 if (!OpC) return false;
686 // If there are no bits set that aren't demanded, nothing to do.
687 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
688 if ((~Demanded & OpC->getValue()) == 0)
691 // This instruction is producing bits that are not demanded. Shrink the RHS.
692 Demanded &= OpC->getValue();
693 I->setOperand(OpNo, Context->getConstantInt(Demanded));
697 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
698 // set of known zero and one bits, compute the maximum and minimum values that
699 // could have the specified known zero and known one bits, returning them in
701 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
702 const APInt& KnownOne,
703 APInt& Min, APInt& Max) {
704 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
705 KnownZero.getBitWidth() == Min.getBitWidth() &&
706 KnownZero.getBitWidth() == Max.getBitWidth() &&
707 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
708 APInt UnknownBits = ~(KnownZero|KnownOne);
710 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
711 // bit if it is unknown.
713 Max = KnownOne|UnknownBits;
715 if (UnknownBits.isNegative()) { // Sign bit is unknown
716 Min.set(Min.getBitWidth()-1);
717 Max.clear(Max.getBitWidth()-1);
721 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
722 // a set of known zero and one bits, compute the maximum and minimum values that
723 // could have the specified known zero and known one bits, returning them in
725 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
726 const APInt &KnownOne,
727 APInt &Min, APInt &Max) {
728 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
729 KnownZero.getBitWidth() == Min.getBitWidth() &&
730 KnownZero.getBitWidth() == Max.getBitWidth() &&
731 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
732 APInt UnknownBits = ~(KnownZero|KnownOne);
734 // The minimum value is when the unknown bits are all zeros.
736 // The maximum value is when the unknown bits are all ones.
737 Max = KnownOne|UnknownBits;
740 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
741 /// SimplifyDemandedBits knows about. See if the instruction has any
742 /// properties that allow us to simplify its operands.
743 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
744 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
745 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
746 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
748 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
749 KnownZero, KnownOne, 0);
750 if (V == 0) return false;
751 if (V == &Inst) return true;
752 ReplaceInstUsesWith(Inst, V);
756 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
757 /// specified instruction operand if possible, updating it in place. It returns
758 /// true if it made any change and false otherwise.
759 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
760 APInt &KnownZero, APInt &KnownOne,
762 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
763 KnownZero, KnownOne, Depth);
764 if (NewVal == 0) return false;
770 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
771 /// value based on the demanded bits. When this function is called, it is known
772 /// that only the bits set in DemandedMask of the result of V are ever used
773 /// downstream. Consequently, depending on the mask and V, it may be possible
774 /// to replace V with a constant or one of its operands. In such cases, this
775 /// function does the replacement and returns true. In all other cases, it
776 /// returns false after analyzing the expression and setting KnownOne and known
777 /// to be one in the expression. KnownZero contains all the bits that are known
778 /// to be zero in the expression. These are provided to potentially allow the
779 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
780 /// the expression. KnownOne and KnownZero always follow the invariant that
781 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
782 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
783 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
784 /// and KnownOne must all be the same.
786 /// This returns null if it did not change anything and it permits no
787 /// simplification. This returns V itself if it did some simplification of V's
788 /// operands based on the information about what bits are demanded. This returns
789 /// some other non-null value if it found out that V is equal to another value
790 /// in the context where the specified bits are demanded, but not for all users.
791 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
792 APInt &KnownZero, APInt &KnownOne,
794 assert(V != 0 && "Null pointer of Value???");
795 assert(Depth <= 6 && "Limit Search Depth");
796 uint32_t BitWidth = DemandedMask.getBitWidth();
797 const Type *VTy = V->getType();
798 assert((TD || !isa<PointerType>(VTy)) &&
799 "SimplifyDemandedBits needs to know bit widths!");
800 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
801 (!VTy->isIntOrIntVector() ||
802 VTy->getScalarSizeInBits() == BitWidth) &&
803 KnownZero.getBitWidth() == BitWidth &&
804 KnownOne.getBitWidth() == BitWidth &&
805 "Value *V, DemandedMask, KnownZero and KnownOne "
806 "must have same BitWidth");
807 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
808 // We know all of the bits for a constant!
809 KnownOne = CI->getValue() & DemandedMask;
810 KnownZero = ~KnownOne & DemandedMask;
813 if (isa<ConstantPointerNull>(V)) {
814 // We know all of the bits for a constant!
816 KnownZero = DemandedMask;
822 if (DemandedMask == 0) { // Not demanding any bits from V.
823 if (isa<UndefValue>(V))
825 return Context->getUndef(VTy);
828 if (Depth == 6) // Limit search depth.
831 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
832 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
834 Instruction *I = dyn_cast<Instruction>(V);
836 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
837 return 0; // Only analyze instructions.
840 // If there are multiple uses of this value and we aren't at the root, then
841 // we can't do any simplifications of the operands, because DemandedMask
842 // only reflects the bits demanded by *one* of the users.
843 if (Depth != 0 && !I->hasOneUse()) {
844 // Despite the fact that we can't simplify this instruction in all User's
845 // context, we can at least compute the knownzero/knownone bits, and we can
846 // do simplifications that apply to *just* the one user if we know that
847 // this instruction has a simpler value in that context.
848 if (I->getOpcode() == Instruction::And) {
849 // If either the LHS or the RHS are Zero, the result is zero.
850 ComputeMaskedBits(I->getOperand(1), DemandedMask,
851 RHSKnownZero, RHSKnownOne, Depth+1);
852 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
853 LHSKnownZero, LHSKnownOne, Depth+1);
855 // If all of the demanded bits are known 1 on one side, return the other.
856 // These bits cannot contribute to the result of the 'and' in this
858 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
859 (DemandedMask & ~LHSKnownZero))
860 return I->getOperand(0);
861 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
862 (DemandedMask & ~RHSKnownZero))
863 return I->getOperand(1);
865 // If all of the demanded bits in the inputs are known zeros, return zero.
866 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
867 return Context->getNullValue(VTy);
869 } else if (I->getOpcode() == Instruction::Or) {
870 // We can simplify (X|Y) -> X or Y in the user's context if we know that
871 // only bits from X or Y are demanded.
873 // If either the LHS or the RHS are One, the result is One.
874 ComputeMaskedBits(I->getOperand(1), DemandedMask,
875 RHSKnownZero, RHSKnownOne, Depth+1);
876 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
877 LHSKnownZero, LHSKnownOne, Depth+1);
879 // If all of the demanded bits are known zero on one side, return the
880 // other. These bits cannot contribute to the result of the 'or' in this
882 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
883 (DemandedMask & ~LHSKnownOne))
884 return I->getOperand(0);
885 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
886 (DemandedMask & ~RHSKnownOne))
887 return I->getOperand(1);
889 // If all of the potentially set bits on one side are known to be set on
890 // the other side, just use the 'other' side.
891 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
892 (DemandedMask & (~RHSKnownZero)))
893 return I->getOperand(0);
894 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
895 (DemandedMask & (~LHSKnownZero)))
896 return I->getOperand(1);
899 // Compute the KnownZero/KnownOne bits to simplify things downstream.
900 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
904 // If this is the root being simplified, allow it to have multiple uses,
905 // just set the DemandedMask to all bits so that we can try to simplify the
906 // operands. This allows visitTruncInst (for example) to simplify the
907 // operand of a trunc without duplicating all the logic below.
908 if (Depth == 0 && !V->hasOneUse())
909 DemandedMask = APInt::getAllOnesValue(BitWidth);
911 switch (I->getOpcode()) {
913 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
915 case Instruction::And:
916 // If either the LHS or the RHS are Zero, the result is zero.
917 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
918 RHSKnownZero, RHSKnownOne, Depth+1) ||
919 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
920 LHSKnownZero, LHSKnownOne, Depth+1))
922 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
923 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
925 // If all of the demanded bits are known 1 on one side, return the other.
926 // These bits cannot contribute to the result of the 'and'.
927 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
928 (DemandedMask & ~LHSKnownZero))
929 return I->getOperand(0);
930 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
931 (DemandedMask & ~RHSKnownZero))
932 return I->getOperand(1);
934 // If all of the demanded bits in the inputs are known zeros, return zero.
935 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
936 return Context->getNullValue(VTy);
938 // If the RHS is a constant, see if we can simplify it.
939 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
942 // Output known-1 bits are only known if set in both the LHS & RHS.
943 RHSKnownOne &= LHSKnownOne;
944 // Output known-0 are known to be clear if zero in either the LHS | RHS.
945 RHSKnownZero |= LHSKnownZero;
947 case Instruction::Or:
948 // If either the LHS or the RHS are One, the result is One.
949 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
950 RHSKnownZero, RHSKnownOne, Depth+1) ||
951 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
952 LHSKnownZero, LHSKnownOne, Depth+1))
954 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
955 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
957 // If all of the demanded bits are known zero on one side, return the other.
958 // These bits cannot contribute to the result of the 'or'.
959 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
960 (DemandedMask & ~LHSKnownOne))
961 return I->getOperand(0);
962 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
963 (DemandedMask & ~RHSKnownOne))
964 return I->getOperand(1);
966 // If all of the potentially set bits on one side are known to be set on
967 // the other side, just use the 'other' side.
968 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
969 (DemandedMask & (~RHSKnownZero)))
970 return I->getOperand(0);
971 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
972 (DemandedMask & (~LHSKnownZero)))
973 return I->getOperand(1);
975 // If the RHS is a constant, see if we can simplify it.
976 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
979 // Output known-0 bits are only known if clear in both the LHS & RHS.
980 RHSKnownZero &= LHSKnownZero;
981 // Output known-1 are known to be set if set in either the LHS | RHS.
982 RHSKnownOne |= LHSKnownOne;
984 case Instruction::Xor: {
985 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
986 RHSKnownZero, RHSKnownOne, Depth+1) ||
987 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
988 LHSKnownZero, LHSKnownOne, Depth+1))
990 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
991 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
993 // If all of the demanded bits are known zero on one side, return the other.
994 // These bits cannot contribute to the result of the 'xor'.
995 if ((DemandedMask & RHSKnownZero) == DemandedMask)
996 return I->getOperand(0);
997 if ((DemandedMask & LHSKnownZero) == DemandedMask)
998 return I->getOperand(1);
1000 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1001 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1002 (RHSKnownOne & LHSKnownOne);
1003 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1004 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1005 (RHSKnownOne & LHSKnownZero);
1007 // If all of the demanded bits are known to be zero on one side or the
1008 // other, turn this into an *inclusive* or.
1009 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1010 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1012 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1014 return InsertNewInstBefore(Or, *I);
1017 // If all of the demanded bits on one side are known, and all of the set
1018 // bits on that side are also known to be set on the other side, turn this
1019 // into an AND, as we know the bits will be cleared.
1020 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1021 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1023 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1024 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1026 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1027 return InsertNewInstBefore(And, *I);
1031 // If the RHS is a constant, see if we can simplify it.
1032 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1033 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1036 RHSKnownZero = KnownZeroOut;
1037 RHSKnownOne = KnownOneOut;
1040 case Instruction::Select:
1041 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1042 RHSKnownZero, RHSKnownOne, Depth+1) ||
1043 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1044 LHSKnownZero, LHSKnownOne, Depth+1))
1046 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1047 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1049 // If the operands are constants, see if we can simplify them.
1050 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1051 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1054 // Only known if known in both the LHS and RHS.
1055 RHSKnownOne &= LHSKnownOne;
1056 RHSKnownZero &= LHSKnownZero;
1058 case Instruction::Trunc: {
1059 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1060 DemandedMask.zext(truncBf);
1061 RHSKnownZero.zext(truncBf);
1062 RHSKnownOne.zext(truncBf);
1063 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1064 RHSKnownZero, RHSKnownOne, Depth+1))
1066 DemandedMask.trunc(BitWidth);
1067 RHSKnownZero.trunc(BitWidth);
1068 RHSKnownOne.trunc(BitWidth);
1069 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1072 case Instruction::BitCast:
1073 if (!I->getOperand(0)->getType()->isIntOrIntVector())
1074 return false; // vector->int or fp->int?
1076 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1077 if (const VectorType *SrcVTy =
1078 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1079 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1080 // Don't touch a bitcast between vectors of different element counts.
1083 // Don't touch a scalar-to-vector bitcast.
1085 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1086 // Don't touch a vector-to-scalar bitcast.
1089 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1090 RHSKnownZero, RHSKnownOne, Depth+1))
1092 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1094 case Instruction::ZExt: {
1095 // Compute the bits in the result that are not present in the input.
1096 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1098 DemandedMask.trunc(SrcBitWidth);
1099 RHSKnownZero.trunc(SrcBitWidth);
1100 RHSKnownOne.trunc(SrcBitWidth);
1101 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1102 RHSKnownZero, RHSKnownOne, Depth+1))
1104 DemandedMask.zext(BitWidth);
1105 RHSKnownZero.zext(BitWidth);
1106 RHSKnownOne.zext(BitWidth);
1107 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1108 // The top bits are known to be zero.
1109 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1112 case Instruction::SExt: {
1113 // Compute the bits in the result that are not present in the input.
1114 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1116 APInt InputDemandedBits = DemandedMask &
1117 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1119 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1120 // If any of the sign extended bits are demanded, we know that the sign
1122 if ((NewBits & DemandedMask) != 0)
1123 InputDemandedBits.set(SrcBitWidth-1);
1125 InputDemandedBits.trunc(SrcBitWidth);
1126 RHSKnownZero.trunc(SrcBitWidth);
1127 RHSKnownOne.trunc(SrcBitWidth);
1128 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1129 RHSKnownZero, RHSKnownOne, Depth+1))
1131 InputDemandedBits.zext(BitWidth);
1132 RHSKnownZero.zext(BitWidth);
1133 RHSKnownOne.zext(BitWidth);
1134 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1136 // If the sign bit of the input is known set or clear, then we know the
1137 // top bits of the result.
1139 // If the input sign bit is known zero, or if the NewBits are not demanded
1140 // convert this into a zero extension.
1141 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1142 // Convert to ZExt cast
1143 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1144 return InsertNewInstBefore(NewCast, *I);
1145 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1146 RHSKnownOne |= NewBits;
1150 case Instruction::Add: {
1151 // Figure out what the input bits are. If the top bits of the and result
1152 // are not demanded, then the add doesn't demand them from its input
1154 unsigned NLZ = DemandedMask.countLeadingZeros();
1156 // If there is a constant on the RHS, there are a variety of xformations
1158 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159 // If null, this should be simplified elsewhere. Some of the xforms here
1160 // won't work if the RHS is zero.
1164 // If the top bit of the output is demanded, demand everything from the
1165 // input. Otherwise, we demand all the input bits except NLZ top bits.
1166 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1168 // Find information about known zero/one bits in the input.
1169 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1170 LHSKnownZero, LHSKnownOne, Depth+1))
1173 // If the RHS of the add has bits set that can't affect the input, reduce
1175 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1178 // Avoid excess work.
1179 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1182 // Turn it into OR if input bits are zero.
1183 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1185 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1187 return InsertNewInstBefore(Or, *I);
1190 // We can say something about the output known-zero and known-one bits,
1191 // depending on potential carries from the input constant and the
1192 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1193 // bits set and the RHS constant is 0x01001, then we know we have a known
1194 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1196 // To compute this, we first compute the potential carry bits. These are
1197 // the bits which may be modified. I'm not aware of a better way to do
1199 const APInt &RHSVal = RHS->getValue();
1200 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1202 // Now that we know which bits have carries, compute the known-1/0 sets.
1204 // Bits are known one if they are known zero in one operand and one in the
1205 // other, and there is no input carry.
1206 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1207 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1209 // Bits are known zero if they are known zero in both operands and there
1210 // is no input carry.
1211 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1213 // If the high-bits of this ADD are not demanded, then it does not demand
1214 // the high bits of its LHS or RHS.
1215 if (DemandedMask[BitWidth-1] == 0) {
1216 // Right fill the mask of bits for this ADD to demand the most
1217 // significant bit and all those below it.
1218 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1219 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1220 LHSKnownZero, LHSKnownOne, Depth+1) ||
1221 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1222 LHSKnownZero, LHSKnownOne, Depth+1))
1228 case Instruction::Sub:
1229 // If the high-bits of this SUB are not demanded, then it does not demand
1230 // the high bits of its LHS or RHS.
1231 if (DemandedMask[BitWidth-1] == 0) {
1232 // Right fill the mask of bits for this SUB to demand the most
1233 // significant bit and all those below it.
1234 uint32_t NLZ = DemandedMask.countLeadingZeros();
1235 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1236 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1237 LHSKnownZero, LHSKnownOne, Depth+1) ||
1238 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1239 LHSKnownZero, LHSKnownOne, Depth+1))
1242 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1243 // the known zeros and ones.
1244 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1246 case Instruction::Shl:
1247 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1248 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1249 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1250 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1251 RHSKnownZero, RHSKnownOne, Depth+1))
1253 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1254 RHSKnownZero <<= ShiftAmt;
1255 RHSKnownOne <<= ShiftAmt;
1256 // low bits known zero.
1258 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1261 case Instruction::LShr:
1262 // For a logical shift right
1263 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1264 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1266 // Unsigned shift right.
1267 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1268 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1269 RHSKnownZero, RHSKnownOne, Depth+1))
1271 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1272 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1273 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1275 // Compute the new bits that are at the top now.
1276 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1277 RHSKnownZero |= HighBits; // high bits known zero.
1281 case Instruction::AShr:
1282 // If this is an arithmetic shift right and only the low-bit is set, we can
1283 // always convert this into a logical shr, even if the shift amount is
1284 // variable. The low bit of the shift cannot be an input sign bit unless
1285 // the shift amount is >= the size of the datatype, which is undefined.
1286 if (DemandedMask == 1) {
1287 // Perform the logical shift right.
1288 Instruction *NewVal = BinaryOperator::CreateLShr(
1289 I->getOperand(0), I->getOperand(1), I->getName());
1290 return InsertNewInstBefore(NewVal, *I);
1293 // If the sign bit is the only bit demanded by this ashr, then there is no
1294 // need to do it, the shift doesn't change the high bit.
1295 if (DemandedMask.isSignBit())
1296 return I->getOperand(0);
1298 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1299 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1301 // Signed shift right.
1302 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1303 // If any of the "high bits" are demanded, we should set the sign bit as
1305 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1306 DemandedMaskIn.set(BitWidth-1);
1307 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1308 RHSKnownZero, RHSKnownOne, Depth+1))
1310 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1311 // Compute the new bits that are at the top now.
1312 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1313 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1314 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1316 // Handle the sign bits.
1317 APInt SignBit(APInt::getSignBit(BitWidth));
1318 // Adjust to where it is now in the mask.
1319 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1321 // If the input sign bit is known to be zero, or if none of the top bits
1322 // are demanded, turn this into an unsigned shift right.
1323 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1324 (HighBits & ~DemandedMask) == HighBits) {
1325 // Perform the logical shift right.
1326 Instruction *NewVal = BinaryOperator::CreateLShr(
1327 I->getOperand(0), SA, I->getName());
1328 return InsertNewInstBefore(NewVal, *I);
1329 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1330 RHSKnownOne |= HighBits;
1334 case Instruction::SRem:
1335 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1336 APInt RA = Rem->getValue().abs();
1337 if (RA.isPowerOf2()) {
1338 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
1339 return I->getOperand(0);
1341 APInt LowBits = RA - 1;
1342 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1343 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1344 LHSKnownZero, LHSKnownOne, Depth+1))
1347 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1348 LHSKnownZero |= ~LowBits;
1350 KnownZero |= LHSKnownZero & DemandedMask;
1352 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
1356 case Instruction::URem: {
1357 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1358 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1359 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1360 KnownZero2, KnownOne2, Depth+1) ||
1361 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1362 KnownZero2, KnownOne2, Depth+1))
1365 unsigned Leaders = KnownZero2.countLeadingOnes();
1366 Leaders = std::max(Leaders,
1367 KnownZero2.countLeadingOnes());
1368 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1371 case Instruction::Call:
1372 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1373 switch (II->getIntrinsicID()) {
1375 case Intrinsic::bswap: {
1376 // If the only bits demanded come from one byte of the bswap result,
1377 // just shift the input byte into position to eliminate the bswap.
1378 unsigned NLZ = DemandedMask.countLeadingZeros();
1379 unsigned NTZ = DemandedMask.countTrailingZeros();
1381 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1382 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1383 // have 14 leading zeros, round to 8.
1386 // If we need exactly one byte, we can do this transformation.
1387 if (BitWidth-NLZ-NTZ == 8) {
1388 unsigned ResultBit = NTZ;
1389 unsigned InputBit = BitWidth-NTZ-8;
1391 // Replace this with either a left or right shift to get the byte into
1393 Instruction *NewVal;
1394 if (InputBit > ResultBit)
1395 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1396 Context->getConstantInt(I->getType(), InputBit-ResultBit));
1398 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1399 Context->getConstantInt(I->getType(), ResultBit-InputBit));
1400 NewVal->takeName(I);
1401 return InsertNewInstBefore(NewVal, *I);
1404 // TODO: Could compute known zero/one bits based on the input.
1409 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1413 // If the client is only demanding bits that we know, return the known
1415 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1416 Constant *C = Context->getConstantInt(RHSKnownOne);
1417 if (isa<PointerType>(V->getType()))
1418 C = Context->getConstantExprIntToPtr(C, V->getType());
1425 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1426 /// any number of elements. DemandedElts contains the set of elements that are
1427 /// actually used by the caller. This method analyzes which elements of the
1428 /// operand are undef and returns that information in UndefElts.
1430 /// If the information about demanded elements can be used to simplify the
1431 /// operation, the operation is simplified, then the resultant value is
1432 /// returned. This returns null if no change was made.
1433 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1436 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1437 APInt EltMask(APInt::getAllOnesValue(VWidth));
1438 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1440 if (isa<UndefValue>(V)) {
1441 // If the entire vector is undefined, just return this info.
1442 UndefElts = EltMask;
1444 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1445 UndefElts = EltMask;
1446 return Context->getUndef(V->getType());
1450 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1451 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1452 Constant *Undef = Context->getUndef(EltTy);
1454 std::vector<Constant*> Elts;
1455 for (unsigned i = 0; i != VWidth; ++i)
1456 if (!DemandedElts[i]) { // If not demanded, set to undef.
1457 Elts.push_back(Undef);
1459 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1460 Elts.push_back(Undef);
1462 } else { // Otherwise, defined.
1463 Elts.push_back(CP->getOperand(i));
1466 // If we changed the constant, return it.
1467 Constant *NewCP = Context->getConstantVector(Elts);
1468 return NewCP != CP ? NewCP : 0;
1469 } else if (isa<ConstantAggregateZero>(V)) {
1470 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1473 // Check if this is identity. If so, return 0 since we are not simplifying
1475 if (DemandedElts == ((1ULL << VWidth) -1))
1478 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1479 Constant *Zero = Context->getNullValue(EltTy);
1480 Constant *Undef = Context->getUndef(EltTy);
1481 std::vector<Constant*> Elts;
1482 for (unsigned i = 0; i != VWidth; ++i) {
1483 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1484 Elts.push_back(Elt);
1486 UndefElts = DemandedElts ^ EltMask;
1487 return Context->getConstantVector(Elts);
1490 // Limit search depth.
1494 // If multiple users are using the root value, procede with
1495 // simplification conservatively assuming that all elements
1497 if (!V->hasOneUse()) {
1498 // Quit if we find multiple users of a non-root value though.
1499 // They'll be handled when it's their turn to be visited by
1500 // the main instcombine process.
1502 // TODO: Just compute the UndefElts information recursively.
1505 // Conservatively assume that all elements are needed.
1506 DemandedElts = EltMask;
1509 Instruction *I = dyn_cast<Instruction>(V);
1510 if (!I) return 0; // Only analyze instructions.
1512 bool MadeChange = false;
1513 APInt UndefElts2(VWidth, 0);
1515 switch (I->getOpcode()) {
1518 case Instruction::InsertElement: {
1519 // If this is a variable index, we don't know which element it overwrites.
1520 // demand exactly the same input as we produce.
1521 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1523 // Note that we can't propagate undef elt info, because we don't know
1524 // which elt is getting updated.
1525 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1526 UndefElts2, Depth+1);
1527 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1531 // If this is inserting an element that isn't demanded, remove this
1533 unsigned IdxNo = Idx->getZExtValue();
1534 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1535 return AddSoonDeadInstToWorklist(*I, 0);
1537 // Otherwise, the element inserted overwrites whatever was there, so the
1538 // input demanded set is simpler than the output set.
1539 APInt DemandedElts2 = DemandedElts;
1540 DemandedElts2.clear(IdxNo);
1541 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1542 UndefElts, Depth+1);
1543 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1545 // The inserted element is defined.
1546 UndefElts.clear(IdxNo);
1549 case Instruction::ShuffleVector: {
1550 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1551 uint64_t LHSVWidth =
1552 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1553 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1554 for (unsigned i = 0; i < VWidth; i++) {
1555 if (DemandedElts[i]) {
1556 unsigned MaskVal = Shuffle->getMaskValue(i);
1557 if (MaskVal != -1u) {
1558 assert(MaskVal < LHSVWidth * 2 &&
1559 "shufflevector mask index out of range!");
1560 if (MaskVal < LHSVWidth)
1561 LeftDemanded.set(MaskVal);
1563 RightDemanded.set(MaskVal - LHSVWidth);
1568 APInt UndefElts4(LHSVWidth, 0);
1569 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1570 UndefElts4, Depth+1);
1571 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1573 APInt UndefElts3(LHSVWidth, 0);
1574 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1575 UndefElts3, Depth+1);
1576 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1578 bool NewUndefElts = false;
1579 for (unsigned i = 0; i < VWidth; i++) {
1580 unsigned MaskVal = Shuffle->getMaskValue(i);
1581 if (MaskVal == -1u) {
1583 } else if (MaskVal < LHSVWidth) {
1584 if (UndefElts4[MaskVal]) {
1585 NewUndefElts = true;
1589 if (UndefElts3[MaskVal - LHSVWidth]) {
1590 NewUndefElts = true;
1597 // Add additional discovered undefs.
1598 std::vector<Constant*> Elts;
1599 for (unsigned i = 0; i < VWidth; ++i) {
1601 Elts.push_back(Context->getUndef(Type::Int32Ty));
1603 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1604 Shuffle->getMaskValue(i)));
1606 I->setOperand(2, Context->getConstantVector(Elts));
1611 case Instruction::BitCast: {
1612 // Vector->vector casts only.
1613 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1615 unsigned InVWidth = VTy->getNumElements();
1616 APInt InputDemandedElts(InVWidth, 0);
1619 if (VWidth == InVWidth) {
1620 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1621 // elements as are demanded of us.
1623 InputDemandedElts = DemandedElts;
1624 } else if (VWidth > InVWidth) {
1628 // If there are more elements in the result than there are in the source,
1629 // then an input element is live if any of the corresponding output
1630 // elements are live.
1631 Ratio = VWidth/InVWidth;
1632 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1633 if (DemandedElts[OutIdx])
1634 InputDemandedElts.set(OutIdx/Ratio);
1640 // If there are more elements in the source than there are in the result,
1641 // then an input element is live if the corresponding output element is
1643 Ratio = InVWidth/VWidth;
1644 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1645 if (DemandedElts[InIdx/Ratio])
1646 InputDemandedElts.set(InIdx);
1649 // div/rem demand all inputs, because they don't want divide by zero.
1650 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1651 UndefElts2, Depth+1);
1653 I->setOperand(0, TmpV);
1657 UndefElts = UndefElts2;
1658 if (VWidth > InVWidth) {
1659 llvm_unreachable("Unimp");
1660 // If there are more elements in the result than there are in the source,
1661 // then an output element is undef if the corresponding input element is
1663 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1664 if (UndefElts2[OutIdx/Ratio])
1665 UndefElts.set(OutIdx);
1666 } else if (VWidth < InVWidth) {
1667 llvm_unreachable("Unimp");
1668 // If there are more elements in the source than there are in the result,
1669 // then a result element is undef if all of the corresponding input
1670 // elements are undef.
1671 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1672 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1673 if (!UndefElts2[InIdx]) // Not undef?
1674 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
1678 case Instruction::And:
1679 case Instruction::Or:
1680 case Instruction::Xor:
1681 case Instruction::Add:
1682 case Instruction::Sub:
1683 case Instruction::Mul:
1684 // div/rem demand all inputs, because they don't want divide by zero.
1685 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1686 UndefElts, Depth+1);
1687 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1688 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1689 UndefElts2, Depth+1);
1690 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1692 // Output elements are undefined if both are undefined. Consider things
1693 // like undef&0. The result is known zero, not undef.
1694 UndefElts &= UndefElts2;
1697 case Instruction::Call: {
1698 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1700 switch (II->getIntrinsicID()) {
1703 // Binary vector operations that work column-wise. A dest element is a
1704 // function of the corresponding input elements from the two inputs.
1705 case Intrinsic::x86_sse_sub_ss:
1706 case Intrinsic::x86_sse_mul_ss:
1707 case Intrinsic::x86_sse_min_ss:
1708 case Intrinsic::x86_sse_max_ss:
1709 case Intrinsic::x86_sse2_sub_sd:
1710 case Intrinsic::x86_sse2_mul_sd:
1711 case Intrinsic::x86_sse2_min_sd:
1712 case Intrinsic::x86_sse2_max_sd:
1713 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1714 UndefElts, Depth+1);
1715 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1716 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1717 UndefElts2, Depth+1);
1718 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1720 // If only the low elt is demanded and this is a scalarizable intrinsic,
1721 // scalarize it now.
1722 if (DemandedElts == 1) {
1723 switch (II->getIntrinsicID()) {
1725 case Intrinsic::x86_sse_sub_ss:
1726 case Intrinsic::x86_sse_mul_ss:
1727 case Intrinsic::x86_sse2_sub_sd:
1728 case Intrinsic::x86_sse2_mul_sd:
1729 // TODO: Lower MIN/MAX/ABS/etc
1730 Value *LHS = II->getOperand(1);
1731 Value *RHS = II->getOperand(2);
1732 // Extract the element as scalars.
1733 LHS = InsertNewInstBefore(new ExtractElementInst(LHS,
1734 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1735 RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1736 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1738 switch (II->getIntrinsicID()) {
1739 default: llvm_unreachable("Case stmts out of sync!");
1740 case Intrinsic::x86_sse_sub_ss:
1741 case Intrinsic::x86_sse2_sub_sd:
1742 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1743 II->getName()), *II);
1745 case Intrinsic::x86_sse_mul_ss:
1746 case Intrinsic::x86_sse2_mul_sd:
1747 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1748 II->getName()), *II);
1753 InsertElementInst::Create(
1754 Context->getUndef(II->getType()), TmpV,
1755 Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
1756 InsertNewInstBefore(New, *II);
1757 AddSoonDeadInstToWorklist(*II, 0);
1762 // Output elements are undefined if both are undefined. Consider things
1763 // like undef&0. The result is known zero, not undef.
1764 UndefElts &= UndefElts2;
1770 return MadeChange ? I : 0;
1774 /// AssociativeOpt - Perform an optimization on an associative operator. This
1775 /// function is designed to check a chain of associative operators for a
1776 /// potential to apply a certain optimization. Since the optimization may be
1777 /// applicable if the expression was reassociated, this checks the chain, then
1778 /// reassociates the expression as necessary to expose the optimization
1779 /// opportunity. This makes use of a special Functor, which must define
1780 /// 'shouldApply' and 'apply' methods.
1782 template<typename Functor>
1783 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1784 LLVMContext *Context) {
1785 unsigned Opcode = Root.getOpcode();
1786 Value *LHS = Root.getOperand(0);
1788 // Quick check, see if the immediate LHS matches...
1789 if (F.shouldApply(LHS))
1790 return F.apply(Root);
1792 // Otherwise, if the LHS is not of the same opcode as the root, return.
1793 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1794 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1795 // Should we apply this transform to the RHS?
1796 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1798 // If not to the RHS, check to see if we should apply to the LHS...
1799 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1800 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1804 // If the functor wants to apply the optimization to the RHS of LHSI,
1805 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1807 // Now all of the instructions are in the current basic block, go ahead
1808 // and perform the reassociation.
1809 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1811 // First move the selected RHS to the LHS of the root...
1812 Root.setOperand(0, LHSI->getOperand(1));
1814 // Make what used to be the LHS of the root be the user of the root...
1815 Value *ExtraOperand = TmpLHSI->getOperand(1);
1816 if (&Root == TmpLHSI) {
1817 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1820 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1821 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1822 BasicBlock::iterator ARI = &Root; ++ARI;
1823 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1826 // Now propagate the ExtraOperand down the chain of instructions until we
1828 while (TmpLHSI != LHSI) {
1829 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1830 // Move the instruction to immediately before the chain we are
1831 // constructing to avoid breaking dominance properties.
1832 NextLHSI->moveBefore(ARI);
1835 Value *NextOp = NextLHSI->getOperand(1);
1836 NextLHSI->setOperand(1, ExtraOperand);
1838 ExtraOperand = NextOp;
1841 // Now that the instructions are reassociated, have the functor perform
1842 // the transformation...
1843 return F.apply(Root);
1846 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1853 // AddRHS - Implements: X + X --> X << 1
1856 LLVMContext *Context;
1857 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1858 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1859 Instruction *apply(BinaryOperator &Add) const {
1860 return BinaryOperator::CreateShl(Add.getOperand(0),
1861 Context->getConstantInt(Add.getType(), 1));
1865 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1867 struct AddMaskingAnd {
1869 LLVMContext *Context;
1870 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1871 bool shouldApply(Value *LHS) const {
1873 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1874 Context->getConstantExprAnd(C1, C2)->isNullValue();
1876 Instruction *apply(BinaryOperator &Add) const {
1877 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1883 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1885 LLVMContext *Context = IC->getContext();
1887 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1888 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1891 // Figure out if the constant is the left or the right argument.
1892 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1893 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1895 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1897 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1898 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1901 Value *Op0 = SO, *Op1 = ConstOperand;
1903 std::swap(Op0, Op1);
1905 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1906 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1907 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1908 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1909 Op0, Op1, SO->getName()+".cmp");
1911 llvm_unreachable("Unknown binary instruction type!");
1913 return IC->InsertNewInstBefore(New, I);
1916 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1917 // constant as the other operand, try to fold the binary operator into the
1918 // select arguments. This also works for Cast instructions, which obviously do
1919 // not have a second operand.
1920 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1922 // Don't modify shared select instructions
1923 if (!SI->hasOneUse()) return 0;
1924 Value *TV = SI->getOperand(1);
1925 Value *FV = SI->getOperand(2);
1927 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1928 // Bool selects with constant operands can be folded to logical ops.
1929 if (SI->getType() == Type::Int1Ty) return 0;
1931 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1932 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1934 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1941 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1942 /// node as operand #0, see if we can fold the instruction into the PHI (which
1943 /// is only possible if all operands to the PHI are constants).
1944 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1945 PHINode *PN = cast<PHINode>(I.getOperand(0));
1946 unsigned NumPHIValues = PN->getNumIncomingValues();
1947 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1949 // Check to see if all of the operands of the PHI are constants. If there is
1950 // one non-constant value, remember the BB it is. If there is more than one
1951 // or if *it* is a PHI, bail out.
1952 BasicBlock *NonConstBB = 0;
1953 for (unsigned i = 0; i != NumPHIValues; ++i)
1954 if (!isa<Constant>(PN->getIncomingValue(i))) {
1955 if (NonConstBB) return 0; // More than one non-const value.
1956 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1957 NonConstBB = PN->getIncomingBlock(i);
1959 // If the incoming non-constant value is in I's block, we have an infinite
1961 if (NonConstBB == I.getParent())
1965 // If there is exactly one non-constant value, we can insert a copy of the
1966 // operation in that block. However, if this is a critical edge, we would be
1967 // inserting the computation one some other paths (e.g. inside a loop). Only
1968 // do this if the pred block is unconditionally branching into the phi block.
1970 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1971 if (!BI || !BI->isUnconditional()) return 0;
1974 // Okay, we can do the transformation: create the new PHI node.
1975 PHINode *NewPN = PHINode::Create(I.getType(), "");
1976 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1977 InsertNewInstBefore(NewPN, *PN);
1978 NewPN->takeName(PN);
1980 // Next, add all of the operands to the PHI.
1981 if (I.getNumOperands() == 2) {
1982 Constant *C = cast<Constant>(I.getOperand(1));
1983 for (unsigned i = 0; i != NumPHIValues; ++i) {
1985 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1986 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1987 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
1989 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
1991 assert(PN->getIncomingBlock(i) == NonConstBB);
1992 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1993 InV = BinaryOperator::Create(BO->getOpcode(),
1994 PN->getIncomingValue(i), C, "phitmp",
1995 NonConstBB->getTerminator());
1996 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1997 InV = CmpInst::Create(*Context, CI->getOpcode(),
1999 PN->getIncomingValue(i), C, "phitmp",
2000 NonConstBB->getTerminator());
2002 llvm_unreachable("Unknown binop!");
2004 AddToWorkList(cast<Instruction>(InV));
2006 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2009 CastInst *CI = cast<CastInst>(&I);
2010 const Type *RetTy = CI->getType();
2011 for (unsigned i = 0; i != NumPHIValues; ++i) {
2013 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2014 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2016 assert(PN->getIncomingBlock(i) == NonConstBB);
2017 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2018 I.getType(), "phitmp",
2019 NonConstBB->getTerminator());
2020 AddToWorkList(cast<Instruction>(InV));
2022 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2025 return ReplaceInstUsesWith(I, NewPN);
2029 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2030 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2031 /// This basically requires proving that the add in the original type would not
2032 /// overflow to change the sign bit or have a carry out.
2033 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2034 // There are different heuristics we can use for this. Here are some simple
2037 // Add has the property that adding any two 2's complement numbers can only
2038 // have one carry bit which can change a sign. As such, if LHS and RHS each
2039 // have at least two sign bits, we know that the addition of the two values will
2040 // sign extend fine.
2041 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2045 // If one of the operands only has one non-zero bit, and if the other operand
2046 // has a known-zero bit in a more significant place than it (not including the
2047 // sign bit) the ripple may go up to and fill the zero, but won't change the
2048 // sign. For example, (X & ~4) + 1.
2056 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2057 bool Changed = SimplifyCommutative(I);
2058 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2060 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2061 // X + undef -> undef
2062 if (isa<UndefValue>(RHS))
2063 return ReplaceInstUsesWith(I, RHS);
2066 if (RHSC->isNullValue())
2067 return ReplaceInstUsesWith(I, LHS);
2069 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2070 // X + (signbit) --> X ^ signbit
2071 const APInt& Val = CI->getValue();
2072 uint32_t BitWidth = Val.getBitWidth();
2073 if (Val == APInt::getSignBit(BitWidth))
2074 return BinaryOperator::CreateXor(LHS, RHS);
2076 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2077 // (X & 254)+1 -> (X&254)|1
2078 if (SimplifyDemandedInstructionBits(I))
2081 // zext(bool) + C -> bool ? C + 1 : C
2082 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2083 if (ZI->getSrcTy() == Type::Int1Ty)
2084 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2087 if (isa<PHINode>(LHS))
2088 if (Instruction *NV = FoldOpIntoPhi(I))
2091 ConstantInt *XorRHS = 0;
2093 if (isa<ConstantInt>(RHSC) &&
2094 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2095 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2096 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2098 uint32_t Size = TySizeBits / 2;
2099 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2100 APInt CFF80Val(-C0080Val);
2102 if (TySizeBits > Size) {
2103 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2104 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2105 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2106 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2107 // This is a sign extend if the top bits are known zero.
2108 if (!MaskedValueIsZero(XorLHS,
2109 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2110 Size = 0; // Not a sign ext, but can't be any others either.
2115 C0080Val = APIntOps::lshr(C0080Val, Size);
2116 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2117 } while (Size >= 1);
2119 // FIXME: This shouldn't be necessary. When the backends can handle types
2120 // with funny bit widths then this switch statement should be removed. It
2121 // is just here to get the size of the "middle" type back up to something
2122 // that the back ends can handle.
2123 const Type *MiddleType = 0;
2126 case 32: MiddleType = Type::Int32Ty; break;
2127 case 16: MiddleType = Type::Int16Ty; break;
2128 case 8: MiddleType = Type::Int8Ty; break;
2131 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2132 InsertNewInstBefore(NewTrunc, I);
2133 return new SExtInst(NewTrunc, I.getType(), I.getName());
2138 if (I.getType() == Type::Int1Ty)
2139 return BinaryOperator::CreateXor(LHS, RHS);
2142 if (I.getType()->isInteger()) {
2143 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2146 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2147 if (RHSI->getOpcode() == Instruction::Sub)
2148 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2149 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2151 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2152 if (LHSI->getOpcode() == Instruction::Sub)
2153 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2154 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2159 // -A + -B --> -(A + B)
2160 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2161 if (LHS->getType()->isIntOrIntVector()) {
2162 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2163 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2164 InsertNewInstBefore(NewAdd, I);
2165 return BinaryOperator::CreateNeg(*Context, NewAdd);
2169 return BinaryOperator::CreateSub(RHS, LHSV);
2173 if (!isa<Constant>(RHS))
2174 if (Value *V = dyn_castNegVal(RHS, Context))
2175 return BinaryOperator::CreateSub(LHS, V);
2179 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2180 if (X == RHS) // X*C + X --> X * (C+1)
2181 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2183 // X*C1 + X*C2 --> X * (C1+C2)
2185 if (X == dyn_castFoldableMul(RHS, C1, Context))
2186 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2189 // X + X*C --> X * (C+1)
2190 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2191 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2193 // X + ~X --> -1 since ~X = -X-1
2194 if (dyn_castNotVal(LHS, Context) == RHS ||
2195 dyn_castNotVal(RHS, Context) == LHS)
2196 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2199 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2200 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2201 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2204 // A+B --> A|B iff A and B have no bits set in common.
2205 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2206 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2207 APInt LHSKnownOne(IT->getBitWidth(), 0);
2208 APInt LHSKnownZero(IT->getBitWidth(), 0);
2209 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2210 if (LHSKnownZero != 0) {
2211 APInt RHSKnownOne(IT->getBitWidth(), 0);
2212 APInt RHSKnownZero(IT->getBitWidth(), 0);
2213 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2215 // No bits in common -> bitwise or.
2216 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2217 return BinaryOperator::CreateOr(LHS, RHS);
2221 // W*X + Y*Z --> W * (X+Z) iff W == Y
2222 if (I.getType()->isIntOrIntVector()) {
2223 Value *W, *X, *Y, *Z;
2224 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2225 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2229 } else if (Y == X) {
2231 } else if (X == Z) {
2238 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2239 LHS->getName()), I);
2240 return BinaryOperator::CreateMul(W, NewAdd);
2245 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2247 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
2248 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2250 // (X & FF00) + xx00 -> (X+xx00) & FF00
2251 if (LHS->hasOneUse() &&
2252 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2253 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2254 if (Anded == CRHS) {
2255 // See if all bits from the first bit set in the Add RHS up are included
2256 // in the mask. First, get the rightmost bit.
2257 const APInt& AddRHSV = CRHS->getValue();
2259 // Form a mask of all bits from the lowest bit added through the top.
2260 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2262 // See if the and mask includes all of these bits.
2263 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2265 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2266 // Okay, the xform is safe. Insert the new add pronto.
2267 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2268 LHS->getName()), I);
2269 return BinaryOperator::CreateAnd(NewAdd, C2);
2274 // Try to fold constant add into select arguments.
2275 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2276 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2280 // add (select X 0 (sub n A)) A --> select X A n
2282 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2285 SI = dyn_cast<SelectInst>(RHS);
2288 if (SI && SI->hasOneUse()) {
2289 Value *TV = SI->getTrueValue();
2290 Value *FV = SI->getFalseValue();
2293 // Can we fold the add into the argument of the select?
2294 // We check both true and false select arguments for a matching subtract.
2295 if (match(FV, m_Zero(), *Context) &&
2296 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2297 // Fold the add into the true select value.
2298 return SelectInst::Create(SI->getCondition(), N, A);
2299 if (match(TV, m_Zero(), *Context) &&
2300 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2301 // Fold the add into the false select value.
2302 return SelectInst::Create(SI->getCondition(), A, N);
2306 // Check for (add (sext x), y), see if we can merge this into an
2307 // integer add followed by a sext.
2308 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2309 // (add (sext x), cst) --> (sext (add x, cst'))
2310 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2312 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2313 if (LHSConv->hasOneUse() &&
2314 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2315 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2316 // Insert the new, smaller add.
2317 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2319 InsertNewInstBefore(NewAdd, I);
2320 return new SExtInst(NewAdd, I.getType());
2324 // (add (sext x), (sext y)) --> (sext (add int x, y))
2325 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2326 // Only do this if x/y have the same type, if at last one of them has a
2327 // single use (so we don't increase the number of sexts), and if the
2328 // integer add will not overflow.
2329 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2330 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2331 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2332 RHSConv->getOperand(0))) {
2333 // Insert the new integer add.
2334 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2335 RHSConv->getOperand(0),
2337 InsertNewInstBefore(NewAdd, I);
2338 return new SExtInst(NewAdd, I.getType());
2343 return Changed ? &I : 0;
2346 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2347 bool Changed = SimplifyCommutative(I);
2348 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2350 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2352 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2353 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2354 (I.getType())->getValueAPF()))
2355 return ReplaceInstUsesWith(I, LHS);
2358 if (isa<PHINode>(LHS))
2359 if (Instruction *NV = FoldOpIntoPhi(I))
2364 // -A + -B --> -(A + B)
2365 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2366 return BinaryOperator::CreateFSub(RHS, LHSV);
2369 if (!isa<Constant>(RHS))
2370 if (Value *V = dyn_castFNegVal(RHS, Context))
2371 return BinaryOperator::CreateFSub(LHS, V);
2373 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2374 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2375 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2376 return ReplaceInstUsesWith(I, LHS);
2378 // Check for (add double (sitofp x), y), see if we can merge this into an
2379 // integer add followed by a promotion.
2380 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2381 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2382 // ... if the constant fits in the integer value. This is useful for things
2383 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2384 // requires a constant pool load, and generally allows the add to be better
2386 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2388 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2389 if (LHSConv->hasOneUse() &&
2390 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2391 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2392 // Insert the new integer add.
2393 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2395 InsertNewInstBefore(NewAdd, I);
2396 return new SIToFPInst(NewAdd, I.getType());
2400 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2401 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2402 // Only do this if x/y have the same type, if at last one of them has a
2403 // single use (so we don't increase the number of int->fp conversions),
2404 // and if the integer add will not overflow.
2405 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2406 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2407 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2408 RHSConv->getOperand(0))) {
2409 // Insert the new integer add.
2410 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2411 RHSConv->getOperand(0),
2413 InsertNewInstBefore(NewAdd, I);
2414 return new SIToFPInst(NewAdd, I.getType());
2419 return Changed ? &I : 0;
2422 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2423 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2425 if (Op0 == Op1) // sub X, X -> 0
2426 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2428 // If this is a 'B = x-(-A)', change to B = x+A...
2429 if (Value *V = dyn_castNegVal(Op1, Context))
2430 return BinaryOperator::CreateAdd(Op0, V);
2432 if (isa<UndefValue>(Op0))
2433 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2434 if (isa<UndefValue>(Op1))
2435 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2437 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2438 // Replace (-1 - A) with (~A)...
2439 if (C->isAllOnesValue())
2440 return BinaryOperator::CreateNot(*Context, Op1);
2442 // C - ~X == X + (1+C)
2444 if (match(Op1, m_Not(m_Value(X)), *Context))
2445 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2447 // -(X >>u 31) -> (X >>s 31)
2448 // -(X >>s 31) -> (X >>u 31)
2450 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2451 if (SI->getOpcode() == Instruction::LShr) {
2452 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2453 // Check to see if we are shifting out everything but the sign bit.
2454 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2455 SI->getType()->getPrimitiveSizeInBits()-1) {
2456 // Ok, the transformation is safe. Insert AShr.
2457 return BinaryOperator::Create(Instruction::AShr,
2458 SI->getOperand(0), CU, SI->getName());
2462 else if (SI->getOpcode() == Instruction::AShr) {
2463 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2464 // Check to see if we are shifting out everything but the sign bit.
2465 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2466 SI->getType()->getPrimitiveSizeInBits()-1) {
2467 // Ok, the transformation is safe. Insert LShr.
2468 return BinaryOperator::CreateLShr(
2469 SI->getOperand(0), CU, SI->getName());
2476 // Try to fold constant sub into select arguments.
2477 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2478 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2481 // C - zext(bool) -> bool ? C - 1 : C
2482 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2483 if (ZI->getSrcTy() == Type::Int1Ty)
2484 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2487 if (I.getType() == Type::Int1Ty)
2488 return BinaryOperator::CreateXor(Op0, Op1);
2490 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2491 if (Op1I->getOpcode() == Instruction::Add) {
2492 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2493 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2495 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2496 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2498 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2499 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2500 // C1-(X+C2) --> (C1-C2)-X
2501 return BinaryOperator::CreateSub(
2502 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2506 if (Op1I->hasOneUse()) {
2507 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2508 // is not used by anyone else...
2510 if (Op1I->getOpcode() == Instruction::Sub) {
2511 // Swap the two operands of the subexpr...
2512 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2513 Op1I->setOperand(0, IIOp1);
2514 Op1I->setOperand(1, IIOp0);
2516 // Create the new top level add instruction...
2517 return BinaryOperator::CreateAdd(Op0, Op1);
2520 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2522 if (Op1I->getOpcode() == Instruction::And &&
2523 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2524 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2527 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2528 OtherOp, "B.not"), I);
2529 return BinaryOperator::CreateAnd(Op0, NewNot);
2532 // 0 - (X sdiv C) -> (X sdiv -C)
2533 if (Op1I->getOpcode() == Instruction::SDiv)
2534 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2536 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2537 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2538 Context->getConstantExprNeg(DivRHS));
2540 // X - X*C --> X * (1-C)
2541 ConstantInt *C2 = 0;
2542 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2544 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2546 return BinaryOperator::CreateMul(Op0, CP1);
2551 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2552 if (Op0I->getOpcode() == Instruction::Add) {
2553 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2554 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2555 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2556 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2557 } else if (Op0I->getOpcode() == Instruction::Sub) {
2558 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2559 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2565 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2566 if (X == Op1) // X*C - X --> X * (C-1)
2567 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2569 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2570 if (X == dyn_castFoldableMul(Op1, C2, Context))
2571 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2576 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2577 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2579 // If this is a 'B = x-(-A)', change to B = x+A...
2580 if (Value *V = dyn_castFNegVal(Op1, Context))
2581 return BinaryOperator::CreateFAdd(Op0, V);
2583 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2584 if (Op1I->getOpcode() == Instruction::FAdd) {
2585 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2586 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2588 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2589 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2597 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2598 /// comparison only checks the sign bit. If it only checks the sign bit, set
2599 /// TrueIfSigned if the result of the comparison is true when the input value is
2601 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2602 bool &TrueIfSigned) {
2604 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2605 TrueIfSigned = true;
2606 return RHS->isZero();
2607 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2608 TrueIfSigned = true;
2609 return RHS->isAllOnesValue();
2610 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2611 TrueIfSigned = false;
2612 return RHS->isAllOnesValue();
2613 case ICmpInst::ICMP_UGT:
2614 // True if LHS u> RHS and RHS == high-bit-mask - 1
2615 TrueIfSigned = true;
2616 return RHS->getValue() ==
2617 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2618 case ICmpInst::ICMP_UGE:
2619 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2620 TrueIfSigned = true;
2621 return RHS->getValue().isSignBit();
2627 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2628 bool Changed = SimplifyCommutative(I);
2629 Value *Op0 = I.getOperand(0);
2631 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2632 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2634 // Simplify mul instructions with a constant RHS...
2635 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2636 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2638 // ((X << C1)*C2) == (X * (C2 << C1))
2639 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2640 if (SI->getOpcode() == Instruction::Shl)
2641 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2642 return BinaryOperator::CreateMul(SI->getOperand(0),
2643 Context->getConstantExprShl(CI, ShOp));
2646 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2647 if (CI->equalsInt(1)) // X * 1 == X
2648 return ReplaceInstUsesWith(I, Op0);
2649 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2650 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2652 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2653 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2654 return BinaryOperator::CreateShl(Op0,
2655 Context->getConstantInt(Op0->getType(), Val.logBase2()));
2657 } else if (isa<VectorType>(Op1->getType())) {
2658 if (Op1->isNullValue())
2659 return ReplaceInstUsesWith(I, Op1);
2661 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2662 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2663 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2665 // As above, vector X*splat(1.0) -> X in all defined cases.
2666 if (Constant *Splat = Op1V->getSplatValue()) {
2667 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2668 if (CI->equalsInt(1))
2669 return ReplaceInstUsesWith(I, Op0);
2674 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2675 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2676 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2677 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2678 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2680 InsertNewInstBefore(Add, I);
2681 Value *C1C2 = Context->getConstantExprMul(Op1,
2682 cast<Constant>(Op0I->getOperand(1)));
2683 return BinaryOperator::CreateAdd(Add, C1C2);
2687 // Try to fold constant mul into select arguments.
2688 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2689 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2692 if (isa<PHINode>(Op0))
2693 if (Instruction *NV = FoldOpIntoPhi(I))
2697 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2698 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2699 return BinaryOperator::CreateMul(Op0v, Op1v);
2701 // (X / Y) * Y = X - (X % Y)
2702 // (X / Y) * -Y = (X % Y) - X
2704 Value *Op1 = I.getOperand(1);
2705 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2707 (BO->getOpcode() != Instruction::UDiv &&
2708 BO->getOpcode() != Instruction::SDiv)) {
2710 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2712 Value *Neg = dyn_castNegVal(Op1, Context);
2713 if (BO && BO->hasOneUse() &&
2714 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2715 (BO->getOpcode() == Instruction::UDiv ||
2716 BO->getOpcode() == Instruction::SDiv)) {
2717 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2720 if (BO->getOpcode() == Instruction::UDiv)
2721 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2723 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2725 InsertNewInstBefore(Rem, I);
2729 return BinaryOperator::CreateSub(Op0BO, Rem);
2731 return BinaryOperator::CreateSub(Rem, Op0BO);
2735 if (I.getType() == Type::Int1Ty)
2736 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2738 // If one of the operands of the multiply is a cast from a boolean value, then
2739 // we know the bool is either zero or one, so this is a 'masking' multiply.
2740 // See if we can simplify things based on how the boolean was originally
2742 CastInst *BoolCast = 0;
2743 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2744 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2747 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2748 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2751 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2752 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2753 const Type *SCOpTy = SCIOp0->getType();
2756 // If the icmp is true iff the sign bit of X is set, then convert this
2757 // multiply into a shift/and combination.
2758 if (isa<ConstantInt>(SCIOp1) &&
2759 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2761 // Shift the X value right to turn it into "all signbits".
2762 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2763 SCOpTy->getPrimitiveSizeInBits()-1);
2765 InsertNewInstBefore(
2766 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2767 BoolCast->getOperand(0)->getName()+
2770 // If the multiply type is not the same as the source type, sign extend
2771 // or truncate to the multiply type.
2772 if (I.getType() != V->getType()) {
2773 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2774 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2775 Instruction::CastOps opcode =
2776 (SrcBits == DstBits ? Instruction::BitCast :
2777 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2778 V = InsertCastBefore(opcode, V, I.getType(), I);
2781 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2782 return BinaryOperator::CreateAnd(V, OtherOp);
2787 return Changed ? &I : 0;
2790 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2791 bool Changed = SimplifyCommutative(I);
2792 Value *Op0 = I.getOperand(0);
2794 // Simplify mul instructions with a constant RHS...
2795 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2796 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2797 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2798 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2799 if (Op1F->isExactlyValue(1.0))
2800 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2801 } else if (isa<VectorType>(Op1->getType())) {
2802 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2803 // As above, vector X*splat(1.0) -> X in all defined cases.
2804 if (Constant *Splat = Op1V->getSplatValue()) {
2805 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2806 if (F->isExactlyValue(1.0))
2807 return ReplaceInstUsesWith(I, Op0);
2812 // Try to fold constant mul into select arguments.
2813 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2814 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2817 if (isa<PHINode>(Op0))
2818 if (Instruction *NV = FoldOpIntoPhi(I))
2822 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2823 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2824 return BinaryOperator::CreateFMul(Op0v, Op1v);
2826 return Changed ? &I : 0;
2829 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2831 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2832 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2834 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2835 int NonNullOperand = -1;
2836 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2837 if (ST->isNullValue())
2839 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2840 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2841 if (ST->isNullValue())
2844 if (NonNullOperand == -1)
2847 Value *SelectCond = SI->getOperand(0);
2849 // Change the div/rem to use 'Y' instead of the select.
2850 I.setOperand(1, SI->getOperand(NonNullOperand));
2852 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2853 // problem. However, the select, or the condition of the select may have
2854 // multiple uses. Based on our knowledge that the operand must be non-zero,
2855 // propagate the known value for the select into other uses of it, and
2856 // propagate a known value of the condition into its other users.
2858 // If the select and condition only have a single use, don't bother with this,
2860 if (SI->use_empty() && SelectCond->hasOneUse())
2863 // Scan the current block backward, looking for other uses of SI.
2864 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2866 while (BBI != BBFront) {
2868 // If we found a call to a function, we can't assume it will return, so
2869 // information from below it cannot be propagated above it.
2870 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2873 // Replace uses of the select or its condition with the known values.
2874 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2877 *I = SI->getOperand(NonNullOperand);
2879 } else if (*I == SelectCond) {
2880 *I = NonNullOperand == 1 ? Context->getTrue() :
2881 Context->getFalse();
2886 // If we past the instruction, quit looking for it.
2889 if (&*BBI == SelectCond)
2892 // If we ran out of things to eliminate, break out of the loop.
2893 if (SelectCond == 0 && SI == 0)
2901 /// This function implements the transforms on div instructions that work
2902 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2903 /// used by the visitors to those instructions.
2904 /// @brief Transforms common to all three div instructions
2905 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2908 // undef / X -> 0 for integer.
2909 // undef / X -> undef for FP (the undef could be a snan).
2910 if (isa<UndefValue>(Op0)) {
2911 if (Op0->getType()->isFPOrFPVector())
2912 return ReplaceInstUsesWith(I, Op0);
2913 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2916 // X / undef -> undef
2917 if (isa<UndefValue>(Op1))
2918 return ReplaceInstUsesWith(I, Op1);
2923 /// This function implements the transforms common to both integer division
2924 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2925 /// division instructions.
2926 /// @brief Common integer divide transforms
2927 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2928 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2930 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2932 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2933 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2934 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2935 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2938 Constant *CI = Context->getConstantInt(I.getType(), 1);
2939 return ReplaceInstUsesWith(I, CI);
2942 if (Instruction *Common = commonDivTransforms(I))
2945 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2946 // This does not apply for fdiv.
2947 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2950 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2952 if (RHS->equalsInt(1))
2953 return ReplaceInstUsesWith(I, Op0);
2955 // (X / C1) / C2 -> X / (C1*C2)
2956 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2957 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2958 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2959 if (MultiplyOverflows(RHS, LHSRHS,
2960 I.getOpcode()==Instruction::SDiv, Context))
2961 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2963 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2964 Context->getConstantExprMul(RHS, LHSRHS));
2967 if (!RHS->isZero()) { // avoid X udiv 0
2968 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2969 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2971 if (isa<PHINode>(Op0))
2972 if (Instruction *NV = FoldOpIntoPhi(I))
2977 // 0 / X == 0, we don't need to preserve faults!
2978 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2979 if (LHS->equalsInt(0))
2980 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2982 // It can't be division by zero, hence it must be division by one.
2983 if (I.getType() == Type::Int1Ty)
2984 return ReplaceInstUsesWith(I, Op0);
2986 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2987 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2990 return ReplaceInstUsesWith(I, Op0);
2996 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2997 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2999 // Handle the integer div common cases
3000 if (Instruction *Common = commonIDivTransforms(I))
3003 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3004 // X udiv C^2 -> X >> C
3005 // Check to see if this is an unsigned division with an exact power of 2,
3006 // if so, convert to a right shift.
3007 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3008 return BinaryOperator::CreateLShr(Op0,
3009 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3011 // X udiv C, where C >= signbit
3012 if (C->getValue().isNegative()) {
3013 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3014 ICmpInst::ICMP_ULT, Op0, C),
3016 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3017 Context->getConstantInt(I.getType(), 1));
3021 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3022 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3023 if (RHSI->getOpcode() == Instruction::Shl &&
3024 isa<ConstantInt>(RHSI->getOperand(0))) {
3025 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3026 if (C1.isPowerOf2()) {
3027 Value *N = RHSI->getOperand(1);
3028 const Type *NTy = N->getType();
3029 if (uint32_t C2 = C1.logBase2()) {
3030 Constant *C2V = Context->getConstantInt(NTy, C2);
3031 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3033 return BinaryOperator::CreateLShr(Op0, N);
3038 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3039 // where C1&C2 are powers of two.
3040 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3041 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3042 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3043 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3044 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3045 // Compute the shift amounts
3046 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3047 // Construct the "on true" case of the select
3048 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3049 Instruction *TSI = BinaryOperator::CreateLShr(
3050 Op0, TC, SI->getName()+".t");
3051 TSI = InsertNewInstBefore(TSI, I);
3053 // Construct the "on false" case of the select
3054 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
3055 Instruction *FSI = BinaryOperator::CreateLShr(
3056 Op0, FC, SI->getName()+".f");
3057 FSI = InsertNewInstBefore(FSI, I);
3059 // construct the select instruction and return it.
3060 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3066 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3067 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3069 // Handle the integer div common cases
3070 if (Instruction *Common = commonIDivTransforms(I))
3073 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3075 if (RHS->isAllOnesValue())
3076 return BinaryOperator::CreateNeg(*Context, Op0);
3079 // If the sign bits of both operands are zero (i.e. we can prove they are
3080 // unsigned inputs), turn this into a udiv.
3081 if (I.getType()->isInteger()) {
3082 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3083 if (MaskedValueIsZero(Op0, Mask)) {
3084 if (MaskedValueIsZero(Op1, Mask)) {
3085 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3086 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3088 ConstantInt *ShiftedInt;
3089 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3090 ShiftedInt->getValue().isPowerOf2()) {
3091 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3092 // Safe because the only negative value (1 << Y) can take on is
3093 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3094 // the sign bit set.
3095 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3103 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3104 return commonDivTransforms(I);
3107 /// This function implements the transforms on rem instructions that work
3108 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3109 /// is used by the visitors to those instructions.
3110 /// @brief Transforms common to all three rem instructions
3111 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3112 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3114 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3115 if (I.getType()->isFPOrFPVector())
3116 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3117 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3119 if (isa<UndefValue>(Op1))
3120 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3122 // Handle cases involving: rem X, (select Cond, Y, Z)
3123 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3129 /// This function implements the transforms common to both integer remainder
3130 /// instructions (urem and srem). It is called by the visitors to those integer
3131 /// remainder instructions.
3132 /// @brief Common integer remainder transforms
3133 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3134 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3136 if (Instruction *common = commonRemTransforms(I))
3139 // 0 % X == 0 for integer, we don't need to preserve faults!
3140 if (Constant *LHS = dyn_cast<Constant>(Op0))
3141 if (LHS->isNullValue())
3142 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3144 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3145 // X % 0 == undef, we don't need to preserve faults!
3146 if (RHS->equalsInt(0))
3147 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3149 if (RHS->equalsInt(1)) // X % 1 == 0
3150 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3152 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3153 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3154 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3156 } else if (isa<PHINode>(Op0I)) {
3157 if (Instruction *NV = FoldOpIntoPhi(I))
3161 // See if we can fold away this rem instruction.
3162 if (SimplifyDemandedInstructionBits(I))
3170 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3171 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3173 if (Instruction *common = commonIRemTransforms(I))
3176 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3177 // X urem C^2 -> X and C
3178 // Check to see if this is an unsigned remainder with an exact power of 2,
3179 // if so, convert to a bitwise and.
3180 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3181 if (C->getValue().isPowerOf2())
3182 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3185 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3186 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3187 if (RHSI->getOpcode() == Instruction::Shl &&
3188 isa<ConstantInt>(RHSI->getOperand(0))) {
3189 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3190 Constant *N1 = Context->getAllOnesValue(I.getType());
3191 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3193 return BinaryOperator::CreateAnd(Op0, Add);
3198 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3199 // where C1&C2 are powers of two.
3200 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3201 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3202 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3203 // STO == 0 and SFO == 0 handled above.
3204 if ((STO->getValue().isPowerOf2()) &&
3205 (SFO->getValue().isPowerOf2())) {
3206 Value *TrueAnd = InsertNewInstBefore(
3207 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3208 SI->getName()+".t"), I);
3209 Value *FalseAnd = InsertNewInstBefore(
3210 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3211 SI->getName()+".f"), I);
3212 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3220 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3221 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3223 // Handle the integer rem common cases
3224 if (Instruction *common = commonIRemTransforms(I))
3227 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3228 if (!isa<Constant>(RHSNeg) ||
3229 (isa<ConstantInt>(RHSNeg) &&
3230 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3232 AddUsesToWorkList(I);
3233 I.setOperand(1, RHSNeg);
3237 // If the sign bits of both operands are zero (i.e. we can prove they are
3238 // unsigned inputs), turn this into a urem.
3239 if (I.getType()->isInteger()) {
3240 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3241 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3242 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3243 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3247 // If it's a constant vector, flip any negative values positive.
3248 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3249 unsigned VWidth = RHSV->getNumOperands();
3251 bool hasNegative = false;
3252 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3253 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3254 if (RHS->getValue().isNegative())
3258 std::vector<Constant *> Elts(VWidth);
3259 for (unsigned i = 0; i != VWidth; ++i) {
3260 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3261 if (RHS->getValue().isNegative())
3262 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3268 Constant *NewRHSV = Context->getConstantVector(Elts);
3269 if (NewRHSV != RHSV) {
3270 AddUsesToWorkList(I);
3271 I.setOperand(1, NewRHSV);
3280 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3281 return commonRemTransforms(I);
3284 // isOneBitSet - Return true if there is exactly one bit set in the specified
3286 static bool isOneBitSet(const ConstantInt *CI) {
3287 return CI->getValue().isPowerOf2();
3290 // isHighOnes - Return true if the constant is of the form 1+0+.
3291 // This is the same as lowones(~X).
3292 static bool isHighOnes(const ConstantInt *CI) {
3293 return (~CI->getValue() + 1).isPowerOf2();
3296 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3297 /// are carefully arranged to allow folding of expressions such as:
3299 /// (A < B) | (A > B) --> (A != B)
3301 /// Note that this is only valid if the first and second predicates have the
3302 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3304 /// Three bits are used to represent the condition, as follows:
3309 /// <=> Value Definition
3310 /// 000 0 Always false
3317 /// 111 7 Always true
3319 static unsigned getICmpCode(const ICmpInst *ICI) {
3320 switch (ICI->getPredicate()) {
3322 case ICmpInst::ICMP_UGT: return 1; // 001
3323 case ICmpInst::ICMP_SGT: return 1; // 001
3324 case ICmpInst::ICMP_EQ: return 2; // 010
3325 case ICmpInst::ICMP_UGE: return 3; // 011
3326 case ICmpInst::ICMP_SGE: return 3; // 011
3327 case ICmpInst::ICMP_ULT: return 4; // 100
3328 case ICmpInst::ICMP_SLT: return 4; // 100
3329 case ICmpInst::ICMP_NE: return 5; // 101
3330 case ICmpInst::ICMP_ULE: return 6; // 110
3331 case ICmpInst::ICMP_SLE: return 6; // 110
3334 llvm_unreachable("Invalid ICmp predicate!");
3339 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3340 /// predicate into a three bit mask. It also returns whether it is an ordered
3341 /// predicate by reference.
3342 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3345 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3346 case FCmpInst::FCMP_UNO: return 0; // 000
3347 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3348 case FCmpInst::FCMP_UGT: return 1; // 001
3349 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3350 case FCmpInst::FCMP_UEQ: return 2; // 010
3351 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3352 case FCmpInst::FCMP_UGE: return 3; // 011
3353 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3354 case FCmpInst::FCMP_ULT: return 4; // 100
3355 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3356 case FCmpInst::FCMP_UNE: return 5; // 101
3357 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3358 case FCmpInst::FCMP_ULE: return 6; // 110
3361 // Not expecting FCMP_FALSE and FCMP_TRUE;
3362 llvm_unreachable("Unexpected FCmp predicate!");
3367 /// getICmpValue - This is the complement of getICmpCode, which turns an
3368 /// opcode and two operands into either a constant true or false, or a brand
3369 /// new ICmp instruction. The sign is passed in to determine which kind
3370 /// of predicate to use in the new icmp instruction.
3371 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3372 LLVMContext *Context) {
3374 default: llvm_unreachable("Illegal ICmp code!");
3375 case 0: return Context->getFalse();
3378 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3380 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3381 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
3384 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3386 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3389 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3391 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3392 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
3395 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3397 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3398 case 7: return Context->getTrue();
3402 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3403 /// opcode and two operands into either a FCmp instruction. isordered is passed
3404 /// in to determine which kind of predicate to use in the new fcmp instruction.
3405 static Value *getFCmpValue(bool isordered, unsigned code,
3406 Value *LHS, Value *RHS, LLVMContext *Context) {
3408 default: llvm_unreachable("Illegal FCmp code!");
3411 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3413 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3416 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3418 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3421 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3423 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3426 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3428 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3431 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3433 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3436 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3438 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3441 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3443 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3444 case 7: return Context->getTrue();
3448 /// PredicatesFoldable - Return true if both predicates match sign or if at
3449 /// least one of them is an equality comparison (which is signless).
3450 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3451 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3452 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3453 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3457 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3458 struct FoldICmpLogical {
3461 ICmpInst::Predicate pred;
3462 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3463 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3464 pred(ICI->getPredicate()) {}
3465 bool shouldApply(Value *V) const {
3466 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3467 if (PredicatesFoldable(pred, ICI->getPredicate()))
3468 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3469 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3472 Instruction *apply(Instruction &Log) const {
3473 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3474 if (ICI->getOperand(0) != LHS) {
3475 assert(ICI->getOperand(1) == LHS);
3476 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3479 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3480 unsigned LHSCode = getICmpCode(ICI);
3481 unsigned RHSCode = getICmpCode(RHSICI);
3483 switch (Log.getOpcode()) {
3484 case Instruction::And: Code = LHSCode & RHSCode; break;
3485 case Instruction::Or: Code = LHSCode | RHSCode; break;
3486 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3487 default: llvm_unreachable("Illegal logical opcode!"); return 0;
3490 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3491 ICmpInst::isSignedPredicate(ICI->getPredicate());
3493 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3494 if (Instruction *I = dyn_cast<Instruction>(RV))
3496 // Otherwise, it's a constant boolean value...
3497 return IC.ReplaceInstUsesWith(Log, RV);
3500 } // end anonymous namespace
3502 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3503 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3504 // guaranteed to be a binary operator.
3505 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3507 ConstantInt *AndRHS,
3508 BinaryOperator &TheAnd) {
3509 Value *X = Op->getOperand(0);
3510 Constant *Together = 0;
3512 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3514 switch (Op->getOpcode()) {
3515 case Instruction::Xor:
3516 if (Op->hasOneUse()) {
3517 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3518 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3519 InsertNewInstBefore(And, TheAnd);
3521 return BinaryOperator::CreateXor(And, Together);
3524 case Instruction::Or:
3525 if (Together == AndRHS) // (X | C) & C --> C
3526 return ReplaceInstUsesWith(TheAnd, AndRHS);
3528 if (Op->hasOneUse() && Together != OpRHS) {
3529 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3530 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3531 InsertNewInstBefore(Or, TheAnd);
3533 return BinaryOperator::CreateAnd(Or, AndRHS);
3536 case Instruction::Add:
3537 if (Op->hasOneUse()) {
3538 // Adding a one to a single bit bit-field should be turned into an XOR
3539 // of the bit. First thing to check is to see if this AND is with a
3540 // single bit constant.
3541 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3543 // If there is only one bit set...
3544 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3545 // Ok, at this point, we know that we are masking the result of the
3546 // ADD down to exactly one bit. If the constant we are adding has
3547 // no bits set below this bit, then we can eliminate the ADD.
3548 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3550 // Check to see if any bits below the one bit set in AndRHSV are set.
3551 if ((AddRHS & (AndRHSV-1)) == 0) {
3552 // If not, the only thing that can effect the output of the AND is
3553 // the bit specified by AndRHSV. If that bit is set, the effect of
3554 // the XOR is to toggle the bit. If it is clear, then the ADD has
3556 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3557 TheAnd.setOperand(0, X);
3560 // Pull the XOR out of the AND.
3561 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3562 InsertNewInstBefore(NewAnd, TheAnd);
3563 NewAnd->takeName(Op);
3564 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3571 case Instruction::Shl: {
3572 // We know that the AND will not produce any of the bits shifted in, so if
3573 // the anded constant includes them, clear them now!
3575 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3576 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3577 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3578 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3580 if (CI->getValue() == ShlMask) {
3581 // Masking out bits that the shift already masks
3582 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3583 } else if (CI != AndRHS) { // Reducing bits set in and.
3584 TheAnd.setOperand(1, CI);
3589 case Instruction::LShr:
3591 // We know that the AND will not produce any of the bits shifted in, so if
3592 // the anded constant includes them, clear them now! This only applies to
3593 // unsigned shifts, because a signed shr may bring in set bits!
3595 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3596 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3597 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3598 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3600 if (CI->getValue() == ShrMask) {
3601 // Masking out bits that the shift already masks.
3602 return ReplaceInstUsesWith(TheAnd, Op);
3603 } else if (CI != AndRHS) {
3604 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3609 case Instruction::AShr:
3611 // See if this is shifting in some sign extension, then masking it out
3613 if (Op->hasOneUse()) {
3614 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3615 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3616 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3617 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3618 if (C == AndRHS) { // Masking out bits shifted in.
3619 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3620 // Make the argument unsigned.
3621 Value *ShVal = Op->getOperand(0);
3622 ShVal = InsertNewInstBefore(
3623 BinaryOperator::CreateLShr(ShVal, OpRHS,
3624 Op->getName()), TheAnd);
3625 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3634 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3635 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3636 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3637 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3638 /// insert new instructions.
3639 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3640 bool isSigned, bool Inside,
3642 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
3643 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3644 "Lo is not <= Hi in range emission code!");
3647 if (Lo == Hi) // Trivially false.
3648 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3650 // V >= Min && V < Hi --> V < Hi
3651 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3652 ICmpInst::Predicate pred = (isSigned ?
3653 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3654 return new ICmpInst(*Context, pred, V, Hi);
3657 // Emit V-Lo <u Hi-Lo
3658 Constant *NegLo = Context->getConstantExprNeg(Lo);
3659 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3660 InsertNewInstBefore(Add, IB);
3661 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3662 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3665 if (Lo == Hi) // Trivially true.
3666 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3668 // V < Min || V >= Hi -> V > Hi-1
3669 Hi = SubOne(cast<ConstantInt>(Hi), Context);
3670 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3671 ICmpInst::Predicate pred = (isSigned ?
3672 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3673 return new ICmpInst(*Context, pred, V, Hi);
3676 // Emit V-Lo >u Hi-1-Lo
3677 // Note that Hi has already had one subtracted from it, above.
3678 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3679 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3680 InsertNewInstBefore(Add, IB);
3681 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3682 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3685 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3686 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3687 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3688 // not, since all 1s are not contiguous.
3689 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3690 const APInt& V = Val->getValue();
3691 uint32_t BitWidth = Val->getType()->getBitWidth();
3692 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3694 // look for the first zero bit after the run of ones
3695 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3696 // look for the first non-zero bit
3697 ME = V.getActiveBits();
3701 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3702 /// where isSub determines whether the operator is a sub. If we can fold one of
3703 /// the following xforms:
3705 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3706 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3707 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3709 /// return (A +/- B).
3711 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3712 ConstantInt *Mask, bool isSub,
3714 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3715 if (!LHSI || LHSI->getNumOperands() != 2 ||
3716 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3718 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3720 switch (LHSI->getOpcode()) {
3722 case Instruction::And:
3723 if (Context->getConstantExprAnd(N, Mask) == Mask) {
3724 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3725 if ((Mask->getValue().countLeadingZeros() +
3726 Mask->getValue().countPopulation()) ==
3727 Mask->getValue().getBitWidth())
3730 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3731 // part, we don't need any explicit masks to take them out of A. If that
3732 // is all N is, ignore it.
3733 uint32_t MB = 0, ME = 0;
3734 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3735 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3736 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3737 if (MaskedValueIsZero(RHS, Mask))
3742 case Instruction::Or:
3743 case Instruction::Xor:
3744 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3745 if ((Mask->getValue().countLeadingZeros() +
3746 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3747 && Context->getConstantExprAnd(N, Mask)->isNullValue())
3754 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3756 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3757 return InsertNewInstBefore(New, I);
3760 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3761 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3762 ICmpInst *LHS, ICmpInst *RHS) {
3764 ConstantInt *LHSCst, *RHSCst;
3765 ICmpInst::Predicate LHSCC, RHSCC;
3767 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3768 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3769 m_ConstantInt(LHSCst)), *Context) ||
3770 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3771 m_ConstantInt(RHSCst)), *Context))
3774 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3775 // where C is a power of 2
3776 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3777 LHSCst->getValue().isPowerOf2()) {
3778 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3779 InsertNewInstBefore(NewOr, I);
3780 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3783 // From here on, we only handle:
3784 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3785 if (Val != Val2) return 0;
3787 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3788 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3789 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3790 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3791 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3794 // We can't fold (ugt x, C) & (sgt x, C2).
3795 if (!PredicatesFoldable(LHSCC, RHSCC))
3798 // Ensure that the larger constant is on the RHS.
3800 if (ICmpInst::isSignedPredicate(LHSCC) ||
3801 (ICmpInst::isEquality(LHSCC) &&
3802 ICmpInst::isSignedPredicate(RHSCC)))
3803 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3805 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3808 std::swap(LHS, RHS);
3809 std::swap(LHSCst, RHSCst);
3810 std::swap(LHSCC, RHSCC);
3813 // At this point, we know we have have two icmp instructions
3814 // comparing a value against two constants and and'ing the result
3815 // together. Because of the above check, we know that we only have
3816 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3817 // (from the FoldICmpLogical check above), that the two constants
3818 // are not equal and that the larger constant is on the RHS
3819 assert(LHSCst != RHSCst && "Compares not folded above?");
3822 default: llvm_unreachable("Unknown integer condition code!");
3823 case ICmpInst::ICMP_EQ:
3825 default: llvm_unreachable("Unknown integer condition code!");
3826 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3827 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3828 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3829 return ReplaceInstUsesWith(I, Context->getFalse());
3830 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3831 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3832 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3833 return ReplaceInstUsesWith(I, LHS);
3835 case ICmpInst::ICMP_NE:
3837 default: llvm_unreachable("Unknown integer condition code!");
3838 case ICmpInst::ICMP_ULT:
3839 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3840 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3841 break; // (X != 13 & X u< 15) -> no change
3842 case ICmpInst::ICMP_SLT:
3843 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3844 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3845 break; // (X != 13 & X s< 15) -> no change
3846 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3847 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3848 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3849 return ReplaceInstUsesWith(I, RHS);
3850 case ICmpInst::ICMP_NE:
3851 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3852 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3853 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3854 Val->getName()+".off");
3855 InsertNewInstBefore(Add, I);
3856 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3857 Context->getConstantInt(Add->getType(), 1));
3859 break; // (X != 13 & X != 15) -> no change
3862 case ICmpInst::ICMP_ULT:
3864 default: llvm_unreachable("Unknown integer condition code!");
3865 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3866 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3867 return ReplaceInstUsesWith(I, Context->getFalse());
3868 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3870 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3871 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3872 return ReplaceInstUsesWith(I, LHS);
3873 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3877 case ICmpInst::ICMP_SLT:
3879 default: llvm_unreachable("Unknown integer condition code!");
3880 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3881 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3882 return ReplaceInstUsesWith(I, Context->getFalse());
3883 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3885 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3886 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3887 return ReplaceInstUsesWith(I, LHS);
3888 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3892 case ICmpInst::ICMP_UGT:
3894 default: llvm_unreachable("Unknown integer condition code!");
3895 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3896 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3897 return ReplaceInstUsesWith(I, RHS);
3898 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3900 case ICmpInst::ICMP_NE:
3901 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3902 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3903 break; // (X u> 13 & X != 15) -> no change
3904 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3905 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3906 RHSCst, false, true, I);
3907 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3911 case ICmpInst::ICMP_SGT:
3913 default: llvm_unreachable("Unknown integer condition code!");
3914 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3915 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3916 return ReplaceInstUsesWith(I, RHS);
3917 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3919 case ICmpInst::ICMP_NE:
3920 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3921 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3922 break; // (X s> 13 & X != 15) -> no change
3923 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3924 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3925 RHSCst, true, true, I);
3926 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3936 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3937 bool Changed = SimplifyCommutative(I);
3938 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3940 if (isa<UndefValue>(Op1)) // X & undef -> 0
3941 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3945 return ReplaceInstUsesWith(I, Op1);
3947 // See if we can simplify any instructions used by the instruction whose sole
3948 // purpose is to compute bits we don't care about.
3949 if (SimplifyDemandedInstructionBits(I))
3951 if (isa<VectorType>(I.getType())) {
3952 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3953 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3954 return ReplaceInstUsesWith(I, I.getOperand(0));
3955 } else if (isa<ConstantAggregateZero>(Op1)) {
3956 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3960 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3961 const APInt& AndRHSMask = AndRHS->getValue();
3962 APInt NotAndRHS(~AndRHSMask);
3964 // Optimize a variety of ((val OP C1) & C2) combinations...
3965 if (isa<BinaryOperator>(Op0)) {
3966 Instruction *Op0I = cast<Instruction>(Op0);
3967 Value *Op0LHS = Op0I->getOperand(0);
3968 Value *Op0RHS = Op0I->getOperand(1);
3969 switch (Op0I->getOpcode()) {
3970 case Instruction::Xor:
3971 case Instruction::Or:
3972 // If the mask is only needed on one incoming arm, push it up.
3973 if (Op0I->hasOneUse()) {
3974 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3975 // Not masking anything out for the LHS, move to RHS.
3976 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3977 Op0RHS->getName()+".masked");
3978 InsertNewInstBefore(NewRHS, I);
3979 return BinaryOperator::Create(
3980 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3982 if (!isa<Constant>(Op0RHS) &&
3983 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3984 // Not masking anything out for the RHS, move to LHS.
3985 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3986 Op0LHS->getName()+".masked");
3987 InsertNewInstBefore(NewLHS, I);
3988 return BinaryOperator::Create(
3989 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3994 case Instruction::Add:
3995 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3996 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3997 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3998 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3999 return BinaryOperator::CreateAnd(V, AndRHS);
4000 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4001 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4004 case Instruction::Sub:
4005 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4006 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4007 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4008 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4009 return BinaryOperator::CreateAnd(V, AndRHS);
4011 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4012 // has 1's for all bits that the subtraction with A might affect.
4013 if (Op0I->hasOneUse()) {
4014 uint32_t BitWidth = AndRHSMask.getBitWidth();
4015 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4016 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4018 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4019 if (!(A && A->isZero()) && // avoid infinite recursion.
4020 MaskedValueIsZero(Op0LHS, Mask)) {
4021 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4022 InsertNewInstBefore(NewNeg, I);
4023 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4028 case Instruction::Shl:
4029 case Instruction::LShr:
4030 // (1 << x) & 1 --> zext(x == 0)
4031 // (1 >> x) & 1 --> zext(x == 0)
4032 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4033 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4034 Op0RHS, Context->getNullValue(I.getType()));
4035 InsertNewInstBefore(NewICmp, I);
4036 return new ZExtInst(NewICmp, I.getType());
4041 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4042 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4044 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4045 // If this is an integer truncation or change from signed-to-unsigned, and
4046 // if the source is an and/or with immediate, transform it. This
4047 // frequently occurs for bitfield accesses.
4048 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4049 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4050 CastOp->getNumOperands() == 2)
4051 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4052 if (CastOp->getOpcode() == Instruction::And) {
4053 // Change: and (cast (and X, C1) to T), C2
4054 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4055 // This will fold the two constants together, which may allow
4056 // other simplifications.
4057 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4058 CastOp->getOperand(0), I.getType(),
4059 CastOp->getName()+".shrunk");
4060 NewCast = InsertNewInstBefore(NewCast, I);
4061 // trunc_or_bitcast(C1)&C2
4063 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4064 C3 = Context->getConstantExprAnd(C3, AndRHS);
4065 return BinaryOperator::CreateAnd(NewCast, C3);
4066 } else if (CastOp->getOpcode() == Instruction::Or) {
4067 // Change: and (cast (or X, C1) to T), C2
4068 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4070 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4071 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4073 return ReplaceInstUsesWith(I, AndRHS);
4079 // Try to fold constant and into select arguments.
4080 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4081 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4083 if (isa<PHINode>(Op0))
4084 if (Instruction *NV = FoldOpIntoPhi(I))
4088 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4089 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4091 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4092 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4094 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4095 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4096 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4097 I.getName()+".demorgan");
4098 InsertNewInstBefore(Or, I);
4099 return BinaryOperator::CreateNot(*Context, Or);
4103 Value *A = 0, *B = 0, *C = 0, *D = 0;
4104 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4105 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4106 return ReplaceInstUsesWith(I, Op1);
4108 // (A|B) & ~(A&B) -> A^B
4109 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4110 if ((A == C && B == D) || (A == D && B == C))
4111 return BinaryOperator::CreateXor(A, B);
4115 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4116 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4117 return ReplaceInstUsesWith(I, Op0);
4119 // ~(A&B) & (A|B) -> A^B
4120 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4121 if ((A == C && B == D) || (A == D && B == C))
4122 return BinaryOperator::CreateXor(A, B);
4126 if (Op0->hasOneUse() &&
4127 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4128 if (A == Op1) { // (A^B)&A -> A&(A^B)
4129 I.swapOperands(); // Simplify below
4130 std::swap(Op0, Op1);
4131 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4132 cast<BinaryOperator>(Op0)->swapOperands();
4133 I.swapOperands(); // Simplify below
4134 std::swap(Op0, Op1);
4138 if (Op1->hasOneUse() &&
4139 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4140 if (B == Op0) { // B&(A^B) -> B&(B^A)
4141 cast<BinaryOperator>(Op1)->swapOperands();
4144 if (A == Op0) { // A&(A^B) -> A & ~B
4145 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4146 InsertNewInstBefore(NotB, I);
4147 return BinaryOperator::CreateAnd(A, NotB);
4151 // (A&((~A)|B)) -> A&B
4152 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4153 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4154 return BinaryOperator::CreateAnd(A, Op1);
4155 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4156 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4157 return BinaryOperator::CreateAnd(A, Op0);
4160 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4161 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4162 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4165 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4166 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4170 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4171 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4172 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4173 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4174 const Type *SrcTy = Op0C->getOperand(0)->getType();
4175 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4176 // Only do this if the casts both really cause code to be generated.
4177 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4179 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4181 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4182 Op1C->getOperand(0),
4184 InsertNewInstBefore(NewOp, I);
4185 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4189 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4190 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4191 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4192 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4193 SI0->getOperand(1) == SI1->getOperand(1) &&
4194 (SI0->hasOneUse() || SI1->hasOneUse())) {
4195 Instruction *NewOp =
4196 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4198 SI0->getName()), I);
4199 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4200 SI1->getOperand(1));
4204 // If and'ing two fcmp, try combine them into one.
4205 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4206 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4207 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4208 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4209 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4210 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4211 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4212 // If either of the constants are nans, then the whole thing returns
4214 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4215 return ReplaceInstUsesWith(I, Context->getFalse());
4216 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4217 LHS->getOperand(0), RHS->getOperand(0));
4220 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4221 FCmpInst::Predicate Op0CC, Op1CC;
4222 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4223 m_Value(Op0RHS)), *Context) &&
4224 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4225 m_Value(Op1RHS)), *Context)) {
4226 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4227 // Swap RHS operands to match LHS.
4228 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4229 std::swap(Op1LHS, Op1RHS);
4231 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4232 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4234 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4236 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4237 Op1CC == FCmpInst::FCMP_FALSE)
4238 return ReplaceInstUsesWith(I, Context->getFalse());
4239 else if (Op0CC == FCmpInst::FCMP_TRUE)
4240 return ReplaceInstUsesWith(I, Op1);
4241 else if (Op1CC == FCmpInst::FCMP_TRUE)
4242 return ReplaceInstUsesWith(I, Op0);
4245 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4246 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4248 std::swap(Op0, Op1);
4249 std::swap(Op0Pred, Op1Pred);
4250 std::swap(Op0Ordered, Op1Ordered);
4253 // uno && ueq -> uno && (uno || eq) -> ueq
4254 // ord && olt -> ord && (ord && lt) -> olt
4255 if (Op0Ordered == Op1Ordered)
4256 return ReplaceInstUsesWith(I, Op1);
4257 // uno && oeq -> uno && (ord && eq) -> false
4258 // uno && ord -> false
4260 return ReplaceInstUsesWith(I, Context->getFalse());
4261 // ord && ueq -> ord && (uno || eq) -> oeq
4262 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4263 Op0LHS, Op0RHS, Context));
4271 return Changed ? &I : 0;
4274 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4275 /// capable of providing pieces of a bswap. The subexpression provides pieces
4276 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4277 /// the expression came from the corresponding "byte swapped" byte in some other
4278 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4279 /// we know that the expression deposits the low byte of %X into the high byte
4280 /// of the bswap result and that all other bytes are zero. This expression is
4281 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4284 /// This function returns true if the match was unsuccessful and false if so.
4285 /// On entry to the function the "OverallLeftShift" is a signed integer value
4286 /// indicating the number of bytes that the subexpression is later shifted. For
4287 /// example, if the expression is later right shifted by 16 bits, the
4288 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4289 /// byte of ByteValues is actually being set.
4291 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4292 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4293 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4294 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4295 /// always in the local (OverallLeftShift) coordinate space.
4297 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4298 SmallVector<Value*, 8> &ByteValues) {
4299 if (Instruction *I = dyn_cast<Instruction>(V)) {
4300 // If this is an or instruction, it may be an inner node of the bswap.
4301 if (I->getOpcode() == Instruction::Or) {
4302 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4304 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4308 // If this is a logical shift by a constant multiple of 8, recurse with
4309 // OverallLeftShift and ByteMask adjusted.
4310 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4312 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4313 // Ensure the shift amount is defined and of a byte value.
4314 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4317 unsigned ByteShift = ShAmt >> 3;
4318 if (I->getOpcode() == Instruction::Shl) {
4319 // X << 2 -> collect(X, +2)
4320 OverallLeftShift += ByteShift;
4321 ByteMask >>= ByteShift;
4323 // X >>u 2 -> collect(X, -2)
4324 OverallLeftShift -= ByteShift;
4325 ByteMask <<= ByteShift;
4326 ByteMask &= (~0U >> (32-ByteValues.size()));
4329 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4330 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4332 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4336 // If this is a logical 'and' with a mask that clears bytes, clear the
4337 // corresponding bytes in ByteMask.
4338 if (I->getOpcode() == Instruction::And &&
4339 isa<ConstantInt>(I->getOperand(1))) {
4340 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4341 unsigned NumBytes = ByteValues.size();
4342 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4343 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4345 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4346 // If this byte is masked out by a later operation, we don't care what
4348 if ((ByteMask & (1 << i)) == 0)
4351 // If the AndMask is all zeros for this byte, clear the bit.
4352 APInt MaskB = AndMask & Byte;
4354 ByteMask &= ~(1U << i);
4358 // If the AndMask is not all ones for this byte, it's not a bytezap.
4362 // Otherwise, this byte is kept.
4365 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4370 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4371 // the input value to the bswap. Some observations: 1) if more than one byte
4372 // is demanded from this input, then it could not be successfully assembled
4373 // into a byteswap. At least one of the two bytes would not be aligned with
4374 // their ultimate destination.
4375 if (!isPowerOf2_32(ByteMask)) return true;
4376 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4378 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4379 // is demanded, it needs to go into byte 0 of the result. This means that the
4380 // byte needs to be shifted until it lands in the right byte bucket. The
4381 // shift amount depends on the position: if the byte is coming from the high
4382 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4383 // low part, it must be shifted left.
4384 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4385 if (InputByteNo < ByteValues.size()/2) {
4386 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4389 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4393 // If the destination byte value is already defined, the values are or'd
4394 // together, which isn't a bswap (unless it's an or of the same bits).
4395 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4397 ByteValues[DestByteNo] = V;
4401 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4402 /// If so, insert the new bswap intrinsic and return it.
4403 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4404 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4405 if (!ITy || ITy->getBitWidth() % 16 ||
4406 // ByteMask only allows up to 32-byte values.
4407 ITy->getBitWidth() > 32*8)
4408 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4410 /// ByteValues - For each byte of the result, we keep track of which value
4411 /// defines each byte.
4412 SmallVector<Value*, 8> ByteValues;
4413 ByteValues.resize(ITy->getBitWidth()/8);
4415 // Try to find all the pieces corresponding to the bswap.
4416 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4417 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4420 // Check to see if all of the bytes come from the same value.
4421 Value *V = ByteValues[0];
4422 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4424 // Check to make sure that all of the bytes come from the same value.
4425 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4426 if (ByteValues[i] != V)
4428 const Type *Tys[] = { ITy };
4429 Module *M = I.getParent()->getParent()->getParent();
4430 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4431 return CallInst::Create(F, V);
4434 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4435 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4436 /// we can simplify this expression to "cond ? C : D or B".
4437 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4439 LLVMContext *Context) {
4440 // If A is not a select of -1/0, this cannot match.
4442 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4445 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4446 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4447 return SelectInst::Create(Cond, C, B);
4448 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4449 return SelectInst::Create(Cond, C, B);
4450 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4451 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4452 return SelectInst::Create(Cond, C, D);
4453 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4454 return SelectInst::Create(Cond, C, D);
4458 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4459 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4460 ICmpInst *LHS, ICmpInst *RHS) {
4462 ConstantInt *LHSCst, *RHSCst;
4463 ICmpInst::Predicate LHSCC, RHSCC;
4465 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4466 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4467 m_ConstantInt(LHSCst)), *Context) ||
4468 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4469 m_ConstantInt(RHSCst)), *Context))
4472 // From here on, we only handle:
4473 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4474 if (Val != Val2) return 0;
4476 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4477 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4478 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4479 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4480 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4483 // We can't fold (ugt x, C) | (sgt x, C2).
4484 if (!PredicatesFoldable(LHSCC, RHSCC))
4487 // Ensure that the larger constant is on the RHS.
4489 if (ICmpInst::isSignedPredicate(LHSCC) ||
4490 (ICmpInst::isEquality(LHSCC) &&
4491 ICmpInst::isSignedPredicate(RHSCC)))
4492 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4494 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4497 std::swap(LHS, RHS);
4498 std::swap(LHSCst, RHSCst);
4499 std::swap(LHSCC, RHSCC);
4502 // At this point, we know we have have two icmp instructions
4503 // comparing a value against two constants and or'ing the result
4504 // together. Because of the above check, we know that we only have
4505 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4506 // FoldICmpLogical check above), that the two constants are not
4508 assert(LHSCst != RHSCst && "Compares not folded above?");
4511 default: llvm_unreachable("Unknown integer condition code!");
4512 case ICmpInst::ICMP_EQ:
4514 default: llvm_unreachable("Unknown integer condition code!");
4515 case ICmpInst::ICMP_EQ:
4516 if (LHSCst == SubOne(RHSCst, Context)) {
4517 // (X == 13 | X == 14) -> X-13 <u 2
4518 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4519 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4520 Val->getName()+".off");
4521 InsertNewInstBefore(Add, I);
4522 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4523 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4525 break; // (X == 13 | X == 15) -> no change
4526 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4527 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4529 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4530 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4531 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4532 return ReplaceInstUsesWith(I, RHS);
4535 case ICmpInst::ICMP_NE:
4537 default: llvm_unreachable("Unknown integer condition code!");
4538 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4539 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4540 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4541 return ReplaceInstUsesWith(I, LHS);
4542 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4543 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4544 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4545 return ReplaceInstUsesWith(I, Context->getTrue());
4548 case ICmpInst::ICMP_ULT:
4550 default: llvm_unreachable("Unknown integer condition code!");
4551 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4553 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4554 // If RHSCst is [us]MAXINT, it is always false. Not handling
4555 // this can cause overflow.
4556 if (RHSCst->isMaxValue(false))
4557 return ReplaceInstUsesWith(I, LHS);
4558 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4560 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4562 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4563 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4564 return ReplaceInstUsesWith(I, RHS);
4565 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4569 case ICmpInst::ICMP_SLT:
4571 default: llvm_unreachable("Unknown integer condition code!");
4572 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4574 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4575 // If RHSCst is [us]MAXINT, it is always false. Not handling
4576 // this can cause overflow.
4577 if (RHSCst->isMaxValue(true))
4578 return ReplaceInstUsesWith(I, LHS);
4579 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4581 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4583 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4584 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4585 return ReplaceInstUsesWith(I, RHS);
4586 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4590 case ICmpInst::ICMP_UGT:
4592 default: llvm_unreachable("Unknown integer condition code!");
4593 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4594 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4595 return ReplaceInstUsesWith(I, LHS);
4596 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4598 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4599 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4600 return ReplaceInstUsesWith(I, Context->getTrue());
4601 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4605 case ICmpInst::ICMP_SGT:
4607 default: llvm_unreachable("Unknown integer condition code!");
4608 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4609 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4610 return ReplaceInstUsesWith(I, LHS);
4611 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4613 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4614 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4615 return ReplaceInstUsesWith(I, Context->getTrue());
4616 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4624 /// FoldOrWithConstants - This helper function folds:
4626 /// ((A | B) & C1) | (B & C2)
4632 /// when the XOR of the two constants is "all ones" (-1).
4633 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4634 Value *A, Value *B, Value *C) {
4635 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4639 ConstantInt *CI2 = 0;
4640 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4642 APInt Xor = CI1->getValue() ^ CI2->getValue();
4643 if (!Xor.isAllOnesValue()) return 0;
4645 if (V1 == A || V1 == B) {
4646 Instruction *NewOp =
4647 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4648 return BinaryOperator::CreateOr(NewOp, V1);
4654 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4655 bool Changed = SimplifyCommutative(I);
4656 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4658 if (isa<UndefValue>(Op1)) // X | undef -> -1
4659 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4663 return ReplaceInstUsesWith(I, Op0);
4665 // See if we can simplify any instructions used by the instruction whose sole
4666 // purpose is to compute bits we don't care about.
4667 if (SimplifyDemandedInstructionBits(I))
4669 if (isa<VectorType>(I.getType())) {
4670 if (isa<ConstantAggregateZero>(Op1)) {
4671 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4672 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4673 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4674 return ReplaceInstUsesWith(I, I.getOperand(1));
4679 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4680 ConstantInt *C1 = 0; Value *X = 0;
4681 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4682 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4684 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4685 InsertNewInstBefore(Or, I);
4687 return BinaryOperator::CreateAnd(Or,
4688 Context->getConstantInt(RHS->getValue() | C1->getValue()));
4691 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4692 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4694 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4695 InsertNewInstBefore(Or, I);
4697 return BinaryOperator::CreateXor(Or,
4698 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4701 // Try to fold constant and into select arguments.
4702 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4703 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4705 if (isa<PHINode>(Op0))
4706 if (Instruction *NV = FoldOpIntoPhi(I))
4710 Value *A = 0, *B = 0;
4711 ConstantInt *C1 = 0, *C2 = 0;
4713 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4714 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4715 return ReplaceInstUsesWith(I, Op1);
4716 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4717 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4718 return ReplaceInstUsesWith(I, Op0);
4720 // (A | B) | C and A | (B | C) -> bswap if possible.
4721 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4722 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4723 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4724 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4725 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4726 if (Instruction *BSwap = MatchBSwap(I))
4730 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4731 if (Op0->hasOneUse() &&
4732 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4733 MaskedValueIsZero(Op1, C1->getValue())) {
4734 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4735 InsertNewInstBefore(NOr, I);
4737 return BinaryOperator::CreateXor(NOr, C1);
4740 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4741 if (Op1->hasOneUse() &&
4742 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4743 MaskedValueIsZero(Op0, C1->getValue())) {
4744 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4745 InsertNewInstBefore(NOr, I);
4747 return BinaryOperator::CreateXor(NOr, C1);
4751 Value *C = 0, *D = 0;
4752 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4753 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4754 Value *V1 = 0, *V2 = 0, *V3 = 0;
4755 C1 = dyn_cast<ConstantInt>(C);
4756 C2 = dyn_cast<ConstantInt>(D);
4757 if (C1 && C2) { // (A & C1)|(B & C2)
4758 // If we have: ((V + N) & C1) | (V & C2)
4759 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4760 // replace with V+N.
4761 if (C1->getValue() == ~C2->getValue()) {
4762 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4763 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4764 // Add commutes, try both ways.
4765 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4766 return ReplaceInstUsesWith(I, A);
4767 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4768 return ReplaceInstUsesWith(I, A);
4770 // Or commutes, try both ways.
4771 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4772 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4773 // Add commutes, try both ways.
4774 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4775 return ReplaceInstUsesWith(I, B);
4776 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4777 return ReplaceInstUsesWith(I, B);
4780 V1 = 0; V2 = 0; V3 = 0;
4783 // Check to see if we have any common things being and'ed. If so, find the
4784 // terms for V1 & (V2|V3).
4785 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4786 if (A == B) // (A & C)|(A & D) == A & (C|D)
4787 V1 = A, V2 = C, V3 = D;
4788 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4789 V1 = A, V2 = B, V3 = C;
4790 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4791 V1 = C, V2 = A, V3 = D;
4792 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4793 V1 = C, V2 = A, V3 = B;
4797 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4798 return BinaryOperator::CreateAnd(V1, Or);
4802 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4803 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4805 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4807 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4809 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4812 // ((A&~B)|(~A&B)) -> A^B
4813 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4814 match(B, m_Not(m_Specific(A)), *Context)))
4815 return BinaryOperator::CreateXor(A, D);
4816 // ((~B&A)|(~A&B)) -> A^B
4817 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4818 match(B, m_Not(m_Specific(C)), *Context)))
4819 return BinaryOperator::CreateXor(C, D);
4820 // ((A&~B)|(B&~A)) -> A^B
4821 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4822 match(D, m_Not(m_Specific(A)), *Context)))
4823 return BinaryOperator::CreateXor(A, B);
4824 // ((~B&A)|(B&~A)) -> A^B
4825 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4826 match(D, m_Not(m_Specific(C)), *Context)))
4827 return BinaryOperator::CreateXor(C, B);
4830 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4831 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4832 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4833 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4834 SI0->getOperand(1) == SI1->getOperand(1) &&
4835 (SI0->hasOneUse() || SI1->hasOneUse())) {
4836 Instruction *NewOp =
4837 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4839 SI0->getName()), I);
4840 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4841 SI1->getOperand(1));
4845 // ((A|B)&1)|(B&-2) -> (A&1) | B
4846 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4847 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4848 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4849 if (Ret) return Ret;
4851 // (B&-2)|((A|B)&1) -> (A&1) | B
4852 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4853 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4854 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4855 if (Ret) return Ret;
4858 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
4859 if (A == Op1) // ~A | A == -1
4860 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4864 // Note, A is still live here!
4865 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
4867 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4869 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4870 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4871 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4872 I.getName()+".demorgan"), I);
4873 return BinaryOperator::CreateNot(*Context, And);
4877 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4878 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4879 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4882 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4883 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4887 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4888 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4889 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4890 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4891 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4892 !isa<ICmpInst>(Op1C->getOperand(0))) {
4893 const Type *SrcTy = Op0C->getOperand(0)->getType();
4894 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4895 // Only do this if the casts both really cause code to be
4897 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4899 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4901 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4902 Op1C->getOperand(0),
4904 InsertNewInstBefore(NewOp, I);
4905 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4912 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4913 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4914 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4915 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4916 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4917 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4918 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4919 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4920 // If either of the constants are nans, then the whole thing returns
4922 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4923 return ReplaceInstUsesWith(I, Context->getTrue());
4925 // Otherwise, no need to compare the two constants, compare the
4927 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4928 LHS->getOperand(0), RHS->getOperand(0));
4931 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4932 FCmpInst::Predicate Op0CC, Op1CC;
4933 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4934 m_Value(Op0RHS)), *Context) &&
4935 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4936 m_Value(Op1RHS)), *Context)) {
4937 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4938 // Swap RHS operands to match LHS.
4939 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4940 std::swap(Op1LHS, Op1RHS);
4942 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4943 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4945 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4947 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4948 Op1CC == FCmpInst::FCMP_TRUE)
4949 return ReplaceInstUsesWith(I, Context->getTrue());
4950 else if (Op0CC == FCmpInst::FCMP_FALSE)
4951 return ReplaceInstUsesWith(I, Op1);
4952 else if (Op1CC == FCmpInst::FCMP_FALSE)
4953 return ReplaceInstUsesWith(I, Op0);
4956 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4957 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4958 if (Op0Ordered == Op1Ordered) {
4959 // If both are ordered or unordered, return a new fcmp with
4960 // or'ed predicates.
4961 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4962 Op0LHS, Op0RHS, Context);
4963 if (Instruction *I = dyn_cast<Instruction>(RV))
4965 // Otherwise, it's a constant boolean value...
4966 return ReplaceInstUsesWith(I, RV);
4974 return Changed ? &I : 0;
4979 // XorSelf - Implements: X ^ X --> 0
4982 XorSelf(Value *rhs) : RHS(rhs) {}
4983 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4984 Instruction *apply(BinaryOperator &Xor) const {
4991 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4992 bool Changed = SimplifyCommutative(I);
4993 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4995 if (isa<UndefValue>(Op1)) {
4996 if (isa<UndefValue>(Op0))
4997 // Handle undef ^ undef -> 0 special case. This is a common
4999 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5000 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
5003 // xor X, X = 0, even if X is nested in a sequence of Xor's.
5004 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5005 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5006 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5009 // See if we can simplify any instructions used by the instruction whose sole
5010 // purpose is to compute bits we don't care about.
5011 if (SimplifyDemandedInstructionBits(I))
5013 if (isa<VectorType>(I.getType()))
5014 if (isa<ConstantAggregateZero>(Op1))
5015 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
5017 // Is this a ~ operation?
5018 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5019 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5020 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5021 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5022 if (Op0I->getOpcode() == Instruction::And ||
5023 Op0I->getOpcode() == Instruction::Or) {
5024 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5025 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5027 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5028 Op0I->getOperand(1)->getName()+".not");
5029 InsertNewInstBefore(NotY, I);
5030 if (Op0I->getOpcode() == Instruction::And)
5031 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5033 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5040 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5041 if (RHS == Context->getTrue() && Op0->hasOneUse()) {
5042 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5043 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5044 return new ICmpInst(*Context, ICI->getInversePredicate(),
5045 ICI->getOperand(0), ICI->getOperand(1));
5047 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5048 return new FCmpInst(*Context, FCI->getInversePredicate(),
5049 FCI->getOperand(0), FCI->getOperand(1));
5052 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5053 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5054 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5055 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5056 Instruction::CastOps Opcode = Op0C->getOpcode();
5057 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5058 if (RHS == Context->getConstantExprCast(Opcode,
5060 Op0C->getDestTy())) {
5061 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5063 CI->getOpcode(), CI->getInversePredicate(),
5064 CI->getOperand(0), CI->getOperand(1)), I);
5065 NewCI->takeName(CI);
5066 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5073 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5074 // ~(c-X) == X-c-1 == X+(-c-1)
5075 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5076 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5077 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5078 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5079 Context->getConstantInt(I.getType(), 1));
5080 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5083 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5084 if (Op0I->getOpcode() == Instruction::Add) {
5085 // ~(X-c) --> (-c-1)-X
5086 if (RHS->isAllOnesValue()) {
5087 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5088 return BinaryOperator::CreateSub(
5089 Context->getConstantExprSub(NegOp0CI,
5090 Context->getConstantInt(I.getType(), 1)),
5091 Op0I->getOperand(0));
5092 } else if (RHS->getValue().isSignBit()) {
5093 // (X + C) ^ signbit -> (X + C + signbit)
5095 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5096 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5099 } else if (Op0I->getOpcode() == Instruction::Or) {
5100 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5101 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5102 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5103 // Anything in both C1 and C2 is known to be zero, remove it from
5105 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5106 NewRHS = Context->getConstantExprAnd(NewRHS,
5107 Context->getConstantExprNot(CommonBits));
5108 AddToWorkList(Op0I);
5109 I.setOperand(0, Op0I->getOperand(0));
5110 I.setOperand(1, NewRHS);
5117 // Try to fold constant and into select arguments.
5118 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5119 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5121 if (isa<PHINode>(Op0))
5122 if (Instruction *NV = FoldOpIntoPhi(I))
5126 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
5128 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5130 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
5132 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5135 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5138 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5139 if (A == Op0) { // B^(B|A) == (A|B)^B
5140 Op1I->swapOperands();
5142 std::swap(Op0, Op1);
5143 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5144 I.swapOperands(); // Simplified below.
5145 std::swap(Op0, Op1);
5147 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5148 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5149 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5150 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5151 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5153 if (A == Op0) { // A^(A&B) -> A^(B&A)
5154 Op1I->swapOperands();
5157 if (B == Op0) { // A^(B&A) -> (B&A)^A
5158 I.swapOperands(); // Simplified below.
5159 std::swap(Op0, Op1);
5164 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5167 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5168 Op0I->hasOneUse()) {
5169 if (A == Op1) // (B|A)^B == (A|B)^B
5171 if (B == Op1) { // (A|B)^B == A & ~B
5173 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5175 return BinaryOperator::CreateAnd(A, NotB);
5177 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5178 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5179 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5180 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5181 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5183 if (A == Op1) // (A&B)^A -> (B&A)^A
5185 if (B == Op1 && // (B&A)^A == ~B & A
5186 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5188 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5189 return BinaryOperator::CreateAnd(N, Op1);
5194 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5195 if (Op0I && Op1I && Op0I->isShift() &&
5196 Op0I->getOpcode() == Op1I->getOpcode() &&
5197 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5198 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5199 Instruction *NewOp =
5200 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5201 Op1I->getOperand(0),
5202 Op0I->getName()), I);
5203 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5204 Op1I->getOperand(1));
5208 Value *A, *B, *C, *D;
5209 // (A & B)^(A | B) -> A ^ B
5210 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5211 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5212 if ((A == C && B == D) || (A == D && B == C))
5213 return BinaryOperator::CreateXor(A, B);
5215 // (A | B)^(A & B) -> A ^ B
5216 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5217 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5218 if ((A == C && B == D) || (A == D && B == C))
5219 return BinaryOperator::CreateXor(A, B);
5223 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5224 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5225 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5226 // (X & Y)^(X & Y) -> (Y^Z) & X
5227 Value *X = 0, *Y = 0, *Z = 0;
5229 X = A, Y = B, Z = D;
5231 X = A, Y = B, Z = C;
5233 X = B, Y = A, Z = D;
5235 X = B, Y = A, Z = C;
5238 Instruction *NewOp =
5239 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5240 return BinaryOperator::CreateAnd(NewOp, X);
5245 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5246 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5247 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5250 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5251 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5252 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5253 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5254 const Type *SrcTy = Op0C->getOperand(0)->getType();
5255 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5256 // Only do this if the casts both really cause code to be generated.
5257 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5259 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5261 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5262 Op1C->getOperand(0),
5264 InsertNewInstBefore(NewOp, I);
5265 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5270 return Changed ? &I : 0;
5273 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5274 LLVMContext *Context) {
5275 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5278 static bool HasAddOverflow(ConstantInt *Result,
5279 ConstantInt *In1, ConstantInt *In2,
5282 if (In2->getValue().isNegative())
5283 return Result->getValue().sgt(In1->getValue());
5285 return Result->getValue().slt(In1->getValue());
5287 return Result->getValue().ult(In1->getValue());
5290 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5291 /// overflowed for this type.
5292 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5293 Constant *In2, LLVMContext *Context,
5294 bool IsSigned = false) {
5295 Result = Context->getConstantExprAdd(In1, In2);
5297 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5298 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5299 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5300 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5301 ExtractElement(In1, Idx, Context),
5302 ExtractElement(In2, Idx, Context),
5309 return HasAddOverflow(cast<ConstantInt>(Result),
5310 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5314 static bool HasSubOverflow(ConstantInt *Result,
5315 ConstantInt *In1, ConstantInt *In2,
5318 if (In2->getValue().isNegative())
5319 return Result->getValue().slt(In1->getValue());
5321 return Result->getValue().sgt(In1->getValue());
5323 return Result->getValue().ugt(In1->getValue());
5326 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5327 /// overflowed for this type.
5328 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5329 Constant *In2, LLVMContext *Context,
5330 bool IsSigned = false) {
5331 Result = Context->getConstantExprSub(In1, In2);
5333 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5334 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5335 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5336 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5337 ExtractElement(In1, Idx, Context),
5338 ExtractElement(In2, Idx, Context),
5345 return HasSubOverflow(cast<ConstantInt>(Result),
5346 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5350 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5351 /// code necessary to compute the offset from the base pointer (without adding
5352 /// in the base pointer). Return the result as a signed integer of intptr size.
5353 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5354 TargetData &TD = *IC.getTargetData();
5355 gep_type_iterator GTI = gep_type_begin(GEP);
5356 const Type *IntPtrTy = TD.getIntPtrType();
5357 LLVMContext *Context = IC.getContext();
5358 Value *Result = Context->getNullValue(IntPtrTy);
5360 // Build a mask for high order bits.
5361 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5362 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5364 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5367 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5368 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5369 if (OpC->isZero()) continue;
5371 // Handle a struct index, which adds its field offset to the pointer.
5372 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5373 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5375 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5377 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5379 Result = IC.InsertNewInstBefore(
5380 BinaryOperator::CreateAdd(Result,
5381 Context->getConstantInt(IntPtrTy, Size),
5382 GEP->getName()+".offs"), I);
5386 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5388 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5389 Scale = Context->getConstantExprMul(OC, Scale);
5390 if (Constant *RC = dyn_cast<Constant>(Result))
5391 Result = Context->getConstantExprAdd(RC, Scale);
5393 // Emit an add instruction.
5394 Result = IC.InsertNewInstBefore(
5395 BinaryOperator::CreateAdd(Result, Scale,
5396 GEP->getName()+".offs"), I);
5400 // Convert to correct type.
5401 if (Op->getType() != IntPtrTy) {
5402 if (Constant *OpC = dyn_cast<Constant>(Op))
5403 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5405 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5407 Op->getName()+".c"), I);
5410 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5411 if (Constant *OpC = dyn_cast<Constant>(Op))
5412 Op = Context->getConstantExprMul(OpC, Scale);
5413 else // We'll let instcombine(mul) convert this to a shl if possible.
5414 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5415 GEP->getName()+".idx"), I);
5418 // Emit an add instruction.
5419 if (isa<Constant>(Op) && isa<Constant>(Result))
5420 Result = Context->getConstantExprAdd(cast<Constant>(Op),
5421 cast<Constant>(Result));
5423 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5424 GEP->getName()+".offs"), I);
5430 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5431 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5432 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5433 /// be complex, and scales are involved. The above expression would also be
5434 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5435 /// This later form is less amenable to optimization though, and we are allowed
5436 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5438 /// If we can't emit an optimized form for this expression, this returns null.
5440 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5442 TargetData &TD = *IC.getTargetData();
5443 gep_type_iterator GTI = gep_type_begin(GEP);
5445 // Check to see if this gep only has a single variable index. If so, and if
5446 // any constant indices are a multiple of its scale, then we can compute this
5447 // in terms of the scale of the variable index. For example, if the GEP
5448 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5449 // because the expression will cross zero at the same point.
5450 unsigned i, e = GEP->getNumOperands();
5452 for (i = 1; i != e; ++i, ++GTI) {
5453 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5454 // Compute the aggregate offset of constant indices.
5455 if (CI->isZero()) continue;
5457 // Handle a struct index, which adds its field offset to the pointer.
5458 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5459 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5461 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5462 Offset += Size*CI->getSExtValue();
5465 // Found our variable index.
5470 // If there are no variable indices, we must have a constant offset, just
5471 // evaluate it the general way.
5472 if (i == e) return 0;
5474 Value *VariableIdx = GEP->getOperand(i);
5475 // Determine the scale factor of the variable element. For example, this is
5476 // 4 if the variable index is into an array of i32.
5477 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5479 // Verify that there are no other variable indices. If so, emit the hard way.
5480 for (++i, ++GTI; i != e; ++i, ++GTI) {
5481 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5484 // Compute the aggregate offset of constant indices.
5485 if (CI->isZero()) continue;
5487 // Handle a struct index, which adds its field offset to the pointer.
5488 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5489 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5491 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5492 Offset += Size*CI->getSExtValue();
5496 // Okay, we know we have a single variable index, which must be a
5497 // pointer/array/vector index. If there is no offset, life is simple, return
5499 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5501 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5502 // we don't need to bother extending: the extension won't affect where the
5503 // computation crosses zero.
5504 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5505 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5506 VariableIdx->getNameStart(), &I);
5510 // Otherwise, there is an index. The computation we will do will be modulo
5511 // the pointer size, so get it.
5512 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5514 Offset &= PtrSizeMask;
5515 VariableScale &= PtrSizeMask;
5517 // To do this transformation, any constant index must be a multiple of the
5518 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5519 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5520 // multiple of the variable scale.
5521 int64_t NewOffs = Offset / (int64_t)VariableScale;
5522 if (Offset != NewOffs*(int64_t)VariableScale)
5525 // Okay, we can do this evaluation. Start by converting the index to intptr.
5526 const Type *IntPtrTy = TD.getIntPtrType();
5527 if (VariableIdx->getType() != IntPtrTy)
5528 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5530 VariableIdx->getNameStart(), &I);
5531 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5532 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5536 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5537 /// else. At this point we know that the GEP is on the LHS of the comparison.
5538 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5539 ICmpInst::Predicate Cond,
5541 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5543 // Look through bitcasts.
5544 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5545 RHS = BCI->getOperand(0);
5547 Value *PtrBase = GEPLHS->getOperand(0);
5548 if (TD && PtrBase == RHS) {
5549 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5550 // This transformation (ignoring the base and scales) is valid because we
5551 // know pointers can't overflow. See if we can output an optimized form.
5552 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5554 // If not, synthesize the offset the hard way.
5556 Offset = EmitGEPOffset(GEPLHS, I, *this);
5557 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5558 Context->getNullValue(Offset->getType()));
5559 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5560 // If the base pointers are different, but the indices are the same, just
5561 // compare the base pointer.
5562 if (PtrBase != GEPRHS->getOperand(0)) {
5563 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5564 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5565 GEPRHS->getOperand(0)->getType();
5567 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5568 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5569 IndicesTheSame = false;
5573 // If all indices are the same, just compare the base pointers.
5575 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
5576 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5578 // Otherwise, the base pointers are different and the indices are
5579 // different, bail out.
5583 // If one of the GEPs has all zero indices, recurse.
5584 bool AllZeros = true;
5585 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5586 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5587 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5592 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5593 ICmpInst::getSwappedPredicate(Cond), I);
5595 // If the other GEP has all zero indices, recurse.
5597 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5598 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5599 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5604 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5606 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5607 // If the GEPs only differ by one index, compare it.
5608 unsigned NumDifferences = 0; // Keep track of # differences.
5609 unsigned DiffOperand = 0; // The operand that differs.
5610 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5611 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5612 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5613 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5614 // Irreconcilable differences.
5618 if (NumDifferences++) break;
5623 if (NumDifferences == 0) // SAME GEP?
5624 return ReplaceInstUsesWith(I, // No comparison is needed here.
5625 Context->getConstantInt(Type::Int1Ty,
5626 ICmpInst::isTrueWhenEqual(Cond)));
5628 else if (NumDifferences == 1) {
5629 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5630 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5631 // Make sure we do a signed comparison here.
5632 return new ICmpInst(*Context,
5633 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5637 // Only lower this if the icmp is the only user of the GEP or if we expect
5638 // the result to fold to a constant!
5640 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5641 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5642 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5643 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5644 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5645 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5651 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5653 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5656 if (!isa<ConstantFP>(RHSC)) return 0;
5657 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5659 // Get the width of the mantissa. We don't want to hack on conversions that
5660 // might lose information from the integer, e.g. "i64 -> float"
5661 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5662 if (MantissaWidth == -1) return 0; // Unknown.
5664 // Check to see that the input is converted from an integer type that is small
5665 // enough that preserves all bits. TODO: check here for "known" sign bits.
5666 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5667 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5669 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5670 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5674 // If the conversion would lose info, don't hack on this.
5675 if ((int)InputSize > MantissaWidth)
5678 // Otherwise, we can potentially simplify the comparison. We know that it
5679 // will always come through as an integer value and we know the constant is
5680 // not a NAN (it would have been previously simplified).
5681 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5683 ICmpInst::Predicate Pred;
5684 switch (I.getPredicate()) {
5685 default: llvm_unreachable("Unexpected predicate!");
5686 case FCmpInst::FCMP_UEQ:
5687 case FCmpInst::FCMP_OEQ:
5688 Pred = ICmpInst::ICMP_EQ;
5690 case FCmpInst::FCMP_UGT:
5691 case FCmpInst::FCMP_OGT:
5692 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5694 case FCmpInst::FCMP_UGE:
5695 case FCmpInst::FCMP_OGE:
5696 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5698 case FCmpInst::FCMP_ULT:
5699 case FCmpInst::FCMP_OLT:
5700 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5702 case FCmpInst::FCMP_ULE:
5703 case FCmpInst::FCMP_OLE:
5704 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5706 case FCmpInst::FCMP_UNE:
5707 case FCmpInst::FCMP_ONE:
5708 Pred = ICmpInst::ICMP_NE;
5710 case FCmpInst::FCMP_ORD:
5711 return ReplaceInstUsesWith(I, Context->getTrue());
5712 case FCmpInst::FCMP_UNO:
5713 return ReplaceInstUsesWith(I, Context->getFalse());
5716 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5718 // Now we know that the APFloat is a normal number, zero or inf.
5720 // See if the FP constant is too large for the integer. For example,
5721 // comparing an i8 to 300.0.
5722 unsigned IntWidth = IntTy->getScalarSizeInBits();
5725 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5726 // and large values.
5727 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5728 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5729 APFloat::rmNearestTiesToEven);
5730 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5731 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5732 Pred == ICmpInst::ICMP_SLE)
5733 return ReplaceInstUsesWith(I, Context->getTrue());
5734 return ReplaceInstUsesWith(I, Context->getFalse());
5737 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5738 // +INF and large values.
5739 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5740 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5741 APFloat::rmNearestTiesToEven);
5742 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5743 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5744 Pred == ICmpInst::ICMP_ULE)
5745 return ReplaceInstUsesWith(I, Context->getTrue());
5746 return ReplaceInstUsesWith(I, Context->getFalse());
5751 // See if the RHS value is < SignedMin.
5752 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5753 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5754 APFloat::rmNearestTiesToEven);
5755 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5756 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5757 Pred == ICmpInst::ICMP_SGE)
5758 return ReplaceInstUsesWith(I, Context->getTrue());
5759 return ReplaceInstUsesWith(I, Context->getFalse());
5763 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5764 // [0, UMAX], but it may still be fractional. See if it is fractional by
5765 // casting the FP value to the integer value and back, checking for equality.
5766 // Don't do this for zero, because -0.0 is not fractional.
5767 Constant *RHSInt = LHSUnsigned
5768 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5769 : Context->getConstantExprFPToSI(RHSC, IntTy);
5770 if (!RHS.isZero()) {
5771 bool Equal = LHSUnsigned
5772 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5773 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5775 // If we had a comparison against a fractional value, we have to adjust
5776 // the compare predicate and sometimes the value. RHSC is rounded towards
5777 // zero at this point.
5779 default: llvm_unreachable("Unexpected integer comparison!");
5780 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5781 return ReplaceInstUsesWith(I, Context->getTrue());
5782 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5783 return ReplaceInstUsesWith(I, Context->getFalse());
5784 case ICmpInst::ICMP_ULE:
5785 // (float)int <= 4.4 --> int <= 4
5786 // (float)int <= -4.4 --> false
5787 if (RHS.isNegative())
5788 return ReplaceInstUsesWith(I, Context->getFalse());
5790 case ICmpInst::ICMP_SLE:
5791 // (float)int <= 4.4 --> int <= 4
5792 // (float)int <= -4.4 --> int < -4
5793 if (RHS.isNegative())
5794 Pred = ICmpInst::ICMP_SLT;
5796 case ICmpInst::ICMP_ULT:
5797 // (float)int < -4.4 --> false
5798 // (float)int < 4.4 --> int <= 4
5799 if (RHS.isNegative())
5800 return ReplaceInstUsesWith(I, Context->getFalse());
5801 Pred = ICmpInst::ICMP_ULE;
5803 case ICmpInst::ICMP_SLT:
5804 // (float)int < -4.4 --> int < -4
5805 // (float)int < 4.4 --> int <= 4
5806 if (!RHS.isNegative())
5807 Pred = ICmpInst::ICMP_SLE;
5809 case ICmpInst::ICMP_UGT:
5810 // (float)int > 4.4 --> int > 4
5811 // (float)int > -4.4 --> true
5812 if (RHS.isNegative())
5813 return ReplaceInstUsesWith(I, Context->getTrue());
5815 case ICmpInst::ICMP_SGT:
5816 // (float)int > 4.4 --> int > 4
5817 // (float)int > -4.4 --> int >= -4
5818 if (RHS.isNegative())
5819 Pred = ICmpInst::ICMP_SGE;
5821 case ICmpInst::ICMP_UGE:
5822 // (float)int >= -4.4 --> true
5823 // (float)int >= 4.4 --> int > 4
5824 if (!RHS.isNegative())
5825 return ReplaceInstUsesWith(I, Context->getTrue());
5826 Pred = ICmpInst::ICMP_UGT;
5828 case ICmpInst::ICMP_SGE:
5829 // (float)int >= -4.4 --> int >= -4
5830 // (float)int >= 4.4 --> int > 4
5831 if (!RHS.isNegative())
5832 Pred = ICmpInst::ICMP_SGT;
5838 // Lower this FP comparison into an appropriate integer version of the
5840 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5843 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5844 bool Changed = SimplifyCompare(I);
5845 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5847 // Fold trivial predicates.
5848 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5849 return ReplaceInstUsesWith(I, Context->getFalse());
5850 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5851 return ReplaceInstUsesWith(I, Context->getTrue());
5853 // Simplify 'fcmp pred X, X'
5855 switch (I.getPredicate()) {
5856 default: llvm_unreachable("Unknown predicate!");
5857 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5858 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5859 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5860 return ReplaceInstUsesWith(I, Context->getTrue());
5861 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5862 case FCmpInst::FCMP_OLT: // True if ordered and less than
5863 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5864 return ReplaceInstUsesWith(I, Context->getFalse());
5866 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5867 case FCmpInst::FCMP_ULT: // True if unordered or less than
5868 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5869 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5870 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5871 I.setPredicate(FCmpInst::FCMP_UNO);
5872 I.setOperand(1, Context->getNullValue(Op0->getType()));
5875 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5876 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5877 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5878 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5879 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5880 I.setPredicate(FCmpInst::FCMP_ORD);
5881 I.setOperand(1, Context->getNullValue(Op0->getType()));
5886 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5887 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5889 // Handle fcmp with constant RHS
5890 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5891 // If the constant is a nan, see if we can fold the comparison based on it.
5892 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5893 if (CFP->getValueAPF().isNaN()) {
5894 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5895 return ReplaceInstUsesWith(I, Context->getFalse());
5896 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5897 "Comparison must be either ordered or unordered!");
5898 // True if unordered.
5899 return ReplaceInstUsesWith(I, Context->getTrue());
5903 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5904 switch (LHSI->getOpcode()) {
5905 case Instruction::PHI:
5906 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5907 // block. If in the same block, we're encouraging jump threading. If
5908 // not, we are just pessimizing the code by making an i1 phi.
5909 if (LHSI->getParent() == I.getParent())
5910 if (Instruction *NV = FoldOpIntoPhi(I))
5913 case Instruction::SIToFP:
5914 case Instruction::UIToFP:
5915 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5918 case Instruction::Select:
5919 // If either operand of the select is a constant, we can fold the
5920 // comparison into the select arms, which will cause one to be
5921 // constant folded and the select turned into a bitwise or.
5922 Value *Op1 = 0, *Op2 = 0;
5923 if (LHSI->hasOneUse()) {
5924 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5925 // Fold the known value into the constant operand.
5926 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5927 // Insert a new FCmp of the other select operand.
5928 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5929 LHSI->getOperand(2), RHSC,
5931 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5932 // Fold the known value into the constant operand.
5933 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5934 // Insert a new FCmp of the other select operand.
5935 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5936 LHSI->getOperand(1), RHSC,
5942 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5947 return Changed ? &I : 0;
5950 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5951 bool Changed = SimplifyCompare(I);
5952 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5953 const Type *Ty = Op0->getType();
5957 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
5958 I.isTrueWhenEqual()));
5960 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5961 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5963 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5964 // addresses never equal each other! We already know that Op0 != Op1.
5965 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5966 isa<ConstantPointerNull>(Op0)) &&
5967 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5968 isa<ConstantPointerNull>(Op1)))
5969 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
5970 !I.isTrueWhenEqual()));
5972 // icmp's with boolean values can always be turned into bitwise operations
5973 if (Ty == Type::Int1Ty) {
5974 switch (I.getPredicate()) {
5975 default: llvm_unreachable("Invalid icmp instruction!");
5976 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5977 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5978 InsertNewInstBefore(Xor, I);
5979 return BinaryOperator::CreateNot(*Context, Xor);
5981 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5982 return BinaryOperator::CreateXor(Op0, Op1);
5984 case ICmpInst::ICMP_UGT:
5985 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5987 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5988 Instruction *Not = BinaryOperator::CreateNot(*Context,
5989 Op0, I.getName()+"tmp");
5990 InsertNewInstBefore(Not, I);
5991 return BinaryOperator::CreateAnd(Not, Op1);
5993 case ICmpInst::ICMP_SGT:
5994 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
5996 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5997 Instruction *Not = BinaryOperator::CreateNot(*Context,
5998 Op1, I.getName()+"tmp");
5999 InsertNewInstBefore(Not, I);
6000 return BinaryOperator::CreateAnd(Not, Op0);
6002 case ICmpInst::ICMP_UGE:
6003 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6005 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
6006 Instruction *Not = BinaryOperator::CreateNot(*Context,
6007 Op0, I.getName()+"tmp");
6008 InsertNewInstBefore(Not, I);
6009 return BinaryOperator::CreateOr(Not, Op1);
6011 case ICmpInst::ICMP_SGE:
6012 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6014 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
6015 Instruction *Not = BinaryOperator::CreateNot(*Context,
6016 Op1, I.getName()+"tmp");
6017 InsertNewInstBefore(Not, I);
6018 return BinaryOperator::CreateOr(Not, Op0);
6023 unsigned BitWidth = 0;
6025 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6026 else if (Ty->isIntOrIntVector())
6027 BitWidth = Ty->getScalarSizeInBits();
6029 bool isSignBit = false;
6031 // See if we are doing a comparison with a constant.
6032 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6033 Value *A = 0, *B = 0;
6035 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6036 if (I.isEquality() && CI->isNullValue() &&
6037 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6038 // (icmp cond A B) if cond is equality
6039 return new ICmpInst(*Context, I.getPredicate(), A, B);
6042 // If we have an icmp le or icmp ge instruction, turn it into the
6043 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6044 // them being folded in the code below.
6045 switch (I.getPredicate()) {
6047 case ICmpInst::ICMP_ULE:
6048 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
6049 return ReplaceInstUsesWith(I, Context->getTrue());
6050 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6051 AddOne(CI, Context));
6052 case ICmpInst::ICMP_SLE:
6053 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
6054 return ReplaceInstUsesWith(I, Context->getTrue());
6055 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6056 AddOne(CI, Context));
6057 case ICmpInst::ICMP_UGE:
6058 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6059 return ReplaceInstUsesWith(I, Context->getTrue());
6060 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6061 SubOne(CI, Context));
6062 case ICmpInst::ICMP_SGE:
6063 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6064 return ReplaceInstUsesWith(I, Context->getTrue());
6065 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6066 SubOne(CI, Context));
6069 // If this comparison is a normal comparison, it demands all
6070 // bits, if it is a sign bit comparison, it only demands the sign bit.
6072 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6075 // See if we can fold the comparison based on range information we can get
6076 // by checking whether bits are known to be zero or one in the input.
6077 if (BitWidth != 0) {
6078 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6079 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6081 if (SimplifyDemandedBits(I.getOperandUse(0),
6082 isSignBit ? APInt::getSignBit(BitWidth)
6083 : APInt::getAllOnesValue(BitWidth),
6084 Op0KnownZero, Op0KnownOne, 0))
6086 if (SimplifyDemandedBits(I.getOperandUse(1),
6087 APInt::getAllOnesValue(BitWidth),
6088 Op1KnownZero, Op1KnownOne, 0))
6091 // Given the known and unknown bits, compute a range that the LHS could be
6092 // in. Compute the Min, Max and RHS values based on the known bits. For the
6093 // EQ and NE we use unsigned values.
6094 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6095 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6096 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6097 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6099 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6102 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6104 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6108 // If Min and Max are known to be the same, then SimplifyDemandedBits
6109 // figured out that the LHS is a constant. Just constant fold this now so
6110 // that code below can assume that Min != Max.
6111 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6112 return new ICmpInst(*Context, I.getPredicate(),
6113 Context->getConstantInt(Op0Min), Op1);
6114 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6115 return new ICmpInst(*Context, I.getPredicate(), Op0,
6116 Context->getConstantInt(Op1Min));
6118 // Based on the range information we know about the LHS, see if we can
6119 // simplify this comparison. For example, (x&4) < 8 is always true.
6120 switch (I.getPredicate()) {
6121 default: llvm_unreachable("Unknown icmp opcode!");
6122 case ICmpInst::ICMP_EQ:
6123 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6124 return ReplaceInstUsesWith(I, Context->getFalse());
6126 case ICmpInst::ICMP_NE:
6127 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6128 return ReplaceInstUsesWith(I, Context->getTrue());
6130 case ICmpInst::ICMP_ULT:
6131 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6132 return ReplaceInstUsesWith(I, Context->getTrue());
6133 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6134 return ReplaceInstUsesWith(I, Context->getFalse());
6135 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6136 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6137 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6138 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6139 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6140 SubOne(CI, Context));
6142 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6143 if (CI->isMinValue(true))
6144 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6145 Context->getAllOnesValue(Op0->getType()));
6148 case ICmpInst::ICMP_UGT:
6149 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6150 return ReplaceInstUsesWith(I, Context->getTrue());
6151 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6152 return ReplaceInstUsesWith(I, Context->getFalse());
6154 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6155 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6156 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6157 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6158 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6159 AddOne(CI, Context));
6161 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6162 if (CI->isMaxValue(true))
6163 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6164 Context->getNullValue(Op0->getType()));
6167 case ICmpInst::ICMP_SLT:
6168 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6169 return ReplaceInstUsesWith(I, Context->getTrue());
6170 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6171 return ReplaceInstUsesWith(I, Context->getFalse());
6172 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6173 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6174 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6175 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6176 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6177 SubOne(CI, Context));
6180 case ICmpInst::ICMP_SGT:
6181 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6182 return ReplaceInstUsesWith(I, Context->getTrue());
6183 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6184 return ReplaceInstUsesWith(I, Context->getFalse());
6186 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6187 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6188 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6189 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6190 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6191 AddOne(CI, Context));
6194 case ICmpInst::ICMP_SGE:
6195 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6196 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6197 return ReplaceInstUsesWith(I, Context->getTrue());
6198 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6199 return ReplaceInstUsesWith(I, Context->getFalse());
6201 case ICmpInst::ICMP_SLE:
6202 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6203 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6204 return ReplaceInstUsesWith(I, Context->getTrue());
6205 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6206 return ReplaceInstUsesWith(I, Context->getFalse());
6208 case ICmpInst::ICMP_UGE:
6209 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6210 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6211 return ReplaceInstUsesWith(I, Context->getTrue());
6212 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6213 return ReplaceInstUsesWith(I, Context->getFalse());
6215 case ICmpInst::ICMP_ULE:
6216 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6217 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6218 return ReplaceInstUsesWith(I, Context->getTrue());
6219 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6220 return ReplaceInstUsesWith(I, Context->getFalse());
6224 // Turn a signed comparison into an unsigned one if both operands
6225 // are known to have the same sign.
6226 if (I.isSignedPredicate() &&
6227 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6228 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6229 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6232 // Test if the ICmpInst instruction is used exclusively by a select as
6233 // part of a minimum or maximum operation. If so, refrain from doing
6234 // any other folding. This helps out other analyses which understand
6235 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6236 // and CodeGen. And in this case, at least one of the comparison
6237 // operands has at least one user besides the compare (the select),
6238 // which would often largely negate the benefit of folding anyway.
6240 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6241 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6242 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6245 // See if we are doing a comparison between a constant and an instruction that
6246 // can be folded into the comparison.
6247 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6248 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6249 // instruction, see if that instruction also has constants so that the
6250 // instruction can be folded into the icmp
6251 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6252 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6256 // Handle icmp with constant (but not simple integer constant) RHS
6257 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6258 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6259 switch (LHSI->getOpcode()) {
6260 case Instruction::GetElementPtr:
6261 if (RHSC->isNullValue()) {
6262 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6263 bool isAllZeros = true;
6264 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6265 if (!isa<Constant>(LHSI->getOperand(i)) ||
6266 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6271 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6272 Context->getNullValue(LHSI->getOperand(0)->getType()));
6276 case Instruction::PHI:
6277 // Only fold icmp into the PHI if the phi and fcmp are in the same
6278 // block. If in the same block, we're encouraging jump threading. If
6279 // not, we are just pessimizing the code by making an i1 phi.
6280 if (LHSI->getParent() == I.getParent())
6281 if (Instruction *NV = FoldOpIntoPhi(I))
6284 case Instruction::Select: {
6285 // If either operand of the select is a constant, we can fold the
6286 // comparison into the select arms, which will cause one to be
6287 // constant folded and the select turned into a bitwise or.
6288 Value *Op1 = 0, *Op2 = 0;
6289 if (LHSI->hasOneUse()) {
6290 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6291 // Fold the known value into the constant operand.
6292 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6293 // Insert a new ICmp of the other select operand.
6294 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6295 LHSI->getOperand(2), RHSC,
6297 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6298 // Fold the known value into the constant operand.
6299 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6300 // Insert a new ICmp of the other select operand.
6301 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6302 LHSI->getOperand(1), RHSC,
6308 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6311 case Instruction::Malloc:
6312 // If we have (malloc != null), and if the malloc has a single use, we
6313 // can assume it is successful and remove the malloc.
6314 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6315 AddToWorkList(LHSI);
6316 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6317 !I.isTrueWhenEqual()));
6323 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6324 if (User *GEP = dyn_castGetElementPtr(Op0))
6325 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6327 if (User *GEP = dyn_castGetElementPtr(Op1))
6328 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6329 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6332 // Test to see if the operands of the icmp are casted versions of other
6333 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6335 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6336 if (isa<PointerType>(Op0->getType()) &&
6337 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6338 // We keep moving the cast from the left operand over to the right
6339 // operand, where it can often be eliminated completely.
6340 Op0 = CI->getOperand(0);
6342 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6343 // so eliminate it as well.
6344 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6345 Op1 = CI2->getOperand(0);
6347 // If Op1 is a constant, we can fold the cast into the constant.
6348 if (Op0->getType() != Op1->getType()) {
6349 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6350 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6352 // Otherwise, cast the RHS right before the icmp
6353 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6356 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6360 if (isa<CastInst>(Op0)) {
6361 // Handle the special case of: icmp (cast bool to X), <cst>
6362 // This comes up when you have code like
6365 // For generality, we handle any zero-extension of any operand comparison
6366 // with a constant or another cast from the same type.
6367 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6368 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6372 // See if it's the same type of instruction on the left and right.
6373 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6374 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6375 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6376 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6377 switch (Op0I->getOpcode()) {
6379 case Instruction::Add:
6380 case Instruction::Sub:
6381 case Instruction::Xor:
6382 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6383 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6384 Op1I->getOperand(0));
6385 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6386 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6387 if (CI->getValue().isSignBit()) {
6388 ICmpInst::Predicate Pred = I.isSignedPredicate()
6389 ? I.getUnsignedPredicate()
6390 : I.getSignedPredicate();
6391 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6392 Op1I->getOperand(0));
6395 if (CI->getValue().isMaxSignedValue()) {
6396 ICmpInst::Predicate Pred = I.isSignedPredicate()
6397 ? I.getUnsignedPredicate()
6398 : I.getSignedPredicate();
6399 Pred = I.getSwappedPredicate(Pred);
6400 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6401 Op1I->getOperand(0));
6405 case Instruction::Mul:
6406 if (!I.isEquality())
6409 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6410 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6411 // Mask = -1 >> count-trailing-zeros(Cst).
6412 if (!CI->isZero() && !CI->isOne()) {
6413 const APInt &AP = CI->getValue();
6414 ConstantInt *Mask = Context->getConstantInt(
6415 APInt::getLowBitsSet(AP.getBitWidth(),
6417 AP.countTrailingZeros()));
6418 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6420 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6422 InsertNewInstBefore(And1, I);
6423 InsertNewInstBefore(And2, I);
6424 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6433 // ~x < ~y --> y < x
6435 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6436 match(Op1, m_Not(m_Value(B)), *Context))
6437 return new ICmpInst(*Context, I.getPredicate(), B, A);
6440 if (I.isEquality()) {
6441 Value *A, *B, *C, *D;
6443 // -x == -y --> x == y
6444 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6445 match(Op1, m_Neg(m_Value(B)), *Context))
6446 return new ICmpInst(*Context, I.getPredicate(), A, B);
6448 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6449 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6450 Value *OtherVal = A == Op1 ? B : A;
6451 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6452 Context->getNullValue(A->getType()));
6455 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6456 // A^c1 == C^c2 --> A == C^(c1^c2)
6457 ConstantInt *C1, *C2;
6458 if (match(B, m_ConstantInt(C1), *Context) &&
6459 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6461 Context->getConstantInt(C1->getValue() ^ C2->getValue());
6462 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6463 return new ICmpInst(*Context, I.getPredicate(), A,
6464 InsertNewInstBefore(Xor, I));
6467 // A^B == A^D -> B == D
6468 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6469 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6470 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6471 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6475 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6476 (A == Op0 || B == Op0)) {
6477 // A == (A^B) -> B == 0
6478 Value *OtherVal = A == Op0 ? B : A;
6479 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6480 Context->getNullValue(A->getType()));
6483 // (A-B) == A -> B == 0
6484 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6485 return new ICmpInst(*Context, I.getPredicate(), B,
6486 Context->getNullValue(B->getType()));
6488 // A == (A-B) -> B == 0
6489 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6490 return new ICmpInst(*Context, I.getPredicate(), B,
6491 Context->getNullValue(B->getType()));
6493 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6494 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6495 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6496 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6497 Value *X = 0, *Y = 0, *Z = 0;
6500 X = B; Y = D; Z = A;
6501 } else if (A == D) {
6502 X = B; Y = C; Z = A;
6503 } else if (B == C) {
6504 X = A; Y = D; Z = B;
6505 } else if (B == D) {
6506 X = A; Y = C; Z = B;
6509 if (X) { // Build (X^Y) & Z
6510 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6511 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6512 I.setOperand(0, Op1);
6513 I.setOperand(1, Context->getNullValue(Op1->getType()));
6518 return Changed ? &I : 0;
6522 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6523 /// and CmpRHS are both known to be integer constants.
6524 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6525 ConstantInt *DivRHS) {
6526 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6527 const APInt &CmpRHSV = CmpRHS->getValue();
6529 // FIXME: If the operand types don't match the type of the divide
6530 // then don't attempt this transform. The code below doesn't have the
6531 // logic to deal with a signed divide and an unsigned compare (and
6532 // vice versa). This is because (x /s C1) <s C2 produces different
6533 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6534 // (x /u C1) <u C2. Simply casting the operands and result won't
6535 // work. :( The if statement below tests that condition and bails
6537 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6538 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6540 if (DivRHS->isZero())
6541 return 0; // The ProdOV computation fails on divide by zero.
6542 if (DivIsSigned && DivRHS->isAllOnesValue())
6543 return 0; // The overflow computation also screws up here
6544 if (DivRHS->isOne())
6545 return 0; // Not worth bothering, and eliminates some funny cases
6548 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6549 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6550 // C2 (CI). By solving for X we can turn this into a range check
6551 // instead of computing a divide.
6552 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6554 // Determine if the product overflows by seeing if the product is
6555 // not equal to the divide. Make sure we do the same kind of divide
6556 // as in the LHS instruction that we're folding.
6557 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6558 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6560 // Get the ICmp opcode
6561 ICmpInst::Predicate Pred = ICI.getPredicate();
6563 // Figure out the interval that is being checked. For example, a comparison
6564 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6565 // Compute this interval based on the constants involved and the signedness of
6566 // the compare/divide. This computes a half-open interval, keeping track of
6567 // whether either value in the interval overflows. After analysis each
6568 // overflow variable is set to 0 if it's corresponding bound variable is valid
6569 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6570 int LoOverflow = 0, HiOverflow = 0;
6571 Constant *LoBound = 0, *HiBound = 0;
6573 if (!DivIsSigned) { // udiv
6574 // e.g. X/5 op 3 --> [15, 20)
6576 HiOverflow = LoOverflow = ProdOV;
6578 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6579 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6580 if (CmpRHSV == 0) { // (X / pos) op 0
6581 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6582 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6585 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6586 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6587 HiOverflow = LoOverflow = ProdOV;
6589 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6590 } else { // (X / pos) op neg
6591 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6592 HiBound = AddOne(Prod, Context);
6593 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6595 ConstantInt* DivNeg =
6596 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6597 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6601 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6602 if (CmpRHSV == 0) { // (X / neg) op 0
6603 // e.g. X/-5 op 0 --> [-4, 5)
6604 LoBound = AddOne(DivRHS, Context);
6605 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6606 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6607 HiOverflow = 1; // [INTMIN+1, overflow)
6608 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6610 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6611 // e.g. X/-5 op 3 --> [-19, -14)
6612 HiBound = AddOne(Prod, Context);
6613 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6615 LoOverflow = AddWithOverflow(LoBound, HiBound,
6616 DivRHS, Context, true) ? -1 : 0;
6617 } else { // (X / neg) op neg
6618 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6619 LoOverflow = HiOverflow = ProdOV;
6621 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6624 // Dividing by a negative swaps the condition. LT <-> GT
6625 Pred = ICmpInst::getSwappedPredicate(Pred);
6628 Value *X = DivI->getOperand(0);
6630 default: llvm_unreachable("Unhandled icmp opcode!");
6631 case ICmpInst::ICMP_EQ:
6632 if (LoOverflow && HiOverflow)
6633 return ReplaceInstUsesWith(ICI, Context->getFalse());
6634 else if (HiOverflow)
6635 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
6636 ICmpInst::ICMP_UGE, X, LoBound);
6637 else if (LoOverflow)
6638 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
6639 ICmpInst::ICMP_ULT, X, HiBound);
6641 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6642 case ICmpInst::ICMP_NE:
6643 if (LoOverflow && HiOverflow)
6644 return ReplaceInstUsesWith(ICI, Context->getTrue());
6645 else if (HiOverflow)
6646 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
6647 ICmpInst::ICMP_ULT, X, LoBound);
6648 else if (LoOverflow)
6649 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
6650 ICmpInst::ICMP_UGE, X, HiBound);
6652 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6653 case ICmpInst::ICMP_ULT:
6654 case ICmpInst::ICMP_SLT:
6655 if (LoOverflow == +1) // Low bound is greater than input range.
6656 return ReplaceInstUsesWith(ICI, Context->getTrue());
6657 if (LoOverflow == -1) // Low bound is less than input range.
6658 return ReplaceInstUsesWith(ICI, Context->getFalse());
6659 return new ICmpInst(*Context, Pred, X, LoBound);
6660 case ICmpInst::ICMP_UGT:
6661 case ICmpInst::ICMP_SGT:
6662 if (HiOverflow == +1) // High bound greater than input range.
6663 return ReplaceInstUsesWith(ICI, Context->getFalse());
6664 else if (HiOverflow == -1) // High bound less than input range.
6665 return ReplaceInstUsesWith(ICI, Context->getTrue());
6666 if (Pred == ICmpInst::ICMP_UGT)
6667 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6669 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6674 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6676 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6679 const APInt &RHSV = RHS->getValue();
6681 switch (LHSI->getOpcode()) {
6682 case Instruction::Trunc:
6683 if (ICI.isEquality() && LHSI->hasOneUse()) {
6684 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6685 // of the high bits truncated out of x are known.
6686 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6687 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6688 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6689 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6690 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6692 // If all the high bits are known, we can do this xform.
6693 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6694 // Pull in the high bits from known-ones set.
6695 APInt NewRHS(RHS->getValue());
6696 NewRHS.zext(SrcBits);
6698 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6699 Context->getConstantInt(NewRHS));
6704 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6705 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6706 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6708 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6709 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6710 Value *CompareVal = LHSI->getOperand(0);
6712 // If the sign bit of the XorCST is not set, there is no change to
6713 // the operation, just stop using the Xor.
6714 if (!XorCST->getValue().isNegative()) {
6715 ICI.setOperand(0, CompareVal);
6716 AddToWorkList(LHSI);
6720 // Was the old condition true if the operand is positive?
6721 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6723 // If so, the new one isn't.
6724 isTrueIfPositive ^= true;
6726 if (isTrueIfPositive)
6727 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6728 SubOne(RHS, Context));
6730 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6731 AddOne(RHS, Context));
6734 if (LHSI->hasOneUse()) {
6735 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6736 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6737 const APInt &SignBit = XorCST->getValue();
6738 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6739 ? ICI.getUnsignedPredicate()
6740 : ICI.getSignedPredicate();
6741 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6742 Context->getConstantInt(RHSV ^ SignBit));
6745 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6746 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6747 const APInt &NotSignBit = XorCST->getValue();
6748 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6749 ? ICI.getUnsignedPredicate()
6750 : ICI.getSignedPredicate();
6751 Pred = ICI.getSwappedPredicate(Pred);
6752 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6753 Context->getConstantInt(RHSV ^ NotSignBit));
6758 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6759 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6760 LHSI->getOperand(0)->hasOneUse()) {
6761 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6763 // If the LHS is an AND of a truncating cast, we can widen the
6764 // and/compare to be the input width without changing the value
6765 // produced, eliminating a cast.
6766 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6767 // We can do this transformation if either the AND constant does not
6768 // have its sign bit set or if it is an equality comparison.
6769 // Extending a relational comparison when we're checking the sign
6770 // bit would not work.
6771 if (Cast->hasOneUse() &&
6772 (ICI.isEquality() ||
6773 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6775 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6776 APInt NewCST = AndCST->getValue();
6777 NewCST.zext(BitWidth);
6779 NewCI.zext(BitWidth);
6780 Instruction *NewAnd =
6781 BinaryOperator::CreateAnd(Cast->getOperand(0),
6782 Context->getConstantInt(NewCST),LHSI->getName());
6783 InsertNewInstBefore(NewAnd, ICI);
6784 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6785 Context->getConstantInt(NewCI));
6789 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6790 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6791 // happens a LOT in code produced by the C front-end, for bitfield
6793 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6794 if (Shift && !Shift->isShift())
6798 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6799 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6800 const Type *AndTy = AndCST->getType(); // Type of the and.
6802 // We can fold this as long as we can't shift unknown bits
6803 // into the mask. This can only happen with signed shift
6804 // rights, as they sign-extend.
6806 bool CanFold = Shift->isLogicalShift();
6808 // To test for the bad case of the signed shr, see if any
6809 // of the bits shifted in could be tested after the mask.
6810 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6811 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6813 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6814 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6815 AndCST->getValue()) == 0)
6821 if (Shift->getOpcode() == Instruction::Shl)
6822 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6824 NewCst = Context->getConstantExprShl(RHS, ShAmt);
6826 // Check to see if we are shifting out any of the bits being
6828 if (Context->getConstantExpr(Shift->getOpcode(),
6829 NewCst, ShAmt) != RHS) {
6830 // If we shifted bits out, the fold is not going to work out.
6831 // As a special case, check to see if this means that the
6832 // result is always true or false now.
6833 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6834 return ReplaceInstUsesWith(ICI, Context->getFalse());
6835 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6836 return ReplaceInstUsesWith(ICI, Context->getTrue());
6838 ICI.setOperand(1, NewCst);
6839 Constant *NewAndCST;
6840 if (Shift->getOpcode() == Instruction::Shl)
6841 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6843 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6844 LHSI->setOperand(1, NewAndCST);
6845 LHSI->setOperand(0, Shift->getOperand(0));
6846 AddToWorkList(Shift); // Shift is dead.
6847 AddUsesToWorkList(ICI);
6853 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6854 // preferable because it allows the C<<Y expression to be hoisted out
6855 // of a loop if Y is invariant and X is not.
6856 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6857 ICI.isEquality() && !Shift->isArithmeticShift() &&
6858 !isa<Constant>(Shift->getOperand(0))) {
6861 if (Shift->getOpcode() == Instruction::LShr) {
6862 NS = BinaryOperator::CreateShl(AndCST,
6863 Shift->getOperand(1), "tmp");
6865 // Insert a logical shift.
6866 NS = BinaryOperator::CreateLShr(AndCST,
6867 Shift->getOperand(1), "tmp");
6869 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6871 // Compute X & (C << Y).
6872 Instruction *NewAnd =
6873 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6874 InsertNewInstBefore(NewAnd, ICI);
6876 ICI.setOperand(0, NewAnd);
6882 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6883 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6886 uint32_t TypeBits = RHSV.getBitWidth();
6888 // Check that the shift amount is in range. If not, don't perform
6889 // undefined shifts. When the shift is visited it will be
6891 if (ShAmt->uge(TypeBits))
6894 if (ICI.isEquality()) {
6895 // If we are comparing against bits always shifted out, the
6896 // comparison cannot succeed.
6898 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6900 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6901 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6902 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6903 return ReplaceInstUsesWith(ICI, Cst);
6906 if (LHSI->hasOneUse()) {
6907 // Otherwise strength reduce the shift into an and.
6908 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6910 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6911 TypeBits-ShAmtVal));
6914 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6915 Mask, LHSI->getName()+".mask");
6916 Value *And = InsertNewInstBefore(AndI, ICI);
6917 return new ICmpInst(*Context, ICI.getPredicate(), And,
6918 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6922 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6923 bool TrueIfSigned = false;
6924 if (LHSI->hasOneUse() &&
6925 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6926 // (X << 31) <s 0 --> (X&1) != 0
6927 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6928 (TypeBits-ShAmt->getZExtValue()-1));
6930 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6931 Mask, LHSI->getName()+".mask");
6932 Value *And = InsertNewInstBefore(AndI, ICI);
6934 return new ICmpInst(*Context,
6935 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6936 And, Context->getNullValue(And->getType()));
6941 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6942 case Instruction::AShr: {
6943 // Only handle equality comparisons of shift-by-constant.
6944 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6945 if (!ShAmt || !ICI.isEquality()) break;
6947 // Check that the shift amount is in range. If not, don't perform
6948 // undefined shifts. When the shift is visited it will be
6950 uint32_t TypeBits = RHSV.getBitWidth();
6951 if (ShAmt->uge(TypeBits))
6954 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6956 // If we are comparing against bits always shifted out, the
6957 // comparison cannot succeed.
6958 APInt Comp = RHSV << ShAmtVal;
6959 if (LHSI->getOpcode() == Instruction::LShr)
6960 Comp = Comp.lshr(ShAmtVal);
6962 Comp = Comp.ashr(ShAmtVal);
6964 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6965 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6966 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6967 return ReplaceInstUsesWith(ICI, Cst);
6970 // Otherwise, check to see if the bits shifted out are known to be zero.
6971 // If so, we can compare against the unshifted value:
6972 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6973 if (LHSI->hasOneUse() &&
6974 MaskedValueIsZero(LHSI->getOperand(0),
6975 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6976 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6977 Context->getConstantExprShl(RHS, ShAmt));
6980 if (LHSI->hasOneUse()) {
6981 // Otherwise strength reduce the shift into an and.
6982 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6983 Constant *Mask = Context->getConstantInt(Val);
6986 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6987 Mask, LHSI->getName()+".mask");
6988 Value *And = InsertNewInstBefore(AndI, ICI);
6989 return new ICmpInst(*Context, ICI.getPredicate(), And,
6990 Context->getConstantExprShl(RHS, ShAmt));
6995 case Instruction::SDiv:
6996 case Instruction::UDiv:
6997 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6998 // Fold this div into the comparison, producing a range check.
6999 // Determine, based on the divide type, what the range is being
7000 // checked. If there is an overflow on the low or high side, remember
7001 // it, otherwise compute the range [low, hi) bounding the new value.
7002 // See: InsertRangeTest above for the kinds of replacements possible.
7003 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7004 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7009 case Instruction::Add:
7010 // Fold: icmp pred (add, X, C1), C2
7012 if (!ICI.isEquality()) {
7013 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7015 const APInt &LHSV = LHSC->getValue();
7017 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7020 if (ICI.isSignedPredicate()) {
7021 if (CR.getLower().isSignBit()) {
7022 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7023 Context->getConstantInt(CR.getUpper()));
7024 } else if (CR.getUpper().isSignBit()) {
7025 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7026 Context->getConstantInt(CR.getLower()));
7029 if (CR.getLower().isMinValue()) {
7030 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7031 Context->getConstantInt(CR.getUpper()));
7032 } else if (CR.getUpper().isMinValue()) {
7033 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7034 Context->getConstantInt(CR.getLower()));
7041 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7042 if (ICI.isEquality()) {
7043 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7045 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7046 // the second operand is a constant, simplify a bit.
7047 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7048 switch (BO->getOpcode()) {
7049 case Instruction::SRem:
7050 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7051 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7052 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7053 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7054 Instruction *NewRem =
7055 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7057 InsertNewInstBefore(NewRem, ICI);
7058 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
7059 Context->getNullValue(BO->getType()));
7063 case Instruction::Add:
7064 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7065 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7066 if (BO->hasOneUse())
7067 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7068 Context->getConstantExprSub(RHS, BOp1C));
7069 } else if (RHSV == 0) {
7070 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7071 // efficiently invertible, or if the add has just this one use.
7072 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7074 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7075 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7076 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7077 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7078 else if (BO->hasOneUse()) {
7079 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7080 InsertNewInstBefore(Neg, ICI);
7082 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7086 case Instruction::Xor:
7087 // For the xor case, we can xor two constants together, eliminating
7088 // the explicit xor.
7089 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7090 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7091 Context->getConstantExprXor(RHS, BOC));
7094 case Instruction::Sub:
7095 // Replace (([sub|xor] A, B) != 0) with (A != B)
7097 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7101 case Instruction::Or:
7102 // If bits are being or'd in that are not present in the constant we
7103 // are comparing against, then the comparison could never succeed!
7104 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7105 Constant *NotCI = Context->getConstantExprNot(RHS);
7106 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7107 return ReplaceInstUsesWith(ICI,
7108 Context->getConstantInt(Type::Int1Ty,
7113 case Instruction::And:
7114 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7115 // If bits are being compared against that are and'd out, then the
7116 // comparison can never succeed!
7117 if ((RHSV & ~BOC->getValue()) != 0)
7118 return ReplaceInstUsesWith(ICI,
7119 Context->getConstantInt(Type::Int1Ty,
7122 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7123 if (RHS == BOC && RHSV.isPowerOf2())
7124 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7125 ICmpInst::ICMP_NE, LHSI,
7126 Context->getNullValue(RHS->getType()));
7128 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7129 if (BOC->getValue().isSignBit()) {
7130 Value *X = BO->getOperand(0);
7131 Constant *Zero = Context->getNullValue(X->getType());
7132 ICmpInst::Predicate pred = isICMP_NE ?
7133 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7134 return new ICmpInst(*Context, pred, X, Zero);
7137 // ((X & ~7) == 0) --> X < 8
7138 if (RHSV == 0 && isHighOnes(BOC)) {
7139 Value *X = BO->getOperand(0);
7140 Constant *NegX = Context->getConstantExprNeg(BOC);
7141 ICmpInst::Predicate pred = isICMP_NE ?
7142 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7143 return new ICmpInst(*Context, pred, X, NegX);
7148 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7149 // Handle icmp {eq|ne} <intrinsic>, intcst.
7150 if (II->getIntrinsicID() == Intrinsic::bswap) {
7152 ICI.setOperand(0, II->getOperand(1));
7153 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7161 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7162 /// We only handle extending casts so far.
7164 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7165 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7166 Value *LHSCIOp = LHSCI->getOperand(0);
7167 const Type *SrcTy = LHSCIOp->getType();
7168 const Type *DestTy = LHSCI->getType();
7171 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7172 // integer type is the same size as the pointer type.
7173 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7174 TD->getPointerSizeInBits() ==
7175 cast<IntegerType>(DestTy)->getBitWidth()) {
7177 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7178 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7179 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7180 RHSOp = RHSC->getOperand(0);
7181 // If the pointer types don't match, insert a bitcast.
7182 if (LHSCIOp->getType() != RHSOp->getType())
7183 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7187 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7190 // The code below only handles extension cast instructions, so far.
7192 if (LHSCI->getOpcode() != Instruction::ZExt &&
7193 LHSCI->getOpcode() != Instruction::SExt)
7196 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7197 bool isSignedCmp = ICI.isSignedPredicate();
7199 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7200 // Not an extension from the same type?
7201 RHSCIOp = CI->getOperand(0);
7202 if (RHSCIOp->getType() != LHSCIOp->getType())
7205 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7206 // and the other is a zext), then we can't handle this.
7207 if (CI->getOpcode() != LHSCI->getOpcode())
7210 // Deal with equality cases early.
7211 if (ICI.isEquality())
7212 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7214 // A signed comparison of sign extended values simplifies into a
7215 // signed comparison.
7216 if (isSignedCmp && isSignedExt)
7217 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7219 // The other three cases all fold into an unsigned comparison.
7220 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7223 // If we aren't dealing with a constant on the RHS, exit early
7224 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7228 // Compute the constant that would happen if we truncated to SrcTy then
7229 // reextended to DestTy.
7230 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7231 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7234 // If the re-extended constant didn't change...
7236 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7237 // For example, we might have:
7238 // %A = sext i16 %X to i32
7239 // %B = icmp ugt i32 %A, 1330
7240 // It is incorrect to transform this into
7241 // %B = icmp ugt i16 %X, 1330
7242 // because %A may have negative value.
7244 // However, we allow this when the compare is EQ/NE, because they are
7246 if (isSignedExt == isSignedCmp || ICI.isEquality())
7247 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7251 // The re-extended constant changed so the constant cannot be represented
7252 // in the shorter type. Consequently, we cannot emit a simple comparison.
7254 // First, handle some easy cases. We know the result cannot be equal at this
7255 // point so handle the ICI.isEquality() cases
7256 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7257 return ReplaceInstUsesWith(ICI, Context->getFalse());
7258 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7259 return ReplaceInstUsesWith(ICI, Context->getTrue());
7261 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7262 // should have been folded away previously and not enter in here.
7265 // We're performing a signed comparison.
7266 if (cast<ConstantInt>(CI)->getValue().isNegative())
7267 Result = Context->getFalse(); // X < (small) --> false
7269 Result = Context->getTrue(); // X < (large) --> true
7271 // We're performing an unsigned comparison.
7273 // We're performing an unsigned comp with a sign extended value.
7274 // This is true if the input is >= 0. [aka >s -1]
7275 Constant *NegOne = Context->getAllOnesValue(SrcTy);
7276 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7277 LHSCIOp, NegOne, ICI.getName()), ICI);
7279 // Unsigned extend & unsigned compare -> always true.
7280 Result = Context->getTrue();
7284 // Finally, return the value computed.
7285 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7286 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7287 return ReplaceInstUsesWith(ICI, Result);
7289 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7290 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7291 "ICmp should be folded!");
7292 if (Constant *CI = dyn_cast<Constant>(Result))
7293 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7294 return BinaryOperator::CreateNot(*Context, Result);
7297 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7298 return commonShiftTransforms(I);
7301 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7302 return commonShiftTransforms(I);
7305 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7306 if (Instruction *R = commonShiftTransforms(I))
7309 Value *Op0 = I.getOperand(0);
7311 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7312 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7313 if (CSI->isAllOnesValue())
7314 return ReplaceInstUsesWith(I, CSI);
7316 // See if we can turn a signed shr into an unsigned shr.
7317 if (MaskedValueIsZero(Op0,
7318 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7319 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7321 // Arithmetic shifting an all-sign-bit value is a no-op.
7322 unsigned NumSignBits = ComputeNumSignBits(Op0);
7323 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7324 return ReplaceInstUsesWith(I, Op0);
7329 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7330 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7331 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7333 // shl X, 0 == X and shr X, 0 == X
7334 // shl 0, X == 0 and shr 0, X == 0
7335 if (Op1 == Context->getNullValue(Op1->getType()) ||
7336 Op0 == Context->getNullValue(Op0->getType()))
7337 return ReplaceInstUsesWith(I, Op0);
7339 if (isa<UndefValue>(Op0)) {
7340 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7341 return ReplaceInstUsesWith(I, Op0);
7342 else // undef << X -> 0, undef >>u X -> 0
7343 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7345 if (isa<UndefValue>(Op1)) {
7346 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7347 return ReplaceInstUsesWith(I, Op0);
7348 else // X << undef, X >>u undef -> 0
7349 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7352 // See if we can fold away this shift.
7353 if (SimplifyDemandedInstructionBits(I))
7356 // Try to fold constant and into select arguments.
7357 if (isa<Constant>(Op0))
7358 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7359 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7362 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7363 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7368 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7369 BinaryOperator &I) {
7370 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7372 // See if we can simplify any instructions used by the instruction whose sole
7373 // purpose is to compute bits we don't care about.
7374 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7376 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7379 if (Op1->uge(TypeBits)) {
7380 if (I.getOpcode() != Instruction::AShr)
7381 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7383 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7388 // ((X*C1) << C2) == (X * (C1 << C2))
7389 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7390 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7391 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7392 return BinaryOperator::CreateMul(BO->getOperand(0),
7393 Context->getConstantExprShl(BOOp, Op1));
7395 // Try to fold constant and into select arguments.
7396 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7397 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7399 if (isa<PHINode>(Op0))
7400 if (Instruction *NV = FoldOpIntoPhi(I))
7403 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7404 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7405 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7406 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7407 // place. Don't try to do this transformation in this case. Also, we
7408 // require that the input operand is a shift-by-constant so that we have
7409 // confidence that the shifts will get folded together. We could do this
7410 // xform in more cases, but it is unlikely to be profitable.
7411 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7412 isa<ConstantInt>(TrOp->getOperand(1))) {
7413 // Okay, we'll do this xform. Make the shift of shift.
7414 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7415 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7417 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7419 // For logical shifts, the truncation has the effect of making the high
7420 // part of the register be zeros. Emulate this by inserting an AND to
7421 // clear the top bits as needed. This 'and' will usually be zapped by
7422 // other xforms later if dead.
7423 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7424 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7425 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7427 // The mask we constructed says what the trunc would do if occurring
7428 // between the shifts. We want to know the effect *after* the second
7429 // shift. We know that it is a logical shift by a constant, so adjust the
7430 // mask as appropriate.
7431 if (I.getOpcode() == Instruction::Shl)
7432 MaskV <<= Op1->getZExtValue();
7434 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7435 MaskV = MaskV.lshr(Op1->getZExtValue());
7439 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7441 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7443 // Return the value truncated to the interesting size.
7444 return new TruncInst(And, I.getType());
7448 if (Op0->hasOneUse()) {
7449 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7450 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7453 switch (Op0BO->getOpcode()) {
7455 case Instruction::Add:
7456 case Instruction::And:
7457 case Instruction::Or:
7458 case Instruction::Xor: {
7459 // These operators commute.
7460 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7461 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7462 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7463 m_Specific(Op1)), *Context)){
7464 Instruction *YS = BinaryOperator::CreateShl(
7465 Op0BO->getOperand(0), Op1,
7467 InsertNewInstBefore(YS, I); // (Y << C)
7469 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7470 Op0BO->getOperand(1)->getName());
7471 InsertNewInstBefore(X, I); // (X + (Y << C))
7472 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7473 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7474 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7477 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7478 Value *Op0BOOp1 = Op0BO->getOperand(1);
7479 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7481 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7482 m_ConstantInt(CC)), *Context) &&
7483 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7484 Instruction *YS = BinaryOperator::CreateShl(
7485 Op0BO->getOperand(0), Op1,
7487 InsertNewInstBefore(YS, I); // (Y << C)
7489 BinaryOperator::CreateAnd(V1,
7490 Context->getConstantExprShl(CC, Op1),
7491 V1->getName()+".mask");
7492 InsertNewInstBefore(XM, I); // X & (CC << C)
7494 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7499 case Instruction::Sub: {
7500 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7501 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7502 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7503 m_Specific(Op1)), *Context)){
7504 Instruction *YS = BinaryOperator::CreateShl(
7505 Op0BO->getOperand(1), Op1,
7507 InsertNewInstBefore(YS, I); // (Y << C)
7509 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7510 Op0BO->getOperand(0)->getName());
7511 InsertNewInstBefore(X, I); // (X + (Y << C))
7512 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7513 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7514 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7517 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7518 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7519 match(Op0BO->getOperand(0),
7520 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7521 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7522 cast<BinaryOperator>(Op0BO->getOperand(0))
7523 ->getOperand(0)->hasOneUse()) {
7524 Instruction *YS = BinaryOperator::CreateShl(
7525 Op0BO->getOperand(1), Op1,
7527 InsertNewInstBefore(YS, I); // (Y << C)
7529 BinaryOperator::CreateAnd(V1,
7530 Context->getConstantExprShl(CC, Op1),
7531 V1->getName()+".mask");
7532 InsertNewInstBefore(XM, I); // X & (CC << C)
7534 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7542 // If the operand is an bitwise operator with a constant RHS, and the
7543 // shift is the only use, we can pull it out of the shift.
7544 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7545 bool isValid = true; // Valid only for And, Or, Xor
7546 bool highBitSet = false; // Transform if high bit of constant set?
7548 switch (Op0BO->getOpcode()) {
7549 default: isValid = false; break; // Do not perform transform!
7550 case Instruction::Add:
7551 isValid = isLeftShift;
7553 case Instruction::Or:
7554 case Instruction::Xor:
7557 case Instruction::And:
7562 // If this is a signed shift right, and the high bit is modified
7563 // by the logical operation, do not perform the transformation.
7564 // The highBitSet boolean indicates the value of the high bit of
7565 // the constant which would cause it to be modified for this
7568 if (isValid && I.getOpcode() == Instruction::AShr)
7569 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7572 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7574 Instruction *NewShift =
7575 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7576 InsertNewInstBefore(NewShift, I);
7577 NewShift->takeName(Op0BO);
7579 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7586 // Find out if this is a shift of a shift by a constant.
7587 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7588 if (ShiftOp && !ShiftOp->isShift())
7591 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7592 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7593 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7594 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7595 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7596 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7597 Value *X = ShiftOp->getOperand(0);
7599 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7601 const IntegerType *Ty = cast<IntegerType>(I.getType());
7603 // Check for (X << c1) << c2 and (X >> c1) >> c2
7604 if (I.getOpcode() == ShiftOp->getOpcode()) {
7605 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7607 if (AmtSum >= TypeBits) {
7608 if (I.getOpcode() != Instruction::AShr)
7609 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7610 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7613 return BinaryOperator::Create(I.getOpcode(), X,
7614 Context->getConstantInt(Ty, AmtSum));
7615 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7616 I.getOpcode() == Instruction::AShr) {
7617 if (AmtSum >= TypeBits)
7618 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7620 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7621 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7622 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7623 I.getOpcode() == Instruction::LShr) {
7624 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7625 if (AmtSum >= TypeBits)
7626 AmtSum = TypeBits-1;
7628 Instruction *Shift =
7629 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7630 InsertNewInstBefore(Shift, I);
7632 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7633 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7636 // Okay, if we get here, one shift must be left, and the other shift must be
7637 // right. See if the amounts are equal.
7638 if (ShiftAmt1 == ShiftAmt2) {
7639 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7640 if (I.getOpcode() == Instruction::Shl) {
7641 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7642 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7644 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7645 if (I.getOpcode() == Instruction::LShr) {
7646 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7647 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7649 // We can simplify ((X << C) >>s C) into a trunc + sext.
7650 // NOTE: we could do this for any C, but that would make 'unusual' integer
7651 // types. For now, just stick to ones well-supported by the code
7653 const Type *SExtType = 0;
7654 switch (Ty->getBitWidth() - ShiftAmt1) {
7661 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7666 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7667 InsertNewInstBefore(NewTrunc, I);
7668 return new SExtInst(NewTrunc, Ty);
7670 // Otherwise, we can't handle it yet.
7671 } else if (ShiftAmt1 < ShiftAmt2) {
7672 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7674 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7675 if (I.getOpcode() == Instruction::Shl) {
7676 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7677 ShiftOp->getOpcode() == Instruction::AShr);
7678 Instruction *Shift =
7679 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7680 InsertNewInstBefore(Shift, I);
7682 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7683 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7686 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7687 if (I.getOpcode() == Instruction::LShr) {
7688 assert(ShiftOp->getOpcode() == Instruction::Shl);
7689 Instruction *Shift =
7690 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7691 InsertNewInstBefore(Shift, I);
7693 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7694 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7697 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7699 assert(ShiftAmt2 < ShiftAmt1);
7700 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7702 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7703 if (I.getOpcode() == Instruction::Shl) {
7704 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7705 ShiftOp->getOpcode() == Instruction::AShr);
7706 Instruction *Shift =
7707 BinaryOperator::Create(ShiftOp->getOpcode(), X,
7708 Context->getConstantInt(Ty, ShiftDiff));
7709 InsertNewInstBefore(Shift, I);
7711 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7712 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7715 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7716 if (I.getOpcode() == Instruction::LShr) {
7717 assert(ShiftOp->getOpcode() == Instruction::Shl);
7718 Instruction *Shift =
7719 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7720 InsertNewInstBefore(Shift, I);
7722 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7723 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7726 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7733 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7734 /// expression. If so, decompose it, returning some value X, such that Val is
7737 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7738 int &Offset, LLVMContext *Context) {
7739 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7740 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7741 Offset = CI->getZExtValue();
7743 return Context->getConstantInt(Type::Int32Ty, 0);
7744 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7745 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7746 if (I->getOpcode() == Instruction::Shl) {
7747 // This is a value scaled by '1 << the shift amt'.
7748 Scale = 1U << RHS->getZExtValue();
7750 return I->getOperand(0);
7751 } else if (I->getOpcode() == Instruction::Mul) {
7752 // This value is scaled by 'RHS'.
7753 Scale = RHS->getZExtValue();
7755 return I->getOperand(0);
7756 } else if (I->getOpcode() == Instruction::Add) {
7757 // We have X+C. Check to see if we really have (X*C2)+C1,
7758 // where C1 is divisible by C2.
7761 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7763 Offset += RHS->getZExtValue();
7770 // Otherwise, we can't look past this.
7777 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7778 /// try to eliminate the cast by moving the type information into the alloc.
7779 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7780 AllocationInst &AI) {
7781 const PointerType *PTy = cast<PointerType>(CI.getType());
7783 // Remove any uses of AI that are dead.
7784 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7786 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7787 Instruction *User = cast<Instruction>(*UI++);
7788 if (isInstructionTriviallyDead(User)) {
7789 while (UI != E && *UI == User)
7790 ++UI; // If this instruction uses AI more than once, don't break UI.
7793 DOUT << "IC: DCE: " << *User;
7794 EraseInstFromFunction(*User);
7798 // This requires TargetData to get the alloca alignment and size information.
7801 // Get the type really allocated and the type casted to.
7802 const Type *AllocElTy = AI.getAllocatedType();
7803 const Type *CastElTy = PTy->getElementType();
7804 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7806 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7807 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7808 if (CastElTyAlign < AllocElTyAlign) return 0;
7810 // If the allocation has multiple uses, only promote it if we are strictly
7811 // increasing the alignment of the resultant allocation. If we keep it the
7812 // same, we open the door to infinite loops of various kinds. (A reference
7813 // from a dbg.declare doesn't count as a use for this purpose.)
7814 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7815 CastElTyAlign == AllocElTyAlign) return 0;
7817 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7818 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7819 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7821 // See if we can satisfy the modulus by pulling a scale out of the array
7823 unsigned ArraySizeScale;
7825 Value *NumElements = // See if the array size is a decomposable linear expr.
7826 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7827 ArrayOffset, Context);
7829 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7831 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7832 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7834 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7839 // If the allocation size is constant, form a constant mul expression
7840 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7841 if (isa<ConstantInt>(NumElements))
7842 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7843 cast<ConstantInt>(Amt));
7844 // otherwise multiply the amount and the number of elements
7846 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7847 Amt = InsertNewInstBefore(Tmp, AI);
7851 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7852 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7853 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7854 Amt = InsertNewInstBefore(Tmp, AI);
7857 AllocationInst *New;
7858 if (isa<MallocInst>(AI))
7859 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7861 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7862 InsertNewInstBefore(New, AI);
7865 // If the allocation has one real use plus a dbg.declare, just remove the
7867 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7868 EraseInstFromFunction(*DI);
7870 // If the allocation has multiple real uses, insert a cast and change all
7871 // things that used it to use the new cast. This will also hack on CI, but it
7873 else if (!AI.hasOneUse()) {
7874 AddUsesToWorkList(AI);
7875 // New is the allocation instruction, pointer typed. AI is the original
7876 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7877 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7878 InsertNewInstBefore(NewCast, AI);
7879 AI.replaceAllUsesWith(NewCast);
7881 return ReplaceInstUsesWith(CI, New);
7884 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7885 /// and return it as type Ty without inserting any new casts and without
7886 /// changing the computed value. This is used by code that tries to decide
7887 /// whether promoting or shrinking integer operations to wider or smaller types
7888 /// will allow us to eliminate a truncate or extend.
7890 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7891 /// extension operation if Ty is larger.
7893 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7894 /// should return true if trunc(V) can be computed by computing V in the smaller
7895 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7896 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7897 /// efficiently truncated.
7899 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7900 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7901 /// the final result.
7902 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7904 int &NumCastsRemoved){
7905 // We can always evaluate constants in another type.
7906 if (isa<Constant>(V))
7909 Instruction *I = dyn_cast<Instruction>(V);
7910 if (!I) return false;
7912 const Type *OrigTy = V->getType();
7914 // If this is an extension or truncate, we can often eliminate it.
7915 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7916 // If this is a cast from the destination type, we can trivially eliminate
7917 // it, and this will remove a cast overall.
7918 if (I->getOperand(0)->getType() == Ty) {
7919 // If the first operand is itself a cast, and is eliminable, do not count
7920 // this as an eliminable cast. We would prefer to eliminate those two
7922 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7928 // We can't extend or shrink something that has multiple uses: doing so would
7929 // require duplicating the instruction in general, which isn't profitable.
7930 if (!I->hasOneUse()) return false;
7932 unsigned Opc = I->getOpcode();
7934 case Instruction::Add:
7935 case Instruction::Sub:
7936 case Instruction::Mul:
7937 case Instruction::And:
7938 case Instruction::Or:
7939 case Instruction::Xor:
7940 // These operators can all arbitrarily be extended or truncated.
7941 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7943 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7946 case Instruction::UDiv:
7947 case Instruction::URem: {
7948 // UDiv and URem can be truncated if all the truncated bits are zero.
7949 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7950 uint32_t BitWidth = Ty->getScalarSizeInBits();
7951 if (BitWidth < OrigBitWidth) {
7952 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7953 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7954 MaskedValueIsZero(I->getOperand(1), Mask)) {
7955 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7957 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7963 case Instruction::Shl:
7964 // If we are truncating the result of this SHL, and if it's a shift of a
7965 // constant amount, we can always perform a SHL in a smaller type.
7966 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7967 uint32_t BitWidth = Ty->getScalarSizeInBits();
7968 if (BitWidth < OrigTy->getScalarSizeInBits() &&
7969 CI->getLimitedValue(BitWidth) < BitWidth)
7970 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7974 case Instruction::LShr:
7975 // If this is a truncate of a logical shr, we can truncate it to a smaller
7976 // lshr iff we know that the bits we would otherwise be shifting in are
7978 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7979 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7980 uint32_t BitWidth = Ty->getScalarSizeInBits();
7981 if (BitWidth < OrigBitWidth &&
7982 MaskedValueIsZero(I->getOperand(0),
7983 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7984 CI->getLimitedValue(BitWidth) < BitWidth) {
7985 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7990 case Instruction::ZExt:
7991 case Instruction::SExt:
7992 case Instruction::Trunc:
7993 // If this is the same kind of case as our original (e.g. zext+zext), we
7994 // can safely replace it. Note that replacing it does not reduce the number
7995 // of casts in the input.
7999 // sext (zext ty1), ty2 -> zext ty2
8000 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8003 case Instruction::Select: {
8004 SelectInst *SI = cast<SelectInst>(I);
8005 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8007 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8010 case Instruction::PHI: {
8011 // We can change a phi if we can change all operands.
8012 PHINode *PN = cast<PHINode>(I);
8013 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8014 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8020 // TODO: Can handle more cases here.
8027 /// EvaluateInDifferentType - Given an expression that
8028 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8029 /// evaluate the expression.
8030 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8032 if (Constant *C = dyn_cast<Constant>(V))
8033 return Context->getConstantExprIntegerCast(C, Ty,
8034 isSigned /*Sext or ZExt*/);
8036 // Otherwise, it must be an instruction.
8037 Instruction *I = cast<Instruction>(V);
8038 Instruction *Res = 0;
8039 unsigned Opc = I->getOpcode();
8041 case Instruction::Add:
8042 case Instruction::Sub:
8043 case Instruction::Mul:
8044 case Instruction::And:
8045 case Instruction::Or:
8046 case Instruction::Xor:
8047 case Instruction::AShr:
8048 case Instruction::LShr:
8049 case Instruction::Shl:
8050 case Instruction::UDiv:
8051 case Instruction::URem: {
8052 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8053 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8054 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8057 case Instruction::Trunc:
8058 case Instruction::ZExt:
8059 case Instruction::SExt:
8060 // If the source type of the cast is the type we're trying for then we can
8061 // just return the source. There's no need to insert it because it is not
8063 if (I->getOperand(0)->getType() == Ty)
8064 return I->getOperand(0);
8066 // Otherwise, must be the same type of cast, so just reinsert a new one.
8067 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8070 case Instruction::Select: {
8071 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8072 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8073 Res = SelectInst::Create(I->getOperand(0), True, False);
8076 case Instruction::PHI: {
8077 PHINode *OPN = cast<PHINode>(I);
8078 PHINode *NPN = PHINode::Create(Ty);
8079 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8080 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8081 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8087 // TODO: Can handle more cases here.
8088 llvm_unreachable("Unreachable!");
8093 return InsertNewInstBefore(Res, *I);
8096 /// @brief Implement the transforms common to all CastInst visitors.
8097 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8098 Value *Src = CI.getOperand(0);
8100 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8101 // eliminate it now.
8102 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8103 if (Instruction::CastOps opc =
8104 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8105 // The first cast (CSrc) is eliminable so we need to fix up or replace
8106 // the second cast (CI). CSrc will then have a good chance of being dead.
8107 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8111 // If we are casting a select then fold the cast into the select
8112 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8113 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8116 // If we are casting a PHI then fold the cast into the PHI
8117 if (isa<PHINode>(Src))
8118 if (Instruction *NV = FoldOpIntoPhi(CI))
8124 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8125 /// or not there is a sequence of GEP indices into the type that will land us at
8126 /// the specified offset. If so, fill them into NewIndices and return the
8127 /// resultant element type, otherwise return null.
8128 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8129 SmallVectorImpl<Value*> &NewIndices,
8130 const TargetData *TD,
8131 LLVMContext *Context) {
8133 if (!Ty->isSized()) return 0;
8135 // Start with the index over the outer type. Note that the type size
8136 // might be zero (even if the offset isn't zero) if the indexed type
8137 // is something like [0 x {int, int}]
8138 const Type *IntPtrTy = TD->getIntPtrType();
8139 int64_t FirstIdx = 0;
8140 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8141 FirstIdx = Offset/TySize;
8142 Offset -= FirstIdx*TySize;
8144 // Handle hosts where % returns negative instead of values [0..TySize).
8148 assert(Offset >= 0);
8150 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8153 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8155 // Index into the types. If we fail, set OrigBase to null.
8157 // Indexing into tail padding between struct/array elements.
8158 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8161 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8162 const StructLayout *SL = TD->getStructLayout(STy);
8163 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8164 "Offset must stay within the indexed type");
8166 unsigned Elt = SL->getElementContainingOffset(Offset);
8167 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8169 Offset -= SL->getElementOffset(Elt);
8170 Ty = STy->getElementType(Elt);
8171 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8172 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8173 assert(EltSize && "Cannot index into a zero-sized array");
8174 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8176 Ty = AT->getElementType();
8178 // Otherwise, we can't index into the middle of this atomic type, bail.
8186 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8187 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8188 Value *Src = CI.getOperand(0);
8190 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8191 // If casting the result of a getelementptr instruction with no offset, turn
8192 // this into a cast of the original pointer!
8193 if (GEP->hasAllZeroIndices()) {
8194 // Changing the cast operand is usually not a good idea but it is safe
8195 // here because the pointer operand is being replaced with another
8196 // pointer operand so the opcode doesn't need to change.
8198 CI.setOperand(0, GEP->getOperand(0));
8202 // If the GEP has a single use, and the base pointer is a bitcast, and the
8203 // GEP computes a constant offset, see if we can convert these three
8204 // instructions into fewer. This typically happens with unions and other
8205 // non-type-safe code.
8206 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8207 if (GEP->hasAllConstantIndices()) {
8208 // We are guaranteed to get a constant from EmitGEPOffset.
8209 ConstantInt *OffsetV =
8210 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8211 int64_t Offset = OffsetV->getSExtValue();
8213 // Get the base pointer input of the bitcast, and the type it points to.
8214 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8215 const Type *GEPIdxTy =
8216 cast<PointerType>(OrigBase->getType())->getElementType();
8217 SmallVector<Value*, 8> NewIndices;
8218 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8219 // If we were able to index down into an element, create the GEP
8220 // and bitcast the result. This eliminates one bitcast, potentially
8222 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8224 NewIndices.end(), "");
8225 InsertNewInstBefore(NGEP, CI);
8226 NGEP->takeName(GEP);
8228 if (isa<BitCastInst>(CI))
8229 return new BitCastInst(NGEP, CI.getType());
8230 assert(isa<PtrToIntInst>(CI));
8231 return new PtrToIntInst(NGEP, CI.getType());
8237 return commonCastTransforms(CI);
8240 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8241 /// type like i42. We don't want to introduce operations on random non-legal
8242 /// integer types where they don't already exist in the code. In the future,
8243 /// we should consider making this based off target-data, so that 32-bit targets
8244 /// won't get i64 operations etc.
8245 static bool isSafeIntegerType(const Type *Ty) {
8246 switch (Ty->getPrimitiveSizeInBits()) {
8257 /// commonIntCastTransforms - This function implements the common transforms
8258 /// for trunc, zext, and sext.
8259 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8260 if (Instruction *Result = commonCastTransforms(CI))
8263 Value *Src = CI.getOperand(0);
8264 const Type *SrcTy = Src->getType();
8265 const Type *DestTy = CI.getType();
8266 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8267 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8269 // See if we can simplify any instructions used by the LHS whose sole
8270 // purpose is to compute bits we don't care about.
8271 if (SimplifyDemandedInstructionBits(CI))
8274 // If the source isn't an instruction or has more than one use then we
8275 // can't do anything more.
8276 Instruction *SrcI = dyn_cast<Instruction>(Src);
8277 if (!SrcI || !Src->hasOneUse())
8280 // Attempt to propagate the cast into the instruction for int->int casts.
8281 int NumCastsRemoved = 0;
8282 // Only do this if the dest type is a simple type, don't convert the
8283 // expression tree to something weird like i93 unless the source is also
8285 if ((isSafeIntegerType(DestTy->getScalarType()) ||
8286 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8287 CanEvaluateInDifferentType(SrcI, DestTy,
8288 CI.getOpcode(), NumCastsRemoved)) {
8289 // If this cast is a truncate, evaluting in a different type always
8290 // eliminates the cast, so it is always a win. If this is a zero-extension,
8291 // we need to do an AND to maintain the clear top-part of the computation,
8292 // so we require that the input have eliminated at least one cast. If this
8293 // is a sign extension, we insert two new casts (to do the extension) so we
8294 // require that two casts have been eliminated.
8295 bool DoXForm = false;
8296 bool JustReplace = false;
8297 switch (CI.getOpcode()) {
8299 // All the others use floating point so we shouldn't actually
8300 // get here because of the check above.
8301 llvm_unreachable("Unknown cast type");
8302 case Instruction::Trunc:
8305 case Instruction::ZExt: {
8306 DoXForm = NumCastsRemoved >= 1;
8307 if (!DoXForm && 0) {
8308 // If it's unnecessary to issue an AND to clear the high bits, it's
8309 // always profitable to do this xform.
8310 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8311 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8312 if (MaskedValueIsZero(TryRes, Mask))
8313 return ReplaceInstUsesWith(CI, TryRes);
8315 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8316 if (TryI->use_empty())
8317 EraseInstFromFunction(*TryI);
8321 case Instruction::SExt: {
8322 DoXForm = NumCastsRemoved >= 2;
8323 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8324 // If we do not have to emit the truncate + sext pair, then it's always
8325 // profitable to do this xform.
8327 // It's not safe to eliminate the trunc + sext pair if one of the
8328 // eliminated cast is a truncate. e.g.
8329 // t2 = trunc i32 t1 to i16
8330 // t3 = sext i16 t2 to i32
8333 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8334 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8335 if (NumSignBits > (DestBitSize - SrcBitSize))
8336 return ReplaceInstUsesWith(CI, TryRes);
8338 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8339 if (TryI->use_empty())
8340 EraseInstFromFunction(*TryI);
8347 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8349 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8350 CI.getOpcode() == Instruction::SExt);
8352 // Just replace this cast with the result.
8353 return ReplaceInstUsesWith(CI, Res);
8355 assert(Res->getType() == DestTy);
8356 switch (CI.getOpcode()) {
8357 default: llvm_unreachable("Unknown cast type!");
8358 case Instruction::Trunc:
8359 // Just replace this cast with the result.
8360 return ReplaceInstUsesWith(CI, Res);
8361 case Instruction::ZExt: {
8362 assert(SrcBitSize < DestBitSize && "Not a zext?");
8364 // If the high bits are already zero, just replace this cast with the
8366 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8367 if (MaskedValueIsZero(Res, Mask))
8368 return ReplaceInstUsesWith(CI, Res);
8370 // We need to emit an AND to clear the high bits.
8371 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8373 return BinaryOperator::CreateAnd(Res, C);
8375 case Instruction::SExt: {
8376 // If the high bits are already filled with sign bit, just replace this
8377 // cast with the result.
8378 unsigned NumSignBits = ComputeNumSignBits(Res);
8379 if (NumSignBits > (DestBitSize - SrcBitSize))
8380 return ReplaceInstUsesWith(CI, Res);
8382 // We need to emit a cast to truncate, then a cast to sext.
8383 return CastInst::Create(Instruction::SExt,
8384 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8391 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8392 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8394 switch (SrcI->getOpcode()) {
8395 case Instruction::Add:
8396 case Instruction::Mul:
8397 case Instruction::And:
8398 case Instruction::Or:
8399 case Instruction::Xor:
8400 // If we are discarding information, rewrite.
8401 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8402 // Don't insert two casts unless at least one can be eliminated.
8403 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8404 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8405 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8406 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8407 return BinaryOperator::Create(
8408 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8412 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8413 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8414 SrcI->getOpcode() == Instruction::Xor &&
8415 Op1 == Context->getTrue() &&
8416 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8417 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8418 return BinaryOperator::CreateXor(New,
8419 Context->getConstantInt(CI.getType(), 1));
8423 case Instruction::Shl: {
8424 // Canonicalize trunc inside shl, if we can.
8425 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8426 if (CI && DestBitSize < SrcBitSize &&
8427 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8428 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8429 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8430 return BinaryOperator::CreateShl(Op0c, Op1c);
8438 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8439 if (Instruction *Result = commonIntCastTransforms(CI))
8442 Value *Src = CI.getOperand(0);
8443 const Type *Ty = CI.getType();
8444 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8445 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8447 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8448 if (DestBitWidth == 1) {
8449 Constant *One = Context->getConstantInt(Src->getType(), 1);
8450 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8451 Value *Zero = Context->getNullValue(Src->getType());
8452 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8455 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8456 ConstantInt *ShAmtV = 0;
8458 if (Src->hasOneUse() &&
8459 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8460 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8462 // Get a mask for the bits shifting in.
8463 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8464 if (MaskedValueIsZero(ShiftOp, Mask)) {
8465 if (ShAmt >= DestBitWidth) // All zeros.
8466 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8468 // Okay, we can shrink this. Truncate the input, then return a new
8470 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8471 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8472 return BinaryOperator::CreateLShr(V1, V2);
8479 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8480 /// in order to eliminate the icmp.
8481 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8483 // If we are just checking for a icmp eq of a single bit and zext'ing it
8484 // to an integer, then shift the bit to the appropriate place and then
8485 // cast to integer to avoid the comparison.
8486 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8487 const APInt &Op1CV = Op1C->getValue();
8489 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8490 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8491 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8492 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8493 if (!DoXform) return ICI;
8495 Value *In = ICI->getOperand(0);
8496 Value *Sh = Context->getConstantInt(In->getType(),
8497 In->getType()->getScalarSizeInBits()-1);
8498 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8499 In->getName()+".lobit"),
8501 if (In->getType() != CI.getType())
8502 In = CastInst::CreateIntegerCast(In, CI.getType(),
8503 false/*ZExt*/, "tmp", &CI);
8505 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8506 Constant *One = Context->getConstantInt(In->getType(), 1);
8507 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8508 In->getName()+".not"),
8512 return ReplaceInstUsesWith(CI, In);
8517 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8518 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8519 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8520 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8521 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8522 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8523 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8524 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8525 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8526 // This only works for EQ and NE
8527 ICI->isEquality()) {
8528 // If Op1C some other power of two, convert:
8529 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8530 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8531 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8532 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8534 APInt KnownZeroMask(~KnownZero);
8535 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8536 if (!DoXform) return ICI;
8538 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8539 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8540 // (X&4) == 2 --> false
8541 // (X&4) != 2 --> true
8542 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8543 Res = Context->getConstantExprZExt(Res, CI.getType());
8544 return ReplaceInstUsesWith(CI, Res);
8547 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8548 Value *In = ICI->getOperand(0);
8550 // Perform a logical shr by shiftamt.
8551 // Insert the shift to put the result in the low bit.
8552 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8553 Context->getConstantInt(In->getType(), ShiftAmt),
8554 In->getName()+".lobit"), CI);
8557 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8558 Constant *One = Context->getConstantInt(In->getType(), 1);
8559 In = BinaryOperator::CreateXor(In, One, "tmp");
8560 InsertNewInstBefore(cast<Instruction>(In), CI);
8563 if (CI.getType() == In->getType())
8564 return ReplaceInstUsesWith(CI, In);
8566 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8574 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8575 // If one of the common conversion will work ..
8576 if (Instruction *Result = commonIntCastTransforms(CI))
8579 Value *Src = CI.getOperand(0);
8581 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8582 // types and if the sizes are just right we can convert this into a logical
8583 // 'and' which will be much cheaper than the pair of casts.
8584 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8585 // Get the sizes of the types involved. We know that the intermediate type
8586 // will be smaller than A or C, but don't know the relation between A and C.
8587 Value *A = CSrc->getOperand(0);
8588 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8589 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8590 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8591 // If we're actually extending zero bits, then if
8592 // SrcSize < DstSize: zext(a & mask)
8593 // SrcSize == DstSize: a & mask
8594 // SrcSize > DstSize: trunc(a) & mask
8595 if (SrcSize < DstSize) {
8596 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8597 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8599 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8600 InsertNewInstBefore(And, CI);
8601 return new ZExtInst(And, CI.getType());
8602 } else if (SrcSize == DstSize) {
8603 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8604 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8606 } else if (SrcSize > DstSize) {
8607 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8608 InsertNewInstBefore(Trunc, CI);
8609 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8610 return BinaryOperator::CreateAnd(Trunc,
8611 Context->getConstantInt(Trunc->getType(),
8616 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8617 return transformZExtICmp(ICI, CI);
8619 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8620 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8621 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8622 // of the (zext icmp) will be transformed.
8623 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8624 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8625 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8626 (transformZExtICmp(LHS, CI, false) ||
8627 transformZExtICmp(RHS, CI, false))) {
8628 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8629 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8630 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8634 // zext(trunc(t) & C) -> (t & zext(C)).
8635 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8636 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8637 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8638 Value *TI0 = TI->getOperand(0);
8639 if (TI0->getType() == CI.getType())
8641 BinaryOperator::CreateAnd(TI0,
8642 Context->getConstantExprZExt(C, CI.getType()));
8645 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8646 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8647 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8648 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8649 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8650 And->getOperand(1) == C)
8651 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8652 Value *TI0 = TI->getOperand(0);
8653 if (TI0->getType() == CI.getType()) {
8654 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8655 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8656 InsertNewInstBefore(NewAnd, *And);
8657 return BinaryOperator::CreateXor(NewAnd, ZC);
8664 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8665 if (Instruction *I = commonIntCastTransforms(CI))
8668 Value *Src = CI.getOperand(0);
8670 // Canonicalize sign-extend from i1 to a select.
8671 if (Src->getType() == Type::Int1Ty)
8672 return SelectInst::Create(Src,
8673 Context->getAllOnesValue(CI.getType()),
8674 Context->getNullValue(CI.getType()));
8676 // See if the value being truncated is already sign extended. If so, just
8677 // eliminate the trunc/sext pair.
8678 if (Operator::getOpcode(Src) == Instruction::Trunc) {
8679 Value *Op = cast<User>(Src)->getOperand(0);
8680 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8681 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8682 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8683 unsigned NumSignBits = ComputeNumSignBits(Op);
8685 if (OpBits == DestBits) {
8686 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8687 // bits, it is already ready.
8688 if (NumSignBits > DestBits-MidBits)
8689 return ReplaceInstUsesWith(CI, Op);
8690 } else if (OpBits < DestBits) {
8691 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8692 // bits, just sext from i32.
8693 if (NumSignBits > OpBits-MidBits)
8694 return new SExtInst(Op, CI.getType(), "tmp");
8696 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8697 // bits, just truncate to i32.
8698 if (NumSignBits > OpBits-MidBits)
8699 return new TruncInst(Op, CI.getType(), "tmp");
8703 // If the input is a shl/ashr pair of a same constant, then this is a sign
8704 // extension from a smaller value. If we could trust arbitrary bitwidth
8705 // integers, we could turn this into a truncate to the smaller bit and then
8706 // use a sext for the whole extension. Since we don't, look deeper and check
8707 // for a truncate. If the source and dest are the same type, eliminate the
8708 // trunc and extend and just do shifts. For example, turn:
8709 // %a = trunc i32 %i to i8
8710 // %b = shl i8 %a, 6
8711 // %c = ashr i8 %b, 6
8712 // %d = sext i8 %c to i32
8714 // %a = shl i32 %i, 30
8715 // %d = ashr i32 %a, 30
8717 ConstantInt *BA = 0, *CA = 0;
8718 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8719 m_ConstantInt(CA)), *Context) &&
8720 BA == CA && isa<TruncInst>(A)) {
8721 Value *I = cast<TruncInst>(A)->getOperand(0);
8722 if (I->getType() == CI.getType()) {
8723 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8724 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8725 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8726 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8727 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8729 return BinaryOperator::CreateAShr(I, ShAmtV);
8736 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8737 /// in the specified FP type without changing its value.
8738 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8739 LLVMContext *Context) {
8741 APFloat F = CFP->getValueAPF();
8742 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8744 return Context->getConstantFP(F);
8748 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8749 /// through it until we get the source value.
8750 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8751 if (Instruction *I = dyn_cast<Instruction>(V))
8752 if (I->getOpcode() == Instruction::FPExt)
8753 return LookThroughFPExtensions(I->getOperand(0), Context);
8755 // If this value is a constant, return the constant in the smallest FP type
8756 // that can accurately represent it. This allows us to turn
8757 // (float)((double)X+2.0) into x+2.0f.
8758 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8759 if (CFP->getType() == Type::PPC_FP128Ty)
8760 return V; // No constant folding of this.
8761 // See if the value can be truncated to float and then reextended.
8762 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8764 if (CFP->getType() == Type::DoubleTy)
8765 return V; // Won't shrink.
8766 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8768 // Don't try to shrink to various long double types.
8774 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8775 if (Instruction *I = commonCastTransforms(CI))
8778 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8779 // smaller than the destination type, we can eliminate the truncate by doing
8780 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8781 // many builtins (sqrt, etc).
8782 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8783 if (OpI && OpI->hasOneUse()) {
8784 switch (OpI->getOpcode()) {
8786 case Instruction::FAdd:
8787 case Instruction::FSub:
8788 case Instruction::FMul:
8789 case Instruction::FDiv:
8790 case Instruction::FRem:
8791 const Type *SrcTy = OpI->getType();
8792 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8793 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8794 if (LHSTrunc->getType() != SrcTy &&
8795 RHSTrunc->getType() != SrcTy) {
8796 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8797 // If the source types were both smaller than the destination type of
8798 // the cast, do this xform.
8799 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8800 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8801 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8803 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8805 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8814 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8815 return commonCastTransforms(CI);
8818 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8819 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8821 return commonCastTransforms(FI);
8823 // fptoui(uitofp(X)) --> X
8824 // fptoui(sitofp(X)) --> X
8825 // This is safe if the intermediate type has enough bits in its mantissa to
8826 // accurately represent all values of X. For example, do not do this with
8827 // i64->float->i64. This is also safe for sitofp case, because any negative
8828 // 'X' value would cause an undefined result for the fptoui.
8829 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8830 OpI->getOperand(0)->getType() == FI.getType() &&
8831 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8832 OpI->getType()->getFPMantissaWidth())
8833 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8835 return commonCastTransforms(FI);
8838 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8839 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8841 return commonCastTransforms(FI);
8843 // fptosi(sitofp(X)) --> X
8844 // fptosi(uitofp(X)) --> X
8845 // This is safe if the intermediate type has enough bits in its mantissa to
8846 // accurately represent all values of X. For example, do not do this with
8847 // i64->float->i64. This is also safe for sitofp case, because any negative
8848 // 'X' value would cause an undefined result for the fptoui.
8849 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8850 OpI->getOperand(0)->getType() == FI.getType() &&
8851 (int)FI.getType()->getScalarSizeInBits() <=
8852 OpI->getType()->getFPMantissaWidth())
8853 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8855 return commonCastTransforms(FI);
8858 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8859 return commonCastTransforms(CI);
8862 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8863 return commonCastTransforms(CI);
8866 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8867 // If the destination integer type is smaller than the intptr_t type for
8868 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8869 // trunc to be exposed to other transforms. Don't do this for extending
8870 // ptrtoint's, because we don't know if the target sign or zero extends its
8873 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8874 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8875 TD->getIntPtrType(),
8877 return new TruncInst(P, CI.getType());
8880 return commonPointerCastTransforms(CI);
8883 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8884 // If the source integer type is larger than the intptr_t type for
8885 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8886 // allows the trunc to be exposed to other transforms. Don't do this for
8887 // extending inttoptr's, because we don't know if the target sign or zero
8888 // extends to pointers.
8890 CI.getOperand(0)->getType()->getScalarSizeInBits() >
8891 TD->getPointerSizeInBits()) {
8892 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8893 TD->getIntPtrType(),
8895 return new IntToPtrInst(P, CI.getType());
8898 if (Instruction *I = commonCastTransforms(CI))
8904 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8905 // If the operands are integer typed then apply the integer transforms,
8906 // otherwise just apply the common ones.
8907 Value *Src = CI.getOperand(0);
8908 const Type *SrcTy = Src->getType();
8909 const Type *DestTy = CI.getType();
8911 if (isa<PointerType>(SrcTy)) {
8912 if (Instruction *I = commonPointerCastTransforms(CI))
8915 if (Instruction *Result = commonCastTransforms(CI))
8920 // Get rid of casts from one type to the same type. These are useless and can
8921 // be replaced by the operand.
8922 if (DestTy == Src->getType())
8923 return ReplaceInstUsesWith(CI, Src);
8925 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8926 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8927 const Type *DstElTy = DstPTy->getElementType();
8928 const Type *SrcElTy = SrcPTy->getElementType();
8930 // If the address spaces don't match, don't eliminate the bitcast, which is
8931 // required for changing types.
8932 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8935 // If we are casting a malloc or alloca to a pointer to a type of the same
8936 // size, rewrite the allocation instruction to allocate the "right" type.
8937 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8938 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8941 // If the source and destination are pointers, and this cast is equivalent
8942 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8943 // This can enhance SROA and other transforms that want type-safe pointers.
8944 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
8945 unsigned NumZeros = 0;
8946 while (SrcElTy != DstElTy &&
8947 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8948 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8949 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8953 // If we found a path from the src to dest, create the getelementptr now.
8954 if (SrcElTy == DstElTy) {
8955 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8956 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8957 ((Instruction*) NULL));
8961 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8962 if (DestVTy->getNumElements() == 1) {
8963 if (!isa<VectorType>(SrcTy)) {
8964 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8965 DestVTy->getElementType(), CI);
8966 return InsertElementInst::Create(Context->getUndef(DestTy), Elem,
8967 Context->getNullValue(Type::Int32Ty));
8969 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8973 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8974 if (SrcVTy->getNumElements() == 1) {
8975 if (!isa<VectorType>(DestTy)) {
8977 new ExtractElementInst(Src, Context->getNullValue(Type::Int32Ty));
8978 InsertNewInstBefore(Elem, CI);
8979 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8984 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8985 if (SVI->hasOneUse()) {
8986 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8987 // a bitconvert to a vector with the same # elts.
8988 if (isa<VectorType>(DestTy) &&
8989 cast<VectorType>(DestTy)->getNumElements() ==
8990 SVI->getType()->getNumElements() &&
8991 SVI->getType()->getNumElements() ==
8992 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8994 // If either of the operands is a cast from CI.getType(), then
8995 // evaluating the shuffle in the casted destination's type will allow
8996 // us to eliminate at least one cast.
8997 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8998 Tmp->getOperand(0)->getType() == DestTy) ||
8999 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9000 Tmp->getOperand(0)->getType() == DestTy)) {
9001 Value *LHS = InsertCastBefore(Instruction::BitCast,
9002 SVI->getOperand(0), DestTy, CI);
9003 Value *RHS = InsertCastBefore(Instruction::BitCast,
9004 SVI->getOperand(1), DestTy, CI);
9005 // Return a new shuffle vector. Use the same element ID's, as we
9006 // know the vector types match #elts.
9007 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9015 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9017 /// %D = select %cond, %C, %A
9019 /// %C = select %cond, %B, 0
9022 /// Assuming that the specified instruction is an operand to the select, return
9023 /// a bitmask indicating which operands of this instruction are foldable if they
9024 /// equal the other incoming value of the select.
9026 static unsigned GetSelectFoldableOperands(Instruction *I) {
9027 switch (I->getOpcode()) {
9028 case Instruction::Add:
9029 case Instruction::Mul:
9030 case Instruction::And:
9031 case Instruction::Or:
9032 case Instruction::Xor:
9033 return 3; // Can fold through either operand.
9034 case Instruction::Sub: // Can only fold on the amount subtracted.
9035 case Instruction::Shl: // Can only fold on the shift amount.
9036 case Instruction::LShr:
9037 case Instruction::AShr:
9040 return 0; // Cannot fold
9044 /// GetSelectFoldableConstant - For the same transformation as the previous
9045 /// function, return the identity constant that goes into the select.
9046 static Constant *GetSelectFoldableConstant(Instruction *I,
9047 LLVMContext *Context) {
9048 switch (I->getOpcode()) {
9049 default: llvm_unreachable("This cannot happen!");
9050 case Instruction::Add:
9051 case Instruction::Sub:
9052 case Instruction::Or:
9053 case Instruction::Xor:
9054 case Instruction::Shl:
9055 case Instruction::LShr:
9056 case Instruction::AShr:
9057 return Context->getNullValue(I->getType());
9058 case Instruction::And:
9059 return Context->getAllOnesValue(I->getType());
9060 case Instruction::Mul:
9061 return Context->getConstantInt(I->getType(), 1);
9065 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9066 /// have the same opcode and only one use each. Try to simplify this.
9067 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9069 if (TI->getNumOperands() == 1) {
9070 // If this is a non-volatile load or a cast from the same type,
9073 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9076 return 0; // unknown unary op.
9079 // Fold this by inserting a select from the input values.
9080 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9081 FI->getOperand(0), SI.getName()+".v");
9082 InsertNewInstBefore(NewSI, SI);
9083 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
9087 // Only handle binary operators here.
9088 if (!isa<BinaryOperator>(TI))
9091 // Figure out if the operations have any operands in common.
9092 Value *MatchOp, *OtherOpT, *OtherOpF;
9094 if (TI->getOperand(0) == FI->getOperand(0)) {
9095 MatchOp = TI->getOperand(0);
9096 OtherOpT = TI->getOperand(1);
9097 OtherOpF = FI->getOperand(1);
9098 MatchIsOpZero = true;
9099 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9100 MatchOp = TI->getOperand(1);
9101 OtherOpT = TI->getOperand(0);
9102 OtherOpF = FI->getOperand(0);
9103 MatchIsOpZero = false;
9104 } else if (!TI->isCommutative()) {
9106 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9107 MatchOp = TI->getOperand(0);
9108 OtherOpT = TI->getOperand(1);
9109 OtherOpF = FI->getOperand(0);
9110 MatchIsOpZero = true;
9111 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9112 MatchOp = TI->getOperand(1);
9113 OtherOpT = TI->getOperand(0);
9114 OtherOpF = FI->getOperand(1);
9115 MatchIsOpZero = true;
9120 // If we reach here, they do have operations in common.
9121 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9122 OtherOpF, SI.getName()+".v");
9123 InsertNewInstBefore(NewSI, SI);
9125 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9127 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9129 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9131 llvm_unreachable("Shouldn't get here");
9135 static bool isSelect01(Constant *C1, Constant *C2) {
9136 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9139 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9142 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9145 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9146 /// facilitate further optimization.
9147 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9149 // See the comment above GetSelectFoldableOperands for a description of the
9150 // transformation we are doing here.
9151 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9152 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9153 !isa<Constant>(FalseVal)) {
9154 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9155 unsigned OpToFold = 0;
9156 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9158 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9163 Constant *C = GetSelectFoldableConstant(TVI, Context);
9164 Value *OOp = TVI->getOperand(2-OpToFold);
9165 // Avoid creating select between 2 constants unless it's selecting
9167 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9168 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9169 InsertNewInstBefore(NewSel, SI);
9170 NewSel->takeName(TVI);
9171 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9172 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9173 llvm_unreachable("Unknown instruction!!");
9180 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9181 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9182 !isa<Constant>(TrueVal)) {
9183 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9184 unsigned OpToFold = 0;
9185 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9187 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9192 Constant *C = GetSelectFoldableConstant(FVI, Context);
9193 Value *OOp = FVI->getOperand(2-OpToFold);
9194 // Avoid creating select between 2 constants unless it's selecting
9196 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9197 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9198 InsertNewInstBefore(NewSel, SI);
9199 NewSel->takeName(FVI);
9200 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9201 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9202 llvm_unreachable("Unknown instruction!!");
9212 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9213 /// ICmpInst as its first operand.
9215 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9217 bool Changed = false;
9218 ICmpInst::Predicate Pred = ICI->getPredicate();
9219 Value *CmpLHS = ICI->getOperand(0);
9220 Value *CmpRHS = ICI->getOperand(1);
9221 Value *TrueVal = SI.getTrueValue();
9222 Value *FalseVal = SI.getFalseValue();
9224 // Check cases where the comparison is with a constant that
9225 // can be adjusted to fit the min/max idiom. We may edit ICI in
9226 // place here, so make sure the select is the only user.
9227 if (ICI->hasOneUse())
9228 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9231 case ICmpInst::ICMP_ULT:
9232 case ICmpInst::ICMP_SLT: {
9233 // X < MIN ? T : F --> F
9234 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9235 return ReplaceInstUsesWith(SI, FalseVal);
9236 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9237 Constant *AdjustedRHS = SubOne(CI, Context);
9238 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9239 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9240 Pred = ICmpInst::getSwappedPredicate(Pred);
9241 CmpRHS = AdjustedRHS;
9242 std::swap(FalseVal, TrueVal);
9243 ICI->setPredicate(Pred);
9244 ICI->setOperand(1, CmpRHS);
9245 SI.setOperand(1, TrueVal);
9246 SI.setOperand(2, FalseVal);
9251 case ICmpInst::ICMP_UGT:
9252 case ICmpInst::ICMP_SGT: {
9253 // X > MAX ? T : F --> F
9254 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9255 return ReplaceInstUsesWith(SI, FalseVal);
9256 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9257 Constant *AdjustedRHS = AddOne(CI, Context);
9258 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9259 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9260 Pred = ICmpInst::getSwappedPredicate(Pred);
9261 CmpRHS = AdjustedRHS;
9262 std::swap(FalseVal, TrueVal);
9263 ICI->setPredicate(Pred);
9264 ICI->setOperand(1, CmpRHS);
9265 SI.setOperand(1, TrueVal);
9266 SI.setOperand(2, FalseVal);
9273 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9274 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9275 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9276 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9277 match(FalseVal, m_ConstantInt<0>(), *Context))
9278 Pred = ICI->getPredicate();
9279 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9280 match(FalseVal, m_ConstantInt<-1>(), *Context))
9281 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9283 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9284 // If we are just checking for a icmp eq of a single bit and zext'ing it
9285 // to an integer, then shift the bit to the appropriate place and then
9286 // cast to integer to avoid the comparison.
9287 const APInt &Op1CV = CI->getValue();
9289 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9290 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9291 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9292 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9293 Value *In = ICI->getOperand(0);
9294 Value *Sh = Context->getConstantInt(In->getType(),
9295 In->getType()->getScalarSizeInBits()-1);
9296 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9297 In->getName()+".lobit"),
9299 if (In->getType() != SI.getType())
9300 In = CastInst::CreateIntegerCast(In, SI.getType(),
9301 true/*SExt*/, "tmp", ICI);
9303 if (Pred == ICmpInst::ICMP_SGT)
9304 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9305 In->getName()+".not"), *ICI);
9307 return ReplaceInstUsesWith(SI, In);
9312 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9313 // Transform (X == Y) ? X : Y -> Y
9314 if (Pred == ICmpInst::ICMP_EQ)
9315 return ReplaceInstUsesWith(SI, FalseVal);
9316 // Transform (X != Y) ? X : Y -> X
9317 if (Pred == ICmpInst::ICMP_NE)
9318 return ReplaceInstUsesWith(SI, TrueVal);
9319 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9321 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9322 // Transform (X == Y) ? Y : X -> X
9323 if (Pred == ICmpInst::ICMP_EQ)
9324 return ReplaceInstUsesWith(SI, FalseVal);
9325 // Transform (X != Y) ? Y : X -> Y
9326 if (Pred == ICmpInst::ICMP_NE)
9327 return ReplaceInstUsesWith(SI, TrueVal);
9328 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9331 /// NOTE: if we wanted to, this is where to detect integer ABS
9333 return Changed ? &SI : 0;
9336 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9337 Value *CondVal = SI.getCondition();
9338 Value *TrueVal = SI.getTrueValue();
9339 Value *FalseVal = SI.getFalseValue();
9341 // select true, X, Y -> X
9342 // select false, X, Y -> Y
9343 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9344 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9346 // select C, X, X -> X
9347 if (TrueVal == FalseVal)
9348 return ReplaceInstUsesWith(SI, TrueVal);
9350 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9351 return ReplaceInstUsesWith(SI, FalseVal);
9352 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9353 return ReplaceInstUsesWith(SI, TrueVal);
9354 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9355 if (isa<Constant>(TrueVal))
9356 return ReplaceInstUsesWith(SI, TrueVal);
9358 return ReplaceInstUsesWith(SI, FalseVal);
9361 if (SI.getType() == Type::Int1Ty) {
9362 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9363 if (C->getZExtValue()) {
9364 // Change: A = select B, true, C --> A = or B, C
9365 return BinaryOperator::CreateOr(CondVal, FalseVal);
9367 // Change: A = select B, false, C --> A = and !B, C
9369 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9370 "not."+CondVal->getName()), SI);
9371 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9373 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9374 if (C->getZExtValue() == false) {
9375 // Change: A = select B, C, false --> A = and B, C
9376 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9378 // Change: A = select B, C, true --> A = or !B, C
9380 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9381 "not."+CondVal->getName()), SI);
9382 return BinaryOperator::CreateOr(NotCond, TrueVal);
9386 // select a, b, a -> a&b
9387 // select a, a, b -> a|b
9388 if (CondVal == TrueVal)
9389 return BinaryOperator::CreateOr(CondVal, FalseVal);
9390 else if (CondVal == FalseVal)
9391 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9394 // Selecting between two integer constants?
9395 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9396 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9397 // select C, 1, 0 -> zext C to int
9398 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9399 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9400 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9401 // select C, 0, 1 -> zext !C to int
9403 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9404 "not."+CondVal->getName()), SI);
9405 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9408 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9409 // If one of the constants is zero (we know they can't both be) and we
9410 // have an icmp instruction with zero, and we have an 'and' with the
9411 // non-constant value, eliminate this whole mess. This corresponds to
9412 // cases like this: ((X & 27) ? 27 : 0)
9413 if (TrueValC->isZero() || FalseValC->isZero())
9414 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9415 cast<Constant>(IC->getOperand(1))->isNullValue())
9416 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9417 if (ICA->getOpcode() == Instruction::And &&
9418 isa<ConstantInt>(ICA->getOperand(1)) &&
9419 (ICA->getOperand(1) == TrueValC ||
9420 ICA->getOperand(1) == FalseValC) &&
9421 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9422 // Okay, now we know that everything is set up, we just don't
9423 // know whether we have a icmp_ne or icmp_eq and whether the
9424 // true or false val is the zero.
9425 bool ShouldNotVal = !TrueValC->isZero();
9426 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9429 V = InsertNewInstBefore(BinaryOperator::Create(
9430 Instruction::Xor, V, ICA->getOperand(1)), SI);
9431 return ReplaceInstUsesWith(SI, V);
9436 // See if we are selecting two values based on a comparison of the two values.
9437 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9438 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9439 // Transform (X == Y) ? X : Y -> Y
9440 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9441 // This is not safe in general for floating point:
9442 // consider X== -0, Y== +0.
9443 // It becomes safe if either operand is a nonzero constant.
9444 ConstantFP *CFPt, *CFPf;
9445 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9446 !CFPt->getValueAPF().isZero()) ||
9447 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9448 !CFPf->getValueAPF().isZero()))
9449 return ReplaceInstUsesWith(SI, FalseVal);
9451 // Transform (X != Y) ? X : Y -> X
9452 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9453 return ReplaceInstUsesWith(SI, TrueVal);
9454 // NOTE: if we wanted to, this is where to detect MIN/MAX
9456 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9457 // Transform (X == Y) ? Y : X -> X
9458 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9459 // This is not safe in general for floating point:
9460 // consider X== -0, Y== +0.
9461 // It becomes safe if either operand is a nonzero constant.
9462 ConstantFP *CFPt, *CFPf;
9463 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9464 !CFPt->getValueAPF().isZero()) ||
9465 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9466 !CFPf->getValueAPF().isZero()))
9467 return ReplaceInstUsesWith(SI, FalseVal);
9469 // Transform (X != Y) ? Y : X -> Y
9470 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9471 return ReplaceInstUsesWith(SI, TrueVal);
9472 // NOTE: if we wanted to, this is where to detect MIN/MAX
9474 // NOTE: if we wanted to, this is where to detect ABS
9477 // See if we are selecting two values based on a comparison of the two values.
9478 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9479 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9482 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9483 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9484 if (TI->hasOneUse() && FI->hasOneUse()) {
9485 Instruction *AddOp = 0, *SubOp = 0;
9487 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9488 if (TI->getOpcode() == FI->getOpcode())
9489 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9492 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9493 // even legal for FP.
9494 if ((TI->getOpcode() == Instruction::Sub &&
9495 FI->getOpcode() == Instruction::Add) ||
9496 (TI->getOpcode() == Instruction::FSub &&
9497 FI->getOpcode() == Instruction::FAdd)) {
9498 AddOp = FI; SubOp = TI;
9499 } else if ((FI->getOpcode() == Instruction::Sub &&
9500 TI->getOpcode() == Instruction::Add) ||
9501 (FI->getOpcode() == Instruction::FSub &&
9502 TI->getOpcode() == Instruction::FAdd)) {
9503 AddOp = TI; SubOp = FI;
9507 Value *OtherAddOp = 0;
9508 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9509 OtherAddOp = AddOp->getOperand(1);
9510 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9511 OtherAddOp = AddOp->getOperand(0);
9515 // So at this point we know we have (Y -> OtherAddOp):
9516 // select C, (add X, Y), (sub X, Z)
9517 Value *NegVal; // Compute -Z
9518 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9519 NegVal = Context->getConstantExprNeg(C);
9521 NegVal = InsertNewInstBefore(
9522 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9526 Value *NewTrueOp = OtherAddOp;
9527 Value *NewFalseOp = NegVal;
9529 std::swap(NewTrueOp, NewFalseOp);
9530 Instruction *NewSel =
9531 SelectInst::Create(CondVal, NewTrueOp,
9532 NewFalseOp, SI.getName() + ".p");
9534 NewSel = InsertNewInstBefore(NewSel, SI);
9535 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9540 // See if we can fold the select into one of our operands.
9541 if (SI.getType()->isInteger()) {
9542 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9547 if (BinaryOperator::isNot(CondVal)) {
9548 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9549 SI.setOperand(1, FalseVal);
9550 SI.setOperand(2, TrueVal);
9557 /// EnforceKnownAlignment - If the specified pointer points to an object that
9558 /// we control, modify the object's alignment to PrefAlign. This isn't
9559 /// often possible though. If alignment is important, a more reliable approach
9560 /// is to simply align all global variables and allocation instructions to
9561 /// their preferred alignment from the beginning.
9563 static unsigned EnforceKnownAlignment(Value *V,
9564 unsigned Align, unsigned PrefAlign) {
9566 User *U = dyn_cast<User>(V);
9567 if (!U) return Align;
9569 switch (Operator::getOpcode(U)) {
9571 case Instruction::BitCast:
9572 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9573 case Instruction::GetElementPtr: {
9574 // If all indexes are zero, it is just the alignment of the base pointer.
9575 bool AllZeroOperands = true;
9576 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9577 if (!isa<Constant>(*i) ||
9578 !cast<Constant>(*i)->isNullValue()) {
9579 AllZeroOperands = false;
9583 if (AllZeroOperands) {
9584 // Treat this like a bitcast.
9585 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9591 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9592 // If there is a large requested alignment and we can, bump up the alignment
9594 if (!GV->isDeclaration()) {
9595 if (GV->getAlignment() >= PrefAlign)
9596 Align = GV->getAlignment();
9598 GV->setAlignment(PrefAlign);
9602 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9603 // If there is a requested alignment and if this is an alloca, round up. We
9604 // don't do this for malloc, because some systems can't respect the request.
9605 if (isa<AllocaInst>(AI)) {
9606 if (AI->getAlignment() >= PrefAlign)
9607 Align = AI->getAlignment();
9609 AI->setAlignment(PrefAlign);
9618 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9619 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9620 /// and it is more than the alignment of the ultimate object, see if we can
9621 /// increase the alignment of the ultimate object, making this check succeed.
9622 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9623 unsigned PrefAlign) {
9624 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9625 sizeof(PrefAlign) * CHAR_BIT;
9626 APInt Mask = APInt::getAllOnesValue(BitWidth);
9627 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9628 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9629 unsigned TrailZ = KnownZero.countTrailingOnes();
9630 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9632 if (PrefAlign > Align)
9633 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9635 // We don't need to make any adjustment.
9639 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9640 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9641 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9642 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9643 unsigned CopyAlign = MI->getAlignment();
9645 if (CopyAlign < MinAlign) {
9646 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9651 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9653 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9654 if (MemOpLength == 0) return 0;
9656 // Source and destination pointer types are always "i8*" for intrinsic. See
9657 // if the size is something we can handle with a single primitive load/store.
9658 // A single load+store correctly handles overlapping memory in the memmove
9660 unsigned Size = MemOpLength->getZExtValue();
9661 if (Size == 0) return MI; // Delete this mem transfer.
9663 if (Size > 8 || (Size&(Size-1)))
9664 return 0; // If not 1/2/4/8 bytes, exit.
9666 // Use an integer load+store unless we can find something better.
9668 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9670 // Memcpy forces the use of i8* for the source and destination. That means
9671 // that if you're using memcpy to move one double around, you'll get a cast
9672 // from double* to i8*. We'd much rather use a double load+store rather than
9673 // an i64 load+store, here because this improves the odds that the source or
9674 // dest address will be promotable. See if we can find a better type than the
9675 // integer datatype.
9676 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9677 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9678 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9679 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9680 // down through these levels if so.
9681 while (!SrcETy->isSingleValueType()) {
9682 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9683 if (STy->getNumElements() == 1)
9684 SrcETy = STy->getElementType(0);
9687 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9688 if (ATy->getNumElements() == 1)
9689 SrcETy = ATy->getElementType();
9696 if (SrcETy->isSingleValueType())
9697 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9702 // If the memcpy/memmove provides better alignment info than we can
9704 SrcAlign = std::max(SrcAlign, CopyAlign);
9705 DstAlign = std::max(DstAlign, CopyAlign);
9707 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9708 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9709 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9710 InsertNewInstBefore(L, *MI);
9711 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9713 // Set the size of the copy to 0, it will be deleted on the next iteration.
9714 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9718 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9719 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9720 if (MI->getAlignment() < Alignment) {
9721 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9726 // Extract the length and alignment and fill if they are constant.
9727 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9728 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9729 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9731 uint64_t Len = LenC->getZExtValue();
9732 Alignment = MI->getAlignment();
9734 // If the length is zero, this is a no-op
9735 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9737 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9738 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9739 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
9741 Value *Dest = MI->getDest();
9742 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9744 // Alignment 0 is identity for alignment 1 for memset, but not store.
9745 if (Alignment == 0) Alignment = 1;
9747 // Extract the fill value and store.
9748 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9749 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9750 Dest, false, Alignment), *MI);
9752 // Set the size of the copy to 0, it will be deleted on the next iteration.
9753 MI->setLength(Context->getNullValue(LenC->getType()));
9761 /// visitCallInst - CallInst simplification. This mostly only handles folding
9762 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9763 /// the heavy lifting.
9765 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9766 // If the caller function is nounwind, mark the call as nounwind, even if the
9768 if (CI.getParent()->getParent()->doesNotThrow() &&
9769 !CI.doesNotThrow()) {
9770 CI.setDoesNotThrow();
9776 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9777 if (!II) return visitCallSite(&CI);
9779 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9781 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9782 bool Changed = false;
9784 // memmove/cpy/set of zero bytes is a noop.
9785 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9786 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9788 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9789 if (CI->getZExtValue() == 1) {
9790 // Replace the instruction with just byte operations. We would
9791 // transform other cases to loads/stores, but we don't know if
9792 // alignment is sufficient.
9796 // If we have a memmove and the source operation is a constant global,
9797 // then the source and dest pointers can't alias, so we can change this
9798 // into a call to memcpy.
9799 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9800 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9801 if (GVSrc->isConstant()) {
9802 Module *M = CI.getParent()->getParent()->getParent();
9803 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9805 Tys[0] = CI.getOperand(3)->getType();
9807 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9811 // memmove(x,x,size) -> noop.
9812 if (MMI->getSource() == MMI->getDest())
9813 return EraseInstFromFunction(CI);
9816 // If we can determine a pointer alignment that is bigger than currently
9817 // set, update the alignment.
9818 if (isa<MemTransferInst>(MI)) {
9819 if (Instruction *I = SimplifyMemTransfer(MI))
9821 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9822 if (Instruction *I = SimplifyMemSet(MSI))
9826 if (Changed) return II;
9829 switch (II->getIntrinsicID()) {
9831 case Intrinsic::bswap:
9832 // bswap(bswap(x)) -> x
9833 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9834 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9835 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9837 case Intrinsic::ppc_altivec_lvx:
9838 case Intrinsic::ppc_altivec_lvxl:
9839 case Intrinsic::x86_sse_loadu_ps:
9840 case Intrinsic::x86_sse2_loadu_pd:
9841 case Intrinsic::x86_sse2_loadu_dq:
9842 // Turn PPC lvx -> load if the pointer is known aligned.
9843 // Turn X86 loadups -> load if the pointer is known aligned.
9844 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9845 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9846 Context->getPointerTypeUnqual(II->getType()),
9848 return new LoadInst(Ptr);
9851 case Intrinsic::ppc_altivec_stvx:
9852 case Intrinsic::ppc_altivec_stvxl:
9853 // Turn stvx -> store if the pointer is known aligned.
9854 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9855 const Type *OpPtrTy =
9856 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9857 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9858 return new StoreInst(II->getOperand(1), Ptr);
9861 case Intrinsic::x86_sse_storeu_ps:
9862 case Intrinsic::x86_sse2_storeu_pd:
9863 case Intrinsic::x86_sse2_storeu_dq:
9864 // Turn X86 storeu -> store if the pointer is known aligned.
9865 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9866 const Type *OpPtrTy =
9867 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9868 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9869 return new StoreInst(II->getOperand(2), Ptr);
9873 case Intrinsic::x86_sse_cvttss2si: {
9874 // These intrinsics only demands the 0th element of its input vector. If
9875 // we can simplify the input based on that, do so now.
9877 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9878 APInt DemandedElts(VWidth, 1);
9879 APInt UndefElts(VWidth, 0);
9880 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9882 II->setOperand(1, V);
9888 case Intrinsic::ppc_altivec_vperm:
9889 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9890 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9891 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9893 // Check that all of the elements are integer constants or undefs.
9894 bool AllEltsOk = true;
9895 for (unsigned i = 0; i != 16; ++i) {
9896 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9897 !isa<UndefValue>(Mask->getOperand(i))) {
9904 // Cast the input vectors to byte vectors.
9905 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9906 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9907 Value *Result = Context->getUndef(Op0->getType());
9909 // Only extract each element once.
9910 Value *ExtractedElts[32];
9911 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9913 for (unsigned i = 0; i != 16; ++i) {
9914 if (isa<UndefValue>(Mask->getOperand(i)))
9916 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9917 Idx &= 31; // Match the hardware behavior.
9919 if (ExtractedElts[Idx] == 0) {
9921 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
9922 Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
9923 InsertNewInstBefore(Elt, CI);
9924 ExtractedElts[Idx] = Elt;
9927 // Insert this value into the result vector.
9928 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9929 Context->getConstantInt(Type::Int32Ty, i, false),
9931 InsertNewInstBefore(cast<Instruction>(Result), CI);
9933 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9938 case Intrinsic::stackrestore: {
9939 // If the save is right next to the restore, remove the restore. This can
9940 // happen when variable allocas are DCE'd.
9941 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9942 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9943 BasicBlock::iterator BI = SS;
9945 return EraseInstFromFunction(CI);
9949 // Scan down this block to see if there is another stack restore in the
9950 // same block without an intervening call/alloca.
9951 BasicBlock::iterator BI = II;
9952 TerminatorInst *TI = II->getParent()->getTerminator();
9953 bool CannotRemove = false;
9954 for (++BI; &*BI != TI; ++BI) {
9955 if (isa<AllocaInst>(BI)) {
9956 CannotRemove = true;
9959 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9960 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9961 // If there is a stackrestore below this one, remove this one.
9962 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9963 return EraseInstFromFunction(CI);
9964 // Otherwise, ignore the intrinsic.
9966 // If we found a non-intrinsic call, we can't remove the stack
9968 CannotRemove = true;
9974 // If the stack restore is in a return/unwind block and if there are no
9975 // allocas or calls between the restore and the return, nuke the restore.
9976 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9977 return EraseInstFromFunction(CI);
9982 return visitCallSite(II);
9985 // InvokeInst simplification
9987 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9988 return visitCallSite(&II);
9991 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
9992 /// passed through the varargs area, we can eliminate the use of the cast.
9993 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9994 const CastInst * const CI,
9995 const TargetData * const TD,
9997 if (!CI->isLosslessCast())
10000 // The size of ByVal arguments is derived from the type, so we
10001 // can't change to a type with a different size. If the size were
10002 // passed explicitly we could avoid this check.
10003 if (!CS.paramHasAttr(ix, Attribute::ByVal))
10006 const Type* SrcTy =
10007 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10008 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10009 if (!SrcTy->isSized() || !DstTy->isSized())
10011 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10016 // visitCallSite - Improvements for call and invoke instructions.
10018 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10019 bool Changed = false;
10021 // If the callee is a constexpr cast of a function, attempt to move the cast
10022 // to the arguments of the call/invoke.
10023 if (transformConstExprCastCall(CS)) return 0;
10025 Value *Callee = CS.getCalledValue();
10027 if (Function *CalleeF = dyn_cast<Function>(Callee))
10028 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10029 Instruction *OldCall = CS.getInstruction();
10030 // If the call and callee calling conventions don't match, this call must
10031 // be unreachable, as the call is undefined.
10032 new StoreInst(Context->getTrue(),
10033 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10035 if (!OldCall->use_empty())
10036 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10037 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10038 return EraseInstFromFunction(*OldCall);
10042 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10043 // This instruction is not reachable, just remove it. We insert a store to
10044 // undef so that we know that this code is not reachable, despite the fact
10045 // that we can't modify the CFG here.
10046 new StoreInst(Context->getTrue(),
10047 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10048 CS.getInstruction());
10050 if (!CS.getInstruction()->use_empty())
10051 CS.getInstruction()->
10052 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10054 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10055 // Don't break the CFG, insert a dummy cond branch.
10056 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10057 Context->getTrue(), II);
10059 return EraseInstFromFunction(*CS.getInstruction());
10062 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10063 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10064 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10065 return transformCallThroughTrampoline(CS);
10067 const PointerType *PTy = cast<PointerType>(Callee->getType());
10068 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10069 if (FTy->isVarArg()) {
10070 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10071 // See if we can optimize any arguments passed through the varargs area of
10073 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10074 E = CS.arg_end(); I != E; ++I, ++ix) {
10075 CastInst *CI = dyn_cast<CastInst>(*I);
10076 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10077 *I = CI->getOperand(0);
10083 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10084 // Inline asm calls cannot throw - mark them 'nounwind'.
10085 CS.setDoesNotThrow();
10089 return Changed ? CS.getInstruction() : 0;
10092 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10093 // attempt to move the cast to the arguments of the call/invoke.
10095 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10096 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10097 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10098 if (CE->getOpcode() != Instruction::BitCast ||
10099 !isa<Function>(CE->getOperand(0)))
10101 Function *Callee = cast<Function>(CE->getOperand(0));
10102 Instruction *Caller = CS.getInstruction();
10103 const AttrListPtr &CallerPAL = CS.getAttributes();
10105 // Okay, this is a cast from a function to a different type. Unless doing so
10106 // would cause a type conversion of one of our arguments, change this call to
10107 // be a direct call with arguments casted to the appropriate types.
10109 const FunctionType *FT = Callee->getFunctionType();
10110 const Type *OldRetTy = Caller->getType();
10111 const Type *NewRetTy = FT->getReturnType();
10113 if (isa<StructType>(NewRetTy))
10114 return false; // TODO: Handle multiple return values.
10116 // Check to see if we are changing the return type...
10117 if (OldRetTy != NewRetTy) {
10118 if (Callee->isDeclaration() &&
10119 // Conversion is ok if changing from one pointer type to another or from
10120 // a pointer to an integer of the same size.
10121 !((isa<PointerType>(OldRetTy) || !TD ||
10122 OldRetTy == TD->getIntPtrType()) &&
10123 (isa<PointerType>(NewRetTy) || !TD ||
10124 NewRetTy == TD->getIntPtrType())))
10125 return false; // Cannot transform this return value.
10127 if (!Caller->use_empty() &&
10128 // void -> non-void is handled specially
10129 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10130 return false; // Cannot transform this return value.
10132 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10133 Attributes RAttrs = CallerPAL.getRetAttributes();
10134 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10135 return false; // Attribute not compatible with transformed value.
10138 // If the callsite is an invoke instruction, and the return value is used by
10139 // a PHI node in a successor, we cannot change the return type of the call
10140 // because there is no place to put the cast instruction (without breaking
10141 // the critical edge). Bail out in this case.
10142 if (!Caller->use_empty())
10143 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10144 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10146 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10147 if (PN->getParent() == II->getNormalDest() ||
10148 PN->getParent() == II->getUnwindDest())
10152 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10153 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10155 CallSite::arg_iterator AI = CS.arg_begin();
10156 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10157 const Type *ParamTy = FT->getParamType(i);
10158 const Type *ActTy = (*AI)->getType();
10160 if (!CastInst::isCastable(ActTy, ParamTy))
10161 return false; // Cannot transform this parameter value.
10163 if (CallerPAL.getParamAttributes(i + 1)
10164 & Attribute::typeIncompatible(ParamTy))
10165 return false; // Attribute not compatible with transformed value.
10167 // Converting from one pointer type to another or between a pointer and an
10168 // integer of the same size is safe even if we do not have a body.
10169 bool isConvertible = ActTy == ParamTy ||
10170 (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10171 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
10172 if (Callee->isDeclaration() && !isConvertible) return false;
10175 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10176 Callee->isDeclaration())
10177 return false; // Do not delete arguments unless we have a function body.
10179 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10180 !CallerPAL.isEmpty())
10181 // In this case we have more arguments than the new function type, but we
10182 // won't be dropping them. Check that these extra arguments have attributes
10183 // that are compatible with being a vararg call argument.
10184 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10185 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10187 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10188 if (PAttrs & Attribute::VarArgsIncompatible)
10192 // Okay, we decided that this is a safe thing to do: go ahead and start
10193 // inserting cast instructions as necessary...
10194 std::vector<Value*> Args;
10195 Args.reserve(NumActualArgs);
10196 SmallVector<AttributeWithIndex, 8> attrVec;
10197 attrVec.reserve(NumCommonArgs);
10199 // Get any return attributes.
10200 Attributes RAttrs = CallerPAL.getRetAttributes();
10202 // If the return value is not being used, the type may not be compatible
10203 // with the existing attributes. Wipe out any problematic attributes.
10204 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10206 // Add the new return attributes.
10208 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10210 AI = CS.arg_begin();
10211 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10212 const Type *ParamTy = FT->getParamType(i);
10213 if ((*AI)->getType() == ParamTy) {
10214 Args.push_back(*AI);
10216 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10217 false, ParamTy, false);
10218 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10219 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10222 // Add any parameter attributes.
10223 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10224 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10227 // If the function takes more arguments than the call was taking, add them
10229 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10230 Args.push_back(Context->getNullValue(FT->getParamType(i)));
10232 // If we are removing arguments to the function, emit an obnoxious warning...
10233 if (FT->getNumParams() < NumActualArgs) {
10234 if (!FT->isVarArg()) {
10235 cerr << "WARNING: While resolving call to function '"
10236 << Callee->getName() << "' arguments were dropped!\n";
10238 // Add all of the arguments in their promoted form to the arg list...
10239 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10240 const Type *PTy = getPromotedType((*AI)->getType());
10241 if (PTy != (*AI)->getType()) {
10242 // Must promote to pass through va_arg area!
10243 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10245 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10246 InsertNewInstBefore(Cast, *Caller);
10247 Args.push_back(Cast);
10249 Args.push_back(*AI);
10252 // Add any parameter attributes.
10253 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10254 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10259 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10260 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10262 if (NewRetTy == Type::VoidTy)
10263 Caller->setName(""); // Void type should not have a name.
10265 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10268 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10269 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10270 Args.begin(), Args.end(),
10271 Caller->getName(), Caller);
10272 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10273 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10275 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10276 Caller->getName(), Caller);
10277 CallInst *CI = cast<CallInst>(Caller);
10278 if (CI->isTailCall())
10279 cast<CallInst>(NC)->setTailCall();
10280 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10281 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10284 // Insert a cast of the return type as necessary.
10286 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10287 if (NV->getType() != Type::VoidTy) {
10288 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10290 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10292 // If this is an invoke instruction, we should insert it after the first
10293 // non-phi, instruction in the normal successor block.
10294 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10295 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10296 InsertNewInstBefore(NC, *I);
10298 // Otherwise, it's a call, just insert cast right after the call instr
10299 InsertNewInstBefore(NC, *Caller);
10301 AddUsersToWorkList(*Caller);
10303 NV = Context->getUndef(Caller->getType());
10307 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10308 Caller->replaceAllUsesWith(NV);
10309 Caller->eraseFromParent();
10310 RemoveFromWorkList(Caller);
10314 // transformCallThroughTrampoline - Turn a call to a function created by the
10315 // init_trampoline intrinsic into a direct call to the underlying function.
10317 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10318 Value *Callee = CS.getCalledValue();
10319 const PointerType *PTy = cast<PointerType>(Callee->getType());
10320 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10321 const AttrListPtr &Attrs = CS.getAttributes();
10323 // If the call already has the 'nest' attribute somewhere then give up -
10324 // otherwise 'nest' would occur twice after splicing in the chain.
10325 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10328 IntrinsicInst *Tramp =
10329 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10331 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10332 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10333 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10335 const AttrListPtr &NestAttrs = NestF->getAttributes();
10336 if (!NestAttrs.isEmpty()) {
10337 unsigned NestIdx = 1;
10338 const Type *NestTy = 0;
10339 Attributes NestAttr = Attribute::None;
10341 // Look for a parameter marked with the 'nest' attribute.
10342 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10343 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10344 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10345 // Record the parameter type and any other attributes.
10347 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10352 Instruction *Caller = CS.getInstruction();
10353 std::vector<Value*> NewArgs;
10354 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10356 SmallVector<AttributeWithIndex, 8> NewAttrs;
10357 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10359 // Insert the nest argument into the call argument list, which may
10360 // mean appending it. Likewise for attributes.
10362 // Add any result attributes.
10363 if (Attributes Attr = Attrs.getRetAttributes())
10364 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10368 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10370 if (Idx == NestIdx) {
10371 // Add the chain argument and attributes.
10372 Value *NestVal = Tramp->getOperand(3);
10373 if (NestVal->getType() != NestTy)
10374 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10375 NewArgs.push_back(NestVal);
10376 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10382 // Add the original argument and attributes.
10383 NewArgs.push_back(*I);
10384 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10386 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10392 // Add any function attributes.
10393 if (Attributes Attr = Attrs.getFnAttributes())
10394 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10396 // The trampoline may have been bitcast to a bogus type (FTy).
10397 // Handle this by synthesizing a new function type, equal to FTy
10398 // with the chain parameter inserted.
10400 std::vector<const Type*> NewTypes;
10401 NewTypes.reserve(FTy->getNumParams()+1);
10403 // Insert the chain's type into the list of parameter types, which may
10404 // mean appending it.
10407 FunctionType::param_iterator I = FTy->param_begin(),
10408 E = FTy->param_end();
10411 if (Idx == NestIdx)
10412 // Add the chain's type.
10413 NewTypes.push_back(NestTy);
10418 // Add the original type.
10419 NewTypes.push_back(*I);
10425 // Replace the trampoline call with a direct call. Let the generic
10426 // code sort out any function type mismatches.
10427 FunctionType *NewFTy =
10428 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10430 Constant *NewCallee =
10431 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10432 NestF : Context->getConstantExprBitCast(NestF,
10433 Context->getPointerTypeUnqual(NewFTy));
10434 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10436 Instruction *NewCaller;
10437 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10438 NewCaller = InvokeInst::Create(NewCallee,
10439 II->getNormalDest(), II->getUnwindDest(),
10440 NewArgs.begin(), NewArgs.end(),
10441 Caller->getName(), Caller);
10442 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10443 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10445 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10446 Caller->getName(), Caller);
10447 if (cast<CallInst>(Caller)->isTailCall())
10448 cast<CallInst>(NewCaller)->setTailCall();
10449 cast<CallInst>(NewCaller)->
10450 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10451 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10453 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10454 Caller->replaceAllUsesWith(NewCaller);
10455 Caller->eraseFromParent();
10456 RemoveFromWorkList(Caller);
10461 // Replace the trampoline call with a direct call. Since there is no 'nest'
10462 // parameter, there is no need to adjust the argument list. Let the generic
10463 // code sort out any function type mismatches.
10464 Constant *NewCallee =
10465 NestF->getType() == PTy ? NestF :
10466 Context->getConstantExprBitCast(NestF, PTy);
10467 CS.setCalledFunction(NewCallee);
10468 return CS.getInstruction();
10471 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10472 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10473 /// and a single binop.
10474 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10475 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10476 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10477 unsigned Opc = FirstInst->getOpcode();
10478 Value *LHSVal = FirstInst->getOperand(0);
10479 Value *RHSVal = FirstInst->getOperand(1);
10481 const Type *LHSType = LHSVal->getType();
10482 const Type *RHSType = RHSVal->getType();
10484 // Scan to see if all operands are the same opcode, all have one use, and all
10485 // kill their operands (i.e. the operands have one use).
10486 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10487 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10488 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10489 // Verify type of the LHS matches so we don't fold cmp's of different
10490 // types or GEP's with different index types.
10491 I->getOperand(0)->getType() != LHSType ||
10492 I->getOperand(1)->getType() != RHSType)
10495 // If they are CmpInst instructions, check their predicates
10496 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10497 if (cast<CmpInst>(I)->getPredicate() !=
10498 cast<CmpInst>(FirstInst)->getPredicate())
10501 // Keep track of which operand needs a phi node.
10502 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10503 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10506 // Otherwise, this is safe to transform!
10508 Value *InLHS = FirstInst->getOperand(0);
10509 Value *InRHS = FirstInst->getOperand(1);
10510 PHINode *NewLHS = 0, *NewRHS = 0;
10512 NewLHS = PHINode::Create(LHSType,
10513 FirstInst->getOperand(0)->getName() + ".pn");
10514 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10515 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10516 InsertNewInstBefore(NewLHS, PN);
10521 NewRHS = PHINode::Create(RHSType,
10522 FirstInst->getOperand(1)->getName() + ".pn");
10523 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10524 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10525 InsertNewInstBefore(NewRHS, PN);
10529 // Add all operands to the new PHIs.
10530 if (NewLHS || NewRHS) {
10531 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10532 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10534 Value *NewInLHS = InInst->getOperand(0);
10535 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10538 Value *NewInRHS = InInst->getOperand(1);
10539 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10544 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10545 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10546 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10547 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10551 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10552 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10554 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10555 FirstInst->op_end());
10556 // This is true if all GEP bases are allocas and if all indices into them are
10558 bool AllBasePointersAreAllocas = true;
10560 // Scan to see if all operands are the same opcode, all have one use, and all
10561 // kill their operands (i.e. the operands have one use).
10562 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10563 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10564 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10565 GEP->getNumOperands() != FirstInst->getNumOperands())
10568 // Keep track of whether or not all GEPs are of alloca pointers.
10569 if (AllBasePointersAreAllocas &&
10570 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10571 !GEP->hasAllConstantIndices()))
10572 AllBasePointersAreAllocas = false;
10574 // Compare the operand lists.
10575 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10576 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10579 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10580 // if one of the PHIs has a constant for the index. The index may be
10581 // substantially cheaper to compute for the constants, so making it a
10582 // variable index could pessimize the path. This also handles the case
10583 // for struct indices, which must always be constant.
10584 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10585 isa<ConstantInt>(GEP->getOperand(op)))
10588 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10590 FixedOperands[op] = 0; // Needs a PHI.
10594 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10595 // bother doing this transformation. At best, this will just save a bit of
10596 // offset calculation, but all the predecessors will have to materialize the
10597 // stack address into a register anyway. We'd actually rather *clone* the
10598 // load up into the predecessors so that we have a load of a gep of an alloca,
10599 // which can usually all be folded into the load.
10600 if (AllBasePointersAreAllocas)
10603 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10604 // that is variable.
10605 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10607 bool HasAnyPHIs = false;
10608 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10609 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10610 Value *FirstOp = FirstInst->getOperand(i);
10611 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10612 FirstOp->getName()+".pn");
10613 InsertNewInstBefore(NewPN, PN);
10615 NewPN->reserveOperandSpace(e);
10616 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10617 OperandPhis[i] = NewPN;
10618 FixedOperands[i] = NewPN;
10623 // Add all operands to the new PHIs.
10625 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10626 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10627 BasicBlock *InBB = PN.getIncomingBlock(i);
10629 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10630 if (PHINode *OpPhi = OperandPhis[op])
10631 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10635 Value *Base = FixedOperands[0];
10636 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10637 FixedOperands.end());
10641 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10642 /// sink the load out of the block that defines it. This means that it must be
10643 /// obvious the value of the load is not changed from the point of the load to
10644 /// the end of the block it is in.
10646 /// Finally, it is safe, but not profitable, to sink a load targetting a
10647 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10649 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10650 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10652 for (++BBI; BBI != E; ++BBI)
10653 if (BBI->mayWriteToMemory())
10656 // Check for non-address taken alloca. If not address-taken already, it isn't
10657 // profitable to do this xform.
10658 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10659 bool isAddressTaken = false;
10660 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10662 if (isa<LoadInst>(UI)) continue;
10663 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10664 // If storing TO the alloca, then the address isn't taken.
10665 if (SI->getOperand(1) == AI) continue;
10667 isAddressTaken = true;
10671 if (!isAddressTaken && AI->isStaticAlloca())
10675 // If this load is a load from a GEP with a constant offset from an alloca,
10676 // then we don't want to sink it. In its present form, it will be
10677 // load [constant stack offset]. Sinking it will cause us to have to
10678 // materialize the stack addresses in each predecessor in a register only to
10679 // do a shared load from register in the successor.
10680 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10681 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10682 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10689 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10690 // operator and they all are only used by the PHI, PHI together their
10691 // inputs, and do the operation once, to the result of the PHI.
10692 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10693 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10695 // Scan the instruction, looking for input operations that can be folded away.
10696 // If all input operands to the phi are the same instruction (e.g. a cast from
10697 // the same type or "+42") we can pull the operation through the PHI, reducing
10698 // code size and simplifying code.
10699 Constant *ConstantOp = 0;
10700 const Type *CastSrcTy = 0;
10701 bool isVolatile = false;
10702 if (isa<CastInst>(FirstInst)) {
10703 CastSrcTy = FirstInst->getOperand(0)->getType();
10704 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10705 // Can fold binop, compare or shift here if the RHS is a constant,
10706 // otherwise call FoldPHIArgBinOpIntoPHI.
10707 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10708 if (ConstantOp == 0)
10709 return FoldPHIArgBinOpIntoPHI(PN);
10710 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10711 isVolatile = LI->isVolatile();
10712 // We can't sink the load if the loaded value could be modified between the
10713 // load and the PHI.
10714 if (LI->getParent() != PN.getIncomingBlock(0) ||
10715 !isSafeAndProfitableToSinkLoad(LI))
10718 // If the PHI is of volatile loads and the load block has multiple
10719 // successors, sinking it would remove a load of the volatile value from
10720 // the path through the other successor.
10722 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10725 } else if (isa<GetElementPtrInst>(FirstInst)) {
10726 return FoldPHIArgGEPIntoPHI(PN);
10728 return 0; // Cannot fold this operation.
10731 // Check to see if all arguments are the same operation.
10732 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10733 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10734 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10735 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10738 if (I->getOperand(0)->getType() != CastSrcTy)
10739 return 0; // Cast operation must match.
10740 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10741 // We can't sink the load if the loaded value could be modified between
10742 // the load and the PHI.
10743 if (LI->isVolatile() != isVolatile ||
10744 LI->getParent() != PN.getIncomingBlock(i) ||
10745 !isSafeAndProfitableToSinkLoad(LI))
10748 // If the PHI is of volatile loads and the load block has multiple
10749 // successors, sinking it would remove a load of the volatile value from
10750 // the path through the other successor.
10752 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10755 } else if (I->getOperand(1) != ConstantOp) {
10760 // Okay, they are all the same operation. Create a new PHI node of the
10761 // correct type, and PHI together all of the LHS's of the instructions.
10762 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10763 PN.getName()+".in");
10764 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10766 Value *InVal = FirstInst->getOperand(0);
10767 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10769 // Add all operands to the new PHI.
10770 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10771 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10772 if (NewInVal != InVal)
10774 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10779 // The new PHI unions all of the same values together. This is really
10780 // common, so we handle it intelligently here for compile-time speed.
10784 InsertNewInstBefore(NewPN, PN);
10788 // Insert and return the new operation.
10789 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10790 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10791 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10792 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10793 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10794 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10795 PhiVal, ConstantOp);
10796 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10798 // If this was a volatile load that we are merging, make sure to loop through
10799 // and mark all the input loads as non-volatile. If we don't do this, we will
10800 // insert a new volatile load and the old ones will not be deletable.
10802 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10803 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10805 return new LoadInst(PhiVal, "", isVolatile);
10808 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10810 static bool DeadPHICycle(PHINode *PN,
10811 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10812 if (PN->use_empty()) return true;
10813 if (!PN->hasOneUse()) return false;
10815 // Remember this node, and if we find the cycle, return.
10816 if (!PotentiallyDeadPHIs.insert(PN))
10819 // Don't scan crazily complex things.
10820 if (PotentiallyDeadPHIs.size() == 16)
10823 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10824 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10829 /// PHIsEqualValue - Return true if this phi node is always equal to
10830 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10831 /// z = some value; x = phi (y, z); y = phi (x, z)
10832 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10833 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10834 // See if we already saw this PHI node.
10835 if (!ValueEqualPHIs.insert(PN))
10838 // Don't scan crazily complex things.
10839 if (ValueEqualPHIs.size() == 16)
10842 // Scan the operands to see if they are either phi nodes or are equal to
10844 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10845 Value *Op = PN->getIncomingValue(i);
10846 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10847 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10849 } else if (Op != NonPhiInVal)
10857 // PHINode simplification
10859 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10860 // If LCSSA is around, don't mess with Phi nodes
10861 if (MustPreserveLCSSA) return 0;
10863 if (Value *V = PN.hasConstantValue())
10864 return ReplaceInstUsesWith(PN, V);
10866 // If all PHI operands are the same operation, pull them through the PHI,
10867 // reducing code size.
10868 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10869 isa<Instruction>(PN.getIncomingValue(1)) &&
10870 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10871 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10872 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10873 // than themselves more than once.
10874 PN.getIncomingValue(0)->hasOneUse())
10875 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10878 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10879 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10880 // PHI)... break the cycle.
10881 if (PN.hasOneUse()) {
10882 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10883 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10884 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10885 PotentiallyDeadPHIs.insert(&PN);
10886 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10887 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10890 // If this phi has a single use, and if that use just computes a value for
10891 // the next iteration of a loop, delete the phi. This occurs with unused
10892 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10893 // common case here is good because the only other things that catch this
10894 // are induction variable analysis (sometimes) and ADCE, which is only run
10896 if (PHIUser->hasOneUse() &&
10897 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10898 PHIUser->use_back() == &PN) {
10899 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10903 // We sometimes end up with phi cycles that non-obviously end up being the
10904 // same value, for example:
10905 // z = some value; x = phi (y, z); y = phi (x, z)
10906 // where the phi nodes don't necessarily need to be in the same block. Do a
10907 // quick check to see if the PHI node only contains a single non-phi value, if
10908 // so, scan to see if the phi cycle is actually equal to that value.
10910 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10911 // Scan for the first non-phi operand.
10912 while (InValNo != NumOperandVals &&
10913 isa<PHINode>(PN.getIncomingValue(InValNo)))
10916 if (InValNo != NumOperandVals) {
10917 Value *NonPhiInVal = PN.getOperand(InValNo);
10919 // Scan the rest of the operands to see if there are any conflicts, if so
10920 // there is no need to recursively scan other phis.
10921 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10922 Value *OpVal = PN.getIncomingValue(InValNo);
10923 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10927 // If we scanned over all operands, then we have one unique value plus
10928 // phi values. Scan PHI nodes to see if they all merge in each other or
10930 if (InValNo == NumOperandVals) {
10931 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10932 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10933 return ReplaceInstUsesWith(PN, NonPhiInVal);
10940 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10941 Instruction *InsertPoint,
10942 InstCombiner *IC) {
10943 unsigned PtrSize = DTy->getScalarSizeInBits();
10944 unsigned VTySize = V->getType()->getScalarSizeInBits();
10945 // We must cast correctly to the pointer type. Ensure that we
10946 // sign extend the integer value if it is smaller as this is
10947 // used for address computation.
10948 Instruction::CastOps opcode =
10949 (VTySize < PtrSize ? Instruction::SExt :
10950 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10951 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10955 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10956 Value *PtrOp = GEP.getOperand(0);
10957 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10958 // If so, eliminate the noop.
10959 if (GEP.getNumOperands() == 1)
10960 return ReplaceInstUsesWith(GEP, PtrOp);
10962 if (isa<UndefValue>(GEP.getOperand(0)))
10963 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
10965 bool HasZeroPointerIndex = false;
10966 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10967 HasZeroPointerIndex = C->isNullValue();
10969 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10970 return ReplaceInstUsesWith(GEP, PtrOp);
10972 // Eliminate unneeded casts for indices.
10973 bool MadeChange = false;
10975 gep_type_iterator GTI = gep_type_begin(GEP);
10976 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10977 i != e; ++i, ++GTI) {
10978 if (TD && isa<SequentialType>(*GTI)) {
10979 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10980 if (CI->getOpcode() == Instruction::ZExt ||
10981 CI->getOpcode() == Instruction::SExt) {
10982 const Type *SrcTy = CI->getOperand(0)->getType();
10983 // We can eliminate a cast from i32 to i64 iff the target
10984 // is a 32-bit pointer target.
10985 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
10987 *i = CI->getOperand(0);
10991 // If we are using a wider index than needed for this platform, shrink it
10992 // to what we need. If narrower, sign-extend it to what we need.
10993 // If the incoming value needs a cast instruction,
10994 // insert it. This explicit cast can make subsequent optimizations more
10997 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10998 if (Constant *C = dyn_cast<Constant>(Op)) {
10999 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11002 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11007 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11008 if (Constant *C = dyn_cast<Constant>(Op)) {
11009 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11012 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11020 if (MadeChange) return &GEP;
11022 // Combine Indices - If the source pointer to this getelementptr instruction
11023 // is a getelementptr instruction, combine the indices of the two
11024 // getelementptr instructions into a single instruction.
11026 SmallVector<Value*, 8> SrcGEPOperands;
11027 if (User *Src = dyn_castGetElementPtr(PtrOp))
11028 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11030 if (!SrcGEPOperands.empty()) {
11031 // Note that if our source is a gep chain itself that we wait for that
11032 // chain to be resolved before we perform this transformation. This
11033 // avoids us creating a TON of code in some cases.
11035 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11036 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11037 return 0; // Wait until our source is folded to completion.
11039 SmallVector<Value*, 8> Indices;
11041 // Find out whether the last index in the source GEP is a sequential idx.
11042 bool EndsWithSequential = false;
11043 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11044 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11045 EndsWithSequential = !isa<StructType>(*I);
11047 // Can we combine the two pointer arithmetics offsets?
11048 if (EndsWithSequential) {
11049 // Replace: gep (gep %P, long B), long A, ...
11050 // With: T = long A+B; gep %P, T, ...
11052 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11053 if (SO1 == Context->getNullValue(SO1->getType())) {
11055 } else if (GO1 == Context->getNullValue(GO1->getType())) {
11058 // If they aren't the same type, convert both to an integer of the
11059 // target's pointer size.
11060 if (SO1->getType() != GO1->getType()) {
11061 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11063 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11064 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11066 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11068 unsigned PS = TD->getPointerSizeInBits();
11069 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11070 // Convert GO1 to SO1's type.
11071 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11073 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11074 // Convert SO1 to GO1's type.
11075 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11077 const Type *PT = TD->getIntPtrType();
11078 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11079 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11083 if (isa<Constant>(SO1) && isa<Constant>(GO1))
11084 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11085 cast<Constant>(GO1));
11087 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11088 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11092 // Recycle the GEP we already have if possible.
11093 if (SrcGEPOperands.size() == 2) {
11094 GEP.setOperand(0, SrcGEPOperands[0]);
11095 GEP.setOperand(1, Sum);
11098 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11099 SrcGEPOperands.end()-1);
11100 Indices.push_back(Sum);
11101 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11103 } else if (isa<Constant>(*GEP.idx_begin()) &&
11104 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11105 SrcGEPOperands.size() != 1) {
11106 // Otherwise we can do the fold if the first index of the GEP is a zero
11107 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11108 SrcGEPOperands.end());
11109 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11112 if (!Indices.empty())
11113 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11114 Indices.end(), GEP.getName());
11116 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11117 // GEP of global variable. If all of the indices for this GEP are
11118 // constants, we can promote this to a constexpr instead of an instruction.
11120 // Scan for nonconstants...
11121 SmallVector<Constant*, 8> Indices;
11122 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11123 for (; I != E && isa<Constant>(*I); ++I)
11124 Indices.push_back(cast<Constant>(*I));
11126 if (I == E) { // If they are all constants...
11127 Constant *CE = Context->getConstantExprGetElementPtr(GV,
11128 &Indices[0],Indices.size());
11130 // Replace all uses of the GEP with the new constexpr...
11131 return ReplaceInstUsesWith(GEP, CE);
11133 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11134 if (!isa<PointerType>(X->getType())) {
11135 // Not interesting. Source pointer must be a cast from pointer.
11136 } else if (HasZeroPointerIndex) {
11137 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11138 // into : GEP [10 x i8]* X, i32 0, ...
11140 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11141 // into : GEP i8* X, ...
11143 // This occurs when the program declares an array extern like "int X[];"
11144 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11145 const PointerType *XTy = cast<PointerType>(X->getType());
11146 if (const ArrayType *CATy =
11147 dyn_cast<ArrayType>(CPTy->getElementType())) {
11148 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11149 if (CATy->getElementType() == XTy->getElementType()) {
11150 // -> GEP i8* X, ...
11151 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11152 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11154 } else if (const ArrayType *XATy =
11155 dyn_cast<ArrayType>(XTy->getElementType())) {
11156 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11157 if (CATy->getElementType() == XATy->getElementType()) {
11158 // -> GEP [10 x i8]* X, i32 0, ...
11159 // At this point, we know that the cast source type is a pointer
11160 // to an array of the same type as the destination pointer
11161 // array. Because the array type is never stepped over (there
11162 // is a leading zero) we can fold the cast into this GEP.
11163 GEP.setOperand(0, X);
11168 } else if (GEP.getNumOperands() == 2) {
11169 // Transform things like:
11170 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11171 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11172 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11173 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11174 if (TD && isa<ArrayType>(SrcElTy) &&
11175 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11176 TD->getTypeAllocSize(ResElTy)) {
11178 Idx[0] = Context->getNullValue(Type::Int32Ty);
11179 Idx[1] = GEP.getOperand(1);
11180 Value *V = InsertNewInstBefore(
11181 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11182 // V and GEP are both pointer types --> BitCast
11183 return new BitCastInst(V, GEP.getType());
11186 // Transform things like:
11187 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11188 // (where tmp = 8*tmp2) into:
11189 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11191 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11192 uint64_t ArrayEltSize =
11193 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11195 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11196 // allow either a mul, shift, or constant here.
11198 ConstantInt *Scale = 0;
11199 if (ArrayEltSize == 1) {
11200 NewIdx = GEP.getOperand(1);
11202 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11203 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11204 NewIdx = Context->getConstantInt(CI->getType(), 1);
11206 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11207 if (Inst->getOpcode() == Instruction::Shl &&
11208 isa<ConstantInt>(Inst->getOperand(1))) {
11209 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11210 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11211 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11213 NewIdx = Inst->getOperand(0);
11214 } else if (Inst->getOpcode() == Instruction::Mul &&
11215 isa<ConstantInt>(Inst->getOperand(1))) {
11216 Scale = cast<ConstantInt>(Inst->getOperand(1));
11217 NewIdx = Inst->getOperand(0);
11221 // If the index will be to exactly the right offset with the scale taken
11222 // out, perform the transformation. Note, we don't know whether Scale is
11223 // signed or not. We'll use unsigned version of division/modulo
11224 // operation after making sure Scale doesn't have the sign bit set.
11225 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11226 Scale->getZExtValue() % ArrayEltSize == 0) {
11227 Scale = Context->getConstantInt(Scale->getType(),
11228 Scale->getZExtValue() / ArrayEltSize);
11229 if (Scale->getZExtValue() != 1) {
11231 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11233 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11234 NewIdx = InsertNewInstBefore(Sc, GEP);
11237 // Insert the new GEP instruction.
11239 Idx[0] = Context->getNullValue(Type::Int32Ty);
11241 Instruction *NewGEP =
11242 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11243 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11244 // The NewGEP must be pointer typed, so must the old one -> BitCast
11245 return new BitCastInst(NewGEP, GEP.getType());
11251 /// See if we can simplify:
11252 /// X = bitcast A to B*
11253 /// Y = gep X, <...constant indices...>
11254 /// into a gep of the original struct. This is important for SROA and alias
11255 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11256 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11258 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11259 // Determine how much the GEP moves the pointer. We are guaranteed to get
11260 // a constant back from EmitGEPOffset.
11261 ConstantInt *OffsetV =
11262 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11263 int64_t Offset = OffsetV->getSExtValue();
11265 // If this GEP instruction doesn't move the pointer, just replace the GEP
11266 // with a bitcast of the real input to the dest type.
11268 // If the bitcast is of an allocation, and the allocation will be
11269 // converted to match the type of the cast, don't touch this.
11270 if (isa<AllocationInst>(BCI->getOperand(0))) {
11271 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11272 if (Instruction *I = visitBitCast(*BCI)) {
11275 BCI->getParent()->getInstList().insert(BCI, I);
11276 ReplaceInstUsesWith(*BCI, I);
11281 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11284 // Otherwise, if the offset is non-zero, we need to find out if there is a
11285 // field at Offset in 'A's type. If so, we can pull the cast through the
11287 SmallVector<Value*, 8> NewIndices;
11289 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11290 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11291 Instruction *NGEP =
11292 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11294 if (NGEP->getType() == GEP.getType()) return NGEP;
11295 InsertNewInstBefore(NGEP, GEP);
11296 NGEP->takeName(&GEP);
11297 return new BitCastInst(NGEP, GEP.getType());
11305 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11306 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11307 if (AI.isArrayAllocation()) { // Check C != 1
11308 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11309 const Type *NewTy =
11310 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11311 AllocationInst *New = 0;
11313 // Create and insert the replacement instruction...
11314 if (isa<MallocInst>(AI))
11315 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11317 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11318 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11321 InsertNewInstBefore(New, AI);
11323 // Scan to the end of the allocation instructions, to skip over a block of
11324 // allocas if possible...also skip interleaved debug info
11326 BasicBlock::iterator It = New;
11327 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11329 // Now that I is pointing to the first non-allocation-inst in the block,
11330 // insert our getelementptr instruction...
11332 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11336 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11337 New->getName()+".sub", It);
11339 // Now make everything use the getelementptr instead of the original
11341 return ReplaceInstUsesWith(AI, V);
11342 } else if (isa<UndefValue>(AI.getArraySize())) {
11343 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11347 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11348 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11349 // Note that we only do this for alloca's, because malloc should allocate
11350 // and return a unique pointer, even for a zero byte allocation.
11351 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11352 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11354 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11355 if (AI.getAlignment() == 0)
11356 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11362 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11363 Value *Op = FI.getOperand(0);
11365 // free undef -> unreachable.
11366 if (isa<UndefValue>(Op)) {
11367 // Insert a new store to null because we cannot modify the CFG here.
11368 new StoreInst(Context->getTrue(),
11369 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11370 return EraseInstFromFunction(FI);
11373 // If we have 'free null' delete the instruction. This can happen in stl code
11374 // when lots of inlining happens.
11375 if (isa<ConstantPointerNull>(Op))
11376 return EraseInstFromFunction(FI);
11378 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11379 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11380 FI.setOperand(0, CI->getOperand(0));
11384 // Change free (gep X, 0,0,0,0) into free(X)
11385 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11386 if (GEPI->hasAllZeroIndices()) {
11387 AddToWorkList(GEPI);
11388 FI.setOperand(0, GEPI->getOperand(0));
11393 // Change free(malloc) into nothing, if the malloc has a single use.
11394 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11395 if (MI->hasOneUse()) {
11396 EraseInstFromFunction(FI);
11397 return EraseInstFromFunction(*MI);
11404 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11405 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11406 const TargetData *TD) {
11407 User *CI = cast<User>(LI.getOperand(0));
11408 Value *CastOp = CI->getOperand(0);
11409 LLVMContext *Context = IC.getContext();
11412 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11413 // Instead of loading constant c string, use corresponding integer value
11414 // directly if string length is small enough.
11416 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11417 unsigned len = Str.length();
11418 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11419 unsigned numBits = Ty->getPrimitiveSizeInBits();
11420 // Replace LI with immediate integer store.
11421 if ((numBits >> 3) == len + 1) {
11422 APInt StrVal(numBits, 0);
11423 APInt SingleChar(numBits, 0);
11424 if (TD->isLittleEndian()) {
11425 for (signed i = len-1; i >= 0; i--) {
11426 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11427 StrVal = (StrVal << 8) | SingleChar;
11430 for (unsigned i = 0; i < len; i++) {
11431 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11432 StrVal = (StrVal << 8) | SingleChar;
11434 // Append NULL at the end.
11436 StrVal = (StrVal << 8) | SingleChar;
11438 Value *NL = Context->getConstantInt(StrVal);
11439 return IC.ReplaceInstUsesWith(LI, NL);
11445 const PointerType *DestTy = cast<PointerType>(CI->getType());
11446 const Type *DestPTy = DestTy->getElementType();
11447 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11449 // If the address spaces don't match, don't eliminate the cast.
11450 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11453 const Type *SrcPTy = SrcTy->getElementType();
11455 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11456 isa<VectorType>(DestPTy)) {
11457 // If the source is an array, the code below will not succeed. Check to
11458 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11460 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11461 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11462 if (ASrcTy->getNumElements() != 0) {
11464 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11465 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11466 SrcTy = cast<PointerType>(CastOp->getType());
11467 SrcPTy = SrcTy->getElementType();
11470 if (IC.getTargetData() &&
11471 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11472 isa<VectorType>(SrcPTy)) &&
11473 // Do not allow turning this into a load of an integer, which is then
11474 // casted to a pointer, this pessimizes pointer analysis a lot.
11475 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11476 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11477 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11479 // Okay, we are casting from one integer or pointer type to another of
11480 // the same size. Instead of casting the pointer before the load, cast
11481 // the result of the loaded value.
11482 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11484 LI.isVolatile()),LI);
11485 // Now cast the result of the load.
11486 return new BitCastInst(NewLoad, LI.getType());
11493 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11494 Value *Op = LI.getOperand(0);
11496 // Attempt to improve the alignment.
11498 unsigned KnownAlign =
11499 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11501 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11502 LI.getAlignment()))
11503 LI.setAlignment(KnownAlign);
11506 // load (cast X) --> cast (load X) iff safe
11507 if (isa<CastInst>(Op))
11508 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11511 // None of the following transforms are legal for volatile loads.
11512 if (LI.isVolatile()) return 0;
11514 // Do really simple store-to-load forwarding and load CSE, to catch cases
11515 // where there are several consequtive memory accesses to the same location,
11516 // separated by a few arithmetic operations.
11517 BasicBlock::iterator BBI = &LI;
11518 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11519 return ReplaceInstUsesWith(LI, AvailableVal);
11521 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11522 const Value *GEPI0 = GEPI->getOperand(0);
11523 // TODO: Consider a target hook for valid address spaces for this xform.
11524 if (isa<ConstantPointerNull>(GEPI0) &&
11525 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11526 // Insert a new store to null instruction before the load to indicate
11527 // that this code is not reachable. We do this instead of inserting
11528 // an unreachable instruction directly because we cannot modify the
11530 new StoreInst(Context->getUndef(LI.getType()),
11531 Context->getNullValue(Op->getType()), &LI);
11532 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11536 if (Constant *C = dyn_cast<Constant>(Op)) {
11537 // load null/undef -> undef
11538 // TODO: Consider a target hook for valid address spaces for this xform.
11539 if (isa<UndefValue>(C) || (C->isNullValue() &&
11540 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11541 // Insert a new store to null instruction before the load to indicate that
11542 // this code is not reachable. We do this instead of inserting an
11543 // unreachable instruction directly because we cannot modify the CFG.
11544 new StoreInst(Context->getUndef(LI.getType()),
11545 Context->getNullValue(Op->getType()), &LI);
11546 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11549 // Instcombine load (constant global) into the value loaded.
11550 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11551 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11552 return ReplaceInstUsesWith(LI, GV->getInitializer());
11554 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11555 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11556 if (CE->getOpcode() == Instruction::GetElementPtr) {
11557 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11558 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11560 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11562 return ReplaceInstUsesWith(LI, V);
11563 if (CE->getOperand(0)->isNullValue()) {
11564 // Insert a new store to null instruction before the load to indicate
11565 // that this code is not reachable. We do this instead of inserting
11566 // an unreachable instruction directly because we cannot modify the
11568 new StoreInst(Context->getUndef(LI.getType()),
11569 Context->getNullValue(Op->getType()), &LI);
11570 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11573 } else if (CE->isCast()) {
11574 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11580 // If this load comes from anywhere in a constant global, and if the global
11581 // is all undef or zero, we know what it loads.
11582 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11583 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11584 if (GV->getInitializer()->isNullValue())
11585 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11586 else if (isa<UndefValue>(GV->getInitializer()))
11587 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11591 if (Op->hasOneUse()) {
11592 // Change select and PHI nodes to select values instead of addresses: this
11593 // helps alias analysis out a lot, allows many others simplifications, and
11594 // exposes redundancy in the code.
11596 // Note that we cannot do the transformation unless we know that the
11597 // introduced loads cannot trap! Something like this is valid as long as
11598 // the condition is always false: load (select bool %C, int* null, int* %G),
11599 // but it would not be valid if we transformed it to load from null
11600 // unconditionally.
11602 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11603 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11604 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11605 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11606 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11607 SI->getOperand(1)->getName()+".val"), LI);
11608 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11609 SI->getOperand(2)->getName()+".val"), LI);
11610 return SelectInst::Create(SI->getCondition(), V1, V2);
11613 // load (select (cond, null, P)) -> load P
11614 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11615 if (C->isNullValue()) {
11616 LI.setOperand(0, SI->getOperand(2));
11620 // load (select (cond, P, null)) -> load P
11621 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11622 if (C->isNullValue()) {
11623 LI.setOperand(0, SI->getOperand(1));
11631 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11632 /// when possible. This makes it generally easy to do alias analysis and/or
11633 /// SROA/mem2reg of the memory object.
11634 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11635 User *CI = cast<User>(SI.getOperand(1));
11636 Value *CastOp = CI->getOperand(0);
11637 LLVMContext *Context = IC.getContext();
11639 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11640 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11641 if (SrcTy == 0) return 0;
11643 const Type *SrcPTy = SrcTy->getElementType();
11645 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11648 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11649 /// to its first element. This allows us to handle things like:
11650 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11651 /// on 32-bit hosts.
11652 SmallVector<Value*, 4> NewGEPIndices;
11654 // If the source is an array, the code below will not succeed. Check to
11655 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11657 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11658 // Index through pointer.
11659 Constant *Zero = Context->getNullValue(Type::Int32Ty);
11660 NewGEPIndices.push_back(Zero);
11663 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11664 if (!STy->getNumElements()) /* Struct can be empty {} */
11666 NewGEPIndices.push_back(Zero);
11667 SrcPTy = STy->getElementType(0);
11668 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11669 NewGEPIndices.push_back(Zero);
11670 SrcPTy = ATy->getElementType();
11676 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11679 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11682 // If the pointers point into different address spaces or if they point to
11683 // values with different sizes, we can't do the transformation.
11684 if (!IC.getTargetData() ||
11685 SrcTy->getAddressSpace() !=
11686 cast<PointerType>(CI->getType())->getAddressSpace() ||
11687 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11688 IC.getTargetData()->getTypeSizeInBits(DestPTy))
11691 // Okay, we are casting from one integer or pointer type to another of
11692 // the same size. Instead of casting the pointer before
11693 // the store, cast the value to be stored.
11695 Value *SIOp0 = SI.getOperand(0);
11696 Instruction::CastOps opcode = Instruction::BitCast;
11697 const Type* CastSrcTy = SIOp0->getType();
11698 const Type* CastDstTy = SrcPTy;
11699 if (isa<PointerType>(CastDstTy)) {
11700 if (CastSrcTy->isInteger())
11701 opcode = Instruction::IntToPtr;
11702 } else if (isa<IntegerType>(CastDstTy)) {
11703 if (isa<PointerType>(SIOp0->getType()))
11704 opcode = Instruction::PtrToInt;
11707 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11708 // emit a GEP to index into its first field.
11709 if (!NewGEPIndices.empty()) {
11710 if (Constant *C = dyn_cast<Constant>(CastOp))
11711 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
11712 NewGEPIndices.size());
11714 CastOp = IC.InsertNewInstBefore(
11715 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11716 NewGEPIndices.end()), SI);
11719 if (Constant *C = dyn_cast<Constant>(SIOp0))
11720 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11722 NewCast = IC.InsertNewInstBefore(
11723 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11725 return new StoreInst(NewCast, CastOp);
11728 /// equivalentAddressValues - Test if A and B will obviously have the same
11729 /// value. This includes recognizing that %t0 and %t1 will have the same
11730 /// value in code like this:
11731 /// %t0 = getelementptr \@a, 0, 3
11732 /// store i32 0, i32* %t0
11733 /// %t1 = getelementptr \@a, 0, 3
11734 /// %t2 = load i32* %t1
11736 static bool equivalentAddressValues(Value *A, Value *B) {
11737 // Test if the values are trivially equivalent.
11738 if (A == B) return true;
11740 // Test if the values come form identical arithmetic instructions.
11741 if (isa<BinaryOperator>(A) ||
11742 isa<CastInst>(A) ||
11744 isa<GetElementPtrInst>(A))
11745 if (Instruction *BI = dyn_cast<Instruction>(B))
11746 if (cast<Instruction>(A)->isIdenticalTo(BI))
11749 // Otherwise they may not be equivalent.
11753 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11754 // return the llvm.dbg.declare.
11755 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11756 if (!V->hasNUses(2))
11758 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11760 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11762 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11763 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11770 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11771 Value *Val = SI.getOperand(0);
11772 Value *Ptr = SI.getOperand(1);
11774 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11775 EraseInstFromFunction(SI);
11780 // If the RHS is an alloca with a single use, zapify the store, making the
11782 // If the RHS is an alloca with a two uses, the other one being a
11783 // llvm.dbg.declare, zapify the store and the declare, making the
11784 // alloca dead. We must do this to prevent declare's from affecting
11786 if (!SI.isVolatile()) {
11787 if (Ptr->hasOneUse()) {
11788 if (isa<AllocaInst>(Ptr)) {
11789 EraseInstFromFunction(SI);
11793 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11794 if (isa<AllocaInst>(GEP->getOperand(0))) {
11795 if (GEP->getOperand(0)->hasOneUse()) {
11796 EraseInstFromFunction(SI);
11800 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11801 EraseInstFromFunction(*DI);
11802 EraseInstFromFunction(SI);
11809 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11810 EraseInstFromFunction(*DI);
11811 EraseInstFromFunction(SI);
11817 // Attempt to improve the alignment.
11819 unsigned KnownAlign =
11820 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11822 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11823 SI.getAlignment()))
11824 SI.setAlignment(KnownAlign);
11827 // Do really simple DSE, to catch cases where there are several consecutive
11828 // stores to the same location, separated by a few arithmetic operations. This
11829 // situation often occurs with bitfield accesses.
11830 BasicBlock::iterator BBI = &SI;
11831 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11834 // Don't count debug info directives, lest they affect codegen,
11835 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11836 // It is necessary for correctness to skip those that feed into a
11837 // llvm.dbg.declare, as these are not present when debugging is off.
11838 if (isa<DbgInfoIntrinsic>(BBI) ||
11839 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11844 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11845 // Prev store isn't volatile, and stores to the same location?
11846 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11847 SI.getOperand(1))) {
11850 EraseInstFromFunction(*PrevSI);
11856 // If this is a load, we have to stop. However, if the loaded value is from
11857 // the pointer we're loading and is producing the pointer we're storing,
11858 // then *this* store is dead (X = load P; store X -> P).
11859 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11860 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11861 !SI.isVolatile()) {
11862 EraseInstFromFunction(SI);
11866 // Otherwise, this is a load from some other location. Stores before it
11867 // may not be dead.
11871 // Don't skip over loads or things that can modify memory.
11872 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11877 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11879 // store X, null -> turns into 'unreachable' in SimplifyCFG
11880 if (isa<ConstantPointerNull>(Ptr) &&
11881 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11882 if (!isa<UndefValue>(Val)) {
11883 SI.setOperand(0, Context->getUndef(Val->getType()));
11884 if (Instruction *U = dyn_cast<Instruction>(Val))
11885 AddToWorkList(U); // Dropped a use.
11888 return 0; // Do not modify these!
11891 // store undef, Ptr -> noop
11892 if (isa<UndefValue>(Val)) {
11893 EraseInstFromFunction(SI);
11898 // If the pointer destination is a cast, see if we can fold the cast into the
11900 if (isa<CastInst>(Ptr))
11901 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11903 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11905 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11909 // If this store is the last instruction in the basic block (possibly
11910 // excepting debug info instructions and the pointer bitcasts that feed
11911 // into them), and if the block ends with an unconditional branch, try
11912 // to move it to the successor block.
11916 } while (isa<DbgInfoIntrinsic>(BBI) ||
11917 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11918 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11919 if (BI->isUnconditional())
11920 if (SimplifyStoreAtEndOfBlock(SI))
11921 return 0; // xform done!
11926 /// SimplifyStoreAtEndOfBlock - Turn things like:
11927 /// if () { *P = v1; } else { *P = v2 }
11928 /// into a phi node with a store in the successor.
11930 /// Simplify things like:
11931 /// *P = v1; if () { *P = v2; }
11932 /// into a phi node with a store in the successor.
11934 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11935 BasicBlock *StoreBB = SI.getParent();
11937 // Check to see if the successor block has exactly two incoming edges. If
11938 // so, see if the other predecessor contains a store to the same location.
11939 // if so, insert a PHI node (if needed) and move the stores down.
11940 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11942 // Determine whether Dest has exactly two predecessors and, if so, compute
11943 // the other predecessor.
11944 pred_iterator PI = pred_begin(DestBB);
11945 BasicBlock *OtherBB = 0;
11946 if (*PI != StoreBB)
11949 if (PI == pred_end(DestBB))
11952 if (*PI != StoreBB) {
11957 if (++PI != pred_end(DestBB))
11960 // Bail out if all the relevant blocks aren't distinct (this can happen,
11961 // for example, if SI is in an infinite loop)
11962 if (StoreBB == DestBB || OtherBB == DestBB)
11965 // Verify that the other block ends in a branch and is not otherwise empty.
11966 BasicBlock::iterator BBI = OtherBB->getTerminator();
11967 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11968 if (!OtherBr || BBI == OtherBB->begin())
11971 // If the other block ends in an unconditional branch, check for the 'if then
11972 // else' case. there is an instruction before the branch.
11973 StoreInst *OtherStore = 0;
11974 if (OtherBr->isUnconditional()) {
11976 // Skip over debugging info.
11977 while (isa<DbgInfoIntrinsic>(BBI) ||
11978 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11979 if (BBI==OtherBB->begin())
11983 // If this isn't a store, or isn't a store to the same location, bail out.
11984 OtherStore = dyn_cast<StoreInst>(BBI);
11985 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11988 // Otherwise, the other block ended with a conditional branch. If one of the
11989 // destinations is StoreBB, then we have the if/then case.
11990 if (OtherBr->getSuccessor(0) != StoreBB &&
11991 OtherBr->getSuccessor(1) != StoreBB)
11994 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11995 // if/then triangle. See if there is a store to the same ptr as SI that
11996 // lives in OtherBB.
11998 // Check to see if we find the matching store.
11999 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12000 if (OtherStore->getOperand(1) != SI.getOperand(1))
12004 // If we find something that may be using or overwriting the stored
12005 // value, or if we run out of instructions, we can't do the xform.
12006 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12007 BBI == OtherBB->begin())
12011 // In order to eliminate the store in OtherBr, we have to
12012 // make sure nothing reads or overwrites the stored value in
12014 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12015 // FIXME: This should really be AA driven.
12016 if (I->mayReadFromMemory() || I->mayWriteToMemory())
12021 // Insert a PHI node now if we need it.
12022 Value *MergedVal = OtherStore->getOperand(0);
12023 if (MergedVal != SI.getOperand(0)) {
12024 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12025 PN->reserveOperandSpace(2);
12026 PN->addIncoming(SI.getOperand(0), SI.getParent());
12027 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12028 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12031 // Advance to a place where it is safe to insert the new store and
12033 BBI = DestBB->getFirstNonPHI();
12034 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12035 OtherStore->isVolatile()), *BBI);
12037 // Nuke the old stores.
12038 EraseInstFromFunction(SI);
12039 EraseInstFromFunction(*OtherStore);
12045 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12046 // Change br (not X), label True, label False to: br X, label False, True
12048 BasicBlock *TrueDest;
12049 BasicBlock *FalseDest;
12050 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12051 !isa<Constant>(X)) {
12052 // Swap Destinations and condition...
12053 BI.setCondition(X);
12054 BI.setSuccessor(0, FalseDest);
12055 BI.setSuccessor(1, TrueDest);
12059 // Cannonicalize fcmp_one -> fcmp_oeq
12060 FCmpInst::Predicate FPred; Value *Y;
12061 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
12062 TrueDest, FalseDest), *Context))
12063 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12064 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12065 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12066 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12067 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12068 NewSCC->takeName(I);
12069 // Swap Destinations and condition...
12070 BI.setCondition(NewSCC);
12071 BI.setSuccessor(0, FalseDest);
12072 BI.setSuccessor(1, TrueDest);
12073 RemoveFromWorkList(I);
12074 I->eraseFromParent();
12075 AddToWorkList(NewSCC);
12079 // Cannonicalize icmp_ne -> icmp_eq
12080 ICmpInst::Predicate IPred;
12081 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12082 TrueDest, FalseDest), *Context))
12083 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12084 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12085 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12086 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12087 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12088 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12089 NewSCC->takeName(I);
12090 // Swap Destinations and condition...
12091 BI.setCondition(NewSCC);
12092 BI.setSuccessor(0, FalseDest);
12093 BI.setSuccessor(1, TrueDest);
12094 RemoveFromWorkList(I);
12095 I->eraseFromParent();;
12096 AddToWorkList(NewSCC);
12103 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12104 Value *Cond = SI.getCondition();
12105 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12106 if (I->getOpcode() == Instruction::Add)
12107 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12108 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12109 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12111 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12113 SI.setOperand(0, I->getOperand(0));
12121 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12122 Value *Agg = EV.getAggregateOperand();
12124 if (!EV.hasIndices())
12125 return ReplaceInstUsesWith(EV, Agg);
12127 if (Constant *C = dyn_cast<Constant>(Agg)) {
12128 if (isa<UndefValue>(C))
12129 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12131 if (isa<ConstantAggregateZero>(C))
12132 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12134 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12135 // Extract the element indexed by the first index out of the constant
12136 Value *V = C->getOperand(*EV.idx_begin());
12137 if (EV.getNumIndices() > 1)
12138 // Extract the remaining indices out of the constant indexed by the
12140 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12142 return ReplaceInstUsesWith(EV, V);
12144 return 0; // Can't handle other constants
12146 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12147 // We're extracting from an insertvalue instruction, compare the indices
12148 const unsigned *exti, *exte, *insi, *inse;
12149 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12150 exte = EV.idx_end(), inse = IV->idx_end();
12151 exti != exte && insi != inse;
12153 if (*insi != *exti)
12154 // The insert and extract both reference distinctly different elements.
12155 // This means the extract is not influenced by the insert, and we can
12156 // replace the aggregate operand of the extract with the aggregate
12157 // operand of the insert. i.e., replace
12158 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12159 // %E = extractvalue { i32, { i32 } } %I, 0
12161 // %E = extractvalue { i32, { i32 } } %A, 0
12162 return ExtractValueInst::Create(IV->getAggregateOperand(),
12163 EV.idx_begin(), EV.idx_end());
12165 if (exti == exte && insi == inse)
12166 // Both iterators are at the end: Index lists are identical. Replace
12167 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12168 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12170 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12171 if (exti == exte) {
12172 // The extract list is a prefix of the insert list. i.e. replace
12173 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12174 // %E = extractvalue { i32, { i32 } } %I, 1
12176 // %X = extractvalue { i32, { i32 } } %A, 1
12177 // %E = insertvalue { i32 } %X, i32 42, 0
12178 // by switching the order of the insert and extract (though the
12179 // insertvalue should be left in, since it may have other uses).
12180 Value *NewEV = InsertNewInstBefore(
12181 ExtractValueInst::Create(IV->getAggregateOperand(),
12182 EV.idx_begin(), EV.idx_end()),
12184 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12188 // The insert list is a prefix of the extract list
12189 // We can simply remove the common indices from the extract and make it
12190 // operate on the inserted value instead of the insertvalue result.
12192 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12193 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12195 // %E extractvalue { i32 } { i32 42 }, 0
12196 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12199 // Can't simplify extracts from other values. Note that nested extracts are
12200 // already simplified implicitely by the above (extract ( extract (insert) )
12201 // will be translated into extract ( insert ( extract ) ) first and then just
12202 // the value inserted, if appropriate).
12206 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12207 /// is to leave as a vector operation.
12208 static bool CheapToScalarize(Value *V, bool isConstant) {
12209 if (isa<ConstantAggregateZero>(V))
12211 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12212 if (isConstant) return true;
12213 // If all elts are the same, we can extract.
12214 Constant *Op0 = C->getOperand(0);
12215 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12216 if (C->getOperand(i) != Op0)
12220 Instruction *I = dyn_cast<Instruction>(V);
12221 if (!I) return false;
12223 // Insert element gets simplified to the inserted element or is deleted if
12224 // this is constant idx extract element and its a constant idx insertelt.
12225 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12226 isa<ConstantInt>(I->getOperand(2)))
12228 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12230 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12231 if (BO->hasOneUse() &&
12232 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12233 CheapToScalarize(BO->getOperand(1), isConstant)))
12235 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12236 if (CI->hasOneUse() &&
12237 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12238 CheapToScalarize(CI->getOperand(1), isConstant)))
12244 /// Read and decode a shufflevector mask.
12246 /// It turns undef elements into values that are larger than the number of
12247 /// elements in the input.
12248 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12249 unsigned NElts = SVI->getType()->getNumElements();
12250 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12251 return std::vector<unsigned>(NElts, 0);
12252 if (isa<UndefValue>(SVI->getOperand(2)))
12253 return std::vector<unsigned>(NElts, 2*NElts);
12255 std::vector<unsigned> Result;
12256 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12257 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12258 if (isa<UndefValue>(*i))
12259 Result.push_back(NElts*2); // undef -> 8
12261 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12265 /// FindScalarElement - Given a vector and an element number, see if the scalar
12266 /// value is already around as a register, for example if it were inserted then
12267 /// extracted from the vector.
12268 static Value *FindScalarElement(Value *V, unsigned EltNo,
12269 LLVMContext *Context) {
12270 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12271 const VectorType *PTy = cast<VectorType>(V->getType());
12272 unsigned Width = PTy->getNumElements();
12273 if (EltNo >= Width) // Out of range access.
12274 return Context->getUndef(PTy->getElementType());
12276 if (isa<UndefValue>(V))
12277 return Context->getUndef(PTy->getElementType());
12278 else if (isa<ConstantAggregateZero>(V))
12279 return Context->getNullValue(PTy->getElementType());
12280 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12281 return CP->getOperand(EltNo);
12282 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12283 // If this is an insert to a variable element, we don't know what it is.
12284 if (!isa<ConstantInt>(III->getOperand(2)))
12286 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12288 // If this is an insert to the element we are looking for, return the
12290 if (EltNo == IIElt)
12291 return III->getOperand(1);
12293 // Otherwise, the insertelement doesn't modify the value, recurse on its
12295 return FindScalarElement(III->getOperand(0), EltNo, Context);
12296 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12297 unsigned LHSWidth =
12298 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12299 unsigned InEl = getShuffleMask(SVI)[EltNo];
12300 if (InEl < LHSWidth)
12301 return FindScalarElement(SVI->getOperand(0), InEl, Context);
12302 else if (InEl < LHSWidth*2)
12303 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12305 return Context->getUndef(PTy->getElementType());
12308 // Otherwise, we don't know.
12312 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12313 // If vector val is undef, replace extract with scalar undef.
12314 if (isa<UndefValue>(EI.getOperand(0)))
12315 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12317 // If vector val is constant 0, replace extract with scalar 0.
12318 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12319 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12321 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12322 // If vector val is constant with all elements the same, replace EI with
12323 // that element. When the elements are not identical, we cannot replace yet
12324 // (we do that below, but only when the index is constant).
12325 Constant *op0 = C->getOperand(0);
12326 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12327 if (C->getOperand(i) != op0) {
12332 return ReplaceInstUsesWith(EI, op0);
12335 // If extracting a specified index from the vector, see if we can recursively
12336 // find a previously computed scalar that was inserted into the vector.
12337 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12338 unsigned IndexVal = IdxC->getZExtValue();
12339 unsigned VectorWidth =
12340 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12342 // If this is extracting an invalid index, turn this into undef, to avoid
12343 // crashing the code below.
12344 if (IndexVal >= VectorWidth)
12345 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12347 // This instruction only demands the single element from the input vector.
12348 // If the input vector has a single use, simplify it based on this use
12350 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12351 APInt UndefElts(VectorWidth, 0);
12352 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12353 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12354 DemandedMask, UndefElts)) {
12355 EI.setOperand(0, V);
12360 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12361 return ReplaceInstUsesWith(EI, Elt);
12363 // If the this extractelement is directly using a bitcast from a vector of
12364 // the same number of elements, see if we can find the source element from
12365 // it. In this case, we will end up needing to bitcast the scalars.
12366 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12367 if (const VectorType *VT =
12368 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12369 if (VT->getNumElements() == VectorWidth)
12370 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12371 IndexVal, Context))
12372 return new BitCastInst(Elt, EI.getType());
12376 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12377 if (I->hasOneUse()) {
12378 // Push extractelement into predecessor operation if legal and
12379 // profitable to do so
12380 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12381 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12382 if (CheapToScalarize(BO, isConstantElt)) {
12383 ExtractElementInst *newEI0 =
12384 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12385 EI.getName()+".lhs");
12386 ExtractElementInst *newEI1 =
12387 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12388 EI.getName()+".rhs");
12389 InsertNewInstBefore(newEI0, EI);
12390 InsertNewInstBefore(newEI1, EI);
12391 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12393 } else if (isa<LoadInst>(I)) {
12395 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12396 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12397 Context->getPointerType(EI.getType(), AS),EI);
12398 GetElementPtrInst *GEP =
12399 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12400 InsertNewInstBefore(GEP, EI);
12401 return new LoadInst(GEP);
12404 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12405 // Extracting the inserted element?
12406 if (IE->getOperand(2) == EI.getOperand(1))
12407 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12408 // If the inserted and extracted elements are constants, they must not
12409 // be the same value, extract from the pre-inserted value instead.
12410 if (isa<Constant>(IE->getOperand(2)) &&
12411 isa<Constant>(EI.getOperand(1))) {
12412 AddUsesToWorkList(EI);
12413 EI.setOperand(0, IE->getOperand(0));
12416 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12417 // If this is extracting an element from a shufflevector, figure out where
12418 // it came from and extract from the appropriate input element instead.
12419 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12420 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12422 unsigned LHSWidth =
12423 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12425 if (SrcIdx < LHSWidth)
12426 Src = SVI->getOperand(0);
12427 else if (SrcIdx < LHSWidth*2) {
12428 SrcIdx -= LHSWidth;
12429 Src = SVI->getOperand(1);
12431 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12433 return new ExtractElementInst(Src,
12434 Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
12437 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12442 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12443 /// elements from either LHS or RHS, return the shuffle mask and true.
12444 /// Otherwise, return false.
12445 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12446 std::vector<Constant*> &Mask,
12447 LLVMContext *Context) {
12448 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12449 "Invalid CollectSingleShuffleElements");
12450 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12452 if (isa<UndefValue>(V)) {
12453 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12455 } else if (V == LHS) {
12456 for (unsigned i = 0; i != NumElts; ++i)
12457 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12459 } else if (V == RHS) {
12460 for (unsigned i = 0; i != NumElts; ++i)
12461 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12463 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12464 // If this is an insert of an extract from some other vector, include it.
12465 Value *VecOp = IEI->getOperand(0);
12466 Value *ScalarOp = IEI->getOperand(1);
12467 Value *IdxOp = IEI->getOperand(2);
12469 if (!isa<ConstantInt>(IdxOp))
12471 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12473 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12474 // Okay, we can handle this if the vector we are insertinting into is
12475 // transitively ok.
12476 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12477 // If so, update the mask to reflect the inserted undef.
12478 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12481 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12482 if (isa<ConstantInt>(EI->getOperand(1)) &&
12483 EI->getOperand(0)->getType() == V->getType()) {
12484 unsigned ExtractedIdx =
12485 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12487 // This must be extracting from either LHS or RHS.
12488 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12489 // Okay, we can handle this if the vector we are insertinting into is
12490 // transitively ok.
12491 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12492 // If so, update the mask to reflect the inserted value.
12493 if (EI->getOperand(0) == LHS) {
12494 Mask[InsertedIdx % NumElts] =
12495 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12497 assert(EI->getOperand(0) == RHS);
12498 Mask[InsertedIdx % NumElts] =
12499 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12508 // TODO: Handle shufflevector here!
12513 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12514 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12515 /// that computes V and the LHS value of the shuffle.
12516 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12517 Value *&RHS, LLVMContext *Context) {
12518 assert(isa<VectorType>(V->getType()) &&
12519 (RHS == 0 || V->getType() == RHS->getType()) &&
12520 "Invalid shuffle!");
12521 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12523 if (isa<UndefValue>(V)) {
12524 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12526 } else if (isa<ConstantAggregateZero>(V)) {
12527 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12529 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12530 // If this is an insert of an extract from some other vector, include it.
12531 Value *VecOp = IEI->getOperand(0);
12532 Value *ScalarOp = IEI->getOperand(1);
12533 Value *IdxOp = IEI->getOperand(2);
12535 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12536 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12537 EI->getOperand(0)->getType() == V->getType()) {
12538 unsigned ExtractedIdx =
12539 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12540 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12542 // Either the extracted from or inserted into vector must be RHSVec,
12543 // otherwise we'd end up with a shuffle of three inputs.
12544 if (EI->getOperand(0) == RHS || RHS == 0) {
12545 RHS = EI->getOperand(0);
12546 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12547 Mask[InsertedIdx % NumElts] =
12548 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12552 if (VecOp == RHS) {
12553 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12555 // Everything but the extracted element is replaced with the RHS.
12556 for (unsigned i = 0; i != NumElts; ++i) {
12557 if (i != InsertedIdx)
12558 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12563 // If this insertelement is a chain that comes from exactly these two
12564 // vectors, return the vector and the effective shuffle.
12565 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12567 return EI->getOperand(0);
12572 // TODO: Handle shufflevector here!
12574 // Otherwise, can't do anything fancy. Return an identity vector.
12575 for (unsigned i = 0; i != NumElts; ++i)
12576 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12580 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12581 Value *VecOp = IE.getOperand(0);
12582 Value *ScalarOp = IE.getOperand(1);
12583 Value *IdxOp = IE.getOperand(2);
12585 // Inserting an undef or into an undefined place, remove this.
12586 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12587 ReplaceInstUsesWith(IE, VecOp);
12589 // If the inserted element was extracted from some other vector, and if the
12590 // indexes are constant, try to turn this into a shufflevector operation.
12591 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12592 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12593 EI->getOperand(0)->getType() == IE.getType()) {
12594 unsigned NumVectorElts = IE.getType()->getNumElements();
12595 unsigned ExtractedIdx =
12596 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12597 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12599 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12600 return ReplaceInstUsesWith(IE, VecOp);
12602 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12603 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12605 // If we are extracting a value from a vector, then inserting it right
12606 // back into the same place, just use the input vector.
12607 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12608 return ReplaceInstUsesWith(IE, VecOp);
12610 // We could theoretically do this for ANY input. However, doing so could
12611 // turn chains of insertelement instructions into a chain of shufflevector
12612 // instructions, and right now we do not merge shufflevectors. As such,
12613 // only do this in a situation where it is clear that there is benefit.
12614 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12615 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12616 // the values of VecOp, except then one read from EIOp0.
12617 // Build a new shuffle mask.
12618 std::vector<Constant*> Mask;
12619 if (isa<UndefValue>(VecOp))
12620 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12622 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12623 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12626 Mask[InsertedIdx] =
12627 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12628 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12629 Context->getConstantVector(Mask));
12632 // If this insertelement isn't used by some other insertelement, turn it
12633 // (and any insertelements it points to), into one big shuffle.
12634 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12635 std::vector<Constant*> Mask;
12637 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12638 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12639 // We now have a shuffle of LHS, RHS, Mask.
12640 return new ShuffleVectorInst(LHS, RHS,
12641 Context->getConstantVector(Mask));
12646 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12647 APInt UndefElts(VWidth, 0);
12648 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12649 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12656 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12657 Value *LHS = SVI.getOperand(0);
12658 Value *RHS = SVI.getOperand(1);
12659 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12661 bool MadeChange = false;
12663 // Undefined shuffle mask -> undefined value.
12664 if (isa<UndefValue>(SVI.getOperand(2)))
12665 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12667 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12669 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12672 APInt UndefElts(VWidth, 0);
12673 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12674 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12675 LHS = SVI.getOperand(0);
12676 RHS = SVI.getOperand(1);
12680 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12681 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12682 if (LHS == RHS || isa<UndefValue>(LHS)) {
12683 if (isa<UndefValue>(LHS) && LHS == RHS) {
12684 // shuffle(undef,undef,mask) -> undef.
12685 return ReplaceInstUsesWith(SVI, LHS);
12688 // Remap any references to RHS to use LHS.
12689 std::vector<Constant*> Elts;
12690 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12691 if (Mask[i] >= 2*e)
12692 Elts.push_back(Context->getUndef(Type::Int32Ty));
12694 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12695 (Mask[i] < e && isa<UndefValue>(LHS))) {
12696 Mask[i] = 2*e; // Turn into undef.
12697 Elts.push_back(Context->getUndef(Type::Int32Ty));
12699 Mask[i] = Mask[i] % e; // Force to LHS.
12700 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12704 SVI.setOperand(0, SVI.getOperand(1));
12705 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12706 SVI.setOperand(2, Context->getConstantVector(Elts));
12707 LHS = SVI.getOperand(0);
12708 RHS = SVI.getOperand(1);
12712 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12713 bool isLHSID = true, isRHSID = true;
12715 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12716 if (Mask[i] >= e*2) continue; // Ignore undef values.
12717 // Is this an identity shuffle of the LHS value?
12718 isLHSID &= (Mask[i] == i);
12720 // Is this an identity shuffle of the RHS value?
12721 isRHSID &= (Mask[i]-e == i);
12724 // Eliminate identity shuffles.
12725 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12726 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12728 // If the LHS is a shufflevector itself, see if we can combine it with this
12729 // one without producing an unusual shuffle. Here we are really conservative:
12730 // we are absolutely afraid of producing a shuffle mask not in the input
12731 // program, because the code gen may not be smart enough to turn a merged
12732 // shuffle into two specific shuffles: it may produce worse code. As such,
12733 // we only merge two shuffles if the result is one of the two input shuffle
12734 // masks. In this case, merging the shuffles just removes one instruction,
12735 // which we know is safe. This is good for things like turning:
12736 // (splat(splat)) -> splat.
12737 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12738 if (isa<UndefValue>(RHS)) {
12739 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12741 std::vector<unsigned> NewMask;
12742 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12743 if (Mask[i] >= 2*e)
12744 NewMask.push_back(2*e);
12746 NewMask.push_back(LHSMask[Mask[i]]);
12748 // If the result mask is equal to the src shuffle or this shuffle mask, do
12749 // the replacement.
12750 if (NewMask == LHSMask || NewMask == Mask) {
12751 unsigned LHSInNElts =
12752 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12753 std::vector<Constant*> Elts;
12754 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12755 if (NewMask[i] >= LHSInNElts*2) {
12756 Elts.push_back(Context->getUndef(Type::Int32Ty));
12758 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12761 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12762 LHSSVI->getOperand(1),
12763 Context->getConstantVector(Elts));
12768 return MadeChange ? &SVI : 0;
12774 /// TryToSinkInstruction - Try to move the specified instruction from its
12775 /// current block into the beginning of DestBlock, which can only happen if it's
12776 /// safe to move the instruction past all of the instructions between it and the
12777 /// end of its block.
12778 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12779 assert(I->hasOneUse() && "Invariants didn't hold!");
12781 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12782 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12785 // Do not sink alloca instructions out of the entry block.
12786 if (isa<AllocaInst>(I) && I->getParent() ==
12787 &DestBlock->getParent()->getEntryBlock())
12790 // We can only sink load instructions if there is nothing between the load and
12791 // the end of block that could change the value.
12792 if (I->mayReadFromMemory()) {
12793 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12795 if (Scan->mayWriteToMemory())
12799 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12801 CopyPrecedingStopPoint(I, InsertPos);
12802 I->moveBefore(InsertPos);
12808 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12809 /// all reachable code to the worklist.
12811 /// This has a couple of tricks to make the code faster and more powerful. In
12812 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12813 /// them to the worklist (this significantly speeds up instcombine on code where
12814 /// many instructions are dead or constant). Additionally, if we find a branch
12815 /// whose condition is a known constant, we only visit the reachable successors.
12817 static void AddReachableCodeToWorklist(BasicBlock *BB,
12818 SmallPtrSet<BasicBlock*, 64> &Visited,
12820 const TargetData *TD) {
12821 SmallVector<BasicBlock*, 256> Worklist;
12822 Worklist.push_back(BB);
12824 while (!Worklist.empty()) {
12825 BB = Worklist.back();
12826 Worklist.pop_back();
12828 // We have now visited this block! If we've already been here, ignore it.
12829 if (!Visited.insert(BB)) continue;
12831 DbgInfoIntrinsic *DBI_Prev = NULL;
12832 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12833 Instruction *Inst = BBI++;
12835 // DCE instruction if trivially dead.
12836 if (isInstructionTriviallyDead(Inst)) {
12838 DOUT << "IC: DCE: " << *Inst;
12839 Inst->eraseFromParent();
12843 // ConstantProp instruction if trivially constant.
12844 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12845 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12846 Inst->replaceAllUsesWith(C);
12848 Inst->eraseFromParent();
12852 // If there are two consecutive llvm.dbg.stoppoint calls then
12853 // it is likely that the optimizer deleted code in between these
12855 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12858 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12859 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12860 IC.RemoveFromWorkList(DBI_Prev);
12861 DBI_Prev->eraseFromParent();
12863 DBI_Prev = DBI_Next;
12868 IC.AddToWorkList(Inst);
12871 // Recursively visit successors. If this is a branch or switch on a
12872 // constant, only visit the reachable successor.
12873 TerminatorInst *TI = BB->getTerminator();
12874 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12875 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12876 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12877 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12878 Worklist.push_back(ReachableBB);
12881 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12882 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12883 // See if this is an explicit destination.
12884 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12885 if (SI->getCaseValue(i) == Cond) {
12886 BasicBlock *ReachableBB = SI->getSuccessor(i);
12887 Worklist.push_back(ReachableBB);
12891 // Otherwise it is the default destination.
12892 Worklist.push_back(SI->getSuccessor(0));
12897 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12898 Worklist.push_back(TI->getSuccessor(i));
12902 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12903 bool Changed = false;
12904 TD = getAnalysisIfAvailable<TargetData>();
12906 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12907 << F.getNameStr() << "\n");
12910 // Do a depth-first traversal of the function, populate the worklist with
12911 // the reachable instructions. Ignore blocks that are not reachable. Keep
12912 // track of which blocks we visit.
12913 SmallPtrSet<BasicBlock*, 64> Visited;
12914 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12916 // Do a quick scan over the function. If we find any blocks that are
12917 // unreachable, remove any instructions inside of them. This prevents
12918 // the instcombine code from having to deal with some bad special cases.
12919 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12920 if (!Visited.count(BB)) {
12921 Instruction *Term = BB->getTerminator();
12922 while (Term != BB->begin()) { // Remove instrs bottom-up
12923 BasicBlock::iterator I = Term; --I;
12925 DOUT << "IC: DCE: " << *I;
12926 // A debug intrinsic shouldn't force another iteration if we weren't
12927 // going to do one without it.
12928 if (!isa<DbgInfoIntrinsic>(I)) {
12932 if (!I->use_empty())
12933 I->replaceAllUsesWith(Context->getUndef(I->getType()));
12934 I->eraseFromParent();
12939 while (!Worklist.empty()) {
12940 Instruction *I = RemoveOneFromWorkList();
12941 if (I == 0) continue; // skip null values.
12943 // Check to see if we can DCE the instruction.
12944 if (isInstructionTriviallyDead(I)) {
12945 // Add operands to the worklist.
12946 if (I->getNumOperands() < 4)
12947 AddUsesToWorkList(*I);
12950 DOUT << "IC: DCE: " << *I;
12952 I->eraseFromParent();
12953 RemoveFromWorkList(I);
12958 // Instruction isn't dead, see if we can constant propagate it.
12959 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12960 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12962 // Add operands to the worklist.
12963 AddUsesToWorkList(*I);
12964 ReplaceInstUsesWith(*I, C);
12967 I->eraseFromParent();
12968 RemoveFromWorkList(I);
12974 // See if we can constant fold its operands.
12975 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12976 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12977 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12978 F.getContext(), TD))
12985 // See if we can trivially sink this instruction to a successor basic block.
12986 if (I->hasOneUse()) {
12987 BasicBlock *BB = I->getParent();
12988 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12989 if (UserParent != BB) {
12990 bool UserIsSuccessor = false;
12991 // See if the user is one of our successors.
12992 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12993 if (*SI == UserParent) {
12994 UserIsSuccessor = true;
12998 // If the user is one of our immediate successors, and if that successor
12999 // only has us as a predecessors (we'd have to split the critical edge
13000 // otherwise), we can keep going.
13001 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13002 next(pred_begin(UserParent)) == pred_end(UserParent))
13003 // Okay, the CFG is simple enough, try to sink this instruction.
13004 Changed |= TryToSinkInstruction(I, UserParent);
13008 // Now that we have an instruction, try combining it to simplify it...
13012 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13013 if (Instruction *Result = visit(*I)) {
13015 // Should we replace the old instruction with a new one?
13017 DOUT << "IC: Old = " << *I
13018 << " New = " << *Result;
13020 // Everything uses the new instruction now.
13021 I->replaceAllUsesWith(Result);
13023 // Push the new instruction and any users onto the worklist.
13024 AddToWorkList(Result);
13025 AddUsersToWorkList(*Result);
13027 // Move the name to the new instruction first.
13028 Result->takeName(I);
13030 // Insert the new instruction into the basic block...
13031 BasicBlock *InstParent = I->getParent();
13032 BasicBlock::iterator InsertPos = I;
13034 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13035 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13038 InstParent->getInstList().insert(InsertPos, Result);
13040 // Make sure that we reprocess all operands now that we reduced their
13042 AddUsesToWorkList(*I);
13044 // Instructions can end up on the worklist more than once. Make sure
13045 // we do not process an instruction that has been deleted.
13046 RemoveFromWorkList(I);
13048 // Erase the old instruction.
13049 InstParent->getInstList().erase(I);
13052 DOUT << "IC: Mod = " << OrigI
13053 << " New = " << *I;
13056 // If the instruction was modified, it's possible that it is now dead.
13057 // if so, remove it.
13058 if (isInstructionTriviallyDead(I)) {
13059 // Make sure we process all operands now that we are reducing their
13061 AddUsesToWorkList(*I);
13063 // Instructions may end up in the worklist more than once. Erase all
13064 // occurrences of this instruction.
13065 RemoveFromWorkList(I);
13066 I->eraseFromParent();
13069 AddUsersToWorkList(*I);
13076 assert(WorklistMap.empty() && "Worklist empty, but map not?");
13078 // Do an explicit clear, this shrinks the map if needed.
13079 WorklistMap.clear();
13084 bool InstCombiner::runOnFunction(Function &F) {
13085 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13086 Context = &F.getContext();
13088 bool EverMadeChange = false;
13090 // Iterate while there is work to do.
13091 unsigned Iteration = 0;
13092 while (DoOneIteration(F, Iteration++))
13093 EverMadeChange = true;
13094 return EverMadeChange;
13097 FunctionPass *llvm::createInstructionCombiningPass() {
13098 return new InstCombiner();