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/Analysis/ConstantFolding.h"
44 #include "llvm/Analysis/ValueTracking.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/ConstantRange.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Support/InstVisitor.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/PatternMatch.h"
56 #include "llvm/Support/Compiler.h"
57 #include "llvm/ADT/DenseMap.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/SmallPtrSet.h"
60 #include "llvm/ADT/Statistic.h"
61 #include "llvm/ADT/STLExtras.h"
66 using namespace llvm::PatternMatch;
68 STATISTIC(NumCombined , "Number of insts combined");
69 STATISTIC(NumConstProp, "Number of constant folds");
70 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
71 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
72 STATISTIC(NumSunkInst , "Number of instructions sunk");
75 class VISIBILITY_HIDDEN InstCombiner
76 : public FunctionPass,
77 public InstVisitor<InstCombiner, Instruction*> {
78 // Worklist of all of the instructions that need to be simplified.
79 SmallVector<Instruction*, 256> Worklist;
80 DenseMap<Instruction*, unsigned> WorklistMap;
82 bool MustPreserveLCSSA;
84 static char ID; // Pass identification, replacement for typeid
85 InstCombiner() : FunctionPass(&ID) {}
87 LLVMContext *getContext() { return Context; }
89 /// AddToWorkList - Add the specified instruction to the worklist if it
90 /// isn't already in it.
91 void AddToWorkList(Instruction *I) {
92 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
93 Worklist.push_back(I);
96 // RemoveFromWorkList - remove I from the worklist if it exists.
97 void RemoveFromWorkList(Instruction *I) {
98 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
99 if (It == WorklistMap.end()) return; // Not in worklist.
101 // Don't bother moving everything down, just null out the slot.
102 Worklist[It->second] = 0;
104 WorklistMap.erase(It);
107 Instruction *RemoveOneFromWorkList() {
108 Instruction *I = Worklist.back();
110 WorklistMap.erase(I);
115 /// AddUsersToWorkList - When an instruction is simplified, add all users of
116 /// the instruction to the work lists because they might get more simplified
119 void AddUsersToWorkList(Value &I) {
120 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
122 AddToWorkList(cast<Instruction>(*UI));
125 /// AddUsesToWorkList - When an instruction is simplified, add operands to
126 /// the work lists because they might get more simplified now.
128 void AddUsesToWorkList(Instruction &I) {
129 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
130 if (Instruction *Op = dyn_cast<Instruction>(*i))
134 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
135 /// dead. Add all of its operands to the worklist, turning them into
136 /// undef's to reduce the number of uses of those instructions.
138 /// Return the specified operand before it is turned into an undef.
140 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
141 Value *R = I.getOperand(op);
143 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
144 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
146 // Set the operand to undef to drop the use.
147 *i = Context->getUndef(Op->getType());
154 virtual bool runOnFunction(Function &F);
156 bool DoOneIteration(Function &F, unsigned ItNum);
158 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
159 AU.addRequired<TargetData>();
160 AU.addPreservedID(LCSSAID);
161 AU.setPreservesCFG();
164 TargetData &getTargetData() const { return *TD; }
166 // Visitation implementation - Implement instruction combining for different
167 // instruction types. The semantics are as follows:
169 // null - No change was made
170 // I - Change was made, I is still valid, I may be dead though
171 // otherwise - Change was made, replace I with returned instruction
173 Instruction *visitAdd(BinaryOperator &I);
174 Instruction *visitFAdd(BinaryOperator &I);
175 Instruction *visitSub(BinaryOperator &I);
176 Instruction *visitFSub(BinaryOperator &I);
177 Instruction *visitMul(BinaryOperator &I);
178 Instruction *visitFMul(BinaryOperator &I);
179 Instruction *visitURem(BinaryOperator &I);
180 Instruction *visitSRem(BinaryOperator &I);
181 Instruction *visitFRem(BinaryOperator &I);
182 bool SimplifyDivRemOfSelect(BinaryOperator &I);
183 Instruction *commonRemTransforms(BinaryOperator &I);
184 Instruction *commonIRemTransforms(BinaryOperator &I);
185 Instruction *commonDivTransforms(BinaryOperator &I);
186 Instruction *commonIDivTransforms(BinaryOperator &I);
187 Instruction *visitUDiv(BinaryOperator &I);
188 Instruction *visitSDiv(BinaryOperator &I);
189 Instruction *visitFDiv(BinaryOperator &I);
190 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
191 Instruction *visitAnd(BinaryOperator &I);
192 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
193 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
194 Value *A, Value *B, Value *C);
195 Instruction *visitOr (BinaryOperator &I);
196 Instruction *visitXor(BinaryOperator &I);
197 Instruction *visitShl(BinaryOperator &I);
198 Instruction *visitAShr(BinaryOperator &I);
199 Instruction *visitLShr(BinaryOperator &I);
200 Instruction *commonShiftTransforms(BinaryOperator &I);
201 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
203 Instruction *visitFCmpInst(FCmpInst &I);
204 Instruction *visitICmpInst(ICmpInst &I);
205 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
206 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
209 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
210 ConstantInt *DivRHS);
212 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
213 ICmpInst::Predicate Cond, Instruction &I);
214 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
216 Instruction *commonCastTransforms(CastInst &CI);
217 Instruction *commonIntCastTransforms(CastInst &CI);
218 Instruction *commonPointerCastTransforms(CastInst &CI);
219 Instruction *visitTrunc(TruncInst &CI);
220 Instruction *visitZExt(ZExtInst &CI);
221 Instruction *visitSExt(SExtInst &CI);
222 Instruction *visitFPTrunc(FPTruncInst &CI);
223 Instruction *visitFPExt(CastInst &CI);
224 Instruction *visitFPToUI(FPToUIInst &FI);
225 Instruction *visitFPToSI(FPToSIInst &FI);
226 Instruction *visitUIToFP(CastInst &CI);
227 Instruction *visitSIToFP(CastInst &CI);
228 Instruction *visitPtrToInt(PtrToIntInst &CI);
229 Instruction *visitIntToPtr(IntToPtrInst &CI);
230 Instruction *visitBitCast(BitCastInst &CI);
231 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
233 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
234 Instruction *visitSelectInst(SelectInst &SI);
235 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
236 Instruction *visitCallInst(CallInst &CI);
237 Instruction *visitInvokeInst(InvokeInst &II);
238 Instruction *visitPHINode(PHINode &PN);
239 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
240 Instruction *visitAllocationInst(AllocationInst &AI);
241 Instruction *visitFreeInst(FreeInst &FI);
242 Instruction *visitLoadInst(LoadInst &LI);
243 Instruction *visitStoreInst(StoreInst &SI);
244 Instruction *visitBranchInst(BranchInst &BI);
245 Instruction *visitSwitchInst(SwitchInst &SI);
246 Instruction *visitInsertElementInst(InsertElementInst &IE);
247 Instruction *visitExtractElementInst(ExtractElementInst &EI);
248 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
249 Instruction *visitExtractValueInst(ExtractValueInst &EV);
251 // visitInstruction - Specify what to return for unhandled instructions...
252 Instruction *visitInstruction(Instruction &I) { return 0; }
255 Instruction *visitCallSite(CallSite CS);
256 bool transformConstExprCastCall(CallSite CS);
257 Instruction *transformCallThroughTrampoline(CallSite CS);
258 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
259 bool DoXform = true);
260 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
261 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
265 // InsertNewInstBefore - insert an instruction New before instruction Old
266 // in the program. Add the new instruction to the worklist.
268 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
269 assert(New && New->getParent() == 0 &&
270 "New instruction already inserted into a basic block!");
271 BasicBlock *BB = Old.getParent();
272 BB->getInstList().insert(&Old, New); // Insert inst
277 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
278 /// This also adds the cast to the worklist. Finally, this returns the
280 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
282 if (V->getType() == Ty) return V;
284 if (Constant *CV = dyn_cast<Constant>(V))
285 return Context->getConstantExprCast(opc, CV, Ty);
287 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
292 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
293 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
297 // ReplaceInstUsesWith - This method is to be used when an instruction is
298 // found to be dead, replacable with another preexisting expression. Here
299 // we add all uses of I to the worklist, replace all uses of I with the new
300 // value, then return I, so that the inst combiner will know that I was
303 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
304 AddUsersToWorkList(I); // Add all modified instrs to worklist
306 I.replaceAllUsesWith(V);
309 // If we are replacing the instruction with itself, this must be in a
310 // segment of unreachable code, so just clobber the instruction.
311 I.replaceAllUsesWith(Context->getUndef(I.getType()));
316 // EraseInstFromFunction - When dealing with an instruction that has side
317 // effects or produces a void value, we can't rely on DCE to delete the
318 // instruction. Instead, visit methods should return the value returned by
320 Instruction *EraseInstFromFunction(Instruction &I) {
321 assert(I.use_empty() && "Cannot erase instruction that is used!");
322 AddUsesToWorkList(I);
323 RemoveFromWorkList(&I);
325 return 0; // Don't do anything with FI
328 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329 APInt &KnownOne, unsigned Depth = 0) const {
330 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
333 bool MaskedValueIsZero(Value *V, const APInt &Mask,
334 unsigned Depth = 0) const {
335 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338 return llvm::ComputeNumSignBits(Op, TD, Depth);
343 /// SimplifyCommutative - This performs a few simplifications for
344 /// commutative operators.
345 bool SimplifyCommutative(BinaryOperator &I);
347 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
348 /// most-complex to least-complex order.
349 bool SimplifyCompare(CmpInst &I);
351 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
352 /// based on the demanded bits.
353 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
354 APInt& KnownZero, APInt& KnownOne,
356 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
357 APInt& KnownZero, APInt& KnownOne,
360 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
361 /// SimplifyDemandedBits knows about. See if the instruction has any
362 /// properties that allow us to simplify its operands.
363 bool SimplifyDemandedInstructionBits(Instruction &Inst);
365 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
366 APInt& UndefElts, unsigned Depth = 0);
368 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369 // PHI node as operand #0, see if we can fold the instruction into the PHI
370 // (which is only possible if all operands to the PHI are constants).
371 Instruction *FoldOpIntoPhi(Instruction &I);
373 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374 // operator and they all are only used by the PHI, PHI together their
375 // inputs, and do the operation once, to the result of the PHI.
376 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
381 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382 ConstantInt *AndRHS, BinaryOperator &TheAnd);
384 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
385 bool isSub, Instruction &I);
386 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
387 bool isSigned, bool Inside, Instruction &IB);
388 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
389 Instruction *MatchBSwap(BinaryOperator &I);
390 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
391 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
392 Instruction *SimplifyMemSet(MemSetInst *MI);
395 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
397 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
398 unsigned CastOpc, int &NumCastsRemoved);
399 unsigned GetOrEnforceKnownAlignment(Value *V,
400 unsigned PrefAlign = 0);
405 char InstCombiner::ID = 0;
406 static RegisterPass<InstCombiner>
407 X("instcombine", "Combine redundant instructions");
409 // getComplexity: Assign a complexity or rank value to LLVM Values...
410 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411 static unsigned getComplexity(LLVMContext *Context, Value *V) {
412 if (isa<Instruction>(V)) {
413 if (BinaryOperator::isNeg(V) ||
414 BinaryOperator::isFNeg(V) ||
415 BinaryOperator::isNot(V))
419 if (isa<Argument>(V)) return 3;
420 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
423 // isOnlyUse - Return true if this instruction will be deleted if we stop using
425 static bool isOnlyUse(Value *V) {
426 return V->hasOneUse() || isa<Constant>(V);
429 // getPromotedType - Return the specified type promoted as it would be to pass
430 // though a va_arg area...
431 static const Type *getPromotedType(const Type *Ty) {
432 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
433 if (ITy->getBitWidth() < 32)
434 return Type::Int32Ty;
439 /// getBitCastOperand - If the specified operand is a CastInst, a constant
440 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
441 /// operand value, otherwise return null.
442 static Value *getBitCastOperand(Value *V) {
443 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
445 return I->getOperand(0);
446 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
447 // GetElementPtrInst?
448 if (GEP->hasAllZeroIndices())
449 return GEP->getOperand(0);
450 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
451 if (CE->getOpcode() == Instruction::BitCast)
452 // BitCast ConstantExp?
453 return CE->getOperand(0);
454 else if (CE->getOpcode() == Instruction::GetElementPtr) {
455 // GetElementPtr ConstantExp?
456 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
458 ConstantInt *CI = dyn_cast<ConstantInt>(I);
459 if (!CI || !CI->isZero())
460 // Any non-zero indices? Not cast-like.
463 // All-zero indices? This is just like casting.
464 return CE->getOperand(0);
470 /// This function is a wrapper around CastInst::isEliminableCastPair. It
471 /// simply extracts arguments and returns what that function returns.
472 static Instruction::CastOps
473 isEliminableCastPair(
474 const CastInst *CI, ///< The first cast instruction
475 unsigned opcode, ///< The opcode of the second cast instruction
476 const Type *DstTy, ///< The target type for the second cast instruction
477 TargetData *TD ///< The target data for pointer size
480 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
481 const Type *MidTy = CI->getType(); // B from above
483 // Get the opcodes of the two Cast instructions
484 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
485 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
487 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
488 DstTy, TD->getIntPtrType());
490 // We don't want to form an inttoptr or ptrtoint that converts to an integer
491 // type that differs from the pointer size.
492 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
493 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
496 return Instruction::CastOps(Res);
499 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
500 /// in any code being generated. It does not require codegen if V is simple
501 /// enough or if the cast can be folded into other casts.
502 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
503 const Type *Ty, TargetData *TD) {
504 if (V->getType() == Ty || isa<Constant>(V)) return false;
506 // If this is another cast that can be eliminated, it isn't codegen either.
507 if (const CastInst *CI = dyn_cast<CastInst>(V))
508 if (isEliminableCastPair(CI, opcode, Ty, TD))
513 // SimplifyCommutative - This performs a few simplifications for commutative
516 // 1. Order operands such that they are listed from right (least complex) to
517 // left (most complex). This puts constants before unary operators before
520 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
521 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
523 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
524 bool Changed = false;
525 if (getComplexity(Context, I.getOperand(0)) <
526 getComplexity(Context, I.getOperand(1)))
527 Changed = !I.swapOperands();
529 if (!I.isAssociative()) return Changed;
530 Instruction::BinaryOps Opcode = I.getOpcode();
531 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
532 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
533 if (isa<Constant>(I.getOperand(1))) {
534 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
535 cast<Constant>(I.getOperand(1)),
536 cast<Constant>(Op->getOperand(1)));
537 I.setOperand(0, Op->getOperand(0));
538 I.setOperand(1, Folded);
540 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
541 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
542 isOnlyUse(Op) && isOnlyUse(Op1)) {
543 Constant *C1 = cast<Constant>(Op->getOperand(1));
544 Constant *C2 = cast<Constant>(Op1->getOperand(1));
546 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
547 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
548 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
552 I.setOperand(0, New);
553 I.setOperand(1, Folded);
560 /// SimplifyCompare - For a CmpInst this function just orders the operands
561 /// so that theyare listed from right (least complex) to left (most complex).
562 /// This puts constants before unary operators before binary operators.
563 bool InstCombiner::SimplifyCompare(CmpInst &I) {
564 if (getComplexity(Context, I.getOperand(0)) >=
565 getComplexity(Context, I.getOperand(1)))
568 // Compare instructions are not associative so there's nothing else we can do.
572 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
573 // if the LHS is a constant zero (which is the 'negate' form).
575 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
576 if (BinaryOperator::isNeg(V))
577 return BinaryOperator::getNegArgument(V);
579 // Constants can be considered to be negated values if they can be folded.
580 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
581 return Context->getConstantExprNeg(C);
583 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
584 if (C->getType()->getElementType()->isInteger())
585 return Context->getConstantExprNeg(C);
590 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
591 // instruction if the LHS is a constant negative zero (which is the 'negate'
594 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
595 if (BinaryOperator::isFNeg(V))
596 return BinaryOperator::getFNegArgument(V);
598 // Constants can be considered to be negated values if they can be folded.
599 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
600 return Context->getConstantExprFNeg(C);
602 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
603 if (C->getType()->getElementType()->isFloatingPoint())
604 return Context->getConstantExprFNeg(C);
609 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
610 if (BinaryOperator::isNot(V))
611 return BinaryOperator::getNotArgument(V);
613 // Constants can be considered to be not'ed values...
614 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
615 return Context->getConstantInt(~C->getValue());
619 // dyn_castFoldableMul - If this value is a multiply that can be folded into
620 // other computations (because it has a constant operand), return the
621 // non-constant operand of the multiply, and set CST to point to the multiplier.
622 // Otherwise, return null.
624 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
625 LLVMContext *Context) {
626 if (V->hasOneUse() && V->getType()->isInteger())
627 if (Instruction *I = dyn_cast<Instruction>(V)) {
628 if (I->getOpcode() == Instruction::Mul)
629 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
630 return I->getOperand(0);
631 if (I->getOpcode() == Instruction::Shl)
632 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
633 // The multiplier is really 1 << CST.
634 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
635 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
636 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
637 return I->getOperand(0);
643 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
644 /// expression, return it.
645 static User *dyn_castGetElementPtr(Value *V) {
646 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
647 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
648 if (CE->getOpcode() == Instruction::GetElementPtr)
649 return cast<User>(V);
653 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
654 /// opcode value. Otherwise return UserOp1.
655 static unsigned getOpcode(const Value *V) {
656 if (const Instruction *I = dyn_cast<Instruction>(V))
657 return I->getOpcode();
658 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
659 return CE->getOpcode();
660 // Use UserOp1 to mean there's no opcode.
661 return Instruction::UserOp1;
664 /// AddOne - Add one to a ConstantInt
665 static Constant *AddOne(Constant *C, LLVMContext *Context) {
666 return Context->getConstantExprAdd(C,
667 Context->getConstantInt(C->getType(), 1));
669 /// SubOne - Subtract one from a ConstantInt
670 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
671 return Context->getConstantExprSub(C,
672 Context->getConstantInt(C->getType(), 1));
674 /// MultiplyOverflows - True if the multiply can not be expressed in an int
676 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
677 LLVMContext *Context) {
678 uint32_t W = C1->getBitWidth();
679 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
688 APInt MulExt = LHSExt * RHSExt;
691 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
692 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
693 return MulExt.slt(Min) || MulExt.sgt(Max);
695 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
699 /// ShrinkDemandedConstant - Check to see if the specified operand of the
700 /// specified instruction is a constant integer. If so, check to see if there
701 /// are any bits set in the constant that are not demanded. If so, shrink the
702 /// constant and return true.
703 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
704 APInt Demanded, LLVMContext *Context) {
705 assert(I && "No instruction?");
706 assert(OpNo < I->getNumOperands() && "Operand index too large");
708 // If the operand is not a constant integer, nothing to do.
709 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
710 if (!OpC) return false;
712 // If there are no bits set that aren't demanded, nothing to do.
713 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
714 if ((~Demanded & OpC->getValue()) == 0)
717 // This instruction is producing bits that are not demanded. Shrink the RHS.
718 Demanded &= OpC->getValue();
719 I->setOperand(OpNo, Context->getConstantInt(Demanded));
723 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
724 // set of known zero and one bits, compute the maximum and minimum values that
725 // could have the specified known zero and known one bits, returning them in
727 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
728 const APInt& KnownOne,
729 APInt& Min, APInt& Max) {
730 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
731 KnownZero.getBitWidth() == Min.getBitWidth() &&
732 KnownZero.getBitWidth() == Max.getBitWidth() &&
733 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
734 APInt UnknownBits = ~(KnownZero|KnownOne);
736 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
737 // bit if it is unknown.
739 Max = KnownOne|UnknownBits;
741 if (UnknownBits.isNegative()) { // Sign bit is unknown
742 Min.set(Min.getBitWidth()-1);
743 Max.clear(Max.getBitWidth()-1);
747 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
748 // a set of known zero and one bits, compute the maximum and minimum values that
749 // could have the specified known zero and known one bits, returning them in
751 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
752 const APInt &KnownOne,
753 APInt &Min, APInt &Max) {
754 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
755 KnownZero.getBitWidth() == Min.getBitWidth() &&
756 KnownZero.getBitWidth() == Max.getBitWidth() &&
757 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
758 APInt UnknownBits = ~(KnownZero|KnownOne);
760 // The minimum value is when the unknown bits are all zeros.
762 // The maximum value is when the unknown bits are all ones.
763 Max = KnownOne|UnknownBits;
766 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
767 /// SimplifyDemandedBits knows about. See if the instruction has any
768 /// properties that allow us to simplify its operands.
769 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
770 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
771 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
772 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
774 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
775 KnownZero, KnownOne, 0);
776 if (V == 0) return false;
777 if (V == &Inst) return true;
778 ReplaceInstUsesWith(Inst, V);
782 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
783 /// specified instruction operand if possible, updating it in place. It returns
784 /// true if it made any change and false otherwise.
785 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
786 APInt &KnownZero, APInt &KnownOne,
788 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
789 KnownZero, KnownOne, Depth);
790 if (NewVal == 0) return false;
796 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
797 /// value based on the demanded bits. When this function is called, it is known
798 /// that only the bits set in DemandedMask of the result of V are ever used
799 /// downstream. Consequently, depending on the mask and V, it may be possible
800 /// to replace V with a constant or one of its operands. In such cases, this
801 /// function does the replacement and returns true. In all other cases, it
802 /// returns false after analyzing the expression and setting KnownOne and known
803 /// to be one in the expression. KnownZero contains all the bits that are known
804 /// to be zero in the expression. These are provided to potentially allow the
805 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
806 /// the expression. KnownOne and KnownZero always follow the invariant that
807 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
808 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
809 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
810 /// and KnownOne must all be the same.
812 /// This returns null if it did not change anything and it permits no
813 /// simplification. This returns V itself if it did some simplification of V's
814 /// operands based on the information about what bits are demanded. This returns
815 /// some other non-null value if it found out that V is equal to another value
816 /// in the context where the specified bits are demanded, but not for all users.
817 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
818 APInt &KnownZero, APInt &KnownOne,
820 assert(V != 0 && "Null pointer of Value???");
821 assert(Depth <= 6 && "Limit Search Depth");
822 uint32_t BitWidth = DemandedMask.getBitWidth();
823 const Type *VTy = V->getType();
824 assert((TD || !isa<PointerType>(VTy)) &&
825 "SimplifyDemandedBits needs to know bit widths!");
826 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
827 (!VTy->isIntOrIntVector() ||
828 VTy->getScalarSizeInBits() == BitWidth) &&
829 KnownZero.getBitWidth() == BitWidth &&
830 KnownOne.getBitWidth() == BitWidth &&
831 "Value *V, DemandedMask, KnownZero and KnownOne "
832 "must have same BitWidth");
833 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
834 // We know all of the bits for a constant!
835 KnownOne = CI->getValue() & DemandedMask;
836 KnownZero = ~KnownOne & DemandedMask;
839 if (isa<ConstantPointerNull>(V)) {
840 // We know all of the bits for a constant!
842 KnownZero = DemandedMask;
848 if (DemandedMask == 0) { // Not demanding any bits from V.
849 if (isa<UndefValue>(V))
851 return Context->getUndef(VTy);
854 if (Depth == 6) // Limit search depth.
857 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
858 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
860 Instruction *I = dyn_cast<Instruction>(V);
862 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
863 return 0; // Only analyze instructions.
866 // If there are multiple uses of this value and we aren't at the root, then
867 // we can't do any simplifications of the operands, because DemandedMask
868 // only reflects the bits demanded by *one* of the users.
869 if (Depth != 0 && !I->hasOneUse()) {
870 // Despite the fact that we can't simplify this instruction in all User's
871 // context, we can at least compute the knownzero/knownone bits, and we can
872 // do simplifications that apply to *just* the one user if we know that
873 // this instruction has a simpler value in that context.
874 if (I->getOpcode() == Instruction::And) {
875 // If either the LHS or the RHS are Zero, the result is zero.
876 ComputeMaskedBits(I->getOperand(1), DemandedMask,
877 RHSKnownZero, RHSKnownOne, Depth+1);
878 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
879 LHSKnownZero, LHSKnownOne, Depth+1);
881 // If all of the demanded bits are known 1 on one side, return the other.
882 // These bits cannot contribute to the result of the 'and' in this
884 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
885 (DemandedMask & ~LHSKnownZero))
886 return I->getOperand(0);
887 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
888 (DemandedMask & ~RHSKnownZero))
889 return I->getOperand(1);
891 // If all of the demanded bits in the inputs are known zeros, return zero.
892 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
893 return Context->getNullValue(VTy);
895 } else if (I->getOpcode() == Instruction::Or) {
896 // We can simplify (X|Y) -> X or Y in the user's context if we know that
897 // only bits from X or Y are demanded.
899 // If either the LHS or the RHS are One, the result is One.
900 ComputeMaskedBits(I->getOperand(1), DemandedMask,
901 RHSKnownZero, RHSKnownOne, Depth+1);
902 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
903 LHSKnownZero, LHSKnownOne, Depth+1);
905 // If all of the demanded bits are known zero on one side, return the
906 // other. These bits cannot contribute to the result of the 'or' in this
908 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
909 (DemandedMask & ~LHSKnownOne))
910 return I->getOperand(0);
911 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
912 (DemandedMask & ~RHSKnownOne))
913 return I->getOperand(1);
915 // If all of the potentially set bits on one side are known to be set on
916 // the other side, just use the 'other' side.
917 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
918 (DemandedMask & (~RHSKnownZero)))
919 return I->getOperand(0);
920 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
921 (DemandedMask & (~LHSKnownZero)))
922 return I->getOperand(1);
925 // Compute the KnownZero/KnownOne bits to simplify things downstream.
926 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
930 // If this is the root being simplified, allow it to have multiple uses,
931 // just set the DemandedMask to all bits so that we can try to simplify the
932 // operands. This allows visitTruncInst (for example) to simplify the
933 // operand of a trunc without duplicating all the logic below.
934 if (Depth == 0 && !V->hasOneUse())
935 DemandedMask = APInt::getAllOnesValue(BitWidth);
937 switch (I->getOpcode()) {
939 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
941 case Instruction::And:
942 // If either the LHS or the RHS are Zero, the result is zero.
943 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
944 RHSKnownZero, RHSKnownOne, Depth+1) ||
945 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
946 LHSKnownZero, LHSKnownOne, Depth+1))
948 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
949 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
951 // If all of the demanded bits are known 1 on one side, return the other.
952 // These bits cannot contribute to the result of the 'and'.
953 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
954 (DemandedMask & ~LHSKnownZero))
955 return I->getOperand(0);
956 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
957 (DemandedMask & ~RHSKnownZero))
958 return I->getOperand(1);
960 // If all of the demanded bits in the inputs are known zeros, return zero.
961 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
962 return Context->getNullValue(VTy);
964 // If the RHS is a constant, see if we can simplify it.
965 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
968 // Output known-1 bits are only known if set in both the LHS & RHS.
969 RHSKnownOne &= LHSKnownOne;
970 // Output known-0 are known to be clear if zero in either the LHS | RHS.
971 RHSKnownZero |= LHSKnownZero;
973 case Instruction::Or:
974 // If either the LHS or the RHS are One, the result is One.
975 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
976 RHSKnownZero, RHSKnownOne, Depth+1) ||
977 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
978 LHSKnownZero, LHSKnownOne, Depth+1))
980 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
981 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
983 // If all of the demanded bits are known zero on one side, return the other.
984 // These bits cannot contribute to the result of the 'or'.
985 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
986 (DemandedMask & ~LHSKnownOne))
987 return I->getOperand(0);
988 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
989 (DemandedMask & ~RHSKnownOne))
990 return I->getOperand(1);
992 // If all of the potentially set bits on one side are known to be set on
993 // the other side, just use the 'other' side.
994 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
995 (DemandedMask & (~RHSKnownZero)))
996 return I->getOperand(0);
997 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
998 (DemandedMask & (~LHSKnownZero)))
999 return I->getOperand(1);
1001 // If the RHS is a constant, see if we can simplify it.
1002 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1005 // Output known-0 bits are only known if clear in both the LHS & RHS.
1006 RHSKnownZero &= LHSKnownZero;
1007 // Output known-1 are known to be set if set in either the LHS | RHS.
1008 RHSKnownOne |= LHSKnownOne;
1010 case Instruction::Xor: {
1011 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1012 RHSKnownZero, RHSKnownOne, Depth+1) ||
1013 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1014 LHSKnownZero, LHSKnownOne, Depth+1))
1016 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1017 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1019 // If all of the demanded bits are known zero on one side, return the other.
1020 // These bits cannot contribute to the result of the 'xor'.
1021 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1022 return I->getOperand(0);
1023 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1024 return I->getOperand(1);
1026 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1027 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1028 (RHSKnownOne & LHSKnownOne);
1029 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1030 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1031 (RHSKnownOne & LHSKnownZero);
1033 // If all of the demanded bits are known to be zero on one side or the
1034 // other, turn this into an *inclusive* or.
1035 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1036 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1038 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1040 return InsertNewInstBefore(Or, *I);
1043 // If all of the demanded bits on one side are known, and all of the set
1044 // bits on that side are also known to be set on the other side, turn this
1045 // into an AND, as we know the bits will be cleared.
1046 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1047 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1049 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1050 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1052 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1053 return InsertNewInstBefore(And, *I);
1057 // If the RHS is a constant, see if we can simplify it.
1058 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1059 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1062 RHSKnownZero = KnownZeroOut;
1063 RHSKnownOne = KnownOneOut;
1066 case Instruction::Select:
1067 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1068 RHSKnownZero, RHSKnownOne, Depth+1) ||
1069 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1070 LHSKnownZero, LHSKnownOne, Depth+1))
1072 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1073 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1075 // If the operands are constants, see if we can simplify them.
1076 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1077 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1080 // Only known if known in both the LHS and RHS.
1081 RHSKnownOne &= LHSKnownOne;
1082 RHSKnownZero &= LHSKnownZero;
1084 case Instruction::Trunc: {
1085 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1086 DemandedMask.zext(truncBf);
1087 RHSKnownZero.zext(truncBf);
1088 RHSKnownOne.zext(truncBf);
1089 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1090 RHSKnownZero, RHSKnownOne, Depth+1))
1092 DemandedMask.trunc(BitWidth);
1093 RHSKnownZero.trunc(BitWidth);
1094 RHSKnownOne.trunc(BitWidth);
1095 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1098 case Instruction::BitCast:
1099 if (!I->getOperand(0)->getType()->isIntOrIntVector())
1100 return false; // vector->int or fp->int?
1102 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1103 if (const VectorType *SrcVTy =
1104 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1105 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1106 // Don't touch a bitcast between vectors of different element counts.
1109 // Don't touch a scalar-to-vector bitcast.
1111 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1112 // Don't touch a vector-to-scalar bitcast.
1115 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1116 RHSKnownZero, RHSKnownOne, Depth+1))
1118 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1120 case Instruction::ZExt: {
1121 // Compute the bits in the result that are not present in the input.
1122 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1124 DemandedMask.trunc(SrcBitWidth);
1125 RHSKnownZero.trunc(SrcBitWidth);
1126 RHSKnownOne.trunc(SrcBitWidth);
1127 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1128 RHSKnownZero, RHSKnownOne, Depth+1))
1130 DemandedMask.zext(BitWidth);
1131 RHSKnownZero.zext(BitWidth);
1132 RHSKnownOne.zext(BitWidth);
1133 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1134 // The top bits are known to be zero.
1135 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1138 case Instruction::SExt: {
1139 // Compute the bits in the result that are not present in the input.
1140 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1142 APInt InputDemandedBits = DemandedMask &
1143 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1145 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1146 // If any of the sign extended bits are demanded, we know that the sign
1148 if ((NewBits & DemandedMask) != 0)
1149 InputDemandedBits.set(SrcBitWidth-1);
1151 InputDemandedBits.trunc(SrcBitWidth);
1152 RHSKnownZero.trunc(SrcBitWidth);
1153 RHSKnownOne.trunc(SrcBitWidth);
1154 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1155 RHSKnownZero, RHSKnownOne, Depth+1))
1157 InputDemandedBits.zext(BitWidth);
1158 RHSKnownZero.zext(BitWidth);
1159 RHSKnownOne.zext(BitWidth);
1160 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1162 // If the sign bit of the input is known set or clear, then we know the
1163 // top bits of the result.
1165 // If the input sign bit is known zero, or if the NewBits are not demanded
1166 // convert this into a zero extension.
1167 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1168 // Convert to ZExt cast
1169 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1170 return InsertNewInstBefore(NewCast, *I);
1171 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1172 RHSKnownOne |= NewBits;
1176 case Instruction::Add: {
1177 // Figure out what the input bits are. If the top bits of the and result
1178 // are not demanded, then the add doesn't demand them from its input
1180 unsigned NLZ = DemandedMask.countLeadingZeros();
1182 // If there is a constant on the RHS, there are a variety of xformations
1184 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185 // If null, this should be simplified elsewhere. Some of the xforms here
1186 // won't work if the RHS is zero.
1190 // If the top bit of the output is demanded, demand everything from the
1191 // input. Otherwise, we demand all the input bits except NLZ top bits.
1192 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1194 // Find information about known zero/one bits in the input.
1195 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1196 LHSKnownZero, LHSKnownOne, Depth+1))
1199 // If the RHS of the add has bits set that can't affect the input, reduce
1201 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1204 // Avoid excess work.
1205 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1208 // Turn it into OR if input bits are zero.
1209 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1211 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1213 return InsertNewInstBefore(Or, *I);
1216 // We can say something about the output known-zero and known-one bits,
1217 // depending on potential carries from the input constant and the
1218 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1219 // bits set and the RHS constant is 0x01001, then we know we have a known
1220 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1222 // To compute this, we first compute the potential carry bits. These are
1223 // the bits which may be modified. I'm not aware of a better way to do
1225 const APInt &RHSVal = RHS->getValue();
1226 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1228 // Now that we know which bits have carries, compute the known-1/0 sets.
1230 // Bits are known one if they are known zero in one operand and one in the
1231 // other, and there is no input carry.
1232 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1233 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1235 // Bits are known zero if they are known zero in both operands and there
1236 // is no input carry.
1237 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1239 // If the high-bits of this ADD are not demanded, then it does not demand
1240 // the high bits of its LHS or RHS.
1241 if (DemandedMask[BitWidth-1] == 0) {
1242 // Right fill the mask of bits for this ADD to demand the most
1243 // significant bit and all those below it.
1244 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1245 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1246 LHSKnownZero, LHSKnownOne, Depth+1) ||
1247 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1248 LHSKnownZero, LHSKnownOne, Depth+1))
1254 case Instruction::Sub:
1255 // If the high-bits of this SUB are not demanded, then it does not demand
1256 // the high bits of its LHS or RHS.
1257 if (DemandedMask[BitWidth-1] == 0) {
1258 // Right fill the mask of bits for this SUB to demand the most
1259 // significant bit and all those below it.
1260 uint32_t NLZ = DemandedMask.countLeadingZeros();
1261 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1262 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1263 LHSKnownZero, LHSKnownOne, Depth+1) ||
1264 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1265 LHSKnownZero, LHSKnownOne, Depth+1))
1268 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1269 // the known zeros and ones.
1270 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1272 case Instruction::Shl:
1273 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1274 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1275 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1276 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1277 RHSKnownZero, RHSKnownOne, Depth+1))
1279 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1280 RHSKnownZero <<= ShiftAmt;
1281 RHSKnownOne <<= ShiftAmt;
1282 // low bits known zero.
1284 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1287 case Instruction::LShr:
1288 // For a logical shift right
1289 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1290 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1292 // Unsigned shift right.
1293 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1294 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1295 RHSKnownZero, RHSKnownOne, Depth+1))
1297 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1298 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1299 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1301 // Compute the new bits that are at the top now.
1302 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1303 RHSKnownZero |= HighBits; // high bits known zero.
1307 case Instruction::AShr:
1308 // If this is an arithmetic shift right and only the low-bit is set, we can
1309 // always convert this into a logical shr, even if the shift amount is
1310 // variable. The low bit of the shift cannot be an input sign bit unless
1311 // the shift amount is >= the size of the datatype, which is undefined.
1312 if (DemandedMask == 1) {
1313 // Perform the logical shift right.
1314 Instruction *NewVal = BinaryOperator::CreateLShr(
1315 I->getOperand(0), I->getOperand(1), I->getName());
1316 return InsertNewInstBefore(NewVal, *I);
1319 // If the sign bit is the only bit demanded by this ashr, then there is no
1320 // need to do it, the shift doesn't change the high bit.
1321 if (DemandedMask.isSignBit())
1322 return I->getOperand(0);
1324 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1325 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1327 // Signed shift right.
1328 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1329 // If any of the "high bits" are demanded, we should set the sign bit as
1331 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1332 DemandedMaskIn.set(BitWidth-1);
1333 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1334 RHSKnownZero, RHSKnownOne, Depth+1))
1336 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1337 // Compute the new bits that are at the top now.
1338 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1339 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1340 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1342 // Handle the sign bits.
1343 APInt SignBit(APInt::getSignBit(BitWidth));
1344 // Adjust to where it is now in the mask.
1345 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1347 // If the input sign bit is known to be zero, or if none of the top bits
1348 // are demanded, turn this into an unsigned shift right.
1349 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1350 (HighBits & ~DemandedMask) == HighBits) {
1351 // Perform the logical shift right.
1352 Instruction *NewVal = BinaryOperator::CreateLShr(
1353 I->getOperand(0), SA, I->getName());
1354 return InsertNewInstBefore(NewVal, *I);
1355 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1356 RHSKnownOne |= HighBits;
1360 case Instruction::SRem:
1361 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1362 APInt RA = Rem->getValue().abs();
1363 if (RA.isPowerOf2()) {
1364 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
1365 return I->getOperand(0);
1367 APInt LowBits = RA - 1;
1368 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1369 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1370 LHSKnownZero, LHSKnownOne, Depth+1))
1373 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1374 LHSKnownZero |= ~LowBits;
1376 KnownZero |= LHSKnownZero & DemandedMask;
1378 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
1382 case Instruction::URem: {
1383 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1384 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1385 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1386 KnownZero2, KnownOne2, Depth+1) ||
1387 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1388 KnownZero2, KnownOne2, Depth+1))
1391 unsigned Leaders = KnownZero2.countLeadingOnes();
1392 Leaders = std::max(Leaders,
1393 KnownZero2.countLeadingOnes());
1394 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1397 case Instruction::Call:
1398 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1399 switch (II->getIntrinsicID()) {
1401 case Intrinsic::bswap: {
1402 // If the only bits demanded come from one byte of the bswap result,
1403 // just shift the input byte into position to eliminate the bswap.
1404 unsigned NLZ = DemandedMask.countLeadingZeros();
1405 unsigned NTZ = DemandedMask.countTrailingZeros();
1407 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1408 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1409 // have 14 leading zeros, round to 8.
1412 // If we need exactly one byte, we can do this transformation.
1413 if (BitWidth-NLZ-NTZ == 8) {
1414 unsigned ResultBit = NTZ;
1415 unsigned InputBit = BitWidth-NTZ-8;
1417 // Replace this with either a left or right shift to get the byte into
1419 Instruction *NewVal;
1420 if (InputBit > ResultBit)
1421 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1422 Context->getConstantInt(I->getType(), InputBit-ResultBit));
1424 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1425 Context->getConstantInt(I->getType(), ResultBit-InputBit));
1426 NewVal->takeName(I);
1427 return InsertNewInstBefore(NewVal, *I);
1430 // TODO: Could compute known zero/one bits based on the input.
1435 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1439 // If the client is only demanding bits that we know, return the known
1441 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1442 Constant *C = Context->getConstantInt(RHSKnownOne);
1443 if (isa<PointerType>(V->getType()))
1444 C = Context->getConstantExprIntToPtr(C, V->getType());
1451 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1452 /// any number of elements. DemandedElts contains the set of elements that are
1453 /// actually used by the caller. This method analyzes which elements of the
1454 /// operand are undef and returns that information in UndefElts.
1456 /// If the information about demanded elements can be used to simplify the
1457 /// operation, the operation is simplified, then the resultant value is
1458 /// returned. This returns null if no change was made.
1459 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1462 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1463 APInt EltMask(APInt::getAllOnesValue(VWidth));
1464 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1466 if (isa<UndefValue>(V)) {
1467 // If the entire vector is undefined, just return this info.
1468 UndefElts = EltMask;
1470 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1471 UndefElts = EltMask;
1472 return Context->getUndef(V->getType());
1476 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1477 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1478 Constant *Undef = Context->getUndef(EltTy);
1480 std::vector<Constant*> Elts;
1481 for (unsigned i = 0; i != VWidth; ++i)
1482 if (!DemandedElts[i]) { // If not demanded, set to undef.
1483 Elts.push_back(Undef);
1485 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1486 Elts.push_back(Undef);
1488 } else { // Otherwise, defined.
1489 Elts.push_back(CP->getOperand(i));
1492 // If we changed the constant, return it.
1493 Constant *NewCP = Context->getConstantVector(Elts);
1494 return NewCP != CP ? NewCP : 0;
1495 } else if (isa<ConstantAggregateZero>(V)) {
1496 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1499 // Check if this is identity. If so, return 0 since we are not simplifying
1501 if (DemandedElts == ((1ULL << VWidth) -1))
1504 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1505 Constant *Zero = Context->getNullValue(EltTy);
1506 Constant *Undef = Context->getUndef(EltTy);
1507 std::vector<Constant*> Elts;
1508 for (unsigned i = 0; i != VWidth; ++i) {
1509 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1510 Elts.push_back(Elt);
1512 UndefElts = DemandedElts ^ EltMask;
1513 return Context->getConstantVector(Elts);
1516 // Limit search depth.
1520 // If multiple users are using the root value, procede with
1521 // simplification conservatively assuming that all elements
1523 if (!V->hasOneUse()) {
1524 // Quit if we find multiple users of a non-root value though.
1525 // They'll be handled when it's their turn to be visited by
1526 // the main instcombine process.
1528 // TODO: Just compute the UndefElts information recursively.
1531 // Conservatively assume that all elements are needed.
1532 DemandedElts = EltMask;
1535 Instruction *I = dyn_cast<Instruction>(V);
1536 if (!I) return 0; // Only analyze instructions.
1538 bool MadeChange = false;
1539 APInt UndefElts2(VWidth, 0);
1541 switch (I->getOpcode()) {
1544 case Instruction::InsertElement: {
1545 // If this is a variable index, we don't know which element it overwrites.
1546 // demand exactly the same input as we produce.
1547 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1549 // Note that we can't propagate undef elt info, because we don't know
1550 // which elt is getting updated.
1551 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1552 UndefElts2, Depth+1);
1553 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1557 // If this is inserting an element that isn't demanded, remove this
1559 unsigned IdxNo = Idx->getZExtValue();
1560 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1561 return AddSoonDeadInstToWorklist(*I, 0);
1563 // Otherwise, the element inserted overwrites whatever was there, so the
1564 // input demanded set is simpler than the output set.
1565 APInt DemandedElts2 = DemandedElts;
1566 DemandedElts2.clear(IdxNo);
1567 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1568 UndefElts, Depth+1);
1569 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1571 // The inserted element is defined.
1572 UndefElts.clear(IdxNo);
1575 case Instruction::ShuffleVector: {
1576 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1577 uint64_t LHSVWidth =
1578 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1579 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1580 for (unsigned i = 0; i < VWidth; i++) {
1581 if (DemandedElts[i]) {
1582 unsigned MaskVal = Shuffle->getMaskValue(i);
1583 if (MaskVal != -1u) {
1584 assert(MaskVal < LHSVWidth * 2 &&
1585 "shufflevector mask index out of range!");
1586 if (MaskVal < LHSVWidth)
1587 LeftDemanded.set(MaskVal);
1589 RightDemanded.set(MaskVal - LHSVWidth);
1594 APInt UndefElts4(LHSVWidth, 0);
1595 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1596 UndefElts4, Depth+1);
1597 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1599 APInt UndefElts3(LHSVWidth, 0);
1600 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1601 UndefElts3, Depth+1);
1602 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1604 bool NewUndefElts = false;
1605 for (unsigned i = 0; i < VWidth; i++) {
1606 unsigned MaskVal = Shuffle->getMaskValue(i);
1607 if (MaskVal == -1u) {
1609 } else if (MaskVal < LHSVWidth) {
1610 if (UndefElts4[MaskVal]) {
1611 NewUndefElts = true;
1615 if (UndefElts3[MaskVal - LHSVWidth]) {
1616 NewUndefElts = true;
1623 // Add additional discovered undefs.
1624 std::vector<Constant*> Elts;
1625 for (unsigned i = 0; i < VWidth; ++i) {
1627 Elts.push_back(Context->getUndef(Type::Int32Ty));
1629 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1630 Shuffle->getMaskValue(i)));
1632 I->setOperand(2, Context->getConstantVector(Elts));
1637 case Instruction::BitCast: {
1638 // Vector->vector casts only.
1639 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1641 unsigned InVWidth = VTy->getNumElements();
1642 APInt InputDemandedElts(InVWidth, 0);
1645 if (VWidth == InVWidth) {
1646 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1647 // elements as are demanded of us.
1649 InputDemandedElts = DemandedElts;
1650 } else if (VWidth > InVWidth) {
1654 // If there are more elements in the result than there are in the source,
1655 // then an input element is live if any of the corresponding output
1656 // elements are live.
1657 Ratio = VWidth/InVWidth;
1658 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1659 if (DemandedElts[OutIdx])
1660 InputDemandedElts.set(OutIdx/Ratio);
1666 // If there are more elements in the source than there are in the result,
1667 // then an input element is live if the corresponding output element is
1669 Ratio = InVWidth/VWidth;
1670 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1671 if (DemandedElts[InIdx/Ratio])
1672 InputDemandedElts.set(InIdx);
1675 // div/rem demand all inputs, because they don't want divide by zero.
1676 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1677 UndefElts2, Depth+1);
1679 I->setOperand(0, TmpV);
1683 UndefElts = UndefElts2;
1684 if (VWidth > InVWidth) {
1685 llvm_unreachable("Unimp");
1686 // If there are more elements in the result than there are in the source,
1687 // then an output element is undef if the corresponding input element is
1689 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1690 if (UndefElts2[OutIdx/Ratio])
1691 UndefElts.set(OutIdx);
1692 } else if (VWidth < InVWidth) {
1693 llvm_unreachable("Unimp");
1694 // If there are more elements in the source than there are in the result,
1695 // then a result element is undef if all of the corresponding input
1696 // elements are undef.
1697 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1698 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1699 if (!UndefElts2[InIdx]) // Not undef?
1700 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
1704 case Instruction::And:
1705 case Instruction::Or:
1706 case Instruction::Xor:
1707 case Instruction::Add:
1708 case Instruction::Sub:
1709 case Instruction::Mul:
1710 // div/rem demand all inputs, because they don't want divide by zero.
1711 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1712 UndefElts, Depth+1);
1713 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1714 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1715 UndefElts2, Depth+1);
1716 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1718 // Output elements are undefined if both are undefined. Consider things
1719 // like undef&0. The result is known zero, not undef.
1720 UndefElts &= UndefElts2;
1723 case Instruction::Call: {
1724 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1726 switch (II->getIntrinsicID()) {
1729 // Binary vector operations that work column-wise. A dest element is a
1730 // function of the corresponding input elements from the two inputs.
1731 case Intrinsic::x86_sse_sub_ss:
1732 case Intrinsic::x86_sse_mul_ss:
1733 case Intrinsic::x86_sse_min_ss:
1734 case Intrinsic::x86_sse_max_ss:
1735 case Intrinsic::x86_sse2_sub_sd:
1736 case Intrinsic::x86_sse2_mul_sd:
1737 case Intrinsic::x86_sse2_min_sd:
1738 case Intrinsic::x86_sse2_max_sd:
1739 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1740 UndefElts, Depth+1);
1741 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1742 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1743 UndefElts2, Depth+1);
1744 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1746 // If only the low elt is demanded and this is a scalarizable intrinsic,
1747 // scalarize it now.
1748 if (DemandedElts == 1) {
1749 switch (II->getIntrinsicID()) {
1751 case Intrinsic::x86_sse_sub_ss:
1752 case Intrinsic::x86_sse_mul_ss:
1753 case Intrinsic::x86_sse2_sub_sd:
1754 case Intrinsic::x86_sse2_mul_sd:
1755 // TODO: Lower MIN/MAX/ABS/etc
1756 Value *LHS = II->getOperand(1);
1757 Value *RHS = II->getOperand(2);
1758 // Extract the element as scalars.
1759 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1760 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1762 switch (II->getIntrinsicID()) {
1763 default: llvm_unreachable("Case stmts out of sync!");
1764 case Intrinsic::x86_sse_sub_ss:
1765 case Intrinsic::x86_sse2_sub_sd:
1766 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1767 II->getName()), *II);
1769 case Intrinsic::x86_sse_mul_ss:
1770 case Intrinsic::x86_sse2_mul_sd:
1771 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1772 II->getName()), *II);
1777 InsertElementInst::Create(
1778 Context->getUndef(II->getType()), TmpV, 0U, II->getName());
1779 InsertNewInstBefore(New, *II);
1780 AddSoonDeadInstToWorklist(*II, 0);
1785 // Output elements are undefined if both are undefined. Consider things
1786 // like undef&0. The result is known zero, not undef.
1787 UndefElts &= UndefElts2;
1793 return MadeChange ? I : 0;
1797 /// AssociativeOpt - Perform an optimization on an associative operator. This
1798 /// function is designed to check a chain of associative operators for a
1799 /// potential to apply a certain optimization. Since the optimization may be
1800 /// applicable if the expression was reassociated, this checks the chain, then
1801 /// reassociates the expression as necessary to expose the optimization
1802 /// opportunity. This makes use of a special Functor, which must define
1803 /// 'shouldApply' and 'apply' methods.
1805 template<typename Functor>
1806 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1807 LLVMContext *Context) {
1808 unsigned Opcode = Root.getOpcode();
1809 Value *LHS = Root.getOperand(0);
1811 // Quick check, see if the immediate LHS matches...
1812 if (F.shouldApply(LHS))
1813 return F.apply(Root);
1815 // Otherwise, if the LHS is not of the same opcode as the root, return.
1816 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1817 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1818 // Should we apply this transform to the RHS?
1819 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1821 // If not to the RHS, check to see if we should apply to the LHS...
1822 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1823 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1827 // If the functor wants to apply the optimization to the RHS of LHSI,
1828 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1830 // Now all of the instructions are in the current basic block, go ahead
1831 // and perform the reassociation.
1832 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1834 // First move the selected RHS to the LHS of the root...
1835 Root.setOperand(0, LHSI->getOperand(1));
1837 // Make what used to be the LHS of the root be the user of the root...
1838 Value *ExtraOperand = TmpLHSI->getOperand(1);
1839 if (&Root == TmpLHSI) {
1840 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1843 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1844 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1845 BasicBlock::iterator ARI = &Root; ++ARI;
1846 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1849 // Now propagate the ExtraOperand down the chain of instructions until we
1851 while (TmpLHSI != LHSI) {
1852 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1853 // Move the instruction to immediately before the chain we are
1854 // constructing to avoid breaking dominance properties.
1855 NextLHSI->moveBefore(ARI);
1858 Value *NextOp = NextLHSI->getOperand(1);
1859 NextLHSI->setOperand(1, ExtraOperand);
1861 ExtraOperand = NextOp;
1864 // Now that the instructions are reassociated, have the functor perform
1865 // the transformation...
1866 return F.apply(Root);
1869 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1876 // AddRHS - Implements: X + X --> X << 1
1879 LLVMContext *Context;
1880 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1881 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1882 Instruction *apply(BinaryOperator &Add) const {
1883 return BinaryOperator::CreateShl(Add.getOperand(0),
1884 Context->getConstantInt(Add.getType(), 1));
1888 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1890 struct AddMaskingAnd {
1892 LLVMContext *Context;
1893 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1894 bool shouldApply(Value *LHS) const {
1896 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1897 Context->getConstantExprAnd(C1, C2)->isNullValue();
1899 Instruction *apply(BinaryOperator &Add) const {
1900 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1906 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1908 LLVMContext *Context = IC->getContext();
1910 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1911 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1914 // Figure out if the constant is the left or the right argument.
1915 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1916 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1918 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1920 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1921 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1924 Value *Op0 = SO, *Op1 = ConstOperand;
1926 std::swap(Op0, Op1);
1928 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1929 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1930 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1931 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1932 Op0, Op1, SO->getName()+".cmp");
1934 llvm_unreachable("Unknown binary instruction type!");
1936 return IC->InsertNewInstBefore(New, I);
1939 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1940 // constant as the other operand, try to fold the binary operator into the
1941 // select arguments. This also works for Cast instructions, which obviously do
1942 // not have a second operand.
1943 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1945 // Don't modify shared select instructions
1946 if (!SI->hasOneUse()) return 0;
1947 Value *TV = SI->getOperand(1);
1948 Value *FV = SI->getOperand(2);
1950 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1951 // Bool selects with constant operands can be folded to logical ops.
1952 if (SI->getType() == Type::Int1Ty) return 0;
1954 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1955 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1957 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1964 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1965 /// node as operand #0, see if we can fold the instruction into the PHI (which
1966 /// is only possible if all operands to the PHI are constants).
1967 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1968 PHINode *PN = cast<PHINode>(I.getOperand(0));
1969 unsigned NumPHIValues = PN->getNumIncomingValues();
1970 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1972 // Check to see if all of the operands of the PHI are constants. If there is
1973 // one non-constant value, remember the BB it is. If there is more than one
1974 // or if *it* is a PHI, bail out.
1975 BasicBlock *NonConstBB = 0;
1976 for (unsigned i = 0; i != NumPHIValues; ++i)
1977 if (!isa<Constant>(PN->getIncomingValue(i))) {
1978 if (NonConstBB) return 0; // More than one non-const value.
1979 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1980 NonConstBB = PN->getIncomingBlock(i);
1982 // If the incoming non-constant value is in I's block, we have an infinite
1984 if (NonConstBB == I.getParent())
1988 // If there is exactly one non-constant value, we can insert a copy of the
1989 // operation in that block. However, if this is a critical edge, we would be
1990 // inserting the computation one some other paths (e.g. inside a loop). Only
1991 // do this if the pred block is unconditionally branching into the phi block.
1993 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1994 if (!BI || !BI->isUnconditional()) return 0;
1997 // Okay, we can do the transformation: create the new PHI node.
1998 PHINode *NewPN = PHINode::Create(I.getType(), "");
1999 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2000 InsertNewInstBefore(NewPN, *PN);
2001 NewPN->takeName(PN);
2003 // Next, add all of the operands to the PHI.
2004 if (I.getNumOperands() == 2) {
2005 Constant *C = cast<Constant>(I.getOperand(1));
2006 for (unsigned i = 0; i != NumPHIValues; ++i) {
2008 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2009 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2010 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
2012 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
2014 assert(PN->getIncomingBlock(i) == NonConstBB);
2015 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2016 InV = BinaryOperator::Create(BO->getOpcode(),
2017 PN->getIncomingValue(i), C, "phitmp",
2018 NonConstBB->getTerminator());
2019 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2020 InV = CmpInst::Create(*Context, CI->getOpcode(),
2022 PN->getIncomingValue(i), C, "phitmp",
2023 NonConstBB->getTerminator());
2025 llvm_unreachable("Unknown binop!");
2027 AddToWorkList(cast<Instruction>(InV));
2029 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2032 CastInst *CI = cast<CastInst>(&I);
2033 const Type *RetTy = CI->getType();
2034 for (unsigned i = 0; i != NumPHIValues; ++i) {
2036 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2037 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2039 assert(PN->getIncomingBlock(i) == NonConstBB);
2040 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2041 I.getType(), "phitmp",
2042 NonConstBB->getTerminator());
2043 AddToWorkList(cast<Instruction>(InV));
2045 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2048 return ReplaceInstUsesWith(I, NewPN);
2052 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2053 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2054 /// This basically requires proving that the add in the original type would not
2055 /// overflow to change the sign bit or have a carry out.
2056 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2057 // There are different heuristics we can use for this. Here are some simple
2060 // Add has the property that adding any two 2's complement numbers can only
2061 // have one carry bit which can change a sign. As such, if LHS and RHS each
2062 // have at least two sign bits, we know that the addition of the two values will
2063 // sign extend fine.
2064 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2068 // If one of the operands only has one non-zero bit, and if the other operand
2069 // has a known-zero bit in a more significant place than it (not including the
2070 // sign bit) the ripple may go up to and fill the zero, but won't change the
2071 // sign. For example, (X & ~4) + 1.
2079 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2080 bool Changed = SimplifyCommutative(I);
2081 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2083 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2084 // X + undef -> undef
2085 if (isa<UndefValue>(RHS))
2086 return ReplaceInstUsesWith(I, RHS);
2089 if (RHSC->isNullValue())
2090 return ReplaceInstUsesWith(I, LHS);
2092 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2093 // X + (signbit) --> X ^ signbit
2094 const APInt& Val = CI->getValue();
2095 uint32_t BitWidth = Val.getBitWidth();
2096 if (Val == APInt::getSignBit(BitWidth))
2097 return BinaryOperator::CreateXor(LHS, RHS);
2099 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2100 // (X & 254)+1 -> (X&254)|1
2101 if (SimplifyDemandedInstructionBits(I))
2104 // zext(bool) + C -> bool ? C + 1 : C
2105 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2106 if (ZI->getSrcTy() == Type::Int1Ty)
2107 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2110 if (isa<PHINode>(LHS))
2111 if (Instruction *NV = FoldOpIntoPhi(I))
2114 ConstantInt *XorRHS = 0;
2116 if (isa<ConstantInt>(RHSC) &&
2117 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2118 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2119 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2121 uint32_t Size = TySizeBits / 2;
2122 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2123 APInt CFF80Val(-C0080Val);
2125 if (TySizeBits > Size) {
2126 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2127 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2128 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2129 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2130 // This is a sign extend if the top bits are known zero.
2131 if (!MaskedValueIsZero(XorLHS,
2132 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2133 Size = 0; // Not a sign ext, but can't be any others either.
2138 C0080Val = APIntOps::lshr(C0080Val, Size);
2139 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2140 } while (Size >= 1);
2142 // FIXME: This shouldn't be necessary. When the backends can handle types
2143 // with funny bit widths then this switch statement should be removed. It
2144 // is just here to get the size of the "middle" type back up to something
2145 // that the back ends can handle.
2146 const Type *MiddleType = 0;
2149 case 32: MiddleType = Type::Int32Ty; break;
2150 case 16: MiddleType = Type::Int16Ty; break;
2151 case 8: MiddleType = Type::Int8Ty; break;
2154 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2155 InsertNewInstBefore(NewTrunc, I);
2156 return new SExtInst(NewTrunc, I.getType(), I.getName());
2161 if (I.getType() == Type::Int1Ty)
2162 return BinaryOperator::CreateXor(LHS, RHS);
2165 if (I.getType()->isInteger()) {
2166 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2169 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2170 if (RHSI->getOpcode() == Instruction::Sub)
2171 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2172 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2174 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2175 if (LHSI->getOpcode() == Instruction::Sub)
2176 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2177 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2182 // -A + -B --> -(A + B)
2183 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2184 if (LHS->getType()->isIntOrIntVector()) {
2185 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2186 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2187 InsertNewInstBefore(NewAdd, I);
2188 return BinaryOperator::CreateNeg(*Context, NewAdd);
2192 return BinaryOperator::CreateSub(RHS, LHSV);
2196 if (!isa<Constant>(RHS))
2197 if (Value *V = dyn_castNegVal(RHS, Context))
2198 return BinaryOperator::CreateSub(LHS, V);
2202 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2203 if (X == RHS) // X*C + X --> X * (C+1)
2204 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2206 // X*C1 + X*C2 --> X * (C1+C2)
2208 if (X == dyn_castFoldableMul(RHS, C1, Context))
2209 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2212 // X + X*C --> X * (C+1)
2213 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2214 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2216 // X + ~X --> -1 since ~X = -X-1
2217 if (dyn_castNotVal(LHS, Context) == RHS ||
2218 dyn_castNotVal(RHS, Context) == LHS)
2219 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2222 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2223 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2224 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2227 // A+B --> A|B iff A and B have no bits set in common.
2228 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2229 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2230 APInt LHSKnownOne(IT->getBitWidth(), 0);
2231 APInt LHSKnownZero(IT->getBitWidth(), 0);
2232 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2233 if (LHSKnownZero != 0) {
2234 APInt RHSKnownOne(IT->getBitWidth(), 0);
2235 APInt RHSKnownZero(IT->getBitWidth(), 0);
2236 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2238 // No bits in common -> bitwise or.
2239 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2240 return BinaryOperator::CreateOr(LHS, RHS);
2244 // W*X + Y*Z --> W * (X+Z) iff W == Y
2245 if (I.getType()->isIntOrIntVector()) {
2246 Value *W, *X, *Y, *Z;
2247 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2248 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2252 } else if (Y == X) {
2254 } else if (X == Z) {
2261 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2262 LHS->getName()), I);
2263 return BinaryOperator::CreateMul(W, NewAdd);
2268 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2270 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
2271 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2273 // (X & FF00) + xx00 -> (X+xx00) & FF00
2274 if (LHS->hasOneUse() &&
2275 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2276 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2277 if (Anded == CRHS) {
2278 // See if all bits from the first bit set in the Add RHS up are included
2279 // in the mask. First, get the rightmost bit.
2280 const APInt& AddRHSV = CRHS->getValue();
2282 // Form a mask of all bits from the lowest bit added through the top.
2283 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2285 // See if the and mask includes all of these bits.
2286 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2288 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2289 // Okay, the xform is safe. Insert the new add pronto.
2290 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2291 LHS->getName()), I);
2292 return BinaryOperator::CreateAnd(NewAdd, C2);
2297 // Try to fold constant add into select arguments.
2298 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2299 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2303 // add (cast *A to intptrtype) B ->
2304 // cast (GEP (cast *A to i8*) B) --> intptrtype
2306 CastInst *CI = dyn_cast<CastInst>(LHS);
2309 CI = dyn_cast<CastInst>(RHS);
2312 if (CI && CI->getType()->isSized() &&
2313 (CI->getType()->getScalarSizeInBits() ==
2314 TD->getIntPtrType()->getPrimitiveSizeInBits())
2315 && isa<PointerType>(CI->getOperand(0)->getType())) {
2317 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2318 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2319 Context->getPointerType(Type::Int8Ty, AS), I);
2320 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2321 return new PtrToIntInst(I2, CI->getType());
2325 // add (select X 0 (sub n A)) A --> select X A n
2327 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2330 SI = dyn_cast<SelectInst>(RHS);
2333 if (SI && SI->hasOneUse()) {
2334 Value *TV = SI->getTrueValue();
2335 Value *FV = SI->getFalseValue();
2338 // Can we fold the add into the argument of the select?
2339 // We check both true and false select arguments for a matching subtract.
2340 if (match(FV, m_Zero(), *Context) &&
2341 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2342 // Fold the add into the true select value.
2343 return SelectInst::Create(SI->getCondition(), N, A);
2344 if (match(TV, m_Zero(), *Context) &&
2345 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2346 // Fold the add into the false select value.
2347 return SelectInst::Create(SI->getCondition(), A, N);
2351 // Check for (add (sext x), y), see if we can merge this into an
2352 // integer add followed by a sext.
2353 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2354 // (add (sext x), cst) --> (sext (add x, cst'))
2355 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2357 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2358 if (LHSConv->hasOneUse() &&
2359 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2360 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2361 // Insert the new, smaller add.
2362 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2364 InsertNewInstBefore(NewAdd, I);
2365 return new SExtInst(NewAdd, I.getType());
2369 // (add (sext x), (sext y)) --> (sext (add int x, y))
2370 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2371 // Only do this if x/y have the same type, if at last one of them has a
2372 // single use (so we don't increase the number of sexts), and if the
2373 // integer add will not overflow.
2374 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2375 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2376 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2377 RHSConv->getOperand(0))) {
2378 // Insert the new integer add.
2379 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2380 RHSConv->getOperand(0),
2382 InsertNewInstBefore(NewAdd, I);
2383 return new SExtInst(NewAdd, I.getType());
2388 return Changed ? &I : 0;
2391 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2392 bool Changed = SimplifyCommutative(I);
2393 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2395 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2397 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2398 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2399 (I.getType())->getValueAPF()))
2400 return ReplaceInstUsesWith(I, LHS);
2403 if (isa<PHINode>(LHS))
2404 if (Instruction *NV = FoldOpIntoPhi(I))
2409 // -A + -B --> -(A + B)
2410 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2411 return BinaryOperator::CreateFSub(RHS, LHSV);
2414 if (!isa<Constant>(RHS))
2415 if (Value *V = dyn_castFNegVal(RHS, Context))
2416 return BinaryOperator::CreateFSub(LHS, V);
2418 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2419 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2420 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2421 return ReplaceInstUsesWith(I, LHS);
2423 // Check for (add double (sitofp x), y), see if we can merge this into an
2424 // integer add followed by a promotion.
2425 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2426 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2427 // ... if the constant fits in the integer value. This is useful for things
2428 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2429 // requires a constant pool load, and generally allows the add to be better
2431 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2433 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2434 if (LHSConv->hasOneUse() &&
2435 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2436 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2437 // Insert the new integer add.
2438 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2440 InsertNewInstBefore(NewAdd, I);
2441 return new SIToFPInst(NewAdd, I.getType());
2445 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2446 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2447 // Only do this if x/y have the same type, if at last one of them has a
2448 // single use (so we don't increase the number of int->fp conversions),
2449 // and if the integer add will not overflow.
2450 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2451 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2452 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2453 RHSConv->getOperand(0))) {
2454 // Insert the new integer add.
2455 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2456 RHSConv->getOperand(0),
2458 InsertNewInstBefore(NewAdd, I);
2459 return new SIToFPInst(NewAdd, I.getType());
2464 return Changed ? &I : 0;
2467 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2468 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2470 if (Op0 == Op1) // sub X, X -> 0
2471 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2473 // If this is a 'B = x-(-A)', change to B = x+A...
2474 if (Value *V = dyn_castNegVal(Op1, Context))
2475 return BinaryOperator::CreateAdd(Op0, V);
2477 if (isa<UndefValue>(Op0))
2478 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2479 if (isa<UndefValue>(Op1))
2480 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2482 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2483 // Replace (-1 - A) with (~A)...
2484 if (C->isAllOnesValue())
2485 return BinaryOperator::CreateNot(*Context, Op1);
2487 // C - ~X == X + (1+C)
2489 if (match(Op1, m_Not(m_Value(X)), *Context))
2490 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2492 // -(X >>u 31) -> (X >>s 31)
2493 // -(X >>s 31) -> (X >>u 31)
2495 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2496 if (SI->getOpcode() == Instruction::LShr) {
2497 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2498 // Check to see if we are shifting out everything but the sign bit.
2499 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2500 SI->getType()->getPrimitiveSizeInBits()-1) {
2501 // Ok, the transformation is safe. Insert AShr.
2502 return BinaryOperator::Create(Instruction::AShr,
2503 SI->getOperand(0), CU, SI->getName());
2507 else if (SI->getOpcode() == Instruction::AShr) {
2508 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2509 // Check to see if we are shifting out everything but the sign bit.
2510 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2511 SI->getType()->getPrimitiveSizeInBits()-1) {
2512 // Ok, the transformation is safe. Insert LShr.
2513 return BinaryOperator::CreateLShr(
2514 SI->getOperand(0), CU, SI->getName());
2521 // Try to fold constant sub into select arguments.
2522 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2523 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2526 // C - zext(bool) -> bool ? C - 1 : C
2527 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2528 if (ZI->getSrcTy() == Type::Int1Ty)
2529 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2532 if (I.getType() == Type::Int1Ty)
2533 return BinaryOperator::CreateXor(Op0, Op1);
2535 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2536 if (Op1I->getOpcode() == Instruction::Add) {
2537 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2538 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2540 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2541 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2543 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2544 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2545 // C1-(X+C2) --> (C1-C2)-X
2546 return BinaryOperator::CreateSub(
2547 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2551 if (Op1I->hasOneUse()) {
2552 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2553 // is not used by anyone else...
2555 if (Op1I->getOpcode() == Instruction::Sub) {
2556 // Swap the two operands of the subexpr...
2557 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2558 Op1I->setOperand(0, IIOp1);
2559 Op1I->setOperand(1, IIOp0);
2561 // Create the new top level add instruction...
2562 return BinaryOperator::CreateAdd(Op0, Op1);
2565 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2567 if (Op1I->getOpcode() == Instruction::And &&
2568 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2569 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2572 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2573 OtherOp, "B.not"), I);
2574 return BinaryOperator::CreateAnd(Op0, NewNot);
2577 // 0 - (X sdiv C) -> (X sdiv -C)
2578 if (Op1I->getOpcode() == Instruction::SDiv)
2579 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2581 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2582 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2583 Context->getConstantExprNeg(DivRHS));
2585 // X - X*C --> X * (1-C)
2586 ConstantInt *C2 = 0;
2587 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2589 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2591 return BinaryOperator::CreateMul(Op0, CP1);
2596 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2597 if (Op0I->getOpcode() == Instruction::Add) {
2598 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2599 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2600 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2601 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2602 } else if (Op0I->getOpcode() == Instruction::Sub) {
2603 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2604 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2610 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2611 if (X == Op1) // X*C - X --> X * (C-1)
2612 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2614 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2615 if (X == dyn_castFoldableMul(Op1, C2, Context))
2616 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2621 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2622 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2624 // If this is a 'B = x-(-A)', change to B = x+A...
2625 if (Value *V = dyn_castFNegVal(Op1, Context))
2626 return BinaryOperator::CreateFAdd(Op0, V);
2628 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2629 if (Op1I->getOpcode() == Instruction::FAdd) {
2630 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2631 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2633 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2634 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2642 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2643 /// comparison only checks the sign bit. If it only checks the sign bit, set
2644 /// TrueIfSigned if the result of the comparison is true when the input value is
2646 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2647 bool &TrueIfSigned) {
2649 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2650 TrueIfSigned = true;
2651 return RHS->isZero();
2652 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2653 TrueIfSigned = true;
2654 return RHS->isAllOnesValue();
2655 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2656 TrueIfSigned = false;
2657 return RHS->isAllOnesValue();
2658 case ICmpInst::ICMP_UGT:
2659 // True if LHS u> RHS and RHS == high-bit-mask - 1
2660 TrueIfSigned = true;
2661 return RHS->getValue() ==
2662 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2663 case ICmpInst::ICMP_UGE:
2664 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2665 TrueIfSigned = true;
2666 return RHS->getValue().isSignBit();
2672 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2673 bool Changed = SimplifyCommutative(I);
2674 Value *Op0 = I.getOperand(0);
2676 // TODO: If Op1 is undef and Op0 is finite, return zero.
2677 if (!I.getType()->isFPOrFPVector() &&
2678 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2679 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2681 // Simplify mul instructions with a constant RHS...
2682 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2683 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2685 // ((X << C1)*C2) == (X * (C2 << C1))
2686 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2687 if (SI->getOpcode() == Instruction::Shl)
2688 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2689 return BinaryOperator::CreateMul(SI->getOperand(0),
2690 Context->getConstantExprShl(CI, ShOp));
2693 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2694 if (CI->equalsInt(1)) // X * 1 == X
2695 return ReplaceInstUsesWith(I, Op0);
2696 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2697 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2699 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2700 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2701 return BinaryOperator::CreateShl(Op0,
2702 Context->getConstantInt(Op0->getType(), Val.logBase2()));
2704 } else if (isa<VectorType>(Op1->getType())) {
2705 if (Op1->isNullValue())
2706 return ReplaceInstUsesWith(I, Op1);
2708 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2709 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2710 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2712 // As above, vector X*splat(1.0) -> X in all defined cases.
2713 if (Constant *Splat = Op1V->getSplatValue()) {
2714 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2715 if (CI->equalsInt(1))
2716 return ReplaceInstUsesWith(I, Op0);
2721 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2722 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2723 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2724 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2725 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2727 InsertNewInstBefore(Add, I);
2728 Value *C1C2 = Context->getConstantExprMul(Op1,
2729 cast<Constant>(Op0I->getOperand(1)));
2730 return BinaryOperator::CreateAdd(Add, C1C2);
2734 // Try to fold constant mul into select arguments.
2735 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2736 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2739 if (isa<PHINode>(Op0))
2740 if (Instruction *NV = FoldOpIntoPhi(I))
2744 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2745 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2746 return BinaryOperator::CreateMul(Op0v, Op1v);
2748 // (X / Y) * Y = X - (X % Y)
2749 // (X / Y) * -Y = (X % Y) - X
2751 Value *Op1 = I.getOperand(1);
2752 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2754 (BO->getOpcode() != Instruction::UDiv &&
2755 BO->getOpcode() != Instruction::SDiv)) {
2757 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2759 Value *Neg = dyn_castNegVal(Op1, Context);
2760 if (BO && BO->hasOneUse() &&
2761 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2762 (BO->getOpcode() == Instruction::UDiv ||
2763 BO->getOpcode() == Instruction::SDiv)) {
2764 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2767 if (BO->getOpcode() == Instruction::UDiv)
2768 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2770 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2772 InsertNewInstBefore(Rem, I);
2776 return BinaryOperator::CreateSub(Op0BO, Rem);
2778 return BinaryOperator::CreateSub(Rem, Op0BO);
2782 if (I.getType() == Type::Int1Ty)
2783 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2785 // If one of the operands of the multiply is a cast from a boolean value, then
2786 // we know the bool is either zero or one, so this is a 'masking' multiply.
2787 // See if we can simplify things based on how the boolean was originally
2789 CastInst *BoolCast = 0;
2790 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2791 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2794 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2795 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2798 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2799 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2800 const Type *SCOpTy = SCIOp0->getType();
2803 // If the icmp is true iff the sign bit of X is set, then convert this
2804 // multiply into a shift/and combination.
2805 if (isa<ConstantInt>(SCIOp1) &&
2806 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2808 // Shift the X value right to turn it into "all signbits".
2809 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2810 SCOpTy->getPrimitiveSizeInBits()-1);
2812 InsertNewInstBefore(
2813 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2814 BoolCast->getOperand(0)->getName()+
2817 // If the multiply type is not the same as the source type, sign extend
2818 // or truncate to the multiply type.
2819 if (I.getType() != V->getType()) {
2820 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2821 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2822 Instruction::CastOps opcode =
2823 (SrcBits == DstBits ? Instruction::BitCast :
2824 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2825 V = InsertCastBefore(opcode, V, I.getType(), I);
2828 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2829 return BinaryOperator::CreateAnd(V, OtherOp);
2834 return Changed ? &I : 0;
2837 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2838 bool Changed = SimplifyCommutative(I);
2839 Value *Op0 = I.getOperand(0);
2841 // Simplify mul instructions with a constant RHS...
2842 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2843 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2844 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2845 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2846 if (Op1F->isExactlyValue(1.0))
2847 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2848 } else if (isa<VectorType>(Op1->getType())) {
2849 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2850 // As above, vector X*splat(1.0) -> X in all defined cases.
2851 if (Constant *Splat = Op1V->getSplatValue()) {
2852 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2853 if (F->isExactlyValue(1.0))
2854 return ReplaceInstUsesWith(I, Op0);
2859 // Try to fold constant mul into select arguments.
2860 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2861 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2864 if (isa<PHINode>(Op0))
2865 if (Instruction *NV = FoldOpIntoPhi(I))
2869 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2870 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2871 return BinaryOperator::CreateFMul(Op0v, Op1v);
2873 return Changed ? &I : 0;
2876 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2878 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2879 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2881 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2882 int NonNullOperand = -1;
2883 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2884 if (ST->isNullValue())
2886 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2887 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2888 if (ST->isNullValue())
2891 if (NonNullOperand == -1)
2894 Value *SelectCond = SI->getOperand(0);
2896 // Change the div/rem to use 'Y' instead of the select.
2897 I.setOperand(1, SI->getOperand(NonNullOperand));
2899 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2900 // problem. However, the select, or the condition of the select may have
2901 // multiple uses. Based on our knowledge that the operand must be non-zero,
2902 // propagate the known value for the select into other uses of it, and
2903 // propagate a known value of the condition into its other users.
2905 // If the select and condition only have a single use, don't bother with this,
2907 if (SI->use_empty() && SelectCond->hasOneUse())
2910 // Scan the current block backward, looking for other uses of SI.
2911 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2913 while (BBI != BBFront) {
2915 // If we found a call to a function, we can't assume it will return, so
2916 // information from below it cannot be propagated above it.
2917 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2920 // Replace uses of the select or its condition with the known values.
2921 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2924 *I = SI->getOperand(NonNullOperand);
2926 } else if (*I == SelectCond) {
2927 *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2928 Context->getConstantIntFalse();
2933 // If we past the instruction, quit looking for it.
2936 if (&*BBI == SelectCond)
2939 // If we ran out of things to eliminate, break out of the loop.
2940 if (SelectCond == 0 && SI == 0)
2948 /// This function implements the transforms on div instructions that work
2949 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2950 /// used by the visitors to those instructions.
2951 /// @brief Transforms common to all three div instructions
2952 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2953 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2955 // undef / X -> 0 for integer.
2956 // undef / X -> undef for FP (the undef could be a snan).
2957 if (isa<UndefValue>(Op0)) {
2958 if (Op0->getType()->isFPOrFPVector())
2959 return ReplaceInstUsesWith(I, Op0);
2960 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2963 // X / undef -> undef
2964 if (isa<UndefValue>(Op1))
2965 return ReplaceInstUsesWith(I, Op1);
2970 /// This function implements the transforms common to both integer division
2971 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2972 /// division instructions.
2973 /// @brief Common integer divide transforms
2974 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2975 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2977 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2979 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2980 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2981 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2982 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2985 Constant *CI = Context->getConstantInt(I.getType(), 1);
2986 return ReplaceInstUsesWith(I, CI);
2989 if (Instruction *Common = commonDivTransforms(I))
2992 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2993 // This does not apply for fdiv.
2994 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2997 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2999 if (RHS->equalsInt(1))
3000 return ReplaceInstUsesWith(I, Op0);
3002 // (X / C1) / C2 -> X / (C1*C2)
3003 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3004 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3005 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3006 if (MultiplyOverflows(RHS, LHSRHS,
3007 I.getOpcode()==Instruction::SDiv, Context))
3008 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3010 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3011 Context->getConstantExprMul(RHS, LHSRHS));
3014 if (!RHS->isZero()) { // avoid X udiv 0
3015 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3016 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3018 if (isa<PHINode>(Op0))
3019 if (Instruction *NV = FoldOpIntoPhi(I))
3024 // 0 / X == 0, we don't need to preserve faults!
3025 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3026 if (LHS->equalsInt(0))
3027 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3029 // It can't be division by zero, hence it must be division by one.
3030 if (I.getType() == Type::Int1Ty)
3031 return ReplaceInstUsesWith(I, Op0);
3033 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3034 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3037 return ReplaceInstUsesWith(I, Op0);
3043 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3044 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3046 // Handle the integer div common cases
3047 if (Instruction *Common = commonIDivTransforms(I))
3050 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3051 // X udiv C^2 -> X >> C
3052 // Check to see if this is an unsigned division with an exact power of 2,
3053 // if so, convert to a right shift.
3054 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3055 return BinaryOperator::CreateLShr(Op0,
3056 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3058 // X udiv C, where C >= signbit
3059 if (C->getValue().isNegative()) {
3060 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3061 ICmpInst::ICMP_ULT, Op0, C),
3063 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3064 Context->getConstantInt(I.getType(), 1));
3068 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3069 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3070 if (RHSI->getOpcode() == Instruction::Shl &&
3071 isa<ConstantInt>(RHSI->getOperand(0))) {
3072 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3073 if (C1.isPowerOf2()) {
3074 Value *N = RHSI->getOperand(1);
3075 const Type *NTy = N->getType();
3076 if (uint32_t C2 = C1.logBase2()) {
3077 Constant *C2V = Context->getConstantInt(NTy, C2);
3078 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3080 return BinaryOperator::CreateLShr(Op0, N);
3085 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3086 // where C1&C2 are powers of two.
3087 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3088 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3089 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3090 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3091 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3092 // Compute the shift amounts
3093 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3094 // Construct the "on true" case of the select
3095 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3096 Instruction *TSI = BinaryOperator::CreateLShr(
3097 Op0, TC, SI->getName()+".t");
3098 TSI = InsertNewInstBefore(TSI, I);
3100 // Construct the "on false" case of the select
3101 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
3102 Instruction *FSI = BinaryOperator::CreateLShr(
3103 Op0, FC, SI->getName()+".f");
3104 FSI = InsertNewInstBefore(FSI, I);
3106 // construct the select instruction and return it.
3107 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3113 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3114 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3116 // Handle the integer div common cases
3117 if (Instruction *Common = commonIDivTransforms(I))
3120 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3122 if (RHS->isAllOnesValue())
3123 return BinaryOperator::CreateNeg(*Context, Op0);
3126 // If the sign bits of both operands are zero (i.e. we can prove they are
3127 // unsigned inputs), turn this into a udiv.
3128 if (I.getType()->isInteger()) {
3129 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3130 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3131 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3132 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3139 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3140 return commonDivTransforms(I);
3143 /// This function implements the transforms on rem instructions that work
3144 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3145 /// is used by the visitors to those instructions.
3146 /// @brief Transforms common to all three rem instructions
3147 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3148 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3150 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3151 if (I.getType()->isFPOrFPVector())
3152 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3153 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3155 if (isa<UndefValue>(Op1))
3156 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3158 // Handle cases involving: rem X, (select Cond, Y, Z)
3159 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3165 /// This function implements the transforms common to both integer remainder
3166 /// instructions (urem and srem). It is called by the visitors to those integer
3167 /// remainder instructions.
3168 /// @brief Common integer remainder transforms
3169 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3170 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3172 if (Instruction *common = commonRemTransforms(I))
3175 // 0 % X == 0 for integer, we don't need to preserve faults!
3176 if (Constant *LHS = dyn_cast<Constant>(Op0))
3177 if (LHS->isNullValue())
3178 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3180 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3181 // X % 0 == undef, we don't need to preserve faults!
3182 if (RHS->equalsInt(0))
3183 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3185 if (RHS->equalsInt(1)) // X % 1 == 0
3186 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3188 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3189 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3190 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3192 } else if (isa<PHINode>(Op0I)) {
3193 if (Instruction *NV = FoldOpIntoPhi(I))
3197 // See if we can fold away this rem instruction.
3198 if (SimplifyDemandedInstructionBits(I))
3206 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3207 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3209 if (Instruction *common = commonIRemTransforms(I))
3212 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3213 // X urem C^2 -> X and C
3214 // Check to see if this is an unsigned remainder with an exact power of 2,
3215 // if so, convert to a bitwise and.
3216 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3217 if (C->getValue().isPowerOf2())
3218 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3221 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3222 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3223 if (RHSI->getOpcode() == Instruction::Shl &&
3224 isa<ConstantInt>(RHSI->getOperand(0))) {
3225 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3226 Constant *N1 = Context->getAllOnesValue(I.getType());
3227 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3229 return BinaryOperator::CreateAnd(Op0, Add);
3234 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3235 // where C1&C2 are powers of two.
3236 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3237 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3238 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3239 // STO == 0 and SFO == 0 handled above.
3240 if ((STO->getValue().isPowerOf2()) &&
3241 (SFO->getValue().isPowerOf2())) {
3242 Value *TrueAnd = InsertNewInstBefore(
3243 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3244 SI->getName()+".t"), I);
3245 Value *FalseAnd = InsertNewInstBefore(
3246 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3247 SI->getName()+".f"), I);
3248 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3256 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3257 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3259 // Handle the integer rem common cases
3260 if (Instruction *common = commonIRemTransforms(I))
3263 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3264 if (!isa<Constant>(RHSNeg) ||
3265 (isa<ConstantInt>(RHSNeg) &&
3266 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3268 AddUsesToWorkList(I);
3269 I.setOperand(1, RHSNeg);
3273 // If the sign bits of both operands are zero (i.e. we can prove they are
3274 // unsigned inputs), turn this into a urem.
3275 if (I.getType()->isInteger()) {
3276 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3277 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3278 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3279 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3283 // If it's a constant vector, flip any negative values positive.
3284 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3285 unsigned VWidth = RHSV->getNumOperands();
3287 bool hasNegative = false;
3288 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3289 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3290 if (RHS->getValue().isNegative())
3294 std::vector<Constant *> Elts(VWidth);
3295 for (unsigned i = 0; i != VWidth; ++i) {
3296 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3297 if (RHS->getValue().isNegative())
3298 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3304 Constant *NewRHSV = Context->getConstantVector(Elts);
3305 if (NewRHSV != RHSV) {
3306 AddUsesToWorkList(I);
3307 I.setOperand(1, NewRHSV);
3316 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3317 return commonRemTransforms(I);
3320 // isOneBitSet - Return true if there is exactly one bit set in the specified
3322 static bool isOneBitSet(const ConstantInt *CI) {
3323 return CI->getValue().isPowerOf2();
3326 // isHighOnes - Return true if the constant is of the form 1+0+.
3327 // This is the same as lowones(~X).
3328 static bool isHighOnes(const ConstantInt *CI) {
3329 return (~CI->getValue() + 1).isPowerOf2();
3332 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3333 /// are carefully arranged to allow folding of expressions such as:
3335 /// (A < B) | (A > B) --> (A != B)
3337 /// Note that this is only valid if the first and second predicates have the
3338 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3340 /// Three bits are used to represent the condition, as follows:
3345 /// <=> Value Definition
3346 /// 000 0 Always false
3353 /// 111 7 Always true
3355 static unsigned getICmpCode(const ICmpInst *ICI) {
3356 switch (ICI->getPredicate()) {
3358 case ICmpInst::ICMP_UGT: return 1; // 001
3359 case ICmpInst::ICMP_SGT: return 1; // 001
3360 case ICmpInst::ICMP_EQ: return 2; // 010
3361 case ICmpInst::ICMP_UGE: return 3; // 011
3362 case ICmpInst::ICMP_SGE: return 3; // 011
3363 case ICmpInst::ICMP_ULT: return 4; // 100
3364 case ICmpInst::ICMP_SLT: return 4; // 100
3365 case ICmpInst::ICMP_NE: return 5; // 101
3366 case ICmpInst::ICMP_ULE: return 6; // 110
3367 case ICmpInst::ICMP_SLE: return 6; // 110
3370 llvm_unreachable("Invalid ICmp predicate!");
3375 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3376 /// predicate into a three bit mask. It also returns whether it is an ordered
3377 /// predicate by reference.
3378 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3381 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3382 case FCmpInst::FCMP_UNO: return 0; // 000
3383 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3384 case FCmpInst::FCMP_UGT: return 1; // 001
3385 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3386 case FCmpInst::FCMP_UEQ: return 2; // 010
3387 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3388 case FCmpInst::FCMP_UGE: return 3; // 011
3389 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3390 case FCmpInst::FCMP_ULT: return 4; // 100
3391 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3392 case FCmpInst::FCMP_UNE: return 5; // 101
3393 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3394 case FCmpInst::FCMP_ULE: return 6; // 110
3397 // Not expecting FCMP_FALSE and FCMP_TRUE;
3398 llvm_unreachable("Unexpected FCmp predicate!");
3403 /// getICmpValue - This is the complement of getICmpCode, which turns an
3404 /// opcode and two operands into either a constant true or false, or a brand
3405 /// new ICmp instruction. The sign is passed in to determine which kind
3406 /// of predicate to use in the new icmp instruction.
3407 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3408 LLVMContext *Context) {
3410 default: llvm_unreachable("Illegal ICmp code!");
3411 case 0: return Context->getConstantIntFalse();
3414 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3416 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3417 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
3420 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3422 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3425 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3427 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3428 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
3431 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3433 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3434 case 7: return Context->getConstantIntTrue();
3438 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3439 /// opcode and two operands into either a FCmp instruction. isordered is passed
3440 /// in to determine which kind of predicate to use in the new fcmp instruction.
3441 static Value *getFCmpValue(bool isordered, unsigned code,
3442 Value *LHS, Value *RHS, LLVMContext *Context) {
3444 default: llvm_unreachable("Illegal FCmp code!");
3447 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3449 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3452 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3454 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3457 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3459 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3462 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3464 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3467 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3469 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3472 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3474 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3477 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3479 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3480 case 7: return Context->getConstantIntTrue();
3484 /// PredicatesFoldable - Return true if both predicates match sign or if at
3485 /// least one of them is an equality comparison (which is signless).
3486 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3487 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3488 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3489 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3493 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3494 struct FoldICmpLogical {
3497 ICmpInst::Predicate pred;
3498 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3499 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3500 pred(ICI->getPredicate()) {}
3501 bool shouldApply(Value *V) const {
3502 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3503 if (PredicatesFoldable(pred, ICI->getPredicate()))
3504 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3505 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3508 Instruction *apply(Instruction &Log) const {
3509 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3510 if (ICI->getOperand(0) != LHS) {
3511 assert(ICI->getOperand(1) == LHS);
3512 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3515 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3516 unsigned LHSCode = getICmpCode(ICI);
3517 unsigned RHSCode = getICmpCode(RHSICI);
3519 switch (Log.getOpcode()) {
3520 case Instruction::And: Code = LHSCode & RHSCode; break;
3521 case Instruction::Or: Code = LHSCode | RHSCode; break;
3522 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3523 default: llvm_unreachable("Illegal logical opcode!"); return 0;
3526 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3527 ICmpInst::isSignedPredicate(ICI->getPredicate());
3529 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3530 if (Instruction *I = dyn_cast<Instruction>(RV))
3532 // Otherwise, it's a constant boolean value...
3533 return IC.ReplaceInstUsesWith(Log, RV);
3536 } // end anonymous namespace
3538 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3539 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3540 // guaranteed to be a binary operator.
3541 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3543 ConstantInt *AndRHS,
3544 BinaryOperator &TheAnd) {
3545 Value *X = Op->getOperand(0);
3546 Constant *Together = 0;
3548 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3550 switch (Op->getOpcode()) {
3551 case Instruction::Xor:
3552 if (Op->hasOneUse()) {
3553 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3554 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3555 InsertNewInstBefore(And, TheAnd);
3557 return BinaryOperator::CreateXor(And, Together);
3560 case Instruction::Or:
3561 if (Together == AndRHS) // (X | C) & C --> C
3562 return ReplaceInstUsesWith(TheAnd, AndRHS);
3564 if (Op->hasOneUse() && Together != OpRHS) {
3565 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3566 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3567 InsertNewInstBefore(Or, TheAnd);
3569 return BinaryOperator::CreateAnd(Or, AndRHS);
3572 case Instruction::Add:
3573 if (Op->hasOneUse()) {
3574 // Adding a one to a single bit bit-field should be turned into an XOR
3575 // of the bit. First thing to check is to see if this AND is with a
3576 // single bit constant.
3577 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3579 // If there is only one bit set...
3580 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3581 // Ok, at this point, we know that we are masking the result of the
3582 // ADD down to exactly one bit. If the constant we are adding has
3583 // no bits set below this bit, then we can eliminate the ADD.
3584 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3586 // Check to see if any bits below the one bit set in AndRHSV are set.
3587 if ((AddRHS & (AndRHSV-1)) == 0) {
3588 // If not, the only thing that can effect the output of the AND is
3589 // the bit specified by AndRHSV. If that bit is set, the effect of
3590 // the XOR is to toggle the bit. If it is clear, then the ADD has
3592 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3593 TheAnd.setOperand(0, X);
3596 // Pull the XOR out of the AND.
3597 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3598 InsertNewInstBefore(NewAnd, TheAnd);
3599 NewAnd->takeName(Op);
3600 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3607 case Instruction::Shl: {
3608 // We know that the AND will not produce any of the bits shifted in, so if
3609 // the anded constant includes them, clear them now!
3611 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3612 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3613 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3614 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3616 if (CI->getValue() == ShlMask) {
3617 // Masking out bits that the shift already masks
3618 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3619 } else if (CI != AndRHS) { // Reducing bits set in and.
3620 TheAnd.setOperand(1, CI);
3625 case Instruction::LShr:
3627 // We know that the AND will not produce any of the bits shifted in, so if
3628 // the anded constant includes them, clear them now! This only applies to
3629 // unsigned shifts, because a signed shr may bring in set bits!
3631 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3632 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3633 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3634 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3636 if (CI->getValue() == ShrMask) {
3637 // Masking out bits that the shift already masks.
3638 return ReplaceInstUsesWith(TheAnd, Op);
3639 } else if (CI != AndRHS) {
3640 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3645 case Instruction::AShr:
3647 // See if this is shifting in some sign extension, then masking it out
3649 if (Op->hasOneUse()) {
3650 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3651 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3652 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3653 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3654 if (C == AndRHS) { // Masking out bits shifted in.
3655 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3656 // Make the argument unsigned.
3657 Value *ShVal = Op->getOperand(0);
3658 ShVal = InsertNewInstBefore(
3659 BinaryOperator::CreateLShr(ShVal, OpRHS,
3660 Op->getName()), TheAnd);
3661 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3670 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3671 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3672 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3673 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3674 /// insert new instructions.
3675 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3676 bool isSigned, bool Inside,
3678 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
3679 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3680 "Lo is not <= Hi in range emission code!");
3683 if (Lo == Hi) // Trivially false.
3684 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3686 // V >= Min && V < Hi --> V < Hi
3687 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3688 ICmpInst::Predicate pred = (isSigned ?
3689 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3690 return new ICmpInst(*Context, pred, V, Hi);
3693 // Emit V-Lo <u Hi-Lo
3694 Constant *NegLo = Context->getConstantExprNeg(Lo);
3695 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3696 InsertNewInstBefore(Add, IB);
3697 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3698 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3701 if (Lo == Hi) // Trivially true.
3702 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3704 // V < Min || V >= Hi -> V > Hi-1
3705 Hi = SubOne(cast<ConstantInt>(Hi), Context);
3706 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3707 ICmpInst::Predicate pred = (isSigned ?
3708 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3709 return new ICmpInst(*Context, pred, V, Hi);
3712 // Emit V-Lo >u Hi-1-Lo
3713 // Note that Hi has already had one subtracted from it, above.
3714 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3715 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3716 InsertNewInstBefore(Add, IB);
3717 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3718 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3721 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3722 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3723 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3724 // not, since all 1s are not contiguous.
3725 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3726 const APInt& V = Val->getValue();
3727 uint32_t BitWidth = Val->getType()->getBitWidth();
3728 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3730 // look for the first zero bit after the run of ones
3731 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3732 // look for the first non-zero bit
3733 ME = V.getActiveBits();
3737 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3738 /// where isSub determines whether the operator is a sub. If we can fold one of
3739 /// the following xforms:
3741 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3742 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3743 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3745 /// return (A +/- B).
3747 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3748 ConstantInt *Mask, bool isSub,
3750 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3751 if (!LHSI || LHSI->getNumOperands() != 2 ||
3752 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3754 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3756 switch (LHSI->getOpcode()) {
3758 case Instruction::And:
3759 if (Context->getConstantExprAnd(N, Mask) == Mask) {
3760 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3761 if ((Mask->getValue().countLeadingZeros() +
3762 Mask->getValue().countPopulation()) ==
3763 Mask->getValue().getBitWidth())
3766 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3767 // part, we don't need any explicit masks to take them out of A. If that
3768 // is all N is, ignore it.
3769 uint32_t MB = 0, ME = 0;
3770 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3771 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3772 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3773 if (MaskedValueIsZero(RHS, Mask))
3778 case Instruction::Or:
3779 case Instruction::Xor:
3780 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3781 if ((Mask->getValue().countLeadingZeros() +
3782 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3783 && Context->getConstantExprAnd(N, Mask)->isNullValue())
3790 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3792 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3793 return InsertNewInstBefore(New, I);
3796 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3797 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3798 ICmpInst *LHS, ICmpInst *RHS) {
3800 ConstantInt *LHSCst, *RHSCst;
3801 ICmpInst::Predicate LHSCC, RHSCC;
3803 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3804 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3805 m_ConstantInt(LHSCst)), *Context) ||
3806 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3807 m_ConstantInt(RHSCst)), *Context))
3810 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3811 // where C is a power of 2
3812 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3813 LHSCst->getValue().isPowerOf2()) {
3814 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3815 InsertNewInstBefore(NewOr, I);
3816 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3819 // From here on, we only handle:
3820 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3821 if (Val != Val2) return 0;
3823 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3824 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3825 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3826 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3827 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3830 // We can't fold (ugt x, C) & (sgt x, C2).
3831 if (!PredicatesFoldable(LHSCC, RHSCC))
3834 // Ensure that the larger constant is on the RHS.
3836 if (ICmpInst::isSignedPredicate(LHSCC) ||
3837 (ICmpInst::isEquality(LHSCC) &&
3838 ICmpInst::isSignedPredicate(RHSCC)))
3839 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3841 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3844 std::swap(LHS, RHS);
3845 std::swap(LHSCst, RHSCst);
3846 std::swap(LHSCC, RHSCC);
3849 // At this point, we know we have have two icmp instructions
3850 // comparing a value against two constants and and'ing the result
3851 // together. Because of the above check, we know that we only have
3852 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3853 // (from the FoldICmpLogical check above), that the two constants
3854 // are not equal and that the larger constant is on the RHS
3855 assert(LHSCst != RHSCst && "Compares not folded above?");
3858 default: llvm_unreachable("Unknown integer condition code!");
3859 case ICmpInst::ICMP_EQ:
3861 default: llvm_unreachable("Unknown integer condition code!");
3862 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3863 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3864 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3865 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3866 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3867 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3868 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3869 return ReplaceInstUsesWith(I, LHS);
3871 case ICmpInst::ICMP_NE:
3873 default: llvm_unreachable("Unknown integer condition code!");
3874 case ICmpInst::ICMP_ULT:
3875 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3876 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3877 break; // (X != 13 & X u< 15) -> no change
3878 case ICmpInst::ICMP_SLT:
3879 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3880 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3881 break; // (X != 13 & X s< 15) -> no change
3882 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3883 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3884 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3885 return ReplaceInstUsesWith(I, RHS);
3886 case ICmpInst::ICMP_NE:
3887 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3888 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3889 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3890 Val->getName()+".off");
3891 InsertNewInstBefore(Add, I);
3892 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3893 Context->getConstantInt(Add->getType(), 1));
3895 break; // (X != 13 & X != 15) -> no change
3898 case ICmpInst::ICMP_ULT:
3900 default: llvm_unreachable("Unknown integer condition code!");
3901 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3902 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3903 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3904 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3906 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3907 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3908 return ReplaceInstUsesWith(I, LHS);
3909 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3913 case ICmpInst::ICMP_SLT:
3915 default: llvm_unreachable("Unknown integer condition code!");
3916 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3917 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3918 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3919 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3921 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3922 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3923 return ReplaceInstUsesWith(I, LHS);
3924 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3928 case ICmpInst::ICMP_UGT:
3930 default: llvm_unreachable("Unknown integer condition code!");
3931 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3932 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3933 return ReplaceInstUsesWith(I, RHS);
3934 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3936 case ICmpInst::ICMP_NE:
3937 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3938 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3939 break; // (X u> 13 & X != 15) -> no change
3940 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3941 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3942 RHSCst, false, true, I);
3943 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3947 case ICmpInst::ICMP_SGT:
3949 default: llvm_unreachable("Unknown integer condition code!");
3950 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3951 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3952 return ReplaceInstUsesWith(I, RHS);
3953 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3955 case ICmpInst::ICMP_NE:
3956 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3957 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3958 break; // (X s> 13 & X != 15) -> no change
3959 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3960 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3961 RHSCst, true, true, I);
3962 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3972 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3973 bool Changed = SimplifyCommutative(I);
3974 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3976 if (isa<UndefValue>(Op1)) // X & undef -> 0
3977 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3981 return ReplaceInstUsesWith(I, Op1);
3983 // See if we can simplify any instructions used by the instruction whose sole
3984 // purpose is to compute bits we don't care about.
3985 if (SimplifyDemandedInstructionBits(I))
3987 if (isa<VectorType>(I.getType())) {
3988 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3989 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3990 return ReplaceInstUsesWith(I, I.getOperand(0));
3991 } else if (isa<ConstantAggregateZero>(Op1)) {
3992 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3996 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3997 const APInt& AndRHSMask = AndRHS->getValue();
3998 APInt NotAndRHS(~AndRHSMask);
4000 // Optimize a variety of ((val OP C1) & C2) combinations...
4001 if (isa<BinaryOperator>(Op0)) {
4002 Instruction *Op0I = cast<Instruction>(Op0);
4003 Value *Op0LHS = Op0I->getOperand(0);
4004 Value *Op0RHS = Op0I->getOperand(1);
4005 switch (Op0I->getOpcode()) {
4006 case Instruction::Xor:
4007 case Instruction::Or:
4008 // If the mask is only needed on one incoming arm, push it up.
4009 if (Op0I->hasOneUse()) {
4010 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4011 // Not masking anything out for the LHS, move to RHS.
4012 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4013 Op0RHS->getName()+".masked");
4014 InsertNewInstBefore(NewRHS, I);
4015 return BinaryOperator::Create(
4016 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4018 if (!isa<Constant>(Op0RHS) &&
4019 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4020 // Not masking anything out for the RHS, move to LHS.
4021 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4022 Op0LHS->getName()+".masked");
4023 InsertNewInstBefore(NewLHS, I);
4024 return BinaryOperator::Create(
4025 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4030 case Instruction::Add:
4031 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4032 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4033 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4034 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4035 return BinaryOperator::CreateAnd(V, AndRHS);
4036 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4037 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4040 case Instruction::Sub:
4041 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4042 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4043 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4044 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4045 return BinaryOperator::CreateAnd(V, AndRHS);
4047 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4048 // has 1's for all bits that the subtraction with A might affect.
4049 if (Op0I->hasOneUse()) {
4050 uint32_t BitWidth = AndRHSMask.getBitWidth();
4051 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4052 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4054 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4055 if (!(A && A->isZero()) && // avoid infinite recursion.
4056 MaskedValueIsZero(Op0LHS, Mask)) {
4057 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4058 InsertNewInstBefore(NewNeg, I);
4059 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4064 case Instruction::Shl:
4065 case Instruction::LShr:
4066 // (1 << x) & 1 --> zext(x == 0)
4067 // (1 >> x) & 1 --> zext(x == 0)
4068 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4069 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4070 Op0RHS, Context->getNullValue(I.getType()));
4071 InsertNewInstBefore(NewICmp, I);
4072 return new ZExtInst(NewICmp, I.getType());
4077 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4078 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4080 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4081 // If this is an integer truncation or change from signed-to-unsigned, and
4082 // if the source is an and/or with immediate, transform it. This
4083 // frequently occurs for bitfield accesses.
4084 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4085 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4086 CastOp->getNumOperands() == 2)
4087 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4088 if (CastOp->getOpcode() == Instruction::And) {
4089 // Change: and (cast (and X, C1) to T), C2
4090 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4091 // This will fold the two constants together, which may allow
4092 // other simplifications.
4093 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4094 CastOp->getOperand(0), I.getType(),
4095 CastOp->getName()+".shrunk");
4096 NewCast = InsertNewInstBefore(NewCast, I);
4097 // trunc_or_bitcast(C1)&C2
4099 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4100 C3 = Context->getConstantExprAnd(C3, AndRHS);
4101 return BinaryOperator::CreateAnd(NewCast, C3);
4102 } else if (CastOp->getOpcode() == Instruction::Or) {
4103 // Change: and (cast (or X, C1) to T), C2
4104 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4106 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4107 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4109 return ReplaceInstUsesWith(I, AndRHS);
4115 // Try to fold constant and into select arguments.
4116 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4117 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4119 if (isa<PHINode>(Op0))
4120 if (Instruction *NV = FoldOpIntoPhi(I))
4124 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4125 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4127 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4128 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4130 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4131 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4132 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4133 I.getName()+".demorgan");
4134 InsertNewInstBefore(Or, I);
4135 return BinaryOperator::CreateNot(*Context, Or);
4139 Value *A = 0, *B = 0, *C = 0, *D = 0;
4140 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4141 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4142 return ReplaceInstUsesWith(I, Op1);
4144 // (A|B) & ~(A&B) -> A^B
4145 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4146 if ((A == C && B == D) || (A == D && B == C))
4147 return BinaryOperator::CreateXor(A, B);
4151 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4152 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4153 return ReplaceInstUsesWith(I, Op0);
4155 // ~(A&B) & (A|B) -> A^B
4156 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4157 if ((A == C && B == D) || (A == D && B == C))
4158 return BinaryOperator::CreateXor(A, B);
4162 if (Op0->hasOneUse() &&
4163 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4164 if (A == Op1) { // (A^B)&A -> A&(A^B)
4165 I.swapOperands(); // Simplify below
4166 std::swap(Op0, Op1);
4167 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4168 cast<BinaryOperator>(Op0)->swapOperands();
4169 I.swapOperands(); // Simplify below
4170 std::swap(Op0, Op1);
4174 if (Op1->hasOneUse() &&
4175 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4176 if (B == Op0) { // B&(A^B) -> B&(B^A)
4177 cast<BinaryOperator>(Op1)->swapOperands();
4180 if (A == Op0) { // A&(A^B) -> A & ~B
4181 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4182 InsertNewInstBefore(NotB, I);
4183 return BinaryOperator::CreateAnd(A, NotB);
4187 // (A&((~A)|B)) -> A&B
4188 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4189 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4190 return BinaryOperator::CreateAnd(A, Op1);
4191 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4192 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4193 return BinaryOperator::CreateAnd(A, Op0);
4196 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4197 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4198 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4201 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4202 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4206 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4207 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4208 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4209 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4210 const Type *SrcTy = Op0C->getOperand(0)->getType();
4211 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4212 // Only do this if the casts both really cause code to be generated.
4213 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4215 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4217 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4218 Op1C->getOperand(0),
4220 InsertNewInstBefore(NewOp, I);
4221 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4225 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4226 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4227 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4228 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4229 SI0->getOperand(1) == SI1->getOperand(1) &&
4230 (SI0->hasOneUse() || SI1->hasOneUse())) {
4231 Instruction *NewOp =
4232 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4234 SI0->getName()), I);
4235 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4236 SI1->getOperand(1));
4240 // If and'ing two fcmp, try combine them into one.
4241 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4242 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4243 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4244 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4245 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4246 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4247 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4248 // If either of the constants are nans, then the whole thing returns
4250 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4251 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4252 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4253 LHS->getOperand(0), RHS->getOperand(0));
4256 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4257 FCmpInst::Predicate Op0CC, Op1CC;
4258 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4259 m_Value(Op0RHS)), *Context) &&
4260 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4261 m_Value(Op1RHS)), *Context)) {
4262 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4263 // Swap RHS operands to match LHS.
4264 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4265 std::swap(Op1LHS, Op1RHS);
4267 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4268 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4270 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4272 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4273 Op1CC == FCmpInst::FCMP_FALSE)
4274 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4275 else if (Op0CC == FCmpInst::FCMP_TRUE)
4276 return ReplaceInstUsesWith(I, Op1);
4277 else if (Op1CC == FCmpInst::FCMP_TRUE)
4278 return ReplaceInstUsesWith(I, Op0);
4281 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4282 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4284 std::swap(Op0, Op1);
4285 std::swap(Op0Pred, Op1Pred);
4286 std::swap(Op0Ordered, Op1Ordered);
4289 // uno && ueq -> uno && (uno || eq) -> ueq
4290 // ord && olt -> ord && (ord && lt) -> olt
4291 if (Op0Ordered == Op1Ordered)
4292 return ReplaceInstUsesWith(I, Op1);
4293 // uno && oeq -> uno && (ord && eq) -> false
4294 // uno && ord -> false
4296 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4297 // ord && ueq -> ord && (uno || eq) -> oeq
4298 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4299 Op0LHS, Op0RHS, Context));
4307 return Changed ? &I : 0;
4310 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4311 /// capable of providing pieces of a bswap. The subexpression provides pieces
4312 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4313 /// the expression came from the corresponding "byte swapped" byte in some other
4314 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4315 /// we know that the expression deposits the low byte of %X into the high byte
4316 /// of the bswap result and that all other bytes are zero. This expression is
4317 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4320 /// This function returns true if the match was unsuccessful and false if so.
4321 /// On entry to the function the "OverallLeftShift" is a signed integer value
4322 /// indicating the number of bytes that the subexpression is later shifted. For
4323 /// example, if the expression is later right shifted by 16 bits, the
4324 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4325 /// byte of ByteValues is actually being set.
4327 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4328 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4329 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4330 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4331 /// always in the local (OverallLeftShift) coordinate space.
4333 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4334 SmallVector<Value*, 8> &ByteValues) {
4335 if (Instruction *I = dyn_cast<Instruction>(V)) {
4336 // If this is an or instruction, it may be an inner node of the bswap.
4337 if (I->getOpcode() == Instruction::Or) {
4338 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4340 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4344 // If this is a logical shift by a constant multiple of 8, recurse with
4345 // OverallLeftShift and ByteMask adjusted.
4346 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4348 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4349 // Ensure the shift amount is defined and of a byte value.
4350 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4353 unsigned ByteShift = ShAmt >> 3;
4354 if (I->getOpcode() == Instruction::Shl) {
4355 // X << 2 -> collect(X, +2)
4356 OverallLeftShift += ByteShift;
4357 ByteMask >>= ByteShift;
4359 // X >>u 2 -> collect(X, -2)
4360 OverallLeftShift -= ByteShift;
4361 ByteMask <<= ByteShift;
4362 ByteMask &= (~0U >> (32-ByteValues.size()));
4365 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4366 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4368 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4372 // If this is a logical 'and' with a mask that clears bytes, clear the
4373 // corresponding bytes in ByteMask.
4374 if (I->getOpcode() == Instruction::And &&
4375 isa<ConstantInt>(I->getOperand(1))) {
4376 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4377 unsigned NumBytes = ByteValues.size();
4378 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4379 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4381 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4382 // If this byte is masked out by a later operation, we don't care what
4384 if ((ByteMask & (1 << i)) == 0)
4387 // If the AndMask is all zeros for this byte, clear the bit.
4388 APInt MaskB = AndMask & Byte;
4390 ByteMask &= ~(1U << i);
4394 // If the AndMask is not all ones for this byte, it's not a bytezap.
4398 // Otherwise, this byte is kept.
4401 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4406 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4407 // the input value to the bswap. Some observations: 1) if more than one byte
4408 // is demanded from this input, then it could not be successfully assembled
4409 // into a byteswap. At least one of the two bytes would not be aligned with
4410 // their ultimate destination.
4411 if (!isPowerOf2_32(ByteMask)) return true;
4412 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4414 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4415 // is demanded, it needs to go into byte 0 of the result. This means that the
4416 // byte needs to be shifted until it lands in the right byte bucket. The
4417 // shift amount depends on the position: if the byte is coming from the high
4418 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4419 // low part, it must be shifted left.
4420 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4421 if (InputByteNo < ByteValues.size()/2) {
4422 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4425 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4429 // If the destination byte value is already defined, the values are or'd
4430 // together, which isn't a bswap (unless it's an or of the same bits).
4431 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4433 ByteValues[DestByteNo] = V;
4437 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4438 /// If so, insert the new bswap intrinsic and return it.
4439 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4440 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4441 if (!ITy || ITy->getBitWidth() % 16 ||
4442 // ByteMask only allows up to 32-byte values.
4443 ITy->getBitWidth() > 32*8)
4444 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4446 /// ByteValues - For each byte of the result, we keep track of which value
4447 /// defines each byte.
4448 SmallVector<Value*, 8> ByteValues;
4449 ByteValues.resize(ITy->getBitWidth()/8);
4451 // Try to find all the pieces corresponding to the bswap.
4452 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4453 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4456 // Check to see if all of the bytes come from the same value.
4457 Value *V = ByteValues[0];
4458 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4460 // Check to make sure that all of the bytes come from the same value.
4461 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4462 if (ByteValues[i] != V)
4464 const Type *Tys[] = { ITy };
4465 Module *M = I.getParent()->getParent()->getParent();
4466 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4467 return CallInst::Create(F, V);
4470 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4471 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4472 /// we can simplify this expression to "cond ? C : D or B".
4473 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4475 LLVMContext *Context) {
4476 // If A is not a select of -1/0, this cannot match.
4478 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4481 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4482 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4483 return SelectInst::Create(Cond, C, B);
4484 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4485 return SelectInst::Create(Cond, C, B);
4486 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4487 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4488 return SelectInst::Create(Cond, C, D);
4489 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4490 return SelectInst::Create(Cond, C, D);
4494 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4495 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4496 ICmpInst *LHS, ICmpInst *RHS) {
4498 ConstantInt *LHSCst, *RHSCst;
4499 ICmpInst::Predicate LHSCC, RHSCC;
4501 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4502 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4503 m_ConstantInt(LHSCst)), *Context) ||
4504 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4505 m_ConstantInt(RHSCst)), *Context))
4508 // From here on, we only handle:
4509 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4510 if (Val != Val2) return 0;
4512 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4513 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4514 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4515 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4516 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4519 // We can't fold (ugt x, C) | (sgt x, C2).
4520 if (!PredicatesFoldable(LHSCC, RHSCC))
4523 // Ensure that the larger constant is on the RHS.
4525 if (ICmpInst::isSignedPredicate(LHSCC) ||
4526 (ICmpInst::isEquality(LHSCC) &&
4527 ICmpInst::isSignedPredicate(RHSCC)))
4528 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4530 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4533 std::swap(LHS, RHS);
4534 std::swap(LHSCst, RHSCst);
4535 std::swap(LHSCC, RHSCC);
4538 // At this point, we know we have have two icmp instructions
4539 // comparing a value against two constants and or'ing the result
4540 // together. Because of the above check, we know that we only have
4541 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4542 // FoldICmpLogical check above), that the two constants are not
4544 assert(LHSCst != RHSCst && "Compares not folded above?");
4547 default: llvm_unreachable("Unknown integer condition code!");
4548 case ICmpInst::ICMP_EQ:
4550 default: llvm_unreachable("Unknown integer condition code!");
4551 case ICmpInst::ICMP_EQ:
4552 if (LHSCst == SubOne(RHSCst, Context)) {
4553 // (X == 13 | X == 14) -> X-13 <u 2
4554 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4555 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4556 Val->getName()+".off");
4557 InsertNewInstBefore(Add, I);
4558 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4559 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4561 break; // (X == 13 | X == 15) -> no change
4562 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4563 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4565 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4566 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4567 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4568 return ReplaceInstUsesWith(I, RHS);
4571 case ICmpInst::ICMP_NE:
4573 default: llvm_unreachable("Unknown integer condition code!");
4574 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4575 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4576 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4577 return ReplaceInstUsesWith(I, LHS);
4578 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4579 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4580 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4581 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4584 case ICmpInst::ICMP_ULT:
4586 default: llvm_unreachable("Unknown integer condition code!");
4587 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4589 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4590 // If RHSCst is [us]MAXINT, it is always false. Not handling
4591 // this can cause overflow.
4592 if (RHSCst->isMaxValue(false))
4593 return ReplaceInstUsesWith(I, LHS);
4594 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4596 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4598 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4599 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4600 return ReplaceInstUsesWith(I, RHS);
4601 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4605 case ICmpInst::ICMP_SLT:
4607 default: llvm_unreachable("Unknown integer condition code!");
4608 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4610 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4611 // If RHSCst is [us]MAXINT, it is always false. Not handling
4612 // this can cause overflow.
4613 if (RHSCst->isMaxValue(true))
4614 return ReplaceInstUsesWith(I, LHS);
4615 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4617 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4619 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4620 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4621 return ReplaceInstUsesWith(I, RHS);
4622 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4626 case ICmpInst::ICMP_UGT:
4628 default: llvm_unreachable("Unknown integer condition code!");
4629 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4630 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4631 return ReplaceInstUsesWith(I, LHS);
4632 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4634 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4635 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4636 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4637 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4641 case ICmpInst::ICMP_SGT:
4643 default: llvm_unreachable("Unknown integer condition code!");
4644 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4645 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4646 return ReplaceInstUsesWith(I, LHS);
4647 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4649 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4650 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4651 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4652 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4660 /// FoldOrWithConstants - This helper function folds:
4662 /// ((A | B) & C1) | (B & C2)
4668 /// when the XOR of the two constants is "all ones" (-1).
4669 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4670 Value *A, Value *B, Value *C) {
4671 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4675 ConstantInt *CI2 = 0;
4676 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4678 APInt Xor = CI1->getValue() ^ CI2->getValue();
4679 if (!Xor.isAllOnesValue()) return 0;
4681 if (V1 == A || V1 == B) {
4682 Instruction *NewOp =
4683 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4684 return BinaryOperator::CreateOr(NewOp, V1);
4690 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4691 bool Changed = SimplifyCommutative(I);
4692 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4694 if (isa<UndefValue>(Op1)) // X | undef -> -1
4695 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4699 return ReplaceInstUsesWith(I, Op0);
4701 // See if we can simplify any instructions used by the instruction whose sole
4702 // purpose is to compute bits we don't care about.
4703 if (SimplifyDemandedInstructionBits(I))
4705 if (isa<VectorType>(I.getType())) {
4706 if (isa<ConstantAggregateZero>(Op1)) {
4707 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4708 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4709 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4710 return ReplaceInstUsesWith(I, I.getOperand(1));
4715 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4716 ConstantInt *C1 = 0; Value *X = 0;
4717 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4718 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4720 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4721 InsertNewInstBefore(Or, I);
4723 return BinaryOperator::CreateAnd(Or,
4724 Context->getConstantInt(RHS->getValue() | C1->getValue()));
4727 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4728 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4730 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4731 InsertNewInstBefore(Or, I);
4733 return BinaryOperator::CreateXor(Or,
4734 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4737 // Try to fold constant and into select arguments.
4738 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4739 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4741 if (isa<PHINode>(Op0))
4742 if (Instruction *NV = FoldOpIntoPhi(I))
4746 Value *A = 0, *B = 0;
4747 ConstantInt *C1 = 0, *C2 = 0;
4749 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4750 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4751 return ReplaceInstUsesWith(I, Op1);
4752 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4753 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4754 return ReplaceInstUsesWith(I, Op0);
4756 // (A | B) | C and A | (B | C) -> bswap if possible.
4757 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4758 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4759 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4760 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4761 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4762 if (Instruction *BSwap = MatchBSwap(I))
4766 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4767 if (Op0->hasOneUse() &&
4768 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4769 MaskedValueIsZero(Op1, C1->getValue())) {
4770 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4771 InsertNewInstBefore(NOr, I);
4773 return BinaryOperator::CreateXor(NOr, C1);
4776 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4777 if (Op1->hasOneUse() &&
4778 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4779 MaskedValueIsZero(Op0, C1->getValue())) {
4780 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4781 InsertNewInstBefore(NOr, I);
4783 return BinaryOperator::CreateXor(NOr, C1);
4787 Value *C = 0, *D = 0;
4788 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4789 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4790 Value *V1 = 0, *V2 = 0, *V3 = 0;
4791 C1 = dyn_cast<ConstantInt>(C);
4792 C2 = dyn_cast<ConstantInt>(D);
4793 if (C1 && C2) { // (A & C1)|(B & C2)
4794 // If we have: ((V + N) & C1) | (V & C2)
4795 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4796 // replace with V+N.
4797 if (C1->getValue() == ~C2->getValue()) {
4798 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4799 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4800 // Add commutes, try both ways.
4801 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4802 return ReplaceInstUsesWith(I, A);
4803 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4804 return ReplaceInstUsesWith(I, A);
4806 // Or commutes, try both ways.
4807 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4808 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4809 // Add commutes, try both ways.
4810 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4811 return ReplaceInstUsesWith(I, B);
4812 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4813 return ReplaceInstUsesWith(I, B);
4816 V1 = 0; V2 = 0; V3 = 0;
4819 // Check to see if we have any common things being and'ed. If so, find the
4820 // terms for V1 & (V2|V3).
4821 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4822 if (A == B) // (A & C)|(A & D) == A & (C|D)
4823 V1 = A, V2 = C, V3 = D;
4824 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4825 V1 = A, V2 = B, V3 = C;
4826 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4827 V1 = C, V2 = A, V3 = D;
4828 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4829 V1 = C, V2 = A, V3 = B;
4833 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4834 return BinaryOperator::CreateAnd(V1, Or);
4838 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4839 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4841 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4843 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4845 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4848 // ((A&~B)|(~A&B)) -> A^B
4849 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4850 match(B, m_Not(m_Specific(A)), *Context)))
4851 return BinaryOperator::CreateXor(A, D);
4852 // ((~B&A)|(~A&B)) -> A^B
4853 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4854 match(B, m_Not(m_Specific(C)), *Context)))
4855 return BinaryOperator::CreateXor(C, D);
4856 // ((A&~B)|(B&~A)) -> A^B
4857 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4858 match(D, m_Not(m_Specific(A)), *Context)))
4859 return BinaryOperator::CreateXor(A, B);
4860 // ((~B&A)|(B&~A)) -> A^B
4861 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4862 match(D, m_Not(m_Specific(C)), *Context)))
4863 return BinaryOperator::CreateXor(C, B);
4866 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4867 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4868 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4869 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4870 SI0->getOperand(1) == SI1->getOperand(1) &&
4871 (SI0->hasOneUse() || SI1->hasOneUse())) {
4872 Instruction *NewOp =
4873 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4875 SI0->getName()), I);
4876 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4877 SI1->getOperand(1));
4881 // ((A|B)&1)|(B&-2) -> (A&1) | B
4882 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4883 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4884 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4885 if (Ret) return Ret;
4887 // (B&-2)|((A|B)&1) -> (A&1) | B
4888 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4889 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4890 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4891 if (Ret) return Ret;
4894 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
4895 if (A == Op1) // ~A | A == -1
4896 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4900 // Note, A is still live here!
4901 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
4903 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4905 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4906 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4907 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4908 I.getName()+".demorgan"), I);
4909 return BinaryOperator::CreateNot(*Context, And);
4913 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4914 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4915 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4918 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4919 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4923 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4924 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4925 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4926 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4927 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4928 !isa<ICmpInst>(Op1C->getOperand(0))) {
4929 const Type *SrcTy = Op0C->getOperand(0)->getType();
4930 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4931 // Only do this if the casts both really cause code to be
4933 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4935 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4937 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4938 Op1C->getOperand(0),
4940 InsertNewInstBefore(NewOp, I);
4941 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4948 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4949 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4950 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4951 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4952 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4953 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4954 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4955 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4956 // If either of the constants are nans, then the whole thing returns
4958 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4959 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4961 // Otherwise, no need to compare the two constants, compare the
4963 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4964 LHS->getOperand(0), RHS->getOperand(0));
4967 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4968 FCmpInst::Predicate Op0CC, Op1CC;
4969 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4970 m_Value(Op0RHS)), *Context) &&
4971 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4972 m_Value(Op1RHS)), *Context)) {
4973 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4974 // Swap RHS operands to match LHS.
4975 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4976 std::swap(Op1LHS, Op1RHS);
4978 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4979 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4981 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4983 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4984 Op1CC == FCmpInst::FCMP_TRUE)
4985 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4986 else if (Op0CC == FCmpInst::FCMP_FALSE)
4987 return ReplaceInstUsesWith(I, Op1);
4988 else if (Op1CC == FCmpInst::FCMP_FALSE)
4989 return ReplaceInstUsesWith(I, Op0);
4992 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4993 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4994 if (Op0Ordered == Op1Ordered) {
4995 // If both are ordered or unordered, return a new fcmp with
4996 // or'ed predicates.
4997 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4998 Op0LHS, Op0RHS, Context);
4999 if (Instruction *I = dyn_cast<Instruction>(RV))
5001 // Otherwise, it's a constant boolean value...
5002 return ReplaceInstUsesWith(I, RV);
5010 return Changed ? &I : 0;
5015 // XorSelf - Implements: X ^ X --> 0
5018 XorSelf(Value *rhs) : RHS(rhs) {}
5019 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5020 Instruction *apply(BinaryOperator &Xor) const {
5027 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5028 bool Changed = SimplifyCommutative(I);
5029 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5031 if (isa<UndefValue>(Op1)) {
5032 if (isa<UndefValue>(Op0))
5033 // Handle undef ^ undef -> 0 special case. This is a common
5035 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5036 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
5039 // xor X, X = 0, even if X is nested in a sequence of Xor's.
5040 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5041 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5042 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5045 // See if we can simplify any instructions used by the instruction whose sole
5046 // purpose is to compute bits we don't care about.
5047 if (SimplifyDemandedInstructionBits(I))
5049 if (isa<VectorType>(I.getType()))
5050 if (isa<ConstantAggregateZero>(Op1))
5051 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
5053 // Is this a ~ operation?
5054 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5055 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5056 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5057 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5058 if (Op0I->getOpcode() == Instruction::And ||
5059 Op0I->getOpcode() == Instruction::Or) {
5060 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5061 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5063 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5064 Op0I->getOperand(1)->getName()+".not");
5065 InsertNewInstBefore(NotY, I);
5066 if (Op0I->getOpcode() == Instruction::And)
5067 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5069 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5076 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5077 if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5078 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5079 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5080 return new ICmpInst(*Context, ICI->getInversePredicate(),
5081 ICI->getOperand(0), ICI->getOperand(1));
5083 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5084 return new FCmpInst(*Context, FCI->getInversePredicate(),
5085 FCI->getOperand(0), FCI->getOperand(1));
5088 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5089 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5090 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5091 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5092 Instruction::CastOps Opcode = Op0C->getOpcode();
5093 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5094 if (RHS == Context->getConstantExprCast(Opcode,
5095 Context->getConstantIntTrue(),
5096 Op0C->getDestTy())) {
5097 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5099 CI->getOpcode(), CI->getInversePredicate(),
5100 CI->getOperand(0), CI->getOperand(1)), I);
5101 NewCI->takeName(CI);
5102 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5109 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5110 // ~(c-X) == X-c-1 == X+(-c-1)
5111 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5112 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5113 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5114 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5115 Context->getConstantInt(I.getType(), 1));
5116 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5119 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5120 if (Op0I->getOpcode() == Instruction::Add) {
5121 // ~(X-c) --> (-c-1)-X
5122 if (RHS->isAllOnesValue()) {
5123 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5124 return BinaryOperator::CreateSub(
5125 Context->getConstantExprSub(NegOp0CI,
5126 Context->getConstantInt(I.getType(), 1)),
5127 Op0I->getOperand(0));
5128 } else if (RHS->getValue().isSignBit()) {
5129 // (X + C) ^ signbit -> (X + C + signbit)
5131 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5132 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5135 } else if (Op0I->getOpcode() == Instruction::Or) {
5136 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5137 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5138 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5139 // Anything in both C1 and C2 is known to be zero, remove it from
5141 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5142 NewRHS = Context->getConstantExprAnd(NewRHS,
5143 Context->getConstantExprNot(CommonBits));
5144 AddToWorkList(Op0I);
5145 I.setOperand(0, Op0I->getOperand(0));
5146 I.setOperand(1, NewRHS);
5153 // Try to fold constant and into select arguments.
5154 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5155 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5157 if (isa<PHINode>(Op0))
5158 if (Instruction *NV = FoldOpIntoPhi(I))
5162 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
5164 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5166 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
5168 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5171 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5174 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5175 if (A == Op0) { // B^(B|A) == (A|B)^B
5176 Op1I->swapOperands();
5178 std::swap(Op0, Op1);
5179 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5180 I.swapOperands(); // Simplified below.
5181 std::swap(Op0, Op1);
5183 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5184 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5185 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5186 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5187 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5189 if (A == Op0) { // A^(A&B) -> A^(B&A)
5190 Op1I->swapOperands();
5193 if (B == Op0) { // A^(B&A) -> (B&A)^A
5194 I.swapOperands(); // Simplified below.
5195 std::swap(Op0, Op1);
5200 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5203 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5204 Op0I->hasOneUse()) {
5205 if (A == Op1) // (B|A)^B == (A|B)^B
5207 if (B == Op1) { // (A|B)^B == A & ~B
5209 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5211 return BinaryOperator::CreateAnd(A, NotB);
5213 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5214 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5215 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5216 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5217 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5219 if (A == Op1) // (A&B)^A -> (B&A)^A
5221 if (B == Op1 && // (B&A)^A == ~B & A
5222 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5224 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5225 return BinaryOperator::CreateAnd(N, Op1);
5230 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5231 if (Op0I && Op1I && Op0I->isShift() &&
5232 Op0I->getOpcode() == Op1I->getOpcode() &&
5233 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5234 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5235 Instruction *NewOp =
5236 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5237 Op1I->getOperand(0),
5238 Op0I->getName()), I);
5239 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5240 Op1I->getOperand(1));
5244 Value *A, *B, *C, *D;
5245 // (A & B)^(A | B) -> A ^ B
5246 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5247 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5248 if ((A == C && B == D) || (A == D && B == C))
5249 return BinaryOperator::CreateXor(A, B);
5251 // (A | B)^(A & B) -> A ^ B
5252 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5253 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5254 if ((A == C && B == D) || (A == D && B == C))
5255 return BinaryOperator::CreateXor(A, B);
5259 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5260 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5261 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5262 // (X & Y)^(X & Y) -> (Y^Z) & X
5263 Value *X = 0, *Y = 0, *Z = 0;
5265 X = A, Y = B, Z = D;
5267 X = A, Y = B, Z = C;
5269 X = B, Y = A, Z = D;
5271 X = B, Y = A, Z = C;
5274 Instruction *NewOp =
5275 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5276 return BinaryOperator::CreateAnd(NewOp, X);
5281 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5282 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5283 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5286 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5287 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5288 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5289 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5290 const Type *SrcTy = Op0C->getOperand(0)->getType();
5291 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5292 // Only do this if the casts both really cause code to be generated.
5293 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5295 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5297 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5298 Op1C->getOperand(0),
5300 InsertNewInstBefore(NewOp, I);
5301 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5306 return Changed ? &I : 0;
5309 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5310 LLVMContext *Context) {
5311 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5314 static bool HasAddOverflow(ConstantInt *Result,
5315 ConstantInt *In1, ConstantInt *In2,
5318 if (In2->getValue().isNegative())
5319 return Result->getValue().sgt(In1->getValue());
5321 return Result->getValue().slt(In1->getValue());
5323 return Result->getValue().ult(In1->getValue());
5326 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5327 /// overflowed for this type.
5328 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5329 Constant *In2, LLVMContext *Context,
5330 bool IsSigned = false) {
5331 Result = Context->getConstantExprAdd(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 (HasAddOverflow(ExtractElement(Result, Idx, Context),
5337 ExtractElement(In1, Idx, Context),
5338 ExtractElement(In2, Idx, Context),
5345 return HasAddOverflow(cast<ConstantInt>(Result),
5346 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5350 static bool HasSubOverflow(ConstantInt *Result,
5351 ConstantInt *In1, ConstantInt *In2,
5354 if (In2->getValue().isNegative())
5355 return Result->getValue().slt(In1->getValue());
5357 return Result->getValue().sgt(In1->getValue());
5359 return Result->getValue().ugt(In1->getValue());
5362 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5363 /// overflowed for this type.
5364 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5365 Constant *In2, LLVMContext *Context,
5366 bool IsSigned = false) {
5367 Result = Context->getConstantExprSub(In1, In2);
5369 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5370 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5371 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5372 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5373 ExtractElement(In1, Idx, Context),
5374 ExtractElement(In2, Idx, Context),
5381 return HasSubOverflow(cast<ConstantInt>(Result),
5382 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5386 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5387 /// code necessary to compute the offset from the base pointer (without adding
5388 /// in the base pointer). Return the result as a signed integer of intptr size.
5389 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5390 TargetData &TD = IC.getTargetData();
5391 gep_type_iterator GTI = gep_type_begin(GEP);
5392 const Type *IntPtrTy = TD.getIntPtrType();
5393 LLVMContext *Context = IC.getContext();
5394 Value *Result = Context->getNullValue(IntPtrTy);
5396 // Build a mask for high order bits.
5397 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5398 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5400 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5403 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5404 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5405 if (OpC->isZero()) continue;
5407 // Handle a struct index, which adds its field offset to the pointer.
5408 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5409 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5411 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5413 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5415 Result = IC.InsertNewInstBefore(
5416 BinaryOperator::CreateAdd(Result,
5417 Context->getConstantInt(IntPtrTy, Size),
5418 GEP->getName()+".offs"), I);
5422 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5424 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5425 Scale = Context->getConstantExprMul(OC, Scale);
5426 if (Constant *RC = dyn_cast<Constant>(Result))
5427 Result = Context->getConstantExprAdd(RC, Scale);
5429 // Emit an add instruction.
5430 Result = IC.InsertNewInstBefore(
5431 BinaryOperator::CreateAdd(Result, Scale,
5432 GEP->getName()+".offs"), I);
5436 // Convert to correct type.
5437 if (Op->getType() != IntPtrTy) {
5438 if (Constant *OpC = dyn_cast<Constant>(Op))
5439 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5441 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5443 Op->getName()+".c"), I);
5446 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5447 if (Constant *OpC = dyn_cast<Constant>(Op))
5448 Op = Context->getConstantExprMul(OpC, Scale);
5449 else // We'll let instcombine(mul) convert this to a shl if possible.
5450 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5451 GEP->getName()+".idx"), I);
5454 // Emit an add instruction.
5455 if (isa<Constant>(Op) && isa<Constant>(Result))
5456 Result = Context->getConstantExprAdd(cast<Constant>(Op),
5457 cast<Constant>(Result));
5459 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5460 GEP->getName()+".offs"), I);
5466 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5467 /// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5468 /// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5469 /// complex, and scales are involved. The above expression would also be legal
5470 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5471 /// later form is less amenable to optimization though, and we are allowed to
5472 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5474 /// If we can't emit an optimized form for this expression, this returns null.
5476 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5478 TargetData &TD = IC.getTargetData();
5479 gep_type_iterator GTI = gep_type_begin(GEP);
5481 // Check to see if this gep only has a single variable index. If so, and if
5482 // any constant indices are a multiple of its scale, then we can compute this
5483 // in terms of the scale of the variable index. For example, if the GEP
5484 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5485 // because the expression will cross zero at the same point.
5486 unsigned i, e = GEP->getNumOperands();
5488 for (i = 1; i != e; ++i, ++GTI) {
5489 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5490 // Compute the aggregate offset of constant indices.
5491 if (CI->isZero()) continue;
5493 // Handle a struct index, which adds its field offset to the pointer.
5494 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5495 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5497 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5498 Offset += Size*CI->getSExtValue();
5501 // Found our variable index.
5506 // If there are no variable indices, we must have a constant offset, just
5507 // evaluate it the general way.
5508 if (i == e) return 0;
5510 Value *VariableIdx = GEP->getOperand(i);
5511 // Determine the scale factor of the variable element. For example, this is
5512 // 4 if the variable index is into an array of i32.
5513 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5515 // Verify that there are no other variable indices. If so, emit the hard way.
5516 for (++i, ++GTI; i != e; ++i, ++GTI) {
5517 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5520 // Compute the aggregate offset of constant indices.
5521 if (CI->isZero()) continue;
5523 // Handle a struct index, which adds its field offset to the pointer.
5524 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5525 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5527 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5528 Offset += Size*CI->getSExtValue();
5532 // Okay, we know we have a single variable index, which must be a
5533 // pointer/array/vector index. If there is no offset, life is simple, return
5535 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5537 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5538 // we don't need to bother extending: the extension won't affect where the
5539 // computation crosses zero.
5540 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5541 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5542 VariableIdx->getNameStart(), &I);
5546 // Otherwise, there is an index. The computation we will do will be modulo
5547 // the pointer size, so get it.
5548 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5550 Offset &= PtrSizeMask;
5551 VariableScale &= PtrSizeMask;
5553 // To do this transformation, any constant index must be a multiple of the
5554 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5555 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5556 // multiple of the variable scale.
5557 int64_t NewOffs = Offset / (int64_t)VariableScale;
5558 if (Offset != NewOffs*(int64_t)VariableScale)
5561 // Okay, we can do this evaluation. Start by converting the index to intptr.
5562 const Type *IntPtrTy = TD.getIntPtrType();
5563 if (VariableIdx->getType() != IntPtrTy)
5564 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5566 VariableIdx->getNameStart(), &I);
5567 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5568 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5572 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5573 /// else. At this point we know that the GEP is on the LHS of the comparison.
5574 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5575 ICmpInst::Predicate Cond,
5577 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5579 // Look through bitcasts.
5580 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5581 RHS = BCI->getOperand(0);
5583 Value *PtrBase = GEPLHS->getOperand(0);
5584 if (PtrBase == RHS) {
5585 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5586 // This transformation (ignoring the base and scales) is valid because we
5587 // know pointers can't overflow. See if we can output an optimized form.
5588 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5590 // If not, synthesize the offset the hard way.
5592 Offset = EmitGEPOffset(GEPLHS, I, *this);
5593 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5594 Context->getNullValue(Offset->getType()));
5595 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5596 // If the base pointers are different, but the indices are the same, just
5597 // compare the base pointer.
5598 if (PtrBase != GEPRHS->getOperand(0)) {
5599 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5600 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5601 GEPRHS->getOperand(0)->getType();
5603 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5604 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5605 IndicesTheSame = false;
5609 // If all indices are the same, just compare the base pointers.
5611 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
5612 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5614 // Otherwise, the base pointers are different and the indices are
5615 // different, bail out.
5619 // If one of the GEPs has all zero indices, recurse.
5620 bool AllZeros = true;
5621 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5622 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5623 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5628 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5629 ICmpInst::getSwappedPredicate(Cond), I);
5631 // If the other GEP has all zero indices, recurse.
5633 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5634 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5635 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5640 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5642 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5643 // If the GEPs only differ by one index, compare it.
5644 unsigned NumDifferences = 0; // Keep track of # differences.
5645 unsigned DiffOperand = 0; // The operand that differs.
5646 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5647 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5648 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5649 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5650 // Irreconcilable differences.
5654 if (NumDifferences++) break;
5659 if (NumDifferences == 0) // SAME GEP?
5660 return ReplaceInstUsesWith(I, // No comparison is needed here.
5661 Context->getConstantInt(Type::Int1Ty,
5662 ICmpInst::isTrueWhenEqual(Cond)));
5664 else if (NumDifferences == 1) {
5665 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5666 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5667 // Make sure we do a signed comparison here.
5668 return new ICmpInst(*Context,
5669 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5673 // Only lower this if the icmp is the only user of the GEP or if we expect
5674 // the result to fold to a constant!
5675 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5676 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5677 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5678 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5679 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5680 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5686 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5688 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5691 if (!isa<ConstantFP>(RHSC)) return 0;
5692 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5694 // Get the width of the mantissa. We don't want to hack on conversions that
5695 // might lose information from the integer, e.g. "i64 -> float"
5696 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5697 if (MantissaWidth == -1) return 0; // Unknown.
5699 // Check to see that the input is converted from an integer type that is small
5700 // enough that preserves all bits. TODO: check here for "known" sign bits.
5701 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5702 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5704 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5705 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5709 // If the conversion would lose info, don't hack on this.
5710 if ((int)InputSize > MantissaWidth)
5713 // Otherwise, we can potentially simplify the comparison. We know that it
5714 // will always come through as an integer value and we know the constant is
5715 // not a NAN (it would have been previously simplified).
5716 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5718 ICmpInst::Predicate Pred;
5719 switch (I.getPredicate()) {
5720 default: llvm_unreachable("Unexpected predicate!");
5721 case FCmpInst::FCMP_UEQ:
5722 case FCmpInst::FCMP_OEQ:
5723 Pred = ICmpInst::ICMP_EQ;
5725 case FCmpInst::FCMP_UGT:
5726 case FCmpInst::FCMP_OGT:
5727 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5729 case FCmpInst::FCMP_UGE:
5730 case FCmpInst::FCMP_OGE:
5731 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5733 case FCmpInst::FCMP_ULT:
5734 case FCmpInst::FCMP_OLT:
5735 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5737 case FCmpInst::FCMP_ULE:
5738 case FCmpInst::FCMP_OLE:
5739 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5741 case FCmpInst::FCMP_UNE:
5742 case FCmpInst::FCMP_ONE:
5743 Pred = ICmpInst::ICMP_NE;
5745 case FCmpInst::FCMP_ORD:
5746 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5747 case FCmpInst::FCMP_UNO:
5748 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5751 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5753 // Now we know that the APFloat is a normal number, zero or inf.
5755 // See if the FP constant is too large for the integer. For example,
5756 // comparing an i8 to 300.0.
5757 unsigned IntWidth = IntTy->getScalarSizeInBits();
5760 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5761 // and large values.
5762 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5763 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5764 APFloat::rmNearestTiesToEven);
5765 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5766 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5767 Pred == ICmpInst::ICMP_SLE)
5768 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5769 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5772 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5773 // +INF and large values.
5774 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5775 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5776 APFloat::rmNearestTiesToEven);
5777 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5778 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5779 Pred == ICmpInst::ICMP_ULE)
5780 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5781 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5786 // See if the RHS value is < SignedMin.
5787 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5788 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5789 APFloat::rmNearestTiesToEven);
5790 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5791 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5792 Pred == ICmpInst::ICMP_SGE)
5793 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5794 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5798 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5799 // [0, UMAX], but it may still be fractional. See if it is fractional by
5800 // casting the FP value to the integer value and back, checking for equality.
5801 // Don't do this for zero, because -0.0 is not fractional.
5802 Constant *RHSInt = LHSUnsigned
5803 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5804 : Context->getConstantExprFPToSI(RHSC, IntTy);
5805 if (!RHS.isZero()) {
5806 bool Equal = LHSUnsigned
5807 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5808 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5810 // If we had a comparison against a fractional value, we have to adjust
5811 // the compare predicate and sometimes the value. RHSC is rounded towards
5812 // zero at this point.
5814 default: llvm_unreachable("Unexpected integer comparison!");
5815 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5816 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5817 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5818 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5819 case ICmpInst::ICMP_ULE:
5820 // (float)int <= 4.4 --> int <= 4
5821 // (float)int <= -4.4 --> false
5822 if (RHS.isNegative())
5823 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5825 case ICmpInst::ICMP_SLE:
5826 // (float)int <= 4.4 --> int <= 4
5827 // (float)int <= -4.4 --> int < -4
5828 if (RHS.isNegative())
5829 Pred = ICmpInst::ICMP_SLT;
5831 case ICmpInst::ICMP_ULT:
5832 // (float)int < -4.4 --> false
5833 // (float)int < 4.4 --> int <= 4
5834 if (RHS.isNegative())
5835 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5836 Pred = ICmpInst::ICMP_ULE;
5838 case ICmpInst::ICMP_SLT:
5839 // (float)int < -4.4 --> int < -4
5840 // (float)int < 4.4 --> int <= 4
5841 if (!RHS.isNegative())
5842 Pred = ICmpInst::ICMP_SLE;
5844 case ICmpInst::ICMP_UGT:
5845 // (float)int > 4.4 --> int > 4
5846 // (float)int > -4.4 --> true
5847 if (RHS.isNegative())
5848 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5850 case ICmpInst::ICMP_SGT:
5851 // (float)int > 4.4 --> int > 4
5852 // (float)int > -4.4 --> int >= -4
5853 if (RHS.isNegative())
5854 Pred = ICmpInst::ICMP_SGE;
5856 case ICmpInst::ICMP_UGE:
5857 // (float)int >= -4.4 --> true
5858 // (float)int >= 4.4 --> int > 4
5859 if (!RHS.isNegative())
5860 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5861 Pred = ICmpInst::ICMP_UGT;
5863 case ICmpInst::ICMP_SGE:
5864 // (float)int >= -4.4 --> int >= -4
5865 // (float)int >= 4.4 --> int > 4
5866 if (!RHS.isNegative())
5867 Pred = ICmpInst::ICMP_SGT;
5873 // Lower this FP comparison into an appropriate integer version of the
5875 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5878 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5879 bool Changed = SimplifyCompare(I);
5880 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5882 // Fold trivial predicates.
5883 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5884 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5885 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5886 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5888 // Simplify 'fcmp pred X, X'
5890 switch (I.getPredicate()) {
5891 default: llvm_unreachable("Unknown predicate!");
5892 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5893 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5894 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5895 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5896 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5897 case FCmpInst::FCMP_OLT: // True if ordered and less than
5898 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5899 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5901 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5902 case FCmpInst::FCMP_ULT: // True if unordered or less than
5903 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5904 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5905 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5906 I.setPredicate(FCmpInst::FCMP_UNO);
5907 I.setOperand(1, Context->getNullValue(Op0->getType()));
5910 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5911 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5912 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5913 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5914 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5915 I.setPredicate(FCmpInst::FCMP_ORD);
5916 I.setOperand(1, Context->getNullValue(Op0->getType()));
5921 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5922 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5924 // Handle fcmp with constant RHS
5925 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5926 // If the constant is a nan, see if we can fold the comparison based on it.
5927 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5928 if (CFP->getValueAPF().isNaN()) {
5929 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5930 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5931 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5932 "Comparison must be either ordered or unordered!");
5933 // True if unordered.
5934 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5938 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5939 switch (LHSI->getOpcode()) {
5940 case Instruction::PHI:
5941 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5942 // block. If in the same block, we're encouraging jump threading. If
5943 // not, we are just pessimizing the code by making an i1 phi.
5944 if (LHSI->getParent() == I.getParent())
5945 if (Instruction *NV = FoldOpIntoPhi(I))
5948 case Instruction::SIToFP:
5949 case Instruction::UIToFP:
5950 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5953 case Instruction::Select:
5954 // If either operand of the select is a constant, we can fold the
5955 // comparison into the select arms, which will cause one to be
5956 // constant folded and the select turned into a bitwise or.
5957 Value *Op1 = 0, *Op2 = 0;
5958 if (LHSI->hasOneUse()) {
5959 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5960 // Fold the known value into the constant operand.
5961 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5962 // Insert a new FCmp of the other select operand.
5963 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5964 LHSI->getOperand(2), RHSC,
5966 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5967 // Fold the known value into the constant operand.
5968 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5969 // Insert a new FCmp of the other select operand.
5970 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5971 LHSI->getOperand(1), RHSC,
5977 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5982 return Changed ? &I : 0;
5985 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5986 bool Changed = SimplifyCompare(I);
5987 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5988 const Type *Ty = Op0->getType();
5992 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
5993 I.isTrueWhenEqual()));
5995 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5996 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5998 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5999 // addresses never equal each other! We already know that Op0 != Op1.
6000 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6001 isa<ConstantPointerNull>(Op0)) &&
6002 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6003 isa<ConstantPointerNull>(Op1)))
6004 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6005 !I.isTrueWhenEqual()));
6007 // icmp's with boolean values can always be turned into bitwise operations
6008 if (Ty == Type::Int1Ty) {
6009 switch (I.getPredicate()) {
6010 default: llvm_unreachable("Invalid icmp instruction!");
6011 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
6012 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6013 InsertNewInstBefore(Xor, I);
6014 return BinaryOperator::CreateNot(*Context, Xor);
6016 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
6017 return BinaryOperator::CreateXor(Op0, Op1);
6019 case ICmpInst::ICMP_UGT:
6020 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
6022 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
6023 Instruction *Not = BinaryOperator::CreateNot(*Context,
6024 Op0, I.getName()+"tmp");
6025 InsertNewInstBefore(Not, I);
6026 return BinaryOperator::CreateAnd(Not, Op1);
6028 case ICmpInst::ICMP_SGT:
6029 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
6031 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
6032 Instruction *Not = BinaryOperator::CreateNot(*Context,
6033 Op1, I.getName()+"tmp");
6034 InsertNewInstBefore(Not, I);
6035 return BinaryOperator::CreateAnd(Not, Op0);
6037 case ICmpInst::ICMP_UGE:
6038 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6040 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
6041 Instruction *Not = BinaryOperator::CreateNot(*Context,
6042 Op0, I.getName()+"tmp");
6043 InsertNewInstBefore(Not, I);
6044 return BinaryOperator::CreateOr(Not, Op1);
6046 case ICmpInst::ICMP_SGE:
6047 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6049 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
6050 Instruction *Not = BinaryOperator::CreateNot(*Context,
6051 Op1, I.getName()+"tmp");
6052 InsertNewInstBefore(Not, I);
6053 return BinaryOperator::CreateOr(Not, Op0);
6058 unsigned BitWidth = 0;
6060 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6061 else if (Ty->isIntOrIntVector())
6062 BitWidth = Ty->getScalarSizeInBits();
6064 bool isSignBit = false;
6066 // See if we are doing a comparison with a constant.
6067 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6068 Value *A = 0, *B = 0;
6070 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6071 if (I.isEquality() && CI->isNullValue() &&
6072 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6073 // (icmp cond A B) if cond is equality
6074 return new ICmpInst(*Context, I.getPredicate(), A, B);
6077 // If we have an icmp le or icmp ge instruction, turn it into the
6078 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6079 // them being folded in the code below.
6080 switch (I.getPredicate()) {
6082 case ICmpInst::ICMP_ULE:
6083 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
6084 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6085 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6086 AddOne(CI, Context));
6087 case ICmpInst::ICMP_SLE:
6088 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
6089 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6090 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6091 AddOne(CI, Context));
6092 case ICmpInst::ICMP_UGE:
6093 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6094 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6095 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6096 SubOne(CI, Context));
6097 case ICmpInst::ICMP_SGE:
6098 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6099 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6100 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6101 SubOne(CI, Context));
6104 // If this comparison is a normal comparison, it demands all
6105 // bits, if it is a sign bit comparison, it only demands the sign bit.
6107 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6110 // See if we can fold the comparison based on range information we can get
6111 // by checking whether bits are known to be zero or one in the input.
6112 if (BitWidth != 0) {
6113 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6114 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6116 if (SimplifyDemandedBits(I.getOperandUse(0),
6117 isSignBit ? APInt::getSignBit(BitWidth)
6118 : APInt::getAllOnesValue(BitWidth),
6119 Op0KnownZero, Op0KnownOne, 0))
6121 if (SimplifyDemandedBits(I.getOperandUse(1),
6122 APInt::getAllOnesValue(BitWidth),
6123 Op1KnownZero, Op1KnownOne, 0))
6126 // Given the known and unknown bits, compute a range that the LHS could be
6127 // in. Compute the Min, Max and RHS values based on the known bits. For the
6128 // EQ and NE we use unsigned values.
6129 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6130 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6131 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6132 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6134 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6137 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6139 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6143 // If Min and Max are known to be the same, then SimplifyDemandedBits
6144 // figured out that the LHS is a constant. Just constant fold this now so
6145 // that code below can assume that Min != Max.
6146 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6147 return new ICmpInst(*Context, I.getPredicate(),
6148 Context->getConstantInt(Op0Min), Op1);
6149 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6150 return new ICmpInst(*Context, I.getPredicate(), Op0,
6151 Context->getConstantInt(Op1Min));
6153 // Based on the range information we know about the LHS, see if we can
6154 // simplify this comparison. For example, (x&4) < 8 is always true.
6155 switch (I.getPredicate()) {
6156 default: llvm_unreachable("Unknown icmp opcode!");
6157 case ICmpInst::ICMP_EQ:
6158 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6159 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6161 case ICmpInst::ICMP_NE:
6162 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6163 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6165 case ICmpInst::ICMP_ULT:
6166 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6167 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6168 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6169 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6170 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6171 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6172 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6173 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6174 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6175 SubOne(CI, Context));
6177 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6178 if (CI->isMinValue(true))
6179 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6180 Context->getAllOnesValue(Op0->getType()));
6183 case ICmpInst::ICMP_UGT:
6184 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6185 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6186 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6187 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6189 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6190 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6191 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6192 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6193 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6194 AddOne(CI, Context));
6196 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6197 if (CI->isMaxValue(true))
6198 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6199 Context->getNullValue(Op0->getType()));
6202 case ICmpInst::ICMP_SLT:
6203 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6204 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6205 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6206 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6207 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6208 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6209 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6210 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6211 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6212 SubOne(CI, Context));
6215 case ICmpInst::ICMP_SGT:
6216 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6217 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6218 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6219 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6221 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6222 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6223 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6224 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6225 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6226 AddOne(CI, Context));
6229 case ICmpInst::ICMP_SGE:
6230 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6231 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6232 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6233 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6234 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6236 case ICmpInst::ICMP_SLE:
6237 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6238 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6239 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6240 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6241 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6243 case ICmpInst::ICMP_UGE:
6244 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6245 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6246 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6247 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6248 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6250 case ICmpInst::ICMP_ULE:
6251 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6252 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6253 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6254 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6255 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6259 // Turn a signed comparison into an unsigned one if both operands
6260 // are known to have the same sign.
6261 if (I.isSignedPredicate() &&
6262 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6263 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6264 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6267 // Test if the ICmpInst instruction is used exclusively by a select as
6268 // part of a minimum or maximum operation. If so, refrain from doing
6269 // any other folding. This helps out other analyses which understand
6270 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6271 // and CodeGen. And in this case, at least one of the comparison
6272 // operands has at least one user besides the compare (the select),
6273 // which would often largely negate the benefit of folding anyway.
6275 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6276 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6277 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6280 // See if we are doing a comparison between a constant and an instruction that
6281 // can be folded into the comparison.
6282 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6283 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6284 // instruction, see if that instruction also has constants so that the
6285 // instruction can be folded into the icmp
6286 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6287 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6291 // Handle icmp with constant (but not simple integer constant) RHS
6292 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6293 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6294 switch (LHSI->getOpcode()) {
6295 case Instruction::GetElementPtr:
6296 if (RHSC->isNullValue()) {
6297 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6298 bool isAllZeros = true;
6299 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6300 if (!isa<Constant>(LHSI->getOperand(i)) ||
6301 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6306 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6307 Context->getNullValue(LHSI->getOperand(0)->getType()));
6311 case Instruction::PHI:
6312 // Only fold icmp into the PHI if the phi and fcmp are in the same
6313 // block. If in the same block, we're encouraging jump threading. If
6314 // not, we are just pessimizing the code by making an i1 phi.
6315 if (LHSI->getParent() == I.getParent())
6316 if (Instruction *NV = FoldOpIntoPhi(I))
6319 case Instruction::Select: {
6320 // If either operand of the select is a constant, we can fold the
6321 // comparison into the select arms, which will cause one to be
6322 // constant folded and the select turned into a bitwise or.
6323 Value *Op1 = 0, *Op2 = 0;
6324 if (LHSI->hasOneUse()) {
6325 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6326 // Fold the known value into the constant operand.
6327 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6328 // Insert a new ICmp of the other select operand.
6329 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6330 LHSI->getOperand(2), RHSC,
6332 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6333 // Fold the known value into the constant operand.
6334 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6335 // Insert a new ICmp of the other select operand.
6336 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6337 LHSI->getOperand(1), RHSC,
6343 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6346 case Instruction::Malloc:
6347 // If we have (malloc != null), and if the malloc has a single use, we
6348 // can assume it is successful and remove the malloc.
6349 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6350 AddToWorkList(LHSI);
6351 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6352 !I.isTrueWhenEqual()));
6358 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6359 if (User *GEP = dyn_castGetElementPtr(Op0))
6360 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6362 if (User *GEP = dyn_castGetElementPtr(Op1))
6363 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6364 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6367 // Test to see if the operands of the icmp are casted versions of other
6368 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6370 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6371 if (isa<PointerType>(Op0->getType()) &&
6372 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6373 // We keep moving the cast from the left operand over to the right
6374 // operand, where it can often be eliminated completely.
6375 Op0 = CI->getOperand(0);
6377 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6378 // so eliminate it as well.
6379 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6380 Op1 = CI2->getOperand(0);
6382 // If Op1 is a constant, we can fold the cast into the constant.
6383 if (Op0->getType() != Op1->getType()) {
6384 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6385 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6387 // Otherwise, cast the RHS right before the icmp
6388 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6391 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6395 if (isa<CastInst>(Op0)) {
6396 // Handle the special case of: icmp (cast bool to X), <cst>
6397 // This comes up when you have code like
6400 // For generality, we handle any zero-extension of any operand comparison
6401 // with a constant or another cast from the same type.
6402 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6403 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6407 // See if it's the same type of instruction on the left and right.
6408 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6409 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6410 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6411 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6412 switch (Op0I->getOpcode()) {
6414 case Instruction::Add:
6415 case Instruction::Sub:
6416 case Instruction::Xor:
6417 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6418 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6419 Op1I->getOperand(0));
6420 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6421 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6422 if (CI->getValue().isSignBit()) {
6423 ICmpInst::Predicate Pred = I.isSignedPredicate()
6424 ? I.getUnsignedPredicate()
6425 : I.getSignedPredicate();
6426 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6427 Op1I->getOperand(0));
6430 if (CI->getValue().isMaxSignedValue()) {
6431 ICmpInst::Predicate Pred = I.isSignedPredicate()
6432 ? I.getUnsignedPredicate()
6433 : I.getSignedPredicate();
6434 Pred = I.getSwappedPredicate(Pred);
6435 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6436 Op1I->getOperand(0));
6440 case Instruction::Mul:
6441 if (!I.isEquality())
6444 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6445 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6446 // Mask = -1 >> count-trailing-zeros(Cst).
6447 if (!CI->isZero() && !CI->isOne()) {
6448 const APInt &AP = CI->getValue();
6449 ConstantInt *Mask = Context->getConstantInt(
6450 APInt::getLowBitsSet(AP.getBitWidth(),
6452 AP.countTrailingZeros()));
6453 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6455 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6457 InsertNewInstBefore(And1, I);
6458 InsertNewInstBefore(And2, I);
6459 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6468 // ~x < ~y --> y < x
6470 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6471 match(Op1, m_Not(m_Value(B)), *Context))
6472 return new ICmpInst(*Context, I.getPredicate(), B, A);
6475 if (I.isEquality()) {
6476 Value *A, *B, *C, *D;
6478 // -x == -y --> x == y
6479 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6480 match(Op1, m_Neg(m_Value(B)), *Context))
6481 return new ICmpInst(*Context, I.getPredicate(), A, B);
6483 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6484 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6485 Value *OtherVal = A == Op1 ? B : A;
6486 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6487 Context->getNullValue(A->getType()));
6490 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6491 // A^c1 == C^c2 --> A == C^(c1^c2)
6492 ConstantInt *C1, *C2;
6493 if (match(B, m_ConstantInt(C1), *Context) &&
6494 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6496 Context->getConstantInt(C1->getValue() ^ C2->getValue());
6497 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6498 return new ICmpInst(*Context, I.getPredicate(), A,
6499 InsertNewInstBefore(Xor, I));
6502 // A^B == A^D -> B == D
6503 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6504 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6505 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6506 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6510 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6511 (A == Op0 || B == Op0)) {
6512 // A == (A^B) -> B == 0
6513 Value *OtherVal = A == Op0 ? B : A;
6514 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6515 Context->getNullValue(A->getType()));
6518 // (A-B) == A -> B == 0
6519 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6520 return new ICmpInst(*Context, I.getPredicate(), B,
6521 Context->getNullValue(B->getType()));
6523 // A == (A-B) -> B == 0
6524 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6525 return new ICmpInst(*Context, I.getPredicate(), B,
6526 Context->getNullValue(B->getType()));
6528 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6529 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6530 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6531 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6532 Value *X = 0, *Y = 0, *Z = 0;
6535 X = B; Y = D; Z = A;
6536 } else if (A == D) {
6537 X = B; Y = C; Z = A;
6538 } else if (B == C) {
6539 X = A; Y = D; Z = B;
6540 } else if (B == D) {
6541 X = A; Y = C; Z = B;
6544 if (X) { // Build (X^Y) & Z
6545 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6546 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6547 I.setOperand(0, Op1);
6548 I.setOperand(1, Context->getNullValue(Op1->getType()));
6553 return Changed ? &I : 0;
6557 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6558 /// and CmpRHS are both known to be integer constants.
6559 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6560 ConstantInt *DivRHS) {
6561 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6562 const APInt &CmpRHSV = CmpRHS->getValue();
6564 // FIXME: If the operand types don't match the type of the divide
6565 // then don't attempt this transform. The code below doesn't have the
6566 // logic to deal with a signed divide and an unsigned compare (and
6567 // vice versa). This is because (x /s C1) <s C2 produces different
6568 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6569 // (x /u C1) <u C2. Simply casting the operands and result won't
6570 // work. :( The if statement below tests that condition and bails
6572 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6573 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6575 if (DivRHS->isZero())
6576 return 0; // The ProdOV computation fails on divide by zero.
6577 if (DivIsSigned && DivRHS->isAllOnesValue())
6578 return 0; // The overflow computation also screws up here
6579 if (DivRHS->isOne())
6580 return 0; // Not worth bothering, and eliminates some funny cases
6583 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6584 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6585 // C2 (CI). By solving for X we can turn this into a range check
6586 // instead of computing a divide.
6587 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6589 // Determine if the product overflows by seeing if the product is
6590 // not equal to the divide. Make sure we do the same kind of divide
6591 // as in the LHS instruction that we're folding.
6592 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6593 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6595 // Get the ICmp opcode
6596 ICmpInst::Predicate Pred = ICI.getPredicate();
6598 // Figure out the interval that is being checked. For example, a comparison
6599 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6600 // Compute this interval based on the constants involved and the signedness of
6601 // the compare/divide. This computes a half-open interval, keeping track of
6602 // whether either value in the interval overflows. After analysis each
6603 // overflow variable is set to 0 if it's corresponding bound variable is valid
6604 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6605 int LoOverflow = 0, HiOverflow = 0;
6606 Constant *LoBound = 0, *HiBound = 0;
6608 if (!DivIsSigned) { // udiv
6609 // e.g. X/5 op 3 --> [15, 20)
6611 HiOverflow = LoOverflow = ProdOV;
6613 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6614 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6615 if (CmpRHSV == 0) { // (X / pos) op 0
6616 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6617 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6620 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6621 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6622 HiOverflow = LoOverflow = ProdOV;
6624 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6625 } else { // (X / pos) op neg
6626 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6627 HiBound = AddOne(Prod, Context);
6628 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6630 ConstantInt* DivNeg =
6631 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6632 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6636 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6637 if (CmpRHSV == 0) { // (X / neg) op 0
6638 // e.g. X/-5 op 0 --> [-4, 5)
6639 LoBound = AddOne(DivRHS, Context);
6640 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6641 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6642 HiOverflow = 1; // [INTMIN+1, overflow)
6643 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6645 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6646 // e.g. X/-5 op 3 --> [-19, -14)
6647 HiBound = AddOne(Prod, Context);
6648 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6650 LoOverflow = AddWithOverflow(LoBound, HiBound,
6651 DivRHS, Context, true) ? -1 : 0;
6652 } else { // (X / neg) op neg
6653 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6654 LoOverflow = HiOverflow = ProdOV;
6656 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6659 // Dividing by a negative swaps the condition. LT <-> GT
6660 Pred = ICmpInst::getSwappedPredicate(Pred);
6663 Value *X = DivI->getOperand(0);
6665 default: llvm_unreachable("Unhandled icmp opcode!");
6666 case ICmpInst::ICMP_EQ:
6667 if (LoOverflow && HiOverflow)
6668 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6669 else if (HiOverflow)
6670 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
6671 ICmpInst::ICMP_UGE, X, LoBound);
6672 else if (LoOverflow)
6673 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
6674 ICmpInst::ICMP_ULT, X, HiBound);
6676 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6677 case ICmpInst::ICMP_NE:
6678 if (LoOverflow && HiOverflow)
6679 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6680 else if (HiOverflow)
6681 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
6682 ICmpInst::ICMP_ULT, X, LoBound);
6683 else if (LoOverflow)
6684 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
6685 ICmpInst::ICMP_UGE, X, HiBound);
6687 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6688 case ICmpInst::ICMP_ULT:
6689 case ICmpInst::ICMP_SLT:
6690 if (LoOverflow == +1) // Low bound is greater than input range.
6691 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6692 if (LoOverflow == -1) // Low bound is less than input range.
6693 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6694 return new ICmpInst(*Context, Pred, X, LoBound);
6695 case ICmpInst::ICMP_UGT:
6696 case ICmpInst::ICMP_SGT:
6697 if (HiOverflow == +1) // High bound greater than input range.
6698 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6699 else if (HiOverflow == -1) // High bound less than input range.
6700 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6701 if (Pred == ICmpInst::ICMP_UGT)
6702 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6704 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6709 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6711 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6714 const APInt &RHSV = RHS->getValue();
6716 switch (LHSI->getOpcode()) {
6717 case Instruction::Trunc:
6718 if (ICI.isEquality() && LHSI->hasOneUse()) {
6719 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6720 // of the high bits truncated out of x are known.
6721 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6722 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6723 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6724 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6725 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6727 // If all the high bits are known, we can do this xform.
6728 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6729 // Pull in the high bits from known-ones set.
6730 APInt NewRHS(RHS->getValue());
6731 NewRHS.zext(SrcBits);
6733 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6734 Context->getConstantInt(NewRHS));
6739 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6740 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6741 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6743 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6744 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6745 Value *CompareVal = LHSI->getOperand(0);
6747 // If the sign bit of the XorCST is not set, there is no change to
6748 // the operation, just stop using the Xor.
6749 if (!XorCST->getValue().isNegative()) {
6750 ICI.setOperand(0, CompareVal);
6751 AddToWorkList(LHSI);
6755 // Was the old condition true if the operand is positive?
6756 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6758 // If so, the new one isn't.
6759 isTrueIfPositive ^= true;
6761 if (isTrueIfPositive)
6762 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6763 SubOne(RHS, Context));
6765 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6766 AddOne(RHS, Context));
6769 if (LHSI->hasOneUse()) {
6770 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6771 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6772 const APInt &SignBit = XorCST->getValue();
6773 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6774 ? ICI.getUnsignedPredicate()
6775 : ICI.getSignedPredicate();
6776 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6777 Context->getConstantInt(RHSV ^ SignBit));
6780 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6781 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6782 const APInt &NotSignBit = XorCST->getValue();
6783 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6784 ? ICI.getUnsignedPredicate()
6785 : ICI.getSignedPredicate();
6786 Pred = ICI.getSwappedPredicate(Pred);
6787 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6788 Context->getConstantInt(RHSV ^ NotSignBit));
6793 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6794 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6795 LHSI->getOperand(0)->hasOneUse()) {
6796 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6798 // If the LHS is an AND of a truncating cast, we can widen the
6799 // and/compare to be the input width without changing the value
6800 // produced, eliminating a cast.
6801 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6802 // We can do this transformation if either the AND constant does not
6803 // have its sign bit set or if it is an equality comparison.
6804 // Extending a relational comparison when we're checking the sign
6805 // bit would not work.
6806 if (Cast->hasOneUse() &&
6807 (ICI.isEquality() ||
6808 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6810 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6811 APInt NewCST = AndCST->getValue();
6812 NewCST.zext(BitWidth);
6814 NewCI.zext(BitWidth);
6815 Instruction *NewAnd =
6816 BinaryOperator::CreateAnd(Cast->getOperand(0),
6817 Context->getConstantInt(NewCST),LHSI->getName());
6818 InsertNewInstBefore(NewAnd, ICI);
6819 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6820 Context->getConstantInt(NewCI));
6824 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6825 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6826 // happens a LOT in code produced by the C front-end, for bitfield
6828 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6829 if (Shift && !Shift->isShift())
6833 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6834 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6835 const Type *AndTy = AndCST->getType(); // Type of the and.
6837 // We can fold this as long as we can't shift unknown bits
6838 // into the mask. This can only happen with signed shift
6839 // rights, as they sign-extend.
6841 bool CanFold = Shift->isLogicalShift();
6843 // To test for the bad case of the signed shr, see if any
6844 // of the bits shifted in could be tested after the mask.
6845 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6846 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6848 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6849 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6850 AndCST->getValue()) == 0)
6856 if (Shift->getOpcode() == Instruction::Shl)
6857 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6859 NewCst = Context->getConstantExprShl(RHS, ShAmt);
6861 // Check to see if we are shifting out any of the bits being
6863 if (Context->getConstantExpr(Shift->getOpcode(),
6864 NewCst, ShAmt) != RHS) {
6865 // If we shifted bits out, the fold is not going to work out.
6866 // As a special case, check to see if this means that the
6867 // result is always true or false now.
6868 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6869 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6870 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6871 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6873 ICI.setOperand(1, NewCst);
6874 Constant *NewAndCST;
6875 if (Shift->getOpcode() == Instruction::Shl)
6876 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6878 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6879 LHSI->setOperand(1, NewAndCST);
6880 LHSI->setOperand(0, Shift->getOperand(0));
6881 AddToWorkList(Shift); // Shift is dead.
6882 AddUsesToWorkList(ICI);
6888 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6889 // preferable because it allows the C<<Y expression to be hoisted out
6890 // of a loop if Y is invariant and X is not.
6891 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6892 ICI.isEquality() && !Shift->isArithmeticShift() &&
6893 !isa<Constant>(Shift->getOperand(0))) {
6896 if (Shift->getOpcode() == Instruction::LShr) {
6897 NS = BinaryOperator::CreateShl(AndCST,
6898 Shift->getOperand(1), "tmp");
6900 // Insert a logical shift.
6901 NS = BinaryOperator::CreateLShr(AndCST,
6902 Shift->getOperand(1), "tmp");
6904 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6906 // Compute X & (C << Y).
6907 Instruction *NewAnd =
6908 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6909 InsertNewInstBefore(NewAnd, ICI);
6911 ICI.setOperand(0, NewAnd);
6917 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6918 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6921 uint32_t TypeBits = RHSV.getBitWidth();
6923 // Check that the shift amount is in range. If not, don't perform
6924 // undefined shifts. When the shift is visited it will be
6926 if (ShAmt->uge(TypeBits))
6929 if (ICI.isEquality()) {
6930 // If we are comparing against bits always shifted out, the
6931 // comparison cannot succeed.
6933 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6935 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6936 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6937 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6938 return ReplaceInstUsesWith(ICI, Cst);
6941 if (LHSI->hasOneUse()) {
6942 // Otherwise strength reduce the shift into an and.
6943 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6945 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6946 TypeBits-ShAmtVal));
6949 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6950 Mask, LHSI->getName()+".mask");
6951 Value *And = InsertNewInstBefore(AndI, ICI);
6952 return new ICmpInst(*Context, ICI.getPredicate(), And,
6953 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6957 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6958 bool TrueIfSigned = false;
6959 if (LHSI->hasOneUse() &&
6960 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6961 // (X << 31) <s 0 --> (X&1) != 0
6962 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6963 (TypeBits-ShAmt->getZExtValue()-1));
6965 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6966 Mask, LHSI->getName()+".mask");
6967 Value *And = InsertNewInstBefore(AndI, ICI);
6969 return new ICmpInst(*Context,
6970 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6971 And, Context->getNullValue(And->getType()));
6976 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6977 case Instruction::AShr: {
6978 // Only handle equality comparisons of shift-by-constant.
6979 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6980 if (!ShAmt || !ICI.isEquality()) break;
6982 // Check that the shift amount is in range. If not, don't perform
6983 // undefined shifts. When the shift is visited it will be
6985 uint32_t TypeBits = RHSV.getBitWidth();
6986 if (ShAmt->uge(TypeBits))
6989 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6991 // If we are comparing against bits always shifted out, the
6992 // comparison cannot succeed.
6993 APInt Comp = RHSV << ShAmtVal;
6994 if (LHSI->getOpcode() == Instruction::LShr)
6995 Comp = Comp.lshr(ShAmtVal);
6997 Comp = Comp.ashr(ShAmtVal);
6999 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7000 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7001 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
7002 return ReplaceInstUsesWith(ICI, Cst);
7005 // Otherwise, check to see if the bits shifted out are known to be zero.
7006 // If so, we can compare against the unshifted value:
7007 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
7008 if (LHSI->hasOneUse() &&
7009 MaskedValueIsZero(LHSI->getOperand(0),
7010 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7011 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7012 Context->getConstantExprShl(RHS, ShAmt));
7015 if (LHSI->hasOneUse()) {
7016 // Otherwise strength reduce the shift into an and.
7017 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7018 Constant *Mask = Context->getConstantInt(Val);
7021 BinaryOperator::CreateAnd(LHSI->getOperand(0),
7022 Mask, LHSI->getName()+".mask");
7023 Value *And = InsertNewInstBefore(AndI, ICI);
7024 return new ICmpInst(*Context, ICI.getPredicate(), And,
7025 Context->getConstantExprShl(RHS, ShAmt));
7030 case Instruction::SDiv:
7031 case Instruction::UDiv:
7032 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7033 // Fold this div into the comparison, producing a range check.
7034 // Determine, based on the divide type, what the range is being
7035 // checked. If there is an overflow on the low or high side, remember
7036 // it, otherwise compute the range [low, hi) bounding the new value.
7037 // See: InsertRangeTest above for the kinds of replacements possible.
7038 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7039 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7044 case Instruction::Add:
7045 // Fold: icmp pred (add, X, C1), C2
7047 if (!ICI.isEquality()) {
7048 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7050 const APInt &LHSV = LHSC->getValue();
7052 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7055 if (ICI.isSignedPredicate()) {
7056 if (CR.getLower().isSignBit()) {
7057 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7058 Context->getConstantInt(CR.getUpper()));
7059 } else if (CR.getUpper().isSignBit()) {
7060 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7061 Context->getConstantInt(CR.getLower()));
7064 if (CR.getLower().isMinValue()) {
7065 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7066 Context->getConstantInt(CR.getUpper()));
7067 } else if (CR.getUpper().isMinValue()) {
7068 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7069 Context->getConstantInt(CR.getLower()));
7076 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7077 if (ICI.isEquality()) {
7078 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7080 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7081 // the second operand is a constant, simplify a bit.
7082 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7083 switch (BO->getOpcode()) {
7084 case Instruction::SRem:
7085 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7086 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7087 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7088 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7089 Instruction *NewRem =
7090 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7092 InsertNewInstBefore(NewRem, ICI);
7093 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
7094 Context->getNullValue(BO->getType()));
7098 case Instruction::Add:
7099 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7100 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7101 if (BO->hasOneUse())
7102 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7103 Context->getConstantExprSub(RHS, BOp1C));
7104 } else if (RHSV == 0) {
7105 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7106 // efficiently invertible, or if the add has just this one use.
7107 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7109 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7110 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7111 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7112 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7113 else if (BO->hasOneUse()) {
7114 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7115 InsertNewInstBefore(Neg, ICI);
7117 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7121 case Instruction::Xor:
7122 // For the xor case, we can xor two constants together, eliminating
7123 // the explicit xor.
7124 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7125 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7126 Context->getConstantExprXor(RHS, BOC));
7129 case Instruction::Sub:
7130 // Replace (([sub|xor] A, B) != 0) with (A != B)
7132 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7136 case Instruction::Or:
7137 // If bits are being or'd in that are not present in the constant we
7138 // are comparing against, then the comparison could never succeed!
7139 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7140 Constant *NotCI = Context->getConstantExprNot(RHS);
7141 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7142 return ReplaceInstUsesWith(ICI,
7143 Context->getConstantInt(Type::Int1Ty,
7148 case Instruction::And:
7149 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7150 // If bits are being compared against that are and'd out, then the
7151 // comparison can never succeed!
7152 if ((RHSV & ~BOC->getValue()) != 0)
7153 return ReplaceInstUsesWith(ICI,
7154 Context->getConstantInt(Type::Int1Ty,
7157 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7158 if (RHS == BOC && RHSV.isPowerOf2())
7159 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7160 ICmpInst::ICMP_NE, LHSI,
7161 Context->getNullValue(RHS->getType()));
7163 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7164 if (BOC->getValue().isSignBit()) {
7165 Value *X = BO->getOperand(0);
7166 Constant *Zero = Context->getNullValue(X->getType());
7167 ICmpInst::Predicate pred = isICMP_NE ?
7168 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7169 return new ICmpInst(*Context, pred, X, Zero);
7172 // ((X & ~7) == 0) --> X < 8
7173 if (RHSV == 0 && isHighOnes(BOC)) {
7174 Value *X = BO->getOperand(0);
7175 Constant *NegX = Context->getConstantExprNeg(BOC);
7176 ICmpInst::Predicate pred = isICMP_NE ?
7177 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7178 return new ICmpInst(*Context, pred, X, NegX);
7183 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7184 // Handle icmp {eq|ne} <intrinsic>, intcst.
7185 if (II->getIntrinsicID() == Intrinsic::bswap) {
7187 ICI.setOperand(0, II->getOperand(1));
7188 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7196 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7197 /// We only handle extending casts so far.
7199 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7200 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7201 Value *LHSCIOp = LHSCI->getOperand(0);
7202 const Type *SrcTy = LHSCIOp->getType();
7203 const Type *DestTy = LHSCI->getType();
7206 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7207 // integer type is the same size as the pointer type.
7208 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7209 getTargetData().getPointerSizeInBits() ==
7210 cast<IntegerType>(DestTy)->getBitWidth()) {
7212 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7213 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7214 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7215 RHSOp = RHSC->getOperand(0);
7216 // If the pointer types don't match, insert a bitcast.
7217 if (LHSCIOp->getType() != RHSOp->getType())
7218 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7222 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7225 // The code below only handles extension cast instructions, so far.
7227 if (LHSCI->getOpcode() != Instruction::ZExt &&
7228 LHSCI->getOpcode() != Instruction::SExt)
7231 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7232 bool isSignedCmp = ICI.isSignedPredicate();
7234 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7235 // Not an extension from the same type?
7236 RHSCIOp = CI->getOperand(0);
7237 if (RHSCIOp->getType() != LHSCIOp->getType())
7240 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7241 // and the other is a zext), then we can't handle this.
7242 if (CI->getOpcode() != LHSCI->getOpcode())
7245 // Deal with equality cases early.
7246 if (ICI.isEquality())
7247 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7249 // A signed comparison of sign extended values simplifies into a
7250 // signed comparison.
7251 if (isSignedCmp && isSignedExt)
7252 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7254 // The other three cases all fold into an unsigned comparison.
7255 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7258 // If we aren't dealing with a constant on the RHS, exit early
7259 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7263 // Compute the constant that would happen if we truncated to SrcTy then
7264 // reextended to DestTy.
7265 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7266 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7269 // If the re-extended constant didn't change...
7271 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7272 // For example, we might have:
7273 // %A = sext i16 %X to i32
7274 // %B = icmp ugt i32 %A, 1330
7275 // It is incorrect to transform this into
7276 // %B = icmp ugt i16 %X, 1330
7277 // because %A may have negative value.
7279 // However, we allow this when the compare is EQ/NE, because they are
7281 if (isSignedExt == isSignedCmp || ICI.isEquality())
7282 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7286 // The re-extended constant changed so the constant cannot be represented
7287 // in the shorter type. Consequently, we cannot emit a simple comparison.
7289 // First, handle some easy cases. We know the result cannot be equal at this
7290 // point so handle the ICI.isEquality() cases
7291 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7292 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7293 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7294 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7296 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7297 // should have been folded away previously and not enter in here.
7300 // We're performing a signed comparison.
7301 if (cast<ConstantInt>(CI)->getValue().isNegative())
7302 Result = Context->getConstantIntFalse(); // X < (small) --> false
7304 Result = Context->getConstantIntTrue(); // X < (large) --> true
7306 // We're performing an unsigned comparison.
7308 // We're performing an unsigned comp with a sign extended value.
7309 // This is true if the input is >= 0. [aka >s -1]
7310 Constant *NegOne = Context->getAllOnesValue(SrcTy);
7311 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7312 LHSCIOp, NegOne, ICI.getName()), ICI);
7314 // Unsigned extend & unsigned compare -> always true.
7315 Result = Context->getConstantIntTrue();
7319 // Finally, return the value computed.
7320 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7321 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7322 return ReplaceInstUsesWith(ICI, Result);
7324 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7325 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7326 "ICmp should be folded!");
7327 if (Constant *CI = dyn_cast<Constant>(Result))
7328 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7329 return BinaryOperator::CreateNot(*Context, Result);
7332 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7333 return commonShiftTransforms(I);
7336 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7337 return commonShiftTransforms(I);
7340 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7341 if (Instruction *R = commonShiftTransforms(I))
7344 Value *Op0 = I.getOperand(0);
7346 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7347 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7348 if (CSI->isAllOnesValue())
7349 return ReplaceInstUsesWith(I, CSI);
7351 // See if we can turn a signed shr into an unsigned shr.
7352 if (MaskedValueIsZero(Op0,
7353 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7354 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7356 // Arithmetic shifting an all-sign-bit value is a no-op.
7357 unsigned NumSignBits = ComputeNumSignBits(Op0);
7358 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7359 return ReplaceInstUsesWith(I, Op0);
7364 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7365 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7366 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7368 // shl X, 0 == X and shr X, 0 == X
7369 // shl 0, X == 0 and shr 0, X == 0
7370 if (Op1 == Context->getNullValue(Op1->getType()) ||
7371 Op0 == Context->getNullValue(Op0->getType()))
7372 return ReplaceInstUsesWith(I, Op0);
7374 if (isa<UndefValue>(Op0)) {
7375 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7376 return ReplaceInstUsesWith(I, Op0);
7377 else // undef << X -> 0, undef >>u X -> 0
7378 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7380 if (isa<UndefValue>(Op1)) {
7381 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7382 return ReplaceInstUsesWith(I, Op0);
7383 else // X << undef, X >>u undef -> 0
7384 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7387 // See if we can fold away this shift.
7388 if (SimplifyDemandedInstructionBits(I))
7391 // Try to fold constant and into select arguments.
7392 if (isa<Constant>(Op0))
7393 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7394 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7397 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7398 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7403 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7404 BinaryOperator &I) {
7405 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7407 // See if we can simplify any instructions used by the instruction whose sole
7408 // purpose is to compute bits we don't care about.
7409 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7411 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7414 if (Op1->uge(TypeBits)) {
7415 if (I.getOpcode() != Instruction::AShr)
7416 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7418 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7423 // ((X*C1) << C2) == (X * (C1 << C2))
7424 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7425 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7426 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7427 return BinaryOperator::CreateMul(BO->getOperand(0),
7428 Context->getConstantExprShl(BOOp, Op1));
7430 // Try to fold constant and into select arguments.
7431 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7432 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7434 if (isa<PHINode>(Op0))
7435 if (Instruction *NV = FoldOpIntoPhi(I))
7438 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7439 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7440 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7441 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7442 // place. Don't try to do this transformation in this case. Also, we
7443 // require that the input operand is a shift-by-constant so that we have
7444 // confidence that the shifts will get folded together. We could do this
7445 // xform in more cases, but it is unlikely to be profitable.
7446 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7447 isa<ConstantInt>(TrOp->getOperand(1))) {
7448 // Okay, we'll do this xform. Make the shift of shift.
7449 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7450 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7452 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7454 // For logical shifts, the truncation has the effect of making the high
7455 // part of the register be zeros. Emulate this by inserting an AND to
7456 // clear the top bits as needed. This 'and' will usually be zapped by
7457 // other xforms later if dead.
7458 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7459 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7460 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7462 // The mask we constructed says what the trunc would do if occurring
7463 // between the shifts. We want to know the effect *after* the second
7464 // shift. We know that it is a logical shift by a constant, so adjust the
7465 // mask as appropriate.
7466 if (I.getOpcode() == Instruction::Shl)
7467 MaskV <<= Op1->getZExtValue();
7469 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7470 MaskV = MaskV.lshr(Op1->getZExtValue());
7474 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7476 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7478 // Return the value truncated to the interesting size.
7479 return new TruncInst(And, I.getType());
7483 if (Op0->hasOneUse()) {
7484 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7485 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7488 switch (Op0BO->getOpcode()) {
7490 case Instruction::Add:
7491 case Instruction::And:
7492 case Instruction::Or:
7493 case Instruction::Xor: {
7494 // These operators commute.
7495 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7496 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7497 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7498 m_Specific(Op1)), *Context)){
7499 Instruction *YS = BinaryOperator::CreateShl(
7500 Op0BO->getOperand(0), Op1,
7502 InsertNewInstBefore(YS, I); // (Y << C)
7504 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7505 Op0BO->getOperand(1)->getName());
7506 InsertNewInstBefore(X, I); // (X + (Y << C))
7507 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7508 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7509 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7512 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7513 Value *Op0BOOp1 = Op0BO->getOperand(1);
7514 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7516 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7517 m_ConstantInt(CC)), *Context) &&
7518 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7519 Instruction *YS = BinaryOperator::CreateShl(
7520 Op0BO->getOperand(0), Op1,
7522 InsertNewInstBefore(YS, I); // (Y << C)
7524 BinaryOperator::CreateAnd(V1,
7525 Context->getConstantExprShl(CC, Op1),
7526 V1->getName()+".mask");
7527 InsertNewInstBefore(XM, I); // X & (CC << C)
7529 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7534 case Instruction::Sub: {
7535 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7536 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7537 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7538 m_Specific(Op1)), *Context)){
7539 Instruction *YS = BinaryOperator::CreateShl(
7540 Op0BO->getOperand(1), Op1,
7542 InsertNewInstBefore(YS, I); // (Y << C)
7544 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7545 Op0BO->getOperand(0)->getName());
7546 InsertNewInstBefore(X, I); // (X + (Y << C))
7547 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7548 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7549 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7552 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7553 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7554 match(Op0BO->getOperand(0),
7555 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7556 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7557 cast<BinaryOperator>(Op0BO->getOperand(0))
7558 ->getOperand(0)->hasOneUse()) {
7559 Instruction *YS = BinaryOperator::CreateShl(
7560 Op0BO->getOperand(1), Op1,
7562 InsertNewInstBefore(YS, I); // (Y << C)
7564 BinaryOperator::CreateAnd(V1,
7565 Context->getConstantExprShl(CC, Op1),
7566 V1->getName()+".mask");
7567 InsertNewInstBefore(XM, I); // X & (CC << C)
7569 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7577 // If the operand is an bitwise operator with a constant RHS, and the
7578 // shift is the only use, we can pull it out of the shift.
7579 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7580 bool isValid = true; // Valid only for And, Or, Xor
7581 bool highBitSet = false; // Transform if high bit of constant set?
7583 switch (Op0BO->getOpcode()) {
7584 default: isValid = false; break; // Do not perform transform!
7585 case Instruction::Add:
7586 isValid = isLeftShift;
7588 case Instruction::Or:
7589 case Instruction::Xor:
7592 case Instruction::And:
7597 // If this is a signed shift right, and the high bit is modified
7598 // by the logical operation, do not perform the transformation.
7599 // The highBitSet boolean indicates the value of the high bit of
7600 // the constant which would cause it to be modified for this
7603 if (isValid && I.getOpcode() == Instruction::AShr)
7604 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7607 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7609 Instruction *NewShift =
7610 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7611 InsertNewInstBefore(NewShift, I);
7612 NewShift->takeName(Op0BO);
7614 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7621 // Find out if this is a shift of a shift by a constant.
7622 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7623 if (ShiftOp && !ShiftOp->isShift())
7626 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7627 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7628 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7629 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7630 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7631 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7632 Value *X = ShiftOp->getOperand(0);
7634 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7636 const IntegerType *Ty = cast<IntegerType>(I.getType());
7638 // Check for (X << c1) << c2 and (X >> c1) >> c2
7639 if (I.getOpcode() == ShiftOp->getOpcode()) {
7640 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7642 if (AmtSum >= TypeBits) {
7643 if (I.getOpcode() != Instruction::AShr)
7644 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7645 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7648 return BinaryOperator::Create(I.getOpcode(), X,
7649 Context->getConstantInt(Ty, AmtSum));
7650 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7651 I.getOpcode() == Instruction::AShr) {
7652 if (AmtSum >= TypeBits)
7653 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7655 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7656 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7657 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7658 I.getOpcode() == Instruction::LShr) {
7659 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7660 if (AmtSum >= TypeBits)
7661 AmtSum = TypeBits-1;
7663 Instruction *Shift =
7664 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7665 InsertNewInstBefore(Shift, I);
7667 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7668 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7671 // Okay, if we get here, one shift must be left, and the other shift must be
7672 // right. See if the amounts are equal.
7673 if (ShiftAmt1 == ShiftAmt2) {
7674 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7675 if (I.getOpcode() == Instruction::Shl) {
7676 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7677 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7679 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7680 if (I.getOpcode() == Instruction::LShr) {
7681 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7682 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7684 // We can simplify ((X << C) >>s C) into a trunc + sext.
7685 // NOTE: we could do this for any C, but that would make 'unusual' integer
7686 // types. For now, just stick to ones well-supported by the code
7688 const Type *SExtType = 0;
7689 switch (Ty->getBitWidth() - ShiftAmt1) {
7696 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7701 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7702 InsertNewInstBefore(NewTrunc, I);
7703 return new SExtInst(NewTrunc, Ty);
7705 // Otherwise, we can't handle it yet.
7706 } else if (ShiftAmt1 < ShiftAmt2) {
7707 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7709 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7710 if (I.getOpcode() == Instruction::Shl) {
7711 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7712 ShiftOp->getOpcode() == Instruction::AShr);
7713 Instruction *Shift =
7714 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7715 InsertNewInstBefore(Shift, I);
7717 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7718 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7721 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7722 if (I.getOpcode() == Instruction::LShr) {
7723 assert(ShiftOp->getOpcode() == Instruction::Shl);
7724 Instruction *Shift =
7725 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7726 InsertNewInstBefore(Shift, I);
7728 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7729 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7732 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7734 assert(ShiftAmt2 < ShiftAmt1);
7735 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7737 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7738 if (I.getOpcode() == Instruction::Shl) {
7739 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7740 ShiftOp->getOpcode() == Instruction::AShr);
7741 Instruction *Shift =
7742 BinaryOperator::Create(ShiftOp->getOpcode(), X,
7743 Context->getConstantInt(Ty, ShiftDiff));
7744 InsertNewInstBefore(Shift, I);
7746 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7747 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7750 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7751 if (I.getOpcode() == Instruction::LShr) {
7752 assert(ShiftOp->getOpcode() == Instruction::Shl);
7753 Instruction *Shift =
7754 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7755 InsertNewInstBefore(Shift, I);
7757 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7758 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7761 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7768 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7769 /// expression. If so, decompose it, returning some value X, such that Val is
7772 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7773 int &Offset, LLVMContext *Context) {
7774 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7775 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7776 Offset = CI->getZExtValue();
7778 return Context->getConstantInt(Type::Int32Ty, 0);
7779 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7780 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7781 if (I->getOpcode() == Instruction::Shl) {
7782 // This is a value scaled by '1 << the shift amt'.
7783 Scale = 1U << RHS->getZExtValue();
7785 return I->getOperand(0);
7786 } else if (I->getOpcode() == Instruction::Mul) {
7787 // This value is scaled by 'RHS'.
7788 Scale = RHS->getZExtValue();
7790 return I->getOperand(0);
7791 } else if (I->getOpcode() == Instruction::Add) {
7792 // We have X+C. Check to see if we really have (X*C2)+C1,
7793 // where C1 is divisible by C2.
7796 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7798 Offset += RHS->getZExtValue();
7805 // Otherwise, we can't look past this.
7812 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7813 /// try to eliminate the cast by moving the type information into the alloc.
7814 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7815 AllocationInst &AI) {
7816 const PointerType *PTy = cast<PointerType>(CI.getType());
7818 // Remove any uses of AI that are dead.
7819 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7821 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7822 Instruction *User = cast<Instruction>(*UI++);
7823 if (isInstructionTriviallyDead(User)) {
7824 while (UI != E && *UI == User)
7825 ++UI; // If this instruction uses AI more than once, don't break UI.
7828 DOUT << "IC: DCE: " << *User;
7829 EraseInstFromFunction(*User);
7833 // Get the type really allocated and the type casted to.
7834 const Type *AllocElTy = AI.getAllocatedType();
7835 const Type *CastElTy = PTy->getElementType();
7836 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7838 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7839 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7840 if (CastElTyAlign < AllocElTyAlign) return 0;
7842 // If the allocation has multiple uses, only promote it if we are strictly
7843 // increasing the alignment of the resultant allocation. If we keep it the
7844 // same, we open the door to infinite loops of various kinds. (A reference
7845 // from a dbg.declare doesn't count as a use for this purpose.)
7846 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7847 CastElTyAlign == AllocElTyAlign) return 0;
7849 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7850 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7851 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7853 // See if we can satisfy the modulus by pulling a scale out of the array
7855 unsigned ArraySizeScale;
7857 Value *NumElements = // See if the array size is a decomposable linear expr.
7858 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7859 ArrayOffset, Context);
7861 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7863 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7864 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7866 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7871 // If the allocation size is constant, form a constant mul expression
7872 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7873 if (isa<ConstantInt>(NumElements))
7874 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7875 cast<ConstantInt>(Amt));
7876 // otherwise multiply the amount and the number of elements
7878 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7879 Amt = InsertNewInstBefore(Tmp, AI);
7883 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7884 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7885 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7886 Amt = InsertNewInstBefore(Tmp, AI);
7889 AllocationInst *New;
7890 if (isa<MallocInst>(AI))
7891 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7893 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7894 InsertNewInstBefore(New, AI);
7897 // If the allocation has one real use plus a dbg.declare, just remove the
7899 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7900 EraseInstFromFunction(*DI);
7902 // If the allocation has multiple real uses, insert a cast and change all
7903 // things that used it to use the new cast. This will also hack on CI, but it
7905 else if (!AI.hasOneUse()) {
7906 AddUsesToWorkList(AI);
7907 // New is the allocation instruction, pointer typed. AI is the original
7908 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7909 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7910 InsertNewInstBefore(NewCast, AI);
7911 AI.replaceAllUsesWith(NewCast);
7913 return ReplaceInstUsesWith(CI, New);
7916 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7917 /// and return it as type Ty without inserting any new casts and without
7918 /// changing the computed value. This is used by code that tries to decide
7919 /// whether promoting or shrinking integer operations to wider or smaller types
7920 /// will allow us to eliminate a truncate or extend.
7922 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7923 /// extension operation if Ty is larger.
7925 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7926 /// should return true if trunc(V) can be computed by computing V in the smaller
7927 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7928 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7929 /// efficiently truncated.
7931 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7932 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7933 /// the final result.
7934 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7936 int &NumCastsRemoved){
7937 // We can always evaluate constants in another type.
7938 if (isa<Constant>(V))
7941 Instruction *I = dyn_cast<Instruction>(V);
7942 if (!I) return false;
7944 const Type *OrigTy = V->getType();
7946 // If this is an extension or truncate, we can often eliminate it.
7947 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7948 // If this is a cast from the destination type, we can trivially eliminate
7949 // it, and this will remove a cast overall.
7950 if (I->getOperand(0)->getType() == Ty) {
7951 // If the first operand is itself a cast, and is eliminable, do not count
7952 // this as an eliminable cast. We would prefer to eliminate those two
7954 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7960 // We can't extend or shrink something that has multiple uses: doing so would
7961 // require duplicating the instruction in general, which isn't profitable.
7962 if (!I->hasOneUse()) return false;
7964 unsigned Opc = I->getOpcode();
7966 case Instruction::Add:
7967 case Instruction::Sub:
7968 case Instruction::Mul:
7969 case Instruction::And:
7970 case Instruction::Or:
7971 case Instruction::Xor:
7972 // These operators can all arbitrarily be extended or truncated.
7973 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7975 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7978 case Instruction::UDiv:
7979 case Instruction::URem: {
7980 // UDiv and URem can be truncated if all the truncated bits are zero.
7981 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7982 uint32_t BitWidth = Ty->getScalarSizeInBits();
7983 if (BitWidth < OrigBitWidth) {
7984 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7985 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7986 MaskedValueIsZero(I->getOperand(1), Mask)) {
7987 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7989 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7995 case Instruction::Shl:
7996 // If we are truncating the result of this SHL, and if it's a shift of a
7997 // constant amount, we can always perform a SHL in a smaller type.
7998 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7999 uint32_t BitWidth = Ty->getScalarSizeInBits();
8000 if (BitWidth < OrigTy->getScalarSizeInBits() &&
8001 CI->getLimitedValue(BitWidth) < BitWidth)
8002 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8006 case Instruction::LShr:
8007 // If this is a truncate of a logical shr, we can truncate it to a smaller
8008 // lshr iff we know that the bits we would otherwise be shifting in are
8010 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8011 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8012 uint32_t BitWidth = Ty->getScalarSizeInBits();
8013 if (BitWidth < OrigBitWidth &&
8014 MaskedValueIsZero(I->getOperand(0),
8015 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8016 CI->getLimitedValue(BitWidth) < BitWidth) {
8017 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8022 case Instruction::ZExt:
8023 case Instruction::SExt:
8024 case Instruction::Trunc:
8025 // If this is the same kind of case as our original (e.g. zext+zext), we
8026 // can safely replace it. Note that replacing it does not reduce the number
8027 // of casts in the input.
8031 // sext (zext ty1), ty2 -> zext ty2
8032 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8035 case Instruction::Select: {
8036 SelectInst *SI = cast<SelectInst>(I);
8037 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8039 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8042 case Instruction::PHI: {
8043 // We can change a phi if we can change all operands.
8044 PHINode *PN = cast<PHINode>(I);
8045 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8046 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8052 // TODO: Can handle more cases here.
8059 /// EvaluateInDifferentType - Given an expression that
8060 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8061 /// evaluate the expression.
8062 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8064 if (Constant *C = dyn_cast<Constant>(V))
8065 return Context->getConstantExprIntegerCast(C, Ty,
8066 isSigned /*Sext or ZExt*/);
8068 // Otherwise, it must be an instruction.
8069 Instruction *I = cast<Instruction>(V);
8070 Instruction *Res = 0;
8071 unsigned Opc = I->getOpcode();
8073 case Instruction::Add:
8074 case Instruction::Sub:
8075 case Instruction::Mul:
8076 case Instruction::And:
8077 case Instruction::Or:
8078 case Instruction::Xor:
8079 case Instruction::AShr:
8080 case Instruction::LShr:
8081 case Instruction::Shl:
8082 case Instruction::UDiv:
8083 case Instruction::URem: {
8084 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8085 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8086 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8089 case Instruction::Trunc:
8090 case Instruction::ZExt:
8091 case Instruction::SExt:
8092 // If the source type of the cast is the type we're trying for then we can
8093 // just return the source. There's no need to insert it because it is not
8095 if (I->getOperand(0)->getType() == Ty)
8096 return I->getOperand(0);
8098 // Otherwise, must be the same type of cast, so just reinsert a new one.
8099 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8102 case Instruction::Select: {
8103 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8104 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8105 Res = SelectInst::Create(I->getOperand(0), True, False);
8108 case Instruction::PHI: {
8109 PHINode *OPN = cast<PHINode>(I);
8110 PHINode *NPN = PHINode::Create(Ty);
8111 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8112 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8113 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8119 // TODO: Can handle more cases here.
8120 llvm_unreachable("Unreachable!");
8125 return InsertNewInstBefore(Res, *I);
8128 /// @brief Implement the transforms common to all CastInst visitors.
8129 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8130 Value *Src = CI.getOperand(0);
8132 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8133 // eliminate it now.
8134 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8135 if (Instruction::CastOps opc =
8136 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8137 // The first cast (CSrc) is eliminable so we need to fix up or replace
8138 // the second cast (CI). CSrc will then have a good chance of being dead.
8139 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8143 // If we are casting a select then fold the cast into the select
8144 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8145 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8148 // If we are casting a PHI then fold the cast into the PHI
8149 if (isa<PHINode>(Src))
8150 if (Instruction *NV = FoldOpIntoPhi(CI))
8156 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8157 /// or not there is a sequence of GEP indices into the type that will land us at
8158 /// the specified offset. If so, fill them into NewIndices and return the
8159 /// resultant element type, otherwise return null.
8160 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8161 SmallVectorImpl<Value*> &NewIndices,
8162 const TargetData *TD,
8163 LLVMContext *Context) {
8164 if (!Ty->isSized()) return 0;
8166 // Start with the index over the outer type. Note that the type size
8167 // might be zero (even if the offset isn't zero) if the indexed type
8168 // is something like [0 x {int, int}]
8169 const Type *IntPtrTy = TD->getIntPtrType();
8170 int64_t FirstIdx = 0;
8171 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8172 FirstIdx = Offset/TySize;
8173 Offset -= FirstIdx*TySize;
8175 // Handle hosts where % returns negative instead of values [0..TySize).
8179 assert(Offset >= 0);
8181 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8184 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8186 // Index into the types. If we fail, set OrigBase to null.
8188 // Indexing into tail padding between struct/array elements.
8189 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8192 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8193 const StructLayout *SL = TD->getStructLayout(STy);
8194 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8195 "Offset must stay within the indexed type");
8197 unsigned Elt = SL->getElementContainingOffset(Offset);
8198 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8200 Offset -= SL->getElementOffset(Elt);
8201 Ty = STy->getElementType(Elt);
8202 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8203 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8204 assert(EltSize && "Cannot index into a zero-sized array");
8205 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8207 Ty = AT->getElementType();
8209 // Otherwise, we can't index into the middle of this atomic type, bail.
8217 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8218 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8219 Value *Src = CI.getOperand(0);
8221 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8222 // If casting the result of a getelementptr instruction with no offset, turn
8223 // this into a cast of the original pointer!
8224 if (GEP->hasAllZeroIndices()) {
8225 // Changing the cast operand is usually not a good idea but it is safe
8226 // here because the pointer operand is being replaced with another
8227 // pointer operand so the opcode doesn't need to change.
8229 CI.setOperand(0, GEP->getOperand(0));
8233 // If the GEP has a single use, and the base pointer is a bitcast, and the
8234 // GEP computes a constant offset, see if we can convert these three
8235 // instructions into fewer. This typically happens with unions and other
8236 // non-type-safe code.
8237 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8238 if (GEP->hasAllConstantIndices()) {
8239 // We are guaranteed to get a constant from EmitGEPOffset.
8240 ConstantInt *OffsetV =
8241 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8242 int64_t Offset = OffsetV->getSExtValue();
8244 // Get the base pointer input of the bitcast, and the type it points to.
8245 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8246 const Type *GEPIdxTy =
8247 cast<PointerType>(OrigBase->getType())->getElementType();
8248 SmallVector<Value*, 8> NewIndices;
8249 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8250 // If we were able to index down into an element, create the GEP
8251 // and bitcast the result. This eliminates one bitcast, potentially
8253 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8255 NewIndices.end(), "");
8256 InsertNewInstBefore(NGEP, CI);
8257 NGEP->takeName(GEP);
8259 if (isa<BitCastInst>(CI))
8260 return new BitCastInst(NGEP, CI.getType());
8261 assert(isa<PtrToIntInst>(CI));
8262 return new PtrToIntInst(NGEP, CI.getType());
8268 return commonCastTransforms(CI);
8271 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8272 /// type like i42. We don't want to introduce operations on random non-legal
8273 /// integer types where they don't already exist in the code. In the future,
8274 /// we should consider making this based off target-data, so that 32-bit targets
8275 /// won't get i64 operations etc.
8276 static bool isSafeIntegerType(const Type *Ty) {
8277 switch (Ty->getPrimitiveSizeInBits()) {
8288 /// commonIntCastTransforms - This function implements the common transforms
8289 /// for trunc, zext, and sext.
8290 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8291 if (Instruction *Result = commonCastTransforms(CI))
8294 Value *Src = CI.getOperand(0);
8295 const Type *SrcTy = Src->getType();
8296 const Type *DestTy = CI.getType();
8297 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8298 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8300 // See if we can simplify any instructions used by the LHS whose sole
8301 // purpose is to compute bits we don't care about.
8302 if (SimplifyDemandedInstructionBits(CI))
8305 // If the source isn't an instruction or has more than one use then we
8306 // can't do anything more.
8307 Instruction *SrcI = dyn_cast<Instruction>(Src);
8308 if (!SrcI || !Src->hasOneUse())
8311 // Attempt to propagate the cast into the instruction for int->int casts.
8312 int NumCastsRemoved = 0;
8313 // Only do this if the dest type is a simple type, don't convert the
8314 // expression tree to something weird like i93 unless the source is also
8316 if ((isSafeIntegerType(DestTy->getScalarType()) ||
8317 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8318 CanEvaluateInDifferentType(SrcI, DestTy,
8319 CI.getOpcode(), NumCastsRemoved)) {
8320 // If this cast is a truncate, evaluting in a different type always
8321 // eliminates the cast, so it is always a win. If this is a zero-extension,
8322 // we need to do an AND to maintain the clear top-part of the computation,
8323 // so we require that the input have eliminated at least one cast. If this
8324 // is a sign extension, we insert two new casts (to do the extension) so we
8325 // require that two casts have been eliminated.
8326 bool DoXForm = false;
8327 bool JustReplace = false;
8328 switch (CI.getOpcode()) {
8330 // All the others use floating point so we shouldn't actually
8331 // get here because of the check above.
8332 llvm_unreachable("Unknown cast type");
8333 case Instruction::Trunc:
8336 case Instruction::ZExt: {
8337 DoXForm = NumCastsRemoved >= 1;
8338 if (!DoXForm && 0) {
8339 // If it's unnecessary to issue an AND to clear the high bits, it's
8340 // always profitable to do this xform.
8341 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8342 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8343 if (MaskedValueIsZero(TryRes, Mask))
8344 return ReplaceInstUsesWith(CI, TryRes);
8346 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8347 if (TryI->use_empty())
8348 EraseInstFromFunction(*TryI);
8352 case Instruction::SExt: {
8353 DoXForm = NumCastsRemoved >= 2;
8354 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8355 // If we do not have to emit the truncate + sext pair, then it's always
8356 // profitable to do this xform.
8358 // It's not safe to eliminate the trunc + sext pair if one of the
8359 // eliminated cast is a truncate. e.g.
8360 // t2 = trunc i32 t1 to i16
8361 // t3 = sext i16 t2 to i32
8364 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8365 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8366 if (NumSignBits > (DestBitSize - SrcBitSize))
8367 return ReplaceInstUsesWith(CI, TryRes);
8369 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8370 if (TryI->use_empty())
8371 EraseInstFromFunction(*TryI);
8378 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8380 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8381 CI.getOpcode() == Instruction::SExt);
8383 // Just replace this cast with the result.
8384 return ReplaceInstUsesWith(CI, Res);
8386 assert(Res->getType() == DestTy);
8387 switch (CI.getOpcode()) {
8388 default: llvm_unreachable("Unknown cast type!");
8389 case Instruction::Trunc:
8390 // Just replace this cast with the result.
8391 return ReplaceInstUsesWith(CI, Res);
8392 case Instruction::ZExt: {
8393 assert(SrcBitSize < DestBitSize && "Not a zext?");
8395 // If the high bits are already zero, just replace this cast with the
8397 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8398 if (MaskedValueIsZero(Res, Mask))
8399 return ReplaceInstUsesWith(CI, Res);
8401 // We need to emit an AND to clear the high bits.
8402 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8404 return BinaryOperator::CreateAnd(Res, C);
8406 case Instruction::SExt: {
8407 // If the high bits are already filled with sign bit, just replace this
8408 // cast with the result.
8409 unsigned NumSignBits = ComputeNumSignBits(Res);
8410 if (NumSignBits > (DestBitSize - SrcBitSize))
8411 return ReplaceInstUsesWith(CI, Res);
8413 // We need to emit a cast to truncate, then a cast to sext.
8414 return CastInst::Create(Instruction::SExt,
8415 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8422 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8423 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8425 switch (SrcI->getOpcode()) {
8426 case Instruction::Add:
8427 case Instruction::Mul:
8428 case Instruction::And:
8429 case Instruction::Or:
8430 case Instruction::Xor:
8431 // If we are discarding information, rewrite.
8432 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8433 // Don't insert two casts unless at least one can be eliminated.
8434 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8435 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8436 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8437 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8438 return BinaryOperator::Create(
8439 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8443 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8444 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8445 SrcI->getOpcode() == Instruction::Xor &&
8446 Op1 == Context->getConstantIntTrue() &&
8447 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8448 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8449 return BinaryOperator::CreateXor(New,
8450 Context->getConstantInt(CI.getType(), 1));
8454 case Instruction::Shl: {
8455 // Canonicalize trunc inside shl, if we can.
8456 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8457 if (CI && DestBitSize < SrcBitSize &&
8458 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8459 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8460 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8461 return BinaryOperator::CreateShl(Op0c, Op1c);
8469 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8470 if (Instruction *Result = commonIntCastTransforms(CI))
8473 Value *Src = CI.getOperand(0);
8474 const Type *Ty = CI.getType();
8475 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8476 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8478 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8479 if (DestBitWidth == 1 &&
8480 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8481 Constant *One = Context->getConstantInt(Src->getType(), 1);
8482 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8483 Value *Zero = Context->getNullValue(Src->getType());
8484 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8487 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8488 ConstantInt *ShAmtV = 0;
8490 if (Src->hasOneUse() &&
8491 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8492 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8494 // Get a mask for the bits shifting in.
8495 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8496 if (MaskedValueIsZero(ShiftOp, Mask)) {
8497 if (ShAmt >= DestBitWidth) // All zeros.
8498 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8500 // Okay, we can shrink this. Truncate the input, then return a new
8502 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8503 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8504 return BinaryOperator::CreateLShr(V1, V2);
8511 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8512 /// in order to eliminate the icmp.
8513 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8515 // If we are just checking for a icmp eq of a single bit and zext'ing it
8516 // to an integer, then shift the bit to the appropriate place and then
8517 // cast to integer to avoid the comparison.
8518 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8519 const APInt &Op1CV = Op1C->getValue();
8521 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8522 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8523 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8524 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8525 if (!DoXform) return ICI;
8527 Value *In = ICI->getOperand(0);
8528 Value *Sh = Context->getConstantInt(In->getType(),
8529 In->getType()->getScalarSizeInBits()-1);
8530 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8531 In->getName()+".lobit"),
8533 if (In->getType() != CI.getType())
8534 In = CastInst::CreateIntegerCast(In, CI.getType(),
8535 false/*ZExt*/, "tmp", &CI);
8537 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8538 Constant *One = Context->getConstantInt(In->getType(), 1);
8539 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8540 In->getName()+".not"),
8544 return ReplaceInstUsesWith(CI, In);
8549 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8550 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8551 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8552 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8553 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8554 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8555 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8556 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8557 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8558 // This only works for EQ and NE
8559 ICI->isEquality()) {
8560 // If Op1C some other power of two, convert:
8561 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8562 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8563 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8564 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8566 APInt KnownZeroMask(~KnownZero);
8567 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8568 if (!DoXform) return ICI;
8570 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8571 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8572 // (X&4) == 2 --> false
8573 // (X&4) != 2 --> true
8574 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8575 Res = Context->getConstantExprZExt(Res, CI.getType());
8576 return ReplaceInstUsesWith(CI, Res);
8579 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8580 Value *In = ICI->getOperand(0);
8582 // Perform a logical shr by shiftamt.
8583 // Insert the shift to put the result in the low bit.
8584 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8585 Context->getConstantInt(In->getType(), ShiftAmt),
8586 In->getName()+".lobit"), CI);
8589 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8590 Constant *One = Context->getConstantInt(In->getType(), 1);
8591 In = BinaryOperator::CreateXor(In, One, "tmp");
8592 InsertNewInstBefore(cast<Instruction>(In), CI);
8595 if (CI.getType() == In->getType())
8596 return ReplaceInstUsesWith(CI, In);
8598 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8606 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8607 // If one of the common conversion will work ..
8608 if (Instruction *Result = commonIntCastTransforms(CI))
8611 Value *Src = CI.getOperand(0);
8613 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8614 // types and if the sizes are just right we can convert this into a logical
8615 // 'and' which will be much cheaper than the pair of casts.
8616 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8617 // Get the sizes of the types involved. We know that the intermediate type
8618 // will be smaller than A or C, but don't know the relation between A and C.
8619 Value *A = CSrc->getOperand(0);
8620 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8621 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8622 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8623 // If we're actually extending zero bits, then if
8624 // SrcSize < DstSize: zext(a & mask)
8625 // SrcSize == DstSize: a & mask
8626 // SrcSize > DstSize: trunc(a) & mask
8627 if (SrcSize < DstSize) {
8628 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8629 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8631 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8632 InsertNewInstBefore(And, CI);
8633 return new ZExtInst(And, CI.getType());
8634 } else if (SrcSize == DstSize) {
8635 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8636 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8638 } else if (SrcSize > DstSize) {
8639 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8640 InsertNewInstBefore(Trunc, CI);
8641 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8642 return BinaryOperator::CreateAnd(Trunc,
8643 Context->getConstantInt(Trunc->getType(),
8648 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8649 return transformZExtICmp(ICI, CI);
8651 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8652 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8653 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8654 // of the (zext icmp) will be transformed.
8655 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8656 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8657 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8658 (transformZExtICmp(LHS, CI, false) ||
8659 transformZExtICmp(RHS, CI, false))) {
8660 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8661 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8662 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8666 // zext(trunc(t) & C) -> (t & zext(C)).
8667 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8668 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8669 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8670 Value *TI0 = TI->getOperand(0);
8671 if (TI0->getType() == CI.getType())
8673 BinaryOperator::CreateAnd(TI0,
8674 Context->getConstantExprZExt(C, CI.getType()));
8677 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8678 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8679 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8680 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8681 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8682 And->getOperand(1) == C)
8683 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8684 Value *TI0 = TI->getOperand(0);
8685 if (TI0->getType() == CI.getType()) {
8686 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8687 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8688 InsertNewInstBefore(NewAnd, *And);
8689 return BinaryOperator::CreateXor(NewAnd, ZC);
8696 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8697 if (Instruction *I = commonIntCastTransforms(CI))
8700 Value *Src = CI.getOperand(0);
8702 // Canonicalize sign-extend from i1 to a select.
8703 if (Src->getType() == Type::Int1Ty)
8704 return SelectInst::Create(Src,
8705 Context->getAllOnesValue(CI.getType()),
8706 Context->getNullValue(CI.getType()));
8708 // See if the value being truncated is already sign extended. If so, just
8709 // eliminate the trunc/sext pair.
8710 if (getOpcode(Src) == Instruction::Trunc) {
8711 Value *Op = cast<User>(Src)->getOperand(0);
8712 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8713 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8714 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8715 unsigned NumSignBits = ComputeNumSignBits(Op);
8717 if (OpBits == DestBits) {
8718 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8719 // bits, it is already ready.
8720 if (NumSignBits > DestBits-MidBits)
8721 return ReplaceInstUsesWith(CI, Op);
8722 } else if (OpBits < DestBits) {
8723 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8724 // bits, just sext from i32.
8725 if (NumSignBits > OpBits-MidBits)
8726 return new SExtInst(Op, CI.getType(), "tmp");
8728 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8729 // bits, just truncate to i32.
8730 if (NumSignBits > OpBits-MidBits)
8731 return new TruncInst(Op, CI.getType(), "tmp");
8735 // If the input is a shl/ashr pair of a same constant, then this is a sign
8736 // extension from a smaller value. If we could trust arbitrary bitwidth
8737 // integers, we could turn this into a truncate to the smaller bit and then
8738 // use a sext for the whole extension. Since we don't, look deeper and check
8739 // for a truncate. If the source and dest are the same type, eliminate the
8740 // trunc and extend and just do shifts. For example, turn:
8741 // %a = trunc i32 %i to i8
8742 // %b = shl i8 %a, 6
8743 // %c = ashr i8 %b, 6
8744 // %d = sext i8 %c to i32
8746 // %a = shl i32 %i, 30
8747 // %d = ashr i32 %a, 30
8749 ConstantInt *BA = 0, *CA = 0;
8750 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8751 m_ConstantInt(CA)), *Context) &&
8752 BA == CA && isa<TruncInst>(A)) {
8753 Value *I = cast<TruncInst>(A)->getOperand(0);
8754 if (I->getType() == CI.getType()) {
8755 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8756 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8757 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8758 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8759 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8761 return BinaryOperator::CreateAShr(I, ShAmtV);
8768 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8769 /// in the specified FP type without changing its value.
8770 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8771 LLVMContext *Context) {
8773 APFloat F = CFP->getValueAPF();
8774 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8776 return Context->getConstantFP(F);
8780 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8781 /// through it until we get the source value.
8782 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8783 if (Instruction *I = dyn_cast<Instruction>(V))
8784 if (I->getOpcode() == Instruction::FPExt)
8785 return LookThroughFPExtensions(I->getOperand(0), Context);
8787 // If this value is a constant, return the constant in the smallest FP type
8788 // that can accurately represent it. This allows us to turn
8789 // (float)((double)X+2.0) into x+2.0f.
8790 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8791 if (CFP->getType() == Type::PPC_FP128Ty)
8792 return V; // No constant folding of this.
8793 // See if the value can be truncated to float and then reextended.
8794 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8796 if (CFP->getType() == Type::DoubleTy)
8797 return V; // Won't shrink.
8798 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8800 // Don't try to shrink to various long double types.
8806 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8807 if (Instruction *I = commonCastTransforms(CI))
8810 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8811 // smaller than the destination type, we can eliminate the truncate by doing
8812 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8813 // many builtins (sqrt, etc).
8814 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8815 if (OpI && OpI->hasOneUse()) {
8816 switch (OpI->getOpcode()) {
8818 case Instruction::FAdd:
8819 case Instruction::FSub:
8820 case Instruction::FMul:
8821 case Instruction::FDiv:
8822 case Instruction::FRem:
8823 const Type *SrcTy = OpI->getType();
8824 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8825 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8826 if (LHSTrunc->getType() != SrcTy &&
8827 RHSTrunc->getType() != SrcTy) {
8828 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8829 // If the source types were both smaller than the destination type of
8830 // the cast, do this xform.
8831 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8832 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8833 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8835 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8837 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8846 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8847 return commonCastTransforms(CI);
8850 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8851 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8853 return commonCastTransforms(FI);
8855 // fptoui(uitofp(X)) --> X
8856 // fptoui(sitofp(X)) --> X
8857 // This is safe if the intermediate type has enough bits in its mantissa to
8858 // accurately represent all values of X. For example, do not do this with
8859 // i64->float->i64. This is also safe for sitofp case, because any negative
8860 // 'X' value would cause an undefined result for the fptoui.
8861 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8862 OpI->getOperand(0)->getType() == FI.getType() &&
8863 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8864 OpI->getType()->getFPMantissaWidth())
8865 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8867 return commonCastTransforms(FI);
8870 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8871 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8873 return commonCastTransforms(FI);
8875 // fptosi(sitofp(X)) --> X
8876 // fptosi(uitofp(X)) --> X
8877 // This is safe if the intermediate type has enough bits in its mantissa to
8878 // accurately represent all values of X. For example, do not do this with
8879 // i64->float->i64. This is also safe for sitofp case, because any negative
8880 // 'X' value would cause an undefined result for the fptoui.
8881 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8882 OpI->getOperand(0)->getType() == FI.getType() &&
8883 (int)FI.getType()->getScalarSizeInBits() <=
8884 OpI->getType()->getFPMantissaWidth())
8885 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8887 return commonCastTransforms(FI);
8890 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8891 return commonCastTransforms(CI);
8894 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8895 return commonCastTransforms(CI);
8898 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8899 // If the destination integer type is smaller than the intptr_t type for
8900 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8901 // trunc to be exposed to other transforms. Don't do this for extending
8902 // ptrtoint's, because we don't know if the target sign or zero extends its
8904 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8905 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8906 TD->getIntPtrType(),
8908 return new TruncInst(P, CI.getType());
8911 return commonPointerCastTransforms(CI);
8914 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8915 // If the source integer type is larger than the intptr_t type for
8916 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8917 // allows the trunc to be exposed to other transforms. Don't do this for
8918 // extending inttoptr's, because we don't know if the target sign or zero
8919 // extends to pointers.
8920 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8921 TD->getPointerSizeInBits()) {
8922 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8923 TD->getIntPtrType(),
8925 return new IntToPtrInst(P, CI.getType());
8928 if (Instruction *I = commonCastTransforms(CI))
8931 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8932 if (!DestPointee->isSized()) return 0;
8934 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8937 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8938 m_ConstantInt(Cst)), *Context)) {
8939 // If the source and destination operands have the same type, see if this
8940 // is a single-index GEP.
8941 if (X->getType() == CI.getType()) {
8942 // Get the size of the pointee type.
8943 uint64_t Size = TD->getTypeAllocSize(DestPointee);
8945 // Convert the constant to intptr type.
8946 APInt Offset = Cst->getValue();
8947 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8949 // If Offset is evenly divisible by Size, we can do this xform.
8950 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8951 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8952 return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8955 // TODO: Could handle other cases, e.g. where add is indexing into field of
8957 } else if (CI.getOperand(0)->hasOneUse() &&
8958 match(CI.getOperand(0), m_Add(m_Value(X),
8959 m_ConstantInt(Cst)), *Context)) {
8960 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8961 // "inttoptr+GEP" instead of "add+intptr".
8963 // Get the size of the pointee type.
8964 uint64_t Size = TD->getTypeAllocSize(DestPointee);
8966 // Convert the constant to intptr type.
8967 APInt Offset = Cst->getValue();
8968 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8970 // If Offset is evenly divisible by Size, we can do this xform.
8971 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8972 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8974 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8976 return GetElementPtrInst::Create(P,
8977 Context->getConstantInt(Offset), "tmp");
8983 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8984 // If the operands are integer typed then apply the integer transforms,
8985 // otherwise just apply the common ones.
8986 Value *Src = CI.getOperand(0);
8987 const Type *SrcTy = Src->getType();
8988 const Type *DestTy = CI.getType();
8990 if (isa<PointerType>(SrcTy)) {
8991 if (Instruction *I = commonPointerCastTransforms(CI))
8994 if (Instruction *Result = commonCastTransforms(CI))
8999 // Get rid of casts from one type to the same type. These are useless and can
9000 // be replaced by the operand.
9001 if (DestTy == Src->getType())
9002 return ReplaceInstUsesWith(CI, Src);
9004 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9005 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9006 const Type *DstElTy = DstPTy->getElementType();
9007 const Type *SrcElTy = SrcPTy->getElementType();
9009 // If the address spaces don't match, don't eliminate the bitcast, which is
9010 // required for changing types.
9011 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9014 // If we are casting a malloc or alloca to a pointer to a type of the same
9015 // size, rewrite the allocation instruction to allocate the "right" type.
9016 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9017 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9020 // If the source and destination are pointers, and this cast is equivalent
9021 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
9022 // This can enhance SROA and other transforms that want type-safe pointers.
9023 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9024 unsigned NumZeros = 0;
9025 while (SrcElTy != DstElTy &&
9026 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9027 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9028 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9032 // If we found a path from the src to dest, create the getelementptr now.
9033 if (SrcElTy == DstElTy) {
9034 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9035 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
9036 ((Instruction*) NULL));
9040 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9041 if (SVI->hasOneUse()) {
9042 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9043 // a bitconvert to a vector with the same # elts.
9044 if (isa<VectorType>(DestTy) &&
9045 cast<VectorType>(DestTy)->getNumElements() ==
9046 SVI->getType()->getNumElements() &&
9047 SVI->getType()->getNumElements() ==
9048 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9050 // If either of the operands is a cast from CI.getType(), then
9051 // evaluating the shuffle in the casted destination's type will allow
9052 // us to eliminate at least one cast.
9053 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9054 Tmp->getOperand(0)->getType() == DestTy) ||
9055 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9056 Tmp->getOperand(0)->getType() == DestTy)) {
9057 Value *LHS = InsertCastBefore(Instruction::BitCast,
9058 SVI->getOperand(0), DestTy, CI);
9059 Value *RHS = InsertCastBefore(Instruction::BitCast,
9060 SVI->getOperand(1), DestTy, CI);
9061 // Return a new shuffle vector. Use the same element ID's, as we
9062 // know the vector types match #elts.
9063 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9071 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9073 /// %D = select %cond, %C, %A
9075 /// %C = select %cond, %B, 0
9078 /// Assuming that the specified instruction is an operand to the select, return
9079 /// a bitmask indicating which operands of this instruction are foldable if they
9080 /// equal the other incoming value of the select.
9082 static unsigned GetSelectFoldableOperands(Instruction *I) {
9083 switch (I->getOpcode()) {
9084 case Instruction::Add:
9085 case Instruction::Mul:
9086 case Instruction::And:
9087 case Instruction::Or:
9088 case Instruction::Xor:
9089 return 3; // Can fold through either operand.
9090 case Instruction::Sub: // Can only fold on the amount subtracted.
9091 case Instruction::Shl: // Can only fold on the shift amount.
9092 case Instruction::LShr:
9093 case Instruction::AShr:
9096 return 0; // Cannot fold
9100 /// GetSelectFoldableConstant - For the same transformation as the previous
9101 /// function, return the identity constant that goes into the select.
9102 static Constant *GetSelectFoldableConstant(Instruction *I,
9103 LLVMContext *Context) {
9104 switch (I->getOpcode()) {
9105 default: llvm_unreachable("This cannot happen!");
9106 case Instruction::Add:
9107 case Instruction::Sub:
9108 case Instruction::Or:
9109 case Instruction::Xor:
9110 case Instruction::Shl:
9111 case Instruction::LShr:
9112 case Instruction::AShr:
9113 return Context->getNullValue(I->getType());
9114 case Instruction::And:
9115 return Context->getAllOnesValue(I->getType());
9116 case Instruction::Mul:
9117 return Context->getConstantInt(I->getType(), 1);
9121 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9122 /// have the same opcode and only one use each. Try to simplify this.
9123 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9125 if (TI->getNumOperands() == 1) {
9126 // If this is a non-volatile load or a cast from the same type,
9129 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9132 return 0; // unknown unary op.
9135 // Fold this by inserting a select from the input values.
9136 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9137 FI->getOperand(0), SI.getName()+".v");
9138 InsertNewInstBefore(NewSI, SI);
9139 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
9143 // Only handle binary operators here.
9144 if (!isa<BinaryOperator>(TI))
9147 // Figure out if the operations have any operands in common.
9148 Value *MatchOp, *OtherOpT, *OtherOpF;
9150 if (TI->getOperand(0) == FI->getOperand(0)) {
9151 MatchOp = TI->getOperand(0);
9152 OtherOpT = TI->getOperand(1);
9153 OtherOpF = FI->getOperand(1);
9154 MatchIsOpZero = true;
9155 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9156 MatchOp = TI->getOperand(1);
9157 OtherOpT = TI->getOperand(0);
9158 OtherOpF = FI->getOperand(0);
9159 MatchIsOpZero = false;
9160 } else if (!TI->isCommutative()) {
9162 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9163 MatchOp = TI->getOperand(0);
9164 OtherOpT = TI->getOperand(1);
9165 OtherOpF = FI->getOperand(0);
9166 MatchIsOpZero = true;
9167 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9168 MatchOp = TI->getOperand(1);
9169 OtherOpT = TI->getOperand(0);
9170 OtherOpF = FI->getOperand(1);
9171 MatchIsOpZero = true;
9176 // If we reach here, they do have operations in common.
9177 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9178 OtherOpF, SI.getName()+".v");
9179 InsertNewInstBefore(NewSI, SI);
9181 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9183 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9185 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9187 llvm_unreachable("Shouldn't get here");
9191 static bool isSelect01(Constant *C1, Constant *C2) {
9192 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9195 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9198 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9201 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9202 /// facilitate further optimization.
9203 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9205 // See the comment above GetSelectFoldableOperands for a description of the
9206 // transformation we are doing here.
9207 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9208 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9209 !isa<Constant>(FalseVal)) {
9210 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9211 unsigned OpToFold = 0;
9212 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9214 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9219 Constant *C = GetSelectFoldableConstant(TVI, Context);
9220 Value *OOp = TVI->getOperand(2-OpToFold);
9221 // Avoid creating select between 2 constants unless it's selecting
9223 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9224 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9225 InsertNewInstBefore(NewSel, SI);
9226 NewSel->takeName(TVI);
9227 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9228 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9229 llvm_unreachable("Unknown instruction!!");
9236 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9237 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9238 !isa<Constant>(TrueVal)) {
9239 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9240 unsigned OpToFold = 0;
9241 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9243 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9248 Constant *C = GetSelectFoldableConstant(FVI, Context);
9249 Value *OOp = FVI->getOperand(2-OpToFold);
9250 // Avoid creating select between 2 constants unless it's selecting
9252 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9253 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9254 InsertNewInstBefore(NewSel, SI);
9255 NewSel->takeName(FVI);
9256 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9257 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9258 llvm_unreachable("Unknown instruction!!");
9268 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9269 /// ICmpInst as its first operand.
9271 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9273 bool Changed = false;
9274 ICmpInst::Predicate Pred = ICI->getPredicate();
9275 Value *CmpLHS = ICI->getOperand(0);
9276 Value *CmpRHS = ICI->getOperand(1);
9277 Value *TrueVal = SI.getTrueValue();
9278 Value *FalseVal = SI.getFalseValue();
9280 // Check cases where the comparison is with a constant that
9281 // can be adjusted to fit the min/max idiom. We may edit ICI in
9282 // place here, so make sure the select is the only user.
9283 if (ICI->hasOneUse())
9284 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9287 case ICmpInst::ICMP_ULT:
9288 case ICmpInst::ICMP_SLT: {
9289 // X < MIN ? T : F --> F
9290 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9291 return ReplaceInstUsesWith(SI, FalseVal);
9292 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9293 Constant *AdjustedRHS = SubOne(CI, Context);
9294 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9295 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9296 Pred = ICmpInst::getSwappedPredicate(Pred);
9297 CmpRHS = AdjustedRHS;
9298 std::swap(FalseVal, TrueVal);
9299 ICI->setPredicate(Pred);
9300 ICI->setOperand(1, CmpRHS);
9301 SI.setOperand(1, TrueVal);
9302 SI.setOperand(2, FalseVal);
9307 case ICmpInst::ICMP_UGT:
9308 case ICmpInst::ICMP_SGT: {
9309 // X > MAX ? T : F --> F
9310 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9311 return ReplaceInstUsesWith(SI, FalseVal);
9312 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9313 Constant *AdjustedRHS = AddOne(CI, Context);
9314 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9315 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9316 Pred = ICmpInst::getSwappedPredicate(Pred);
9317 CmpRHS = AdjustedRHS;
9318 std::swap(FalseVal, TrueVal);
9319 ICI->setPredicate(Pred);
9320 ICI->setOperand(1, CmpRHS);
9321 SI.setOperand(1, TrueVal);
9322 SI.setOperand(2, FalseVal);
9329 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9330 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9331 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9332 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9333 match(FalseVal, m_ConstantInt<0>(), *Context))
9334 Pred = ICI->getPredicate();
9335 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9336 match(FalseVal, m_ConstantInt<-1>(), *Context))
9337 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9339 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9340 // If we are just checking for a icmp eq of a single bit and zext'ing it
9341 // to an integer, then shift the bit to the appropriate place and then
9342 // cast to integer to avoid the comparison.
9343 const APInt &Op1CV = CI->getValue();
9345 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9346 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9347 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9348 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9349 Value *In = ICI->getOperand(0);
9350 Value *Sh = Context->getConstantInt(In->getType(),
9351 In->getType()->getScalarSizeInBits()-1);
9352 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9353 In->getName()+".lobit"),
9355 if (In->getType() != SI.getType())
9356 In = CastInst::CreateIntegerCast(In, SI.getType(),
9357 true/*SExt*/, "tmp", ICI);
9359 if (Pred == ICmpInst::ICMP_SGT)
9360 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9361 In->getName()+".not"), *ICI);
9363 return ReplaceInstUsesWith(SI, In);
9368 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9369 // Transform (X == Y) ? X : Y -> Y
9370 if (Pred == ICmpInst::ICMP_EQ)
9371 return ReplaceInstUsesWith(SI, FalseVal);
9372 // Transform (X != Y) ? X : Y -> X
9373 if (Pred == ICmpInst::ICMP_NE)
9374 return ReplaceInstUsesWith(SI, TrueVal);
9375 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9377 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9378 // Transform (X == Y) ? Y : X -> X
9379 if (Pred == ICmpInst::ICMP_EQ)
9380 return ReplaceInstUsesWith(SI, FalseVal);
9381 // Transform (X != Y) ? Y : X -> Y
9382 if (Pred == ICmpInst::ICMP_NE)
9383 return ReplaceInstUsesWith(SI, TrueVal);
9384 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9387 /// NOTE: if we wanted to, this is where to detect integer ABS
9389 return Changed ? &SI : 0;
9392 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9393 Value *CondVal = SI.getCondition();
9394 Value *TrueVal = SI.getTrueValue();
9395 Value *FalseVal = SI.getFalseValue();
9397 // select true, X, Y -> X
9398 // select false, X, Y -> Y
9399 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9400 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9402 // select C, X, X -> X
9403 if (TrueVal == FalseVal)
9404 return ReplaceInstUsesWith(SI, TrueVal);
9406 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9407 return ReplaceInstUsesWith(SI, FalseVal);
9408 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9409 return ReplaceInstUsesWith(SI, TrueVal);
9410 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9411 if (isa<Constant>(TrueVal))
9412 return ReplaceInstUsesWith(SI, TrueVal);
9414 return ReplaceInstUsesWith(SI, FalseVal);
9417 if (SI.getType() == Type::Int1Ty) {
9418 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9419 if (C->getZExtValue()) {
9420 // Change: A = select B, true, C --> A = or B, C
9421 return BinaryOperator::CreateOr(CondVal, FalseVal);
9423 // Change: A = select B, false, C --> A = and !B, C
9425 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9426 "not."+CondVal->getName()), SI);
9427 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9429 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9430 if (C->getZExtValue() == false) {
9431 // Change: A = select B, C, false --> A = and B, C
9432 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9434 // Change: A = select B, C, true --> A = or !B, C
9436 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9437 "not."+CondVal->getName()), SI);
9438 return BinaryOperator::CreateOr(NotCond, TrueVal);
9442 // select a, b, a -> a&b
9443 // select a, a, b -> a|b
9444 if (CondVal == TrueVal)
9445 return BinaryOperator::CreateOr(CondVal, FalseVal);
9446 else if (CondVal == FalseVal)
9447 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9450 // Selecting between two integer constants?
9451 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9452 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9453 // select C, 1, 0 -> zext C to int
9454 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9455 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9456 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9457 // select C, 0, 1 -> zext !C to int
9459 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9460 "not."+CondVal->getName()), SI);
9461 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9464 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9465 // If one of the constants is zero (we know they can't both be) and we
9466 // have an icmp instruction with zero, and we have an 'and' with the
9467 // non-constant value, eliminate this whole mess. This corresponds to
9468 // cases like this: ((X & 27) ? 27 : 0)
9469 if (TrueValC->isZero() || FalseValC->isZero())
9470 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9471 cast<Constant>(IC->getOperand(1))->isNullValue())
9472 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9473 if (ICA->getOpcode() == Instruction::And &&
9474 isa<ConstantInt>(ICA->getOperand(1)) &&
9475 (ICA->getOperand(1) == TrueValC ||
9476 ICA->getOperand(1) == FalseValC) &&
9477 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9478 // Okay, now we know that everything is set up, we just don't
9479 // know whether we have a icmp_ne or icmp_eq and whether the
9480 // true or false val is the zero.
9481 bool ShouldNotVal = !TrueValC->isZero();
9482 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9485 V = InsertNewInstBefore(BinaryOperator::Create(
9486 Instruction::Xor, V, ICA->getOperand(1)), SI);
9487 return ReplaceInstUsesWith(SI, V);
9492 // See if we are selecting two values based on a comparison of the two values.
9493 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9494 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9495 // Transform (X == Y) ? X : Y -> Y
9496 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9497 // This is not safe in general for floating point:
9498 // consider X== -0, Y== +0.
9499 // It becomes safe if either operand is a nonzero constant.
9500 ConstantFP *CFPt, *CFPf;
9501 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9502 !CFPt->getValueAPF().isZero()) ||
9503 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9504 !CFPf->getValueAPF().isZero()))
9505 return ReplaceInstUsesWith(SI, FalseVal);
9507 // Transform (X != Y) ? X : Y -> X
9508 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9509 return ReplaceInstUsesWith(SI, TrueVal);
9510 // NOTE: if we wanted to, this is where to detect MIN/MAX
9512 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9513 // Transform (X == Y) ? Y : X -> X
9514 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9515 // This is not safe in general for floating point:
9516 // consider X== -0, Y== +0.
9517 // It becomes safe if either operand is a nonzero constant.
9518 ConstantFP *CFPt, *CFPf;
9519 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9520 !CFPt->getValueAPF().isZero()) ||
9521 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9522 !CFPf->getValueAPF().isZero()))
9523 return ReplaceInstUsesWith(SI, FalseVal);
9525 // Transform (X != Y) ? Y : X -> Y
9526 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9527 return ReplaceInstUsesWith(SI, TrueVal);
9528 // NOTE: if we wanted to, this is where to detect MIN/MAX
9530 // NOTE: if we wanted to, this is where to detect ABS
9533 // See if we are selecting two values based on a comparison of the two values.
9534 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9535 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9538 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9539 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9540 if (TI->hasOneUse() && FI->hasOneUse()) {
9541 Instruction *AddOp = 0, *SubOp = 0;
9543 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9544 if (TI->getOpcode() == FI->getOpcode())
9545 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9548 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9549 // even legal for FP.
9550 if ((TI->getOpcode() == Instruction::Sub &&
9551 FI->getOpcode() == Instruction::Add) ||
9552 (TI->getOpcode() == Instruction::FSub &&
9553 FI->getOpcode() == Instruction::FAdd)) {
9554 AddOp = FI; SubOp = TI;
9555 } else if ((FI->getOpcode() == Instruction::Sub &&
9556 TI->getOpcode() == Instruction::Add) ||
9557 (FI->getOpcode() == Instruction::FSub &&
9558 TI->getOpcode() == Instruction::FAdd)) {
9559 AddOp = TI; SubOp = FI;
9563 Value *OtherAddOp = 0;
9564 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9565 OtherAddOp = AddOp->getOperand(1);
9566 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9567 OtherAddOp = AddOp->getOperand(0);
9571 // So at this point we know we have (Y -> OtherAddOp):
9572 // select C, (add X, Y), (sub X, Z)
9573 Value *NegVal; // Compute -Z
9574 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9575 NegVal = Context->getConstantExprNeg(C);
9577 NegVal = InsertNewInstBefore(
9578 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9582 Value *NewTrueOp = OtherAddOp;
9583 Value *NewFalseOp = NegVal;
9585 std::swap(NewTrueOp, NewFalseOp);
9586 Instruction *NewSel =
9587 SelectInst::Create(CondVal, NewTrueOp,
9588 NewFalseOp, SI.getName() + ".p");
9590 NewSel = InsertNewInstBefore(NewSel, SI);
9591 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9596 // See if we can fold the select into one of our operands.
9597 if (SI.getType()->isInteger()) {
9598 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9603 if (BinaryOperator::isNot(CondVal)) {
9604 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9605 SI.setOperand(1, FalseVal);
9606 SI.setOperand(2, TrueVal);
9613 /// EnforceKnownAlignment - If the specified pointer points to an object that
9614 /// we control, modify the object's alignment to PrefAlign. This isn't
9615 /// often possible though. If alignment is important, a more reliable approach
9616 /// is to simply align all global variables and allocation instructions to
9617 /// their preferred alignment from the beginning.
9619 static unsigned EnforceKnownAlignment(Value *V,
9620 unsigned Align, unsigned PrefAlign) {
9622 User *U = dyn_cast<User>(V);
9623 if (!U) return Align;
9625 switch (getOpcode(U)) {
9627 case Instruction::BitCast:
9628 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9629 case Instruction::GetElementPtr: {
9630 // If all indexes are zero, it is just the alignment of the base pointer.
9631 bool AllZeroOperands = true;
9632 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9633 if (!isa<Constant>(*i) ||
9634 !cast<Constant>(*i)->isNullValue()) {
9635 AllZeroOperands = false;
9639 if (AllZeroOperands) {
9640 // Treat this like a bitcast.
9641 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9647 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9648 // If there is a large requested alignment and we can, bump up the alignment
9650 if (!GV->isDeclaration()) {
9651 if (GV->getAlignment() >= PrefAlign)
9652 Align = GV->getAlignment();
9654 GV->setAlignment(PrefAlign);
9658 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9659 // If there is a requested alignment and if this is an alloca, round up. We
9660 // don't do this for malloc, because some systems can't respect the request.
9661 if (isa<AllocaInst>(AI)) {
9662 if (AI->getAlignment() >= PrefAlign)
9663 Align = AI->getAlignment();
9665 AI->setAlignment(PrefAlign);
9674 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9675 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9676 /// and it is more than the alignment of the ultimate object, see if we can
9677 /// increase the alignment of the ultimate object, making this check succeed.
9678 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9679 unsigned PrefAlign) {
9680 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9681 sizeof(PrefAlign) * CHAR_BIT;
9682 APInt Mask = APInt::getAllOnesValue(BitWidth);
9683 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9684 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9685 unsigned TrailZ = KnownZero.countTrailingOnes();
9686 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9688 if (PrefAlign > Align)
9689 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9691 // We don't need to make any adjustment.
9695 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9696 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9697 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9698 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9699 unsigned CopyAlign = MI->getAlignment();
9701 if (CopyAlign < MinAlign) {
9702 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9707 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9709 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9710 if (MemOpLength == 0) return 0;
9712 // Source and destination pointer types are always "i8*" for intrinsic. See
9713 // if the size is something we can handle with a single primitive load/store.
9714 // A single load+store correctly handles overlapping memory in the memmove
9716 unsigned Size = MemOpLength->getZExtValue();
9717 if (Size == 0) return MI; // Delete this mem transfer.
9719 if (Size > 8 || (Size&(Size-1)))
9720 return 0; // If not 1/2/4/8 bytes, exit.
9722 // Use an integer load+store unless we can find something better.
9724 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9726 // Memcpy forces the use of i8* for the source and destination. That means
9727 // that if you're using memcpy to move one double around, you'll get a cast
9728 // from double* to i8*. We'd much rather use a double load+store rather than
9729 // an i64 load+store, here because this improves the odds that the source or
9730 // dest address will be promotable. See if we can find a better type than the
9731 // integer datatype.
9732 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9733 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9734 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9735 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9736 // down through these levels if so.
9737 while (!SrcETy->isSingleValueType()) {
9738 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9739 if (STy->getNumElements() == 1)
9740 SrcETy = STy->getElementType(0);
9743 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9744 if (ATy->getNumElements() == 1)
9745 SrcETy = ATy->getElementType();
9752 if (SrcETy->isSingleValueType())
9753 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9758 // If the memcpy/memmove provides better alignment info than we can
9760 SrcAlign = std::max(SrcAlign, CopyAlign);
9761 DstAlign = std::max(DstAlign, CopyAlign);
9763 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9764 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9765 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9766 InsertNewInstBefore(L, *MI);
9767 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9769 // Set the size of the copy to 0, it will be deleted on the next iteration.
9770 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9774 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9775 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9776 if (MI->getAlignment() < Alignment) {
9777 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9782 // Extract the length and alignment and fill if they are constant.
9783 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9784 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9785 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9787 uint64_t Len = LenC->getZExtValue();
9788 Alignment = MI->getAlignment();
9790 // If the length is zero, this is a no-op
9791 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9793 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9794 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9795 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
9797 Value *Dest = MI->getDest();
9798 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9800 // Alignment 0 is identity for alignment 1 for memset, but not store.
9801 if (Alignment == 0) Alignment = 1;
9803 // Extract the fill value and store.
9804 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9805 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9806 Dest, false, Alignment), *MI);
9808 // Set the size of the copy to 0, it will be deleted on the next iteration.
9809 MI->setLength(Context->getNullValue(LenC->getType()));
9817 /// visitCallInst - CallInst simplification. This mostly only handles folding
9818 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9819 /// the heavy lifting.
9821 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9822 // If the caller function is nounwind, mark the call as nounwind, even if the
9824 if (CI.getParent()->getParent()->doesNotThrow() &&
9825 !CI.doesNotThrow()) {
9826 CI.setDoesNotThrow();
9832 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9833 if (!II) return visitCallSite(&CI);
9835 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9837 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9838 bool Changed = false;
9840 // memmove/cpy/set of zero bytes is a noop.
9841 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9842 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9844 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9845 if (CI->getZExtValue() == 1) {
9846 // Replace the instruction with just byte operations. We would
9847 // transform other cases to loads/stores, but we don't know if
9848 // alignment is sufficient.
9852 // If we have a memmove and the source operation is a constant global,
9853 // then the source and dest pointers can't alias, so we can change this
9854 // into a call to memcpy.
9855 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9856 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9857 if (GVSrc->isConstant()) {
9858 Module *M = CI.getParent()->getParent()->getParent();
9859 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9861 Tys[0] = CI.getOperand(3)->getType();
9863 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9867 // memmove(x,x,size) -> noop.
9868 if (MMI->getSource() == MMI->getDest())
9869 return EraseInstFromFunction(CI);
9872 // If we can determine a pointer alignment that is bigger than currently
9873 // set, update the alignment.
9874 if (isa<MemTransferInst>(MI)) {
9875 if (Instruction *I = SimplifyMemTransfer(MI))
9877 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9878 if (Instruction *I = SimplifyMemSet(MSI))
9882 if (Changed) return II;
9885 switch (II->getIntrinsicID()) {
9887 case Intrinsic::bswap:
9888 // bswap(bswap(x)) -> x
9889 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9890 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9891 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9893 case Intrinsic::ppc_altivec_lvx:
9894 case Intrinsic::ppc_altivec_lvxl:
9895 case Intrinsic::x86_sse_loadu_ps:
9896 case Intrinsic::x86_sse2_loadu_pd:
9897 case Intrinsic::x86_sse2_loadu_dq:
9898 // Turn PPC lvx -> load if the pointer is known aligned.
9899 // Turn X86 loadups -> load if the pointer is known aligned.
9900 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9901 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9902 Context->getPointerTypeUnqual(II->getType()),
9904 return new LoadInst(Ptr);
9907 case Intrinsic::ppc_altivec_stvx:
9908 case Intrinsic::ppc_altivec_stvxl:
9909 // Turn stvx -> store if the pointer is known aligned.
9910 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9911 const Type *OpPtrTy =
9912 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9913 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9914 return new StoreInst(II->getOperand(1), Ptr);
9917 case Intrinsic::x86_sse_storeu_ps:
9918 case Intrinsic::x86_sse2_storeu_pd:
9919 case Intrinsic::x86_sse2_storeu_dq:
9920 // Turn X86 storeu -> store if the pointer is known aligned.
9921 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9922 const Type *OpPtrTy =
9923 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9924 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9925 return new StoreInst(II->getOperand(2), Ptr);
9929 case Intrinsic::x86_sse_cvttss2si: {
9930 // These intrinsics only demands the 0th element of its input vector. If
9931 // we can simplify the input based on that, do so now.
9933 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9934 APInt DemandedElts(VWidth, 1);
9935 APInt UndefElts(VWidth, 0);
9936 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9938 II->setOperand(1, V);
9944 case Intrinsic::ppc_altivec_vperm:
9945 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9946 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9947 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9949 // Check that all of the elements are integer constants or undefs.
9950 bool AllEltsOk = true;
9951 for (unsigned i = 0; i != 16; ++i) {
9952 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9953 !isa<UndefValue>(Mask->getOperand(i))) {
9960 // Cast the input vectors to byte vectors.
9961 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9962 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9963 Value *Result = Context->getUndef(Op0->getType());
9965 // Only extract each element once.
9966 Value *ExtractedElts[32];
9967 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9969 for (unsigned i = 0; i != 16; ++i) {
9970 if (isa<UndefValue>(Mask->getOperand(i)))
9972 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9973 Idx &= 31; // Match the hardware behavior.
9975 if (ExtractedElts[Idx] == 0) {
9977 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9978 InsertNewInstBefore(Elt, CI);
9979 ExtractedElts[Idx] = Elt;
9982 // Insert this value into the result vector.
9983 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9985 InsertNewInstBefore(cast<Instruction>(Result), CI);
9987 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9992 case Intrinsic::stackrestore: {
9993 // If the save is right next to the restore, remove the restore. This can
9994 // happen when variable allocas are DCE'd.
9995 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9996 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9997 BasicBlock::iterator BI = SS;
9999 return EraseInstFromFunction(CI);
10003 // Scan down this block to see if there is another stack restore in the
10004 // same block without an intervening call/alloca.
10005 BasicBlock::iterator BI = II;
10006 TerminatorInst *TI = II->getParent()->getTerminator();
10007 bool CannotRemove = false;
10008 for (++BI; &*BI != TI; ++BI) {
10009 if (isa<AllocaInst>(BI)) {
10010 CannotRemove = true;
10013 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10014 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10015 // If there is a stackrestore below this one, remove this one.
10016 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10017 return EraseInstFromFunction(CI);
10018 // Otherwise, ignore the intrinsic.
10020 // If we found a non-intrinsic call, we can't remove the stack
10022 CannotRemove = true;
10028 // If the stack restore is in a return/unwind block and if there are no
10029 // allocas or calls between the restore and the return, nuke the restore.
10030 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10031 return EraseInstFromFunction(CI);
10036 return visitCallSite(II);
10039 // InvokeInst simplification
10041 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10042 return visitCallSite(&II);
10045 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
10046 /// passed through the varargs area, we can eliminate the use of the cast.
10047 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10048 const CastInst * const CI,
10049 const TargetData * const TD,
10051 if (!CI->isLosslessCast())
10054 // The size of ByVal arguments is derived from the type, so we
10055 // can't change to a type with a different size. If the size were
10056 // passed explicitly we could avoid this check.
10057 if (!CS.paramHasAttr(ix, Attribute::ByVal))
10060 const Type* SrcTy =
10061 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10062 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10063 if (!SrcTy->isSized() || !DstTy->isSized())
10065 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10070 // visitCallSite - Improvements for call and invoke instructions.
10072 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10073 bool Changed = false;
10075 // If the callee is a constexpr cast of a function, attempt to move the cast
10076 // to the arguments of the call/invoke.
10077 if (transformConstExprCastCall(CS)) return 0;
10079 Value *Callee = CS.getCalledValue();
10081 if (Function *CalleeF = dyn_cast<Function>(Callee))
10082 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10083 Instruction *OldCall = CS.getInstruction();
10084 // If the call and callee calling conventions don't match, this call must
10085 // be unreachable, as the call is undefined.
10086 new StoreInst(Context->getConstantIntTrue(),
10087 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10089 if (!OldCall->use_empty())
10090 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10091 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10092 return EraseInstFromFunction(*OldCall);
10096 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10097 // This instruction is not reachable, just remove it. We insert a store to
10098 // undef so that we know that this code is not reachable, despite the fact
10099 // that we can't modify the CFG here.
10100 new StoreInst(Context->getConstantIntTrue(),
10101 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10102 CS.getInstruction());
10104 if (!CS.getInstruction()->use_empty())
10105 CS.getInstruction()->
10106 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10108 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10109 // Don't break the CFG, insert a dummy cond branch.
10110 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10111 Context->getConstantIntTrue(), II);
10113 return EraseInstFromFunction(*CS.getInstruction());
10116 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10117 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10118 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10119 return transformCallThroughTrampoline(CS);
10121 const PointerType *PTy = cast<PointerType>(Callee->getType());
10122 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10123 if (FTy->isVarArg()) {
10124 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10125 // See if we can optimize any arguments passed through the varargs area of
10127 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10128 E = CS.arg_end(); I != E; ++I, ++ix) {
10129 CastInst *CI = dyn_cast<CastInst>(*I);
10130 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10131 *I = CI->getOperand(0);
10137 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10138 // Inline asm calls cannot throw - mark them 'nounwind'.
10139 CS.setDoesNotThrow();
10143 return Changed ? CS.getInstruction() : 0;
10146 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10147 // attempt to move the cast to the arguments of the call/invoke.
10149 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10150 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10151 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10152 if (CE->getOpcode() != Instruction::BitCast ||
10153 !isa<Function>(CE->getOperand(0)))
10155 Function *Callee = cast<Function>(CE->getOperand(0));
10156 Instruction *Caller = CS.getInstruction();
10157 const AttrListPtr &CallerPAL = CS.getAttributes();
10159 // Okay, this is a cast from a function to a different type. Unless doing so
10160 // would cause a type conversion of one of our arguments, change this call to
10161 // be a direct call with arguments casted to the appropriate types.
10163 const FunctionType *FT = Callee->getFunctionType();
10164 const Type *OldRetTy = Caller->getType();
10165 const Type *NewRetTy = FT->getReturnType();
10167 if (isa<StructType>(NewRetTy))
10168 return false; // TODO: Handle multiple return values.
10170 // Check to see if we are changing the return type...
10171 if (OldRetTy != NewRetTy) {
10172 if (Callee->isDeclaration() &&
10173 // Conversion is ok if changing from one pointer type to another or from
10174 // a pointer to an integer of the same size.
10175 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10176 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10177 return false; // Cannot transform this return value.
10179 if (!Caller->use_empty() &&
10180 // void -> non-void is handled specially
10181 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10182 return false; // Cannot transform this return value.
10184 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10185 Attributes RAttrs = CallerPAL.getRetAttributes();
10186 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10187 return false; // Attribute not compatible with transformed value.
10190 // If the callsite is an invoke instruction, and the return value is used by
10191 // a PHI node in a successor, we cannot change the return type of the call
10192 // because there is no place to put the cast instruction (without breaking
10193 // the critical edge). Bail out in this case.
10194 if (!Caller->use_empty())
10195 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10196 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10198 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10199 if (PN->getParent() == II->getNormalDest() ||
10200 PN->getParent() == II->getUnwindDest())
10204 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10205 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10207 CallSite::arg_iterator AI = CS.arg_begin();
10208 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10209 const Type *ParamTy = FT->getParamType(i);
10210 const Type *ActTy = (*AI)->getType();
10212 if (!CastInst::isCastable(ActTy, ParamTy))
10213 return false; // Cannot transform this parameter value.
10215 if (CallerPAL.getParamAttributes(i + 1)
10216 & Attribute::typeIncompatible(ParamTy))
10217 return false; // Attribute not compatible with transformed value.
10219 // Converting from one pointer type to another or between a pointer and an
10220 // integer of the same size is safe even if we do not have a body.
10221 bool isConvertible = ActTy == ParamTy ||
10222 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10223 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10224 if (Callee->isDeclaration() && !isConvertible) return false;
10227 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10228 Callee->isDeclaration())
10229 return false; // Do not delete arguments unless we have a function body.
10231 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10232 !CallerPAL.isEmpty())
10233 // In this case we have more arguments than the new function type, but we
10234 // won't be dropping them. Check that these extra arguments have attributes
10235 // that are compatible with being a vararg call argument.
10236 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10237 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10239 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10240 if (PAttrs & Attribute::VarArgsIncompatible)
10244 // Okay, we decided that this is a safe thing to do: go ahead and start
10245 // inserting cast instructions as necessary...
10246 std::vector<Value*> Args;
10247 Args.reserve(NumActualArgs);
10248 SmallVector<AttributeWithIndex, 8> attrVec;
10249 attrVec.reserve(NumCommonArgs);
10251 // Get any return attributes.
10252 Attributes RAttrs = CallerPAL.getRetAttributes();
10254 // If the return value is not being used, the type may not be compatible
10255 // with the existing attributes. Wipe out any problematic attributes.
10256 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10258 // Add the new return attributes.
10260 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10262 AI = CS.arg_begin();
10263 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10264 const Type *ParamTy = FT->getParamType(i);
10265 if ((*AI)->getType() == ParamTy) {
10266 Args.push_back(*AI);
10268 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10269 false, ParamTy, false);
10270 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10271 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10274 // Add any parameter attributes.
10275 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10276 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10279 // If the function takes more arguments than the call was taking, add them
10281 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10282 Args.push_back(Context->getNullValue(FT->getParamType(i)));
10284 // If we are removing arguments to the function, emit an obnoxious warning...
10285 if (FT->getNumParams() < NumActualArgs) {
10286 if (!FT->isVarArg()) {
10287 cerr << "WARNING: While resolving call to function '"
10288 << Callee->getName() << "' arguments were dropped!\n";
10290 // Add all of the arguments in their promoted form to the arg list...
10291 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10292 const Type *PTy = getPromotedType((*AI)->getType());
10293 if (PTy != (*AI)->getType()) {
10294 // Must promote to pass through va_arg area!
10295 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10297 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10298 InsertNewInstBefore(Cast, *Caller);
10299 Args.push_back(Cast);
10301 Args.push_back(*AI);
10304 // Add any parameter attributes.
10305 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10306 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10311 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10312 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10314 if (NewRetTy == Type::VoidTy)
10315 Caller->setName(""); // Void type should not have a name.
10317 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10320 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10321 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10322 Args.begin(), Args.end(),
10323 Caller->getName(), Caller);
10324 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10325 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10327 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10328 Caller->getName(), Caller);
10329 CallInst *CI = cast<CallInst>(Caller);
10330 if (CI->isTailCall())
10331 cast<CallInst>(NC)->setTailCall();
10332 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10333 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10336 // Insert a cast of the return type as necessary.
10338 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10339 if (NV->getType() != Type::VoidTy) {
10340 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10342 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10344 // If this is an invoke instruction, we should insert it after the first
10345 // non-phi, instruction in the normal successor block.
10346 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10347 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10348 InsertNewInstBefore(NC, *I);
10350 // Otherwise, it's a call, just insert cast right after the call instr
10351 InsertNewInstBefore(NC, *Caller);
10353 AddUsersToWorkList(*Caller);
10355 NV = Context->getUndef(Caller->getType());
10359 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10360 Caller->replaceAllUsesWith(NV);
10361 Caller->eraseFromParent();
10362 RemoveFromWorkList(Caller);
10366 // transformCallThroughTrampoline - Turn a call to a function created by the
10367 // init_trampoline intrinsic into a direct call to the underlying function.
10369 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10370 Value *Callee = CS.getCalledValue();
10371 const PointerType *PTy = cast<PointerType>(Callee->getType());
10372 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10373 const AttrListPtr &Attrs = CS.getAttributes();
10375 // If the call already has the 'nest' attribute somewhere then give up -
10376 // otherwise 'nest' would occur twice after splicing in the chain.
10377 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10380 IntrinsicInst *Tramp =
10381 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10383 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10384 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10385 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10387 const AttrListPtr &NestAttrs = NestF->getAttributes();
10388 if (!NestAttrs.isEmpty()) {
10389 unsigned NestIdx = 1;
10390 const Type *NestTy = 0;
10391 Attributes NestAttr = Attribute::None;
10393 // Look for a parameter marked with the 'nest' attribute.
10394 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10395 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10396 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10397 // Record the parameter type and any other attributes.
10399 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10404 Instruction *Caller = CS.getInstruction();
10405 std::vector<Value*> NewArgs;
10406 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10408 SmallVector<AttributeWithIndex, 8> NewAttrs;
10409 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10411 // Insert the nest argument into the call argument list, which may
10412 // mean appending it. Likewise for attributes.
10414 // Add any result attributes.
10415 if (Attributes Attr = Attrs.getRetAttributes())
10416 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10420 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10422 if (Idx == NestIdx) {
10423 // Add the chain argument and attributes.
10424 Value *NestVal = Tramp->getOperand(3);
10425 if (NestVal->getType() != NestTy)
10426 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10427 NewArgs.push_back(NestVal);
10428 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10434 // Add the original argument and attributes.
10435 NewArgs.push_back(*I);
10436 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10438 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10444 // Add any function attributes.
10445 if (Attributes Attr = Attrs.getFnAttributes())
10446 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10448 // The trampoline may have been bitcast to a bogus type (FTy).
10449 // Handle this by synthesizing a new function type, equal to FTy
10450 // with the chain parameter inserted.
10452 std::vector<const Type*> NewTypes;
10453 NewTypes.reserve(FTy->getNumParams()+1);
10455 // Insert the chain's type into the list of parameter types, which may
10456 // mean appending it.
10459 FunctionType::param_iterator I = FTy->param_begin(),
10460 E = FTy->param_end();
10463 if (Idx == NestIdx)
10464 // Add the chain's type.
10465 NewTypes.push_back(NestTy);
10470 // Add the original type.
10471 NewTypes.push_back(*I);
10477 // Replace the trampoline call with a direct call. Let the generic
10478 // code sort out any function type mismatches.
10479 FunctionType *NewFTy =
10480 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10482 Constant *NewCallee =
10483 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10484 NestF : Context->getConstantExprBitCast(NestF,
10485 Context->getPointerTypeUnqual(NewFTy));
10486 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10488 Instruction *NewCaller;
10489 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10490 NewCaller = InvokeInst::Create(NewCallee,
10491 II->getNormalDest(), II->getUnwindDest(),
10492 NewArgs.begin(), NewArgs.end(),
10493 Caller->getName(), Caller);
10494 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10495 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10497 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10498 Caller->getName(), Caller);
10499 if (cast<CallInst>(Caller)->isTailCall())
10500 cast<CallInst>(NewCaller)->setTailCall();
10501 cast<CallInst>(NewCaller)->
10502 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10503 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10505 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10506 Caller->replaceAllUsesWith(NewCaller);
10507 Caller->eraseFromParent();
10508 RemoveFromWorkList(Caller);
10513 // Replace the trampoline call with a direct call. Since there is no 'nest'
10514 // parameter, there is no need to adjust the argument list. Let the generic
10515 // code sort out any function type mismatches.
10516 Constant *NewCallee =
10517 NestF->getType() == PTy ? NestF :
10518 Context->getConstantExprBitCast(NestF, PTy);
10519 CS.setCalledFunction(NewCallee);
10520 return CS.getInstruction();
10523 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10524 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10525 /// and a single binop.
10526 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10527 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10528 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10529 unsigned Opc = FirstInst->getOpcode();
10530 Value *LHSVal = FirstInst->getOperand(0);
10531 Value *RHSVal = FirstInst->getOperand(1);
10533 const Type *LHSType = LHSVal->getType();
10534 const Type *RHSType = RHSVal->getType();
10536 // Scan to see if all operands are the same opcode, all have one use, and all
10537 // kill their operands (i.e. the operands have one use).
10538 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10539 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10540 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10541 // Verify type of the LHS matches so we don't fold cmp's of different
10542 // types or GEP's with different index types.
10543 I->getOperand(0)->getType() != LHSType ||
10544 I->getOperand(1)->getType() != RHSType)
10547 // If they are CmpInst instructions, check their predicates
10548 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10549 if (cast<CmpInst>(I)->getPredicate() !=
10550 cast<CmpInst>(FirstInst)->getPredicate())
10553 // Keep track of which operand needs a phi node.
10554 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10555 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10558 // Otherwise, this is safe to transform!
10560 Value *InLHS = FirstInst->getOperand(0);
10561 Value *InRHS = FirstInst->getOperand(1);
10562 PHINode *NewLHS = 0, *NewRHS = 0;
10564 NewLHS = PHINode::Create(LHSType,
10565 FirstInst->getOperand(0)->getName() + ".pn");
10566 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10567 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10568 InsertNewInstBefore(NewLHS, PN);
10573 NewRHS = PHINode::Create(RHSType,
10574 FirstInst->getOperand(1)->getName() + ".pn");
10575 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10576 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10577 InsertNewInstBefore(NewRHS, PN);
10581 // Add all operands to the new PHIs.
10582 if (NewLHS || NewRHS) {
10583 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10584 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10586 Value *NewInLHS = InInst->getOperand(0);
10587 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10590 Value *NewInRHS = InInst->getOperand(1);
10591 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10596 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10597 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10598 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10599 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10603 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10604 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10606 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10607 FirstInst->op_end());
10608 // This is true if all GEP bases are allocas and if all indices into them are
10610 bool AllBasePointersAreAllocas = true;
10612 // Scan to see if all operands are the same opcode, all have one use, and all
10613 // kill their operands (i.e. the operands have one use).
10614 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10615 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10616 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10617 GEP->getNumOperands() != FirstInst->getNumOperands())
10620 // Keep track of whether or not all GEPs are of alloca pointers.
10621 if (AllBasePointersAreAllocas &&
10622 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10623 !GEP->hasAllConstantIndices()))
10624 AllBasePointersAreAllocas = false;
10626 // Compare the operand lists.
10627 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10628 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10631 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10632 // if one of the PHIs has a constant for the index. The index may be
10633 // substantially cheaper to compute for the constants, so making it a
10634 // variable index could pessimize the path. This also handles the case
10635 // for struct indices, which must always be constant.
10636 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10637 isa<ConstantInt>(GEP->getOperand(op)))
10640 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10642 FixedOperands[op] = 0; // Needs a PHI.
10646 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10647 // bother doing this transformation. At best, this will just save a bit of
10648 // offset calculation, but all the predecessors will have to materialize the
10649 // stack address into a register anyway. We'd actually rather *clone* the
10650 // load up into the predecessors so that we have a load of a gep of an alloca,
10651 // which can usually all be folded into the load.
10652 if (AllBasePointersAreAllocas)
10655 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10656 // that is variable.
10657 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10659 bool HasAnyPHIs = false;
10660 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10661 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10662 Value *FirstOp = FirstInst->getOperand(i);
10663 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10664 FirstOp->getName()+".pn");
10665 InsertNewInstBefore(NewPN, PN);
10667 NewPN->reserveOperandSpace(e);
10668 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10669 OperandPhis[i] = NewPN;
10670 FixedOperands[i] = NewPN;
10675 // Add all operands to the new PHIs.
10677 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10678 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10679 BasicBlock *InBB = PN.getIncomingBlock(i);
10681 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10682 if (PHINode *OpPhi = OperandPhis[op])
10683 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10687 Value *Base = FixedOperands[0];
10688 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10689 FixedOperands.end());
10693 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10694 /// sink the load out of the block that defines it. This means that it must be
10695 /// obvious the value of the load is not changed from the point of the load to
10696 /// the end of the block it is in.
10698 /// Finally, it is safe, but not profitable, to sink a load targetting a
10699 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10701 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10702 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10704 for (++BBI; BBI != E; ++BBI)
10705 if (BBI->mayWriteToMemory())
10708 // Check for non-address taken alloca. If not address-taken already, it isn't
10709 // profitable to do this xform.
10710 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10711 bool isAddressTaken = false;
10712 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10714 if (isa<LoadInst>(UI)) continue;
10715 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10716 // If storing TO the alloca, then the address isn't taken.
10717 if (SI->getOperand(1) == AI) continue;
10719 isAddressTaken = true;
10723 if (!isAddressTaken && AI->isStaticAlloca())
10727 // If this load is a load from a GEP with a constant offset from an alloca,
10728 // then we don't want to sink it. In its present form, it will be
10729 // load [constant stack offset]. Sinking it will cause us to have to
10730 // materialize the stack addresses in each predecessor in a register only to
10731 // do a shared load from register in the successor.
10732 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10733 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10734 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10741 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10742 // operator and they all are only used by the PHI, PHI together their
10743 // inputs, and do the operation once, to the result of the PHI.
10744 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10745 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10747 // Scan the instruction, looking for input operations that can be folded away.
10748 // If all input operands to the phi are the same instruction (e.g. a cast from
10749 // the same type or "+42") we can pull the operation through the PHI, reducing
10750 // code size and simplifying code.
10751 Constant *ConstantOp = 0;
10752 const Type *CastSrcTy = 0;
10753 bool isVolatile = false;
10754 if (isa<CastInst>(FirstInst)) {
10755 CastSrcTy = FirstInst->getOperand(0)->getType();
10756 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10757 // Can fold binop, compare or shift here if the RHS is a constant,
10758 // otherwise call FoldPHIArgBinOpIntoPHI.
10759 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10760 if (ConstantOp == 0)
10761 return FoldPHIArgBinOpIntoPHI(PN);
10762 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10763 isVolatile = LI->isVolatile();
10764 // We can't sink the load if the loaded value could be modified between the
10765 // load and the PHI.
10766 if (LI->getParent() != PN.getIncomingBlock(0) ||
10767 !isSafeAndProfitableToSinkLoad(LI))
10770 // If the PHI is of volatile loads and the load block has multiple
10771 // successors, sinking it would remove a load of the volatile value from
10772 // the path through the other successor.
10774 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10777 } else if (isa<GetElementPtrInst>(FirstInst)) {
10778 return FoldPHIArgGEPIntoPHI(PN);
10780 return 0; // Cannot fold this operation.
10783 // Check to see if all arguments are the same operation.
10784 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10785 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10786 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10787 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10790 if (I->getOperand(0)->getType() != CastSrcTy)
10791 return 0; // Cast operation must match.
10792 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10793 // We can't sink the load if the loaded value could be modified between
10794 // the load and the PHI.
10795 if (LI->isVolatile() != isVolatile ||
10796 LI->getParent() != PN.getIncomingBlock(i) ||
10797 !isSafeAndProfitableToSinkLoad(LI))
10800 // If the PHI is of volatile loads and the load block has multiple
10801 // successors, sinking it would remove a load of the volatile value from
10802 // the path through the other successor.
10804 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10807 } else if (I->getOperand(1) != ConstantOp) {
10812 // Okay, they are all the same operation. Create a new PHI node of the
10813 // correct type, and PHI together all of the LHS's of the instructions.
10814 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10815 PN.getName()+".in");
10816 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10818 Value *InVal = FirstInst->getOperand(0);
10819 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10821 // Add all operands to the new PHI.
10822 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10823 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10824 if (NewInVal != InVal)
10826 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10831 // The new PHI unions all of the same values together. This is really
10832 // common, so we handle it intelligently here for compile-time speed.
10836 InsertNewInstBefore(NewPN, PN);
10840 // Insert and return the new operation.
10841 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10842 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10843 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10844 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10845 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10846 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10847 PhiVal, ConstantOp);
10848 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10850 // If this was a volatile load that we are merging, make sure to loop through
10851 // and mark all the input loads as non-volatile. If we don't do this, we will
10852 // insert a new volatile load and the old ones will not be deletable.
10854 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10855 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10857 return new LoadInst(PhiVal, "", isVolatile);
10860 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10862 static bool DeadPHICycle(PHINode *PN,
10863 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10864 if (PN->use_empty()) return true;
10865 if (!PN->hasOneUse()) return false;
10867 // Remember this node, and if we find the cycle, return.
10868 if (!PotentiallyDeadPHIs.insert(PN))
10871 // Don't scan crazily complex things.
10872 if (PotentiallyDeadPHIs.size() == 16)
10875 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10876 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10881 /// PHIsEqualValue - Return true if this phi node is always equal to
10882 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10883 /// z = some value; x = phi (y, z); y = phi (x, z)
10884 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10885 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10886 // See if we already saw this PHI node.
10887 if (!ValueEqualPHIs.insert(PN))
10890 // Don't scan crazily complex things.
10891 if (ValueEqualPHIs.size() == 16)
10894 // Scan the operands to see if they are either phi nodes or are equal to
10896 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10897 Value *Op = PN->getIncomingValue(i);
10898 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10899 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10901 } else if (Op != NonPhiInVal)
10909 // PHINode simplification
10911 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10912 // If LCSSA is around, don't mess with Phi nodes
10913 if (MustPreserveLCSSA) return 0;
10915 if (Value *V = PN.hasConstantValue())
10916 return ReplaceInstUsesWith(PN, V);
10918 // If all PHI operands are the same operation, pull them through the PHI,
10919 // reducing code size.
10920 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10921 isa<Instruction>(PN.getIncomingValue(1)) &&
10922 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10923 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10924 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10925 // than themselves more than once.
10926 PN.getIncomingValue(0)->hasOneUse())
10927 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10930 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10931 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10932 // PHI)... break the cycle.
10933 if (PN.hasOneUse()) {
10934 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10935 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10936 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10937 PotentiallyDeadPHIs.insert(&PN);
10938 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10939 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10942 // If this phi has a single use, and if that use just computes a value for
10943 // the next iteration of a loop, delete the phi. This occurs with unused
10944 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10945 // common case here is good because the only other things that catch this
10946 // are induction variable analysis (sometimes) and ADCE, which is only run
10948 if (PHIUser->hasOneUse() &&
10949 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10950 PHIUser->use_back() == &PN) {
10951 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10955 // We sometimes end up with phi cycles that non-obviously end up being the
10956 // same value, for example:
10957 // z = some value; x = phi (y, z); y = phi (x, z)
10958 // where the phi nodes don't necessarily need to be in the same block. Do a
10959 // quick check to see if the PHI node only contains a single non-phi value, if
10960 // so, scan to see if the phi cycle is actually equal to that value.
10962 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10963 // Scan for the first non-phi operand.
10964 while (InValNo != NumOperandVals &&
10965 isa<PHINode>(PN.getIncomingValue(InValNo)))
10968 if (InValNo != NumOperandVals) {
10969 Value *NonPhiInVal = PN.getOperand(InValNo);
10971 // Scan the rest of the operands to see if there are any conflicts, if so
10972 // there is no need to recursively scan other phis.
10973 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10974 Value *OpVal = PN.getIncomingValue(InValNo);
10975 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10979 // If we scanned over all operands, then we have one unique value plus
10980 // phi values. Scan PHI nodes to see if they all merge in each other or
10982 if (InValNo == NumOperandVals) {
10983 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10984 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10985 return ReplaceInstUsesWith(PN, NonPhiInVal);
10992 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10993 Instruction *InsertPoint,
10994 InstCombiner *IC) {
10995 unsigned PtrSize = DTy->getScalarSizeInBits();
10996 unsigned VTySize = V->getType()->getScalarSizeInBits();
10997 // We must cast correctly to the pointer type. Ensure that we
10998 // sign extend the integer value if it is smaller as this is
10999 // used for address computation.
11000 Instruction::CastOps opcode =
11001 (VTySize < PtrSize ? Instruction::SExt :
11002 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11003 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11007 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11008 Value *PtrOp = GEP.getOperand(0);
11009 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
11010 // If so, eliminate the noop.
11011 if (GEP.getNumOperands() == 1)
11012 return ReplaceInstUsesWith(GEP, PtrOp);
11014 if (isa<UndefValue>(GEP.getOperand(0)))
11015 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11017 bool HasZeroPointerIndex = false;
11018 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11019 HasZeroPointerIndex = C->isNullValue();
11021 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11022 return ReplaceInstUsesWith(GEP, PtrOp);
11024 // Eliminate unneeded casts for indices.
11025 bool MadeChange = false;
11027 gep_type_iterator GTI = gep_type_begin(GEP);
11028 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11029 i != e; ++i, ++GTI) {
11030 if (isa<SequentialType>(*GTI)) {
11031 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11032 if (CI->getOpcode() == Instruction::ZExt ||
11033 CI->getOpcode() == Instruction::SExt) {
11034 const Type *SrcTy = CI->getOperand(0)->getType();
11035 // We can eliminate a cast from i32 to i64 iff the target
11036 // is a 32-bit pointer target.
11037 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11039 *i = CI->getOperand(0);
11043 // If we are using a wider index than needed for this platform, shrink it
11044 // to what we need. If narrower, sign-extend it to what we need.
11045 // If the incoming value needs a cast instruction,
11046 // insert it. This explicit cast can make subsequent optimizations more
11049 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11050 if (Constant *C = dyn_cast<Constant>(Op)) {
11051 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11054 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11059 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11060 if (Constant *C = dyn_cast<Constant>(Op)) {
11061 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11064 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11072 if (MadeChange) return &GEP;
11074 // Combine Indices - If the source pointer to this getelementptr instruction
11075 // is a getelementptr instruction, combine the indices of the two
11076 // getelementptr instructions into a single instruction.
11078 SmallVector<Value*, 8> SrcGEPOperands;
11079 if (User *Src = dyn_castGetElementPtr(PtrOp))
11080 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11082 if (!SrcGEPOperands.empty()) {
11083 // Note that if our source is a gep chain itself that we wait for that
11084 // chain to be resolved before we perform this transformation. This
11085 // avoids us creating a TON of code in some cases.
11087 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11088 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11089 return 0; // Wait until our source is folded to completion.
11091 SmallVector<Value*, 8> Indices;
11093 // Find out whether the last index in the source GEP is a sequential idx.
11094 bool EndsWithSequential = false;
11095 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11096 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11097 EndsWithSequential = !isa<StructType>(*I);
11099 // Can we combine the two pointer arithmetics offsets?
11100 if (EndsWithSequential) {
11101 // Replace: gep (gep %P, long B), long A, ...
11102 // With: T = long A+B; gep %P, T, ...
11104 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11105 if (SO1 == Context->getNullValue(SO1->getType())) {
11107 } else if (GO1 == Context->getNullValue(GO1->getType())) {
11110 // If they aren't the same type, convert both to an integer of the
11111 // target's pointer size.
11112 if (SO1->getType() != GO1->getType()) {
11113 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11115 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11116 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11118 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11120 unsigned PS = TD->getPointerSizeInBits();
11121 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11122 // Convert GO1 to SO1's type.
11123 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11125 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11126 // Convert SO1 to GO1's type.
11127 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11129 const Type *PT = TD->getIntPtrType();
11130 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11131 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11135 if (isa<Constant>(SO1) && isa<Constant>(GO1))
11136 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11137 cast<Constant>(GO1));
11139 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11140 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11144 // Recycle the GEP we already have if possible.
11145 if (SrcGEPOperands.size() == 2) {
11146 GEP.setOperand(0, SrcGEPOperands[0]);
11147 GEP.setOperand(1, Sum);
11150 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11151 SrcGEPOperands.end()-1);
11152 Indices.push_back(Sum);
11153 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11155 } else if (isa<Constant>(*GEP.idx_begin()) &&
11156 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11157 SrcGEPOperands.size() != 1) {
11158 // Otherwise we can do the fold if the first index of the GEP is a zero
11159 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11160 SrcGEPOperands.end());
11161 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11164 if (!Indices.empty())
11165 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11166 Indices.end(), GEP.getName());
11168 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11169 // GEP of global variable. If all of the indices for this GEP are
11170 // constants, we can promote this to a constexpr instead of an instruction.
11172 // Scan for nonconstants...
11173 SmallVector<Constant*, 8> Indices;
11174 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11175 for (; I != E && isa<Constant>(*I); ++I)
11176 Indices.push_back(cast<Constant>(*I));
11178 if (I == E) { // If they are all constants...
11179 Constant *CE = Context->getConstantExprGetElementPtr(GV,
11180 &Indices[0],Indices.size());
11182 // Replace all uses of the GEP with the new constexpr...
11183 return ReplaceInstUsesWith(GEP, CE);
11185 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11186 if (!isa<PointerType>(X->getType())) {
11187 // Not interesting. Source pointer must be a cast from pointer.
11188 } else if (HasZeroPointerIndex) {
11189 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11190 // into : GEP [10 x i8]* X, i32 0, ...
11192 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11193 // into : GEP i8* X, ...
11195 // This occurs when the program declares an array extern like "int X[];"
11196 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11197 const PointerType *XTy = cast<PointerType>(X->getType());
11198 if (const ArrayType *CATy =
11199 dyn_cast<ArrayType>(CPTy->getElementType())) {
11200 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11201 if (CATy->getElementType() == XTy->getElementType()) {
11202 // -> GEP i8* X, ...
11203 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11204 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11206 } else if (const ArrayType *XATy =
11207 dyn_cast<ArrayType>(XTy->getElementType())) {
11208 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11209 if (CATy->getElementType() == XATy->getElementType()) {
11210 // -> GEP [10 x i8]* X, i32 0, ...
11211 // At this point, we know that the cast source type is a pointer
11212 // to an array of the same type as the destination pointer
11213 // array. Because the array type is never stepped over (there
11214 // is a leading zero) we can fold the cast into this GEP.
11215 GEP.setOperand(0, X);
11220 } else if (GEP.getNumOperands() == 2) {
11221 // Transform things like:
11222 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11223 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11224 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11225 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11226 if (isa<ArrayType>(SrcElTy) &&
11227 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11228 TD->getTypeAllocSize(ResElTy)) {
11230 Idx[0] = Context->getNullValue(Type::Int32Ty);
11231 Idx[1] = GEP.getOperand(1);
11232 Value *V = InsertNewInstBefore(
11233 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11234 // V and GEP are both pointer types --> BitCast
11235 return new BitCastInst(V, GEP.getType());
11238 // Transform things like:
11239 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11240 // (where tmp = 8*tmp2) into:
11241 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11243 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11244 uint64_t ArrayEltSize =
11245 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11247 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11248 // allow either a mul, shift, or constant here.
11250 ConstantInt *Scale = 0;
11251 if (ArrayEltSize == 1) {
11252 NewIdx = GEP.getOperand(1);
11254 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11255 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11256 NewIdx = Context->getConstantInt(CI->getType(), 1);
11258 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11259 if (Inst->getOpcode() == Instruction::Shl &&
11260 isa<ConstantInt>(Inst->getOperand(1))) {
11261 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11262 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11263 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11265 NewIdx = Inst->getOperand(0);
11266 } else if (Inst->getOpcode() == Instruction::Mul &&
11267 isa<ConstantInt>(Inst->getOperand(1))) {
11268 Scale = cast<ConstantInt>(Inst->getOperand(1));
11269 NewIdx = Inst->getOperand(0);
11273 // If the index will be to exactly the right offset with the scale taken
11274 // out, perform the transformation. Note, we don't know whether Scale is
11275 // signed or not. We'll use unsigned version of division/modulo
11276 // operation after making sure Scale doesn't have the sign bit set.
11277 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11278 Scale->getZExtValue() % ArrayEltSize == 0) {
11279 Scale = Context->getConstantInt(Scale->getType(),
11280 Scale->getZExtValue() / ArrayEltSize);
11281 if (Scale->getZExtValue() != 1) {
11283 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11285 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11286 NewIdx = InsertNewInstBefore(Sc, GEP);
11289 // Insert the new GEP instruction.
11291 Idx[0] = Context->getNullValue(Type::Int32Ty);
11293 Instruction *NewGEP =
11294 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11295 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11296 // The NewGEP must be pointer typed, so must the old one -> BitCast
11297 return new BitCastInst(NewGEP, GEP.getType());
11303 /// See if we can simplify:
11304 /// X = bitcast A to B*
11305 /// Y = gep X, <...constant indices...>
11306 /// into a gep of the original struct. This is important for SROA and alias
11307 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11308 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11309 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11310 // Determine how much the GEP moves the pointer. We are guaranteed to get
11311 // a constant back from EmitGEPOffset.
11312 ConstantInt *OffsetV =
11313 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11314 int64_t Offset = OffsetV->getSExtValue();
11316 // If this GEP instruction doesn't move the pointer, just replace the GEP
11317 // with a bitcast of the real input to the dest type.
11319 // If the bitcast is of an allocation, and the allocation will be
11320 // converted to match the type of the cast, don't touch this.
11321 if (isa<AllocationInst>(BCI->getOperand(0))) {
11322 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11323 if (Instruction *I = visitBitCast(*BCI)) {
11326 BCI->getParent()->getInstList().insert(BCI, I);
11327 ReplaceInstUsesWith(*BCI, I);
11332 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11335 // Otherwise, if the offset is non-zero, we need to find out if there is a
11336 // field at Offset in 'A's type. If so, we can pull the cast through the
11338 SmallVector<Value*, 8> NewIndices;
11340 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11341 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11342 Instruction *NGEP =
11343 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11345 if (NGEP->getType() == GEP.getType()) return NGEP;
11346 InsertNewInstBefore(NGEP, GEP);
11347 NGEP->takeName(&GEP);
11348 return new BitCastInst(NGEP, GEP.getType());
11356 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11357 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11358 if (AI.isArrayAllocation()) { // Check C != 1
11359 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11360 const Type *NewTy =
11361 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11362 AllocationInst *New = 0;
11364 // Create and insert the replacement instruction...
11365 if (isa<MallocInst>(AI))
11366 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11368 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11369 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11372 InsertNewInstBefore(New, AI);
11374 // Scan to the end of the allocation instructions, to skip over a block of
11375 // allocas if possible...also skip interleaved debug info
11377 BasicBlock::iterator It = New;
11378 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11380 // Now that I is pointing to the first non-allocation-inst in the block,
11381 // insert our getelementptr instruction...
11383 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11387 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11388 New->getName()+".sub", It);
11390 // Now make everything use the getelementptr instead of the original
11392 return ReplaceInstUsesWith(AI, V);
11393 } else if (isa<UndefValue>(AI.getArraySize())) {
11394 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11398 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11399 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11400 // Note that we only do this for alloca's, because malloc should allocate
11401 // and return a unique pointer, even for a zero byte allocation.
11402 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11403 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11405 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11406 if (AI.getAlignment() == 0)
11407 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11413 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11414 Value *Op = FI.getOperand(0);
11416 // free undef -> unreachable.
11417 if (isa<UndefValue>(Op)) {
11418 // Insert a new store to null because we cannot modify the CFG here.
11419 new StoreInst(Context->getConstantIntTrue(),
11420 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11421 return EraseInstFromFunction(FI);
11424 // If we have 'free null' delete the instruction. This can happen in stl code
11425 // when lots of inlining happens.
11426 if (isa<ConstantPointerNull>(Op))
11427 return EraseInstFromFunction(FI);
11429 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11430 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11431 FI.setOperand(0, CI->getOperand(0));
11435 // Change free (gep X, 0,0,0,0) into free(X)
11436 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11437 if (GEPI->hasAllZeroIndices()) {
11438 AddToWorkList(GEPI);
11439 FI.setOperand(0, GEPI->getOperand(0));
11444 // Change free(malloc) into nothing, if the malloc has a single use.
11445 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11446 if (MI->hasOneUse()) {
11447 EraseInstFromFunction(FI);
11448 return EraseInstFromFunction(*MI);
11455 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11456 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11457 const TargetData *TD) {
11458 User *CI = cast<User>(LI.getOperand(0));
11459 Value *CastOp = CI->getOperand(0);
11460 LLVMContext *Context = IC.getContext();
11463 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11464 // Instead of loading constant c string, use corresponding integer value
11465 // directly if string length is small enough.
11467 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11468 unsigned len = Str.length();
11469 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11470 unsigned numBits = Ty->getPrimitiveSizeInBits();
11471 // Replace LI with immediate integer store.
11472 if ((numBits >> 3) == len + 1) {
11473 APInt StrVal(numBits, 0);
11474 APInt SingleChar(numBits, 0);
11475 if (TD->isLittleEndian()) {
11476 for (signed i = len-1; i >= 0; i--) {
11477 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11478 StrVal = (StrVal << 8) | SingleChar;
11481 for (unsigned i = 0; i < len; i++) {
11482 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11483 StrVal = (StrVal << 8) | SingleChar;
11485 // Append NULL at the end.
11487 StrVal = (StrVal << 8) | SingleChar;
11489 Value *NL = Context->getConstantInt(StrVal);
11490 return IC.ReplaceInstUsesWith(LI, NL);
11496 const PointerType *DestTy = cast<PointerType>(CI->getType());
11497 const Type *DestPTy = DestTy->getElementType();
11498 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11500 // If the address spaces don't match, don't eliminate the cast.
11501 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11504 const Type *SrcPTy = SrcTy->getElementType();
11506 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11507 isa<VectorType>(DestPTy)) {
11508 // If the source is an array, the code below will not succeed. Check to
11509 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11511 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11512 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11513 if (ASrcTy->getNumElements() != 0) {
11515 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11516 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11517 SrcTy = cast<PointerType>(CastOp->getType());
11518 SrcPTy = SrcTy->getElementType();
11521 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11522 isa<VectorType>(SrcPTy)) &&
11523 // Do not allow turning this into a load of an integer, which is then
11524 // casted to a pointer, this pessimizes pointer analysis a lot.
11525 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11526 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11527 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11529 // Okay, we are casting from one integer or pointer type to another of
11530 // the same size. Instead of casting the pointer before the load, cast
11531 // the result of the loaded value.
11532 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11534 LI.isVolatile()),LI);
11535 // Now cast the result of the load.
11536 return new BitCastInst(NewLoad, LI.getType());
11543 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11544 Value *Op = LI.getOperand(0);
11546 // Attempt to improve the alignment.
11547 unsigned KnownAlign =
11548 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11550 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11551 LI.getAlignment()))
11552 LI.setAlignment(KnownAlign);
11554 // load (cast X) --> cast (load X) iff safe
11555 if (isa<CastInst>(Op))
11556 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11559 // None of the following transforms are legal for volatile loads.
11560 if (LI.isVolatile()) return 0;
11562 // Do really simple store-to-load forwarding and load CSE, to catch cases
11563 // where there are several consequtive memory accesses to the same location,
11564 // separated by a few arithmetic operations.
11565 BasicBlock::iterator BBI = &LI;
11566 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11567 return ReplaceInstUsesWith(LI, AvailableVal);
11569 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11570 const Value *GEPI0 = GEPI->getOperand(0);
11571 // TODO: Consider a target hook for valid address spaces for this xform.
11572 if (isa<ConstantPointerNull>(GEPI0) &&
11573 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11574 // Insert a new store to null instruction before the load to indicate
11575 // that this code is not reachable. We do this instead of inserting
11576 // an unreachable instruction directly because we cannot modify the
11578 new StoreInst(Context->getUndef(LI.getType()),
11579 Context->getNullValue(Op->getType()), &LI);
11580 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11584 if (Constant *C = dyn_cast<Constant>(Op)) {
11585 // load null/undef -> undef
11586 // TODO: Consider a target hook for valid address spaces for this xform.
11587 if (isa<UndefValue>(C) || (C->isNullValue() &&
11588 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11589 // Insert a new store to null instruction before the load to indicate that
11590 // this code is not reachable. We do this instead of inserting an
11591 // unreachable instruction directly because we cannot modify the CFG.
11592 new StoreInst(Context->getUndef(LI.getType()),
11593 Context->getNullValue(Op->getType()), &LI);
11594 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11597 // Instcombine load (constant global) into the value loaded.
11598 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11599 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11600 return ReplaceInstUsesWith(LI, GV->getInitializer());
11602 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11603 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11604 if (CE->getOpcode() == Instruction::GetElementPtr) {
11605 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11606 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11608 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11610 return ReplaceInstUsesWith(LI, V);
11611 if (CE->getOperand(0)->isNullValue()) {
11612 // Insert a new store to null instruction before the load to indicate
11613 // that this code is not reachable. We do this instead of inserting
11614 // an unreachable instruction directly because we cannot modify the
11616 new StoreInst(Context->getUndef(LI.getType()),
11617 Context->getNullValue(Op->getType()), &LI);
11618 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11621 } else if (CE->isCast()) {
11622 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11628 // If this load comes from anywhere in a constant global, and if the global
11629 // is all undef or zero, we know what it loads.
11630 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11631 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11632 if (GV->getInitializer()->isNullValue())
11633 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11634 else if (isa<UndefValue>(GV->getInitializer()))
11635 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11639 if (Op->hasOneUse()) {
11640 // Change select and PHI nodes to select values instead of addresses: this
11641 // helps alias analysis out a lot, allows many others simplifications, and
11642 // exposes redundancy in the code.
11644 // Note that we cannot do the transformation unless we know that the
11645 // introduced loads cannot trap! Something like this is valid as long as
11646 // the condition is always false: load (select bool %C, int* null, int* %G),
11647 // but it would not be valid if we transformed it to load from null
11648 // unconditionally.
11650 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11651 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11652 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11653 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11654 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11655 SI->getOperand(1)->getName()+".val"), LI);
11656 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11657 SI->getOperand(2)->getName()+".val"), LI);
11658 return SelectInst::Create(SI->getCondition(), V1, V2);
11661 // load (select (cond, null, P)) -> load P
11662 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11663 if (C->isNullValue()) {
11664 LI.setOperand(0, SI->getOperand(2));
11668 // load (select (cond, P, null)) -> load P
11669 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11670 if (C->isNullValue()) {
11671 LI.setOperand(0, SI->getOperand(1));
11679 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11680 /// when possible. This makes it generally easy to do alias analysis and/or
11681 /// SROA/mem2reg of the memory object.
11682 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11683 User *CI = cast<User>(SI.getOperand(1));
11684 Value *CastOp = CI->getOperand(0);
11685 LLVMContext *Context = IC.getContext();
11687 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11688 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11689 if (SrcTy == 0) return 0;
11691 const Type *SrcPTy = SrcTy->getElementType();
11693 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11696 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11697 /// to its first element. This allows us to handle things like:
11698 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11699 /// on 32-bit hosts.
11700 SmallVector<Value*, 4> NewGEPIndices;
11702 // If the source is an array, the code below will not succeed. Check to
11703 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11705 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11706 // Index through pointer.
11707 Constant *Zero = Context->getNullValue(Type::Int32Ty);
11708 NewGEPIndices.push_back(Zero);
11711 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11712 if (!STy->getNumElements()) /* Struct can be empty {} */
11714 NewGEPIndices.push_back(Zero);
11715 SrcPTy = STy->getElementType(0);
11716 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11717 NewGEPIndices.push_back(Zero);
11718 SrcPTy = ATy->getElementType();
11724 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11727 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11730 // If the pointers point into different address spaces or if they point to
11731 // values with different sizes, we can't do the transformation.
11732 if (SrcTy->getAddressSpace() !=
11733 cast<PointerType>(CI->getType())->getAddressSpace() ||
11734 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11735 IC.getTargetData().getTypeSizeInBits(DestPTy))
11738 // Okay, we are casting from one integer or pointer type to another of
11739 // the same size. Instead of casting the pointer before
11740 // the store, cast the value to be stored.
11742 Value *SIOp0 = SI.getOperand(0);
11743 Instruction::CastOps opcode = Instruction::BitCast;
11744 const Type* CastSrcTy = SIOp0->getType();
11745 const Type* CastDstTy = SrcPTy;
11746 if (isa<PointerType>(CastDstTy)) {
11747 if (CastSrcTy->isInteger())
11748 opcode = Instruction::IntToPtr;
11749 } else if (isa<IntegerType>(CastDstTy)) {
11750 if (isa<PointerType>(SIOp0->getType()))
11751 opcode = Instruction::PtrToInt;
11754 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11755 // emit a GEP to index into its first field.
11756 if (!NewGEPIndices.empty()) {
11757 if (Constant *C = dyn_cast<Constant>(CastOp))
11758 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
11759 NewGEPIndices.size());
11761 CastOp = IC.InsertNewInstBefore(
11762 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11763 NewGEPIndices.end()), SI);
11766 if (Constant *C = dyn_cast<Constant>(SIOp0))
11767 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11769 NewCast = IC.InsertNewInstBefore(
11770 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11772 return new StoreInst(NewCast, CastOp);
11775 /// equivalentAddressValues - Test if A and B will obviously have the same
11776 /// value. This includes recognizing that %t0 and %t1 will have the same
11777 /// value in code like this:
11778 /// %t0 = getelementptr \@a, 0, 3
11779 /// store i32 0, i32* %t0
11780 /// %t1 = getelementptr \@a, 0, 3
11781 /// %t2 = load i32* %t1
11783 static bool equivalentAddressValues(Value *A, Value *B) {
11784 // Test if the values are trivially equivalent.
11785 if (A == B) return true;
11787 // Test if the values come form identical arithmetic instructions.
11788 if (isa<BinaryOperator>(A) ||
11789 isa<CastInst>(A) ||
11791 isa<GetElementPtrInst>(A))
11792 if (Instruction *BI = dyn_cast<Instruction>(B))
11793 if (cast<Instruction>(A)->isIdenticalTo(BI))
11796 // Otherwise they may not be equivalent.
11800 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11801 // return the llvm.dbg.declare.
11802 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11803 if (!V->hasNUses(2))
11805 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11807 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11809 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11810 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11817 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11818 Value *Val = SI.getOperand(0);
11819 Value *Ptr = SI.getOperand(1);
11821 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11822 EraseInstFromFunction(SI);
11827 // If the RHS is an alloca with a single use, zapify the store, making the
11829 // If the RHS is an alloca with a two uses, the other one being a
11830 // llvm.dbg.declare, zapify the store and the declare, making the
11831 // alloca dead. We must do this to prevent declare's from affecting
11833 if (!SI.isVolatile()) {
11834 if (Ptr->hasOneUse()) {
11835 if (isa<AllocaInst>(Ptr)) {
11836 EraseInstFromFunction(SI);
11840 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11841 if (isa<AllocaInst>(GEP->getOperand(0))) {
11842 if (GEP->getOperand(0)->hasOneUse()) {
11843 EraseInstFromFunction(SI);
11847 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11848 EraseInstFromFunction(*DI);
11849 EraseInstFromFunction(SI);
11856 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11857 EraseInstFromFunction(*DI);
11858 EraseInstFromFunction(SI);
11864 // Attempt to improve the alignment.
11865 unsigned KnownAlign =
11866 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11868 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11869 SI.getAlignment()))
11870 SI.setAlignment(KnownAlign);
11872 // Do really simple DSE, to catch cases where there are several consecutive
11873 // stores to the same location, separated by a few arithmetic operations. This
11874 // situation often occurs with bitfield accesses.
11875 BasicBlock::iterator BBI = &SI;
11876 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11879 // Don't count debug info directives, lest they affect codegen,
11880 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11881 // It is necessary for correctness to skip those that feed into a
11882 // llvm.dbg.declare, as these are not present when debugging is off.
11883 if (isa<DbgInfoIntrinsic>(BBI) ||
11884 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11889 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11890 // Prev store isn't volatile, and stores to the same location?
11891 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11892 SI.getOperand(1))) {
11895 EraseInstFromFunction(*PrevSI);
11901 // If this is a load, we have to stop. However, if the loaded value is from
11902 // the pointer we're loading and is producing the pointer we're storing,
11903 // then *this* store is dead (X = load P; store X -> P).
11904 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11905 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11906 !SI.isVolatile()) {
11907 EraseInstFromFunction(SI);
11911 // Otherwise, this is a load from some other location. Stores before it
11912 // may not be dead.
11916 // Don't skip over loads or things that can modify memory.
11917 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11922 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11924 // store X, null -> turns into 'unreachable' in SimplifyCFG
11925 if (isa<ConstantPointerNull>(Ptr) &&
11926 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11927 if (!isa<UndefValue>(Val)) {
11928 SI.setOperand(0, Context->getUndef(Val->getType()));
11929 if (Instruction *U = dyn_cast<Instruction>(Val))
11930 AddToWorkList(U); // Dropped a use.
11933 return 0; // Do not modify these!
11936 // store undef, Ptr -> noop
11937 if (isa<UndefValue>(Val)) {
11938 EraseInstFromFunction(SI);
11943 // If the pointer destination is a cast, see if we can fold the cast into the
11945 if (isa<CastInst>(Ptr))
11946 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11948 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11950 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11954 // If this store is the last instruction in the basic block (possibly
11955 // excepting debug info instructions and the pointer bitcasts that feed
11956 // into them), and if the block ends with an unconditional branch, try
11957 // to move it to the successor block.
11961 } while (isa<DbgInfoIntrinsic>(BBI) ||
11962 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11963 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11964 if (BI->isUnconditional())
11965 if (SimplifyStoreAtEndOfBlock(SI))
11966 return 0; // xform done!
11971 /// SimplifyStoreAtEndOfBlock - Turn things like:
11972 /// if () { *P = v1; } else { *P = v2 }
11973 /// into a phi node with a store in the successor.
11975 /// Simplify things like:
11976 /// *P = v1; if () { *P = v2; }
11977 /// into a phi node with a store in the successor.
11979 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11980 BasicBlock *StoreBB = SI.getParent();
11982 // Check to see if the successor block has exactly two incoming edges. If
11983 // so, see if the other predecessor contains a store to the same location.
11984 // if so, insert a PHI node (if needed) and move the stores down.
11985 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11987 // Determine whether Dest has exactly two predecessors and, if so, compute
11988 // the other predecessor.
11989 pred_iterator PI = pred_begin(DestBB);
11990 BasicBlock *OtherBB = 0;
11991 if (*PI != StoreBB)
11994 if (PI == pred_end(DestBB))
11997 if (*PI != StoreBB) {
12002 if (++PI != pred_end(DestBB))
12005 // Bail out if all the relevant blocks aren't distinct (this can happen,
12006 // for example, if SI is in an infinite loop)
12007 if (StoreBB == DestBB || OtherBB == DestBB)
12010 // Verify that the other block ends in a branch and is not otherwise empty.
12011 BasicBlock::iterator BBI = OtherBB->getTerminator();
12012 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12013 if (!OtherBr || BBI == OtherBB->begin())
12016 // If the other block ends in an unconditional branch, check for the 'if then
12017 // else' case. there is an instruction before the branch.
12018 StoreInst *OtherStore = 0;
12019 if (OtherBr->isUnconditional()) {
12021 // Skip over debugging info.
12022 while (isa<DbgInfoIntrinsic>(BBI) ||
12023 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12024 if (BBI==OtherBB->begin())
12028 // If this isn't a store, or isn't a store to the same location, bail out.
12029 OtherStore = dyn_cast<StoreInst>(BBI);
12030 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12033 // Otherwise, the other block ended with a conditional branch. If one of the
12034 // destinations is StoreBB, then we have the if/then case.
12035 if (OtherBr->getSuccessor(0) != StoreBB &&
12036 OtherBr->getSuccessor(1) != StoreBB)
12039 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12040 // if/then triangle. See if there is a store to the same ptr as SI that
12041 // lives in OtherBB.
12043 // Check to see if we find the matching store.
12044 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12045 if (OtherStore->getOperand(1) != SI.getOperand(1))
12049 // If we find something that may be using or overwriting the stored
12050 // value, or if we run out of instructions, we can't do the xform.
12051 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12052 BBI == OtherBB->begin())
12056 // In order to eliminate the store in OtherBr, we have to
12057 // make sure nothing reads or overwrites the stored value in
12059 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12060 // FIXME: This should really be AA driven.
12061 if (I->mayReadFromMemory() || I->mayWriteToMemory())
12066 // Insert a PHI node now if we need it.
12067 Value *MergedVal = OtherStore->getOperand(0);
12068 if (MergedVal != SI.getOperand(0)) {
12069 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12070 PN->reserveOperandSpace(2);
12071 PN->addIncoming(SI.getOperand(0), SI.getParent());
12072 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12073 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12076 // Advance to a place where it is safe to insert the new store and
12078 BBI = DestBB->getFirstNonPHI();
12079 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12080 OtherStore->isVolatile()), *BBI);
12082 // Nuke the old stores.
12083 EraseInstFromFunction(SI);
12084 EraseInstFromFunction(*OtherStore);
12090 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12091 // Change br (not X), label True, label False to: br X, label False, True
12093 BasicBlock *TrueDest;
12094 BasicBlock *FalseDest;
12095 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12096 !isa<Constant>(X)) {
12097 // Swap Destinations and condition...
12098 BI.setCondition(X);
12099 BI.setSuccessor(0, FalseDest);
12100 BI.setSuccessor(1, TrueDest);
12104 // Cannonicalize fcmp_one -> fcmp_oeq
12105 FCmpInst::Predicate FPred; Value *Y;
12106 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
12107 TrueDest, FalseDest), *Context))
12108 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12109 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12110 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12111 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12112 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12113 NewSCC->takeName(I);
12114 // Swap Destinations and condition...
12115 BI.setCondition(NewSCC);
12116 BI.setSuccessor(0, FalseDest);
12117 BI.setSuccessor(1, TrueDest);
12118 RemoveFromWorkList(I);
12119 I->eraseFromParent();
12120 AddToWorkList(NewSCC);
12124 // Cannonicalize icmp_ne -> icmp_eq
12125 ICmpInst::Predicate IPred;
12126 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12127 TrueDest, FalseDest), *Context))
12128 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12129 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12130 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12131 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12132 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12133 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12134 NewSCC->takeName(I);
12135 // Swap Destinations and condition...
12136 BI.setCondition(NewSCC);
12137 BI.setSuccessor(0, FalseDest);
12138 BI.setSuccessor(1, TrueDest);
12139 RemoveFromWorkList(I);
12140 I->eraseFromParent();;
12141 AddToWorkList(NewSCC);
12148 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12149 Value *Cond = SI.getCondition();
12150 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12151 if (I->getOpcode() == Instruction::Add)
12152 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12153 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12154 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12156 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12158 SI.setOperand(0, I->getOperand(0));
12166 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12167 Value *Agg = EV.getAggregateOperand();
12169 if (!EV.hasIndices())
12170 return ReplaceInstUsesWith(EV, Agg);
12172 if (Constant *C = dyn_cast<Constant>(Agg)) {
12173 if (isa<UndefValue>(C))
12174 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12176 if (isa<ConstantAggregateZero>(C))
12177 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12179 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12180 // Extract the element indexed by the first index out of the constant
12181 Value *V = C->getOperand(*EV.idx_begin());
12182 if (EV.getNumIndices() > 1)
12183 // Extract the remaining indices out of the constant indexed by the
12185 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12187 return ReplaceInstUsesWith(EV, V);
12189 return 0; // Can't handle other constants
12191 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12192 // We're extracting from an insertvalue instruction, compare the indices
12193 const unsigned *exti, *exte, *insi, *inse;
12194 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12195 exte = EV.idx_end(), inse = IV->idx_end();
12196 exti != exte && insi != inse;
12198 if (*insi != *exti)
12199 // The insert and extract both reference distinctly different elements.
12200 // This means the extract is not influenced by the insert, and we can
12201 // replace the aggregate operand of the extract with the aggregate
12202 // operand of the insert. i.e., replace
12203 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12204 // %E = extractvalue { i32, { i32 } } %I, 0
12206 // %E = extractvalue { i32, { i32 } } %A, 0
12207 return ExtractValueInst::Create(IV->getAggregateOperand(),
12208 EV.idx_begin(), EV.idx_end());
12210 if (exti == exte && insi == inse)
12211 // Both iterators are at the end: Index lists are identical. Replace
12212 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12213 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12215 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12216 if (exti == exte) {
12217 // The extract list is a prefix of the insert list. i.e. replace
12218 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12219 // %E = extractvalue { i32, { i32 } } %I, 1
12221 // %X = extractvalue { i32, { i32 } } %A, 1
12222 // %E = insertvalue { i32 } %X, i32 42, 0
12223 // by switching the order of the insert and extract (though the
12224 // insertvalue should be left in, since it may have other uses).
12225 Value *NewEV = InsertNewInstBefore(
12226 ExtractValueInst::Create(IV->getAggregateOperand(),
12227 EV.idx_begin(), EV.idx_end()),
12229 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12233 // The insert list is a prefix of the extract list
12234 // We can simply remove the common indices from the extract and make it
12235 // operate on the inserted value instead of the insertvalue result.
12237 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12238 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12240 // %E extractvalue { i32 } { i32 42 }, 0
12241 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12244 // Can't simplify extracts from other values. Note that nested extracts are
12245 // already simplified implicitely by the above (extract ( extract (insert) )
12246 // will be translated into extract ( insert ( extract ) ) first and then just
12247 // the value inserted, if appropriate).
12251 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12252 /// is to leave as a vector operation.
12253 static bool CheapToScalarize(Value *V, bool isConstant) {
12254 if (isa<ConstantAggregateZero>(V))
12256 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12257 if (isConstant) return true;
12258 // If all elts are the same, we can extract.
12259 Constant *Op0 = C->getOperand(0);
12260 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12261 if (C->getOperand(i) != Op0)
12265 Instruction *I = dyn_cast<Instruction>(V);
12266 if (!I) return false;
12268 // Insert element gets simplified to the inserted element or is deleted if
12269 // this is constant idx extract element and its a constant idx insertelt.
12270 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12271 isa<ConstantInt>(I->getOperand(2)))
12273 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12275 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12276 if (BO->hasOneUse() &&
12277 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12278 CheapToScalarize(BO->getOperand(1), isConstant)))
12280 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12281 if (CI->hasOneUse() &&
12282 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12283 CheapToScalarize(CI->getOperand(1), isConstant)))
12289 /// Read and decode a shufflevector mask.
12291 /// It turns undef elements into values that are larger than the number of
12292 /// elements in the input.
12293 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12294 unsigned NElts = SVI->getType()->getNumElements();
12295 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12296 return std::vector<unsigned>(NElts, 0);
12297 if (isa<UndefValue>(SVI->getOperand(2)))
12298 return std::vector<unsigned>(NElts, 2*NElts);
12300 std::vector<unsigned> Result;
12301 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12302 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12303 if (isa<UndefValue>(*i))
12304 Result.push_back(NElts*2); // undef -> 8
12306 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12310 /// FindScalarElement - Given a vector and an element number, see if the scalar
12311 /// value is already around as a register, for example if it were inserted then
12312 /// extracted from the vector.
12313 static Value *FindScalarElement(Value *V, unsigned EltNo,
12314 LLVMContext *Context) {
12315 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12316 const VectorType *PTy = cast<VectorType>(V->getType());
12317 unsigned Width = PTy->getNumElements();
12318 if (EltNo >= Width) // Out of range access.
12319 return Context->getUndef(PTy->getElementType());
12321 if (isa<UndefValue>(V))
12322 return Context->getUndef(PTy->getElementType());
12323 else if (isa<ConstantAggregateZero>(V))
12324 return Context->getNullValue(PTy->getElementType());
12325 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12326 return CP->getOperand(EltNo);
12327 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12328 // If this is an insert to a variable element, we don't know what it is.
12329 if (!isa<ConstantInt>(III->getOperand(2)))
12331 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12333 // If this is an insert to the element we are looking for, return the
12335 if (EltNo == IIElt)
12336 return III->getOperand(1);
12338 // Otherwise, the insertelement doesn't modify the value, recurse on its
12340 return FindScalarElement(III->getOperand(0), EltNo, Context);
12341 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12342 unsigned LHSWidth =
12343 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12344 unsigned InEl = getShuffleMask(SVI)[EltNo];
12345 if (InEl < LHSWidth)
12346 return FindScalarElement(SVI->getOperand(0), InEl, Context);
12347 else if (InEl < LHSWidth*2)
12348 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12350 return Context->getUndef(PTy->getElementType());
12353 // Otherwise, we don't know.
12357 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12358 // If vector val is undef, replace extract with scalar undef.
12359 if (isa<UndefValue>(EI.getOperand(0)))
12360 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12362 // If vector val is constant 0, replace extract with scalar 0.
12363 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12364 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12366 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12367 // If vector val is constant with all elements the same, replace EI with
12368 // that element. When the elements are not identical, we cannot replace yet
12369 // (we do that below, but only when the index is constant).
12370 Constant *op0 = C->getOperand(0);
12371 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12372 if (C->getOperand(i) != op0) {
12377 return ReplaceInstUsesWith(EI, op0);
12380 // If extracting a specified index from the vector, see if we can recursively
12381 // find a previously computed scalar that was inserted into the vector.
12382 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12383 unsigned IndexVal = IdxC->getZExtValue();
12384 unsigned VectorWidth =
12385 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12387 // If this is extracting an invalid index, turn this into undef, to avoid
12388 // crashing the code below.
12389 if (IndexVal >= VectorWidth)
12390 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12392 // This instruction only demands the single element from the input vector.
12393 // If the input vector has a single use, simplify it based on this use
12395 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12396 APInt UndefElts(VectorWidth, 0);
12397 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12398 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12399 DemandedMask, UndefElts)) {
12400 EI.setOperand(0, V);
12405 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12406 return ReplaceInstUsesWith(EI, Elt);
12408 // If the this extractelement is directly using a bitcast from a vector of
12409 // the same number of elements, see if we can find the source element from
12410 // it. In this case, we will end up needing to bitcast the scalars.
12411 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12412 if (const VectorType *VT =
12413 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12414 if (VT->getNumElements() == VectorWidth)
12415 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12416 IndexVal, Context))
12417 return new BitCastInst(Elt, EI.getType());
12421 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12422 if (I->hasOneUse()) {
12423 // Push extractelement into predecessor operation if legal and
12424 // profitable to do so
12425 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12426 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12427 if (CheapToScalarize(BO, isConstantElt)) {
12428 ExtractElementInst *newEI0 =
12429 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12430 EI.getName()+".lhs");
12431 ExtractElementInst *newEI1 =
12432 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12433 EI.getName()+".rhs");
12434 InsertNewInstBefore(newEI0, EI);
12435 InsertNewInstBefore(newEI1, EI);
12436 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12438 } else if (isa<LoadInst>(I)) {
12440 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12441 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12442 Context->getPointerType(EI.getType(), AS),EI);
12443 GetElementPtrInst *GEP =
12444 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12445 InsertNewInstBefore(GEP, EI);
12446 return new LoadInst(GEP);
12449 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12450 // Extracting the inserted element?
12451 if (IE->getOperand(2) == EI.getOperand(1))
12452 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12453 // If the inserted and extracted elements are constants, they must not
12454 // be the same value, extract from the pre-inserted value instead.
12455 if (isa<Constant>(IE->getOperand(2)) &&
12456 isa<Constant>(EI.getOperand(1))) {
12457 AddUsesToWorkList(EI);
12458 EI.setOperand(0, IE->getOperand(0));
12461 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12462 // If this is extracting an element from a shufflevector, figure out where
12463 // it came from and extract from the appropriate input element instead.
12464 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12465 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12467 unsigned LHSWidth =
12468 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12470 if (SrcIdx < LHSWidth)
12471 Src = SVI->getOperand(0);
12472 else if (SrcIdx < LHSWidth*2) {
12473 SrcIdx -= LHSWidth;
12474 Src = SVI->getOperand(1);
12476 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12478 return new ExtractElementInst(Src, SrcIdx);
12485 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12486 /// elements from either LHS or RHS, return the shuffle mask and true.
12487 /// Otherwise, return false.
12488 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12489 std::vector<Constant*> &Mask,
12490 LLVMContext *Context) {
12491 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12492 "Invalid CollectSingleShuffleElements");
12493 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12495 if (isa<UndefValue>(V)) {
12496 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12498 } else if (V == LHS) {
12499 for (unsigned i = 0; i != NumElts; ++i)
12500 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12502 } else if (V == RHS) {
12503 for (unsigned i = 0; i != NumElts; ++i)
12504 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12506 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12507 // If this is an insert of an extract from some other vector, include it.
12508 Value *VecOp = IEI->getOperand(0);
12509 Value *ScalarOp = IEI->getOperand(1);
12510 Value *IdxOp = IEI->getOperand(2);
12512 if (!isa<ConstantInt>(IdxOp))
12514 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12516 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12517 // Okay, we can handle this if the vector we are insertinting into is
12518 // transitively ok.
12519 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12520 // If so, update the mask to reflect the inserted undef.
12521 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12524 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12525 if (isa<ConstantInt>(EI->getOperand(1)) &&
12526 EI->getOperand(0)->getType() == V->getType()) {
12527 unsigned ExtractedIdx =
12528 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12530 // This must be extracting from either LHS or RHS.
12531 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12532 // Okay, we can handle this if the vector we are insertinting into is
12533 // transitively ok.
12534 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12535 // If so, update the mask to reflect the inserted value.
12536 if (EI->getOperand(0) == LHS) {
12537 Mask[InsertedIdx % NumElts] =
12538 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12540 assert(EI->getOperand(0) == RHS);
12541 Mask[InsertedIdx % NumElts] =
12542 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12551 // TODO: Handle shufflevector here!
12556 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12557 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12558 /// that computes V and the LHS value of the shuffle.
12559 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12560 Value *&RHS, LLVMContext *Context) {
12561 assert(isa<VectorType>(V->getType()) &&
12562 (RHS == 0 || V->getType() == RHS->getType()) &&
12563 "Invalid shuffle!");
12564 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12566 if (isa<UndefValue>(V)) {
12567 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12569 } else if (isa<ConstantAggregateZero>(V)) {
12570 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12572 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12573 // If this is an insert of an extract from some other vector, include it.
12574 Value *VecOp = IEI->getOperand(0);
12575 Value *ScalarOp = IEI->getOperand(1);
12576 Value *IdxOp = IEI->getOperand(2);
12578 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12579 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12580 EI->getOperand(0)->getType() == V->getType()) {
12581 unsigned ExtractedIdx =
12582 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12583 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12585 // Either the extracted from or inserted into vector must be RHSVec,
12586 // otherwise we'd end up with a shuffle of three inputs.
12587 if (EI->getOperand(0) == RHS || RHS == 0) {
12588 RHS = EI->getOperand(0);
12589 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12590 Mask[InsertedIdx % NumElts] =
12591 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12595 if (VecOp == RHS) {
12596 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12598 // Everything but the extracted element is replaced with the RHS.
12599 for (unsigned i = 0; i != NumElts; ++i) {
12600 if (i != InsertedIdx)
12601 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12606 // If this insertelement is a chain that comes from exactly these two
12607 // vectors, return the vector and the effective shuffle.
12608 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12610 return EI->getOperand(0);
12615 // TODO: Handle shufflevector here!
12617 // Otherwise, can't do anything fancy. Return an identity vector.
12618 for (unsigned i = 0; i != NumElts; ++i)
12619 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12623 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12624 Value *VecOp = IE.getOperand(0);
12625 Value *ScalarOp = IE.getOperand(1);
12626 Value *IdxOp = IE.getOperand(2);
12628 // Inserting an undef or into an undefined place, remove this.
12629 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12630 ReplaceInstUsesWith(IE, VecOp);
12632 // If the inserted element was extracted from some other vector, and if the
12633 // indexes are constant, try to turn this into a shufflevector operation.
12634 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12635 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12636 EI->getOperand(0)->getType() == IE.getType()) {
12637 unsigned NumVectorElts = IE.getType()->getNumElements();
12638 unsigned ExtractedIdx =
12639 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12640 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12642 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12643 return ReplaceInstUsesWith(IE, VecOp);
12645 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12646 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12648 // If we are extracting a value from a vector, then inserting it right
12649 // back into the same place, just use the input vector.
12650 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12651 return ReplaceInstUsesWith(IE, VecOp);
12653 // We could theoretically do this for ANY input. However, doing so could
12654 // turn chains of insertelement instructions into a chain of shufflevector
12655 // instructions, and right now we do not merge shufflevectors. As such,
12656 // only do this in a situation where it is clear that there is benefit.
12657 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12658 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12659 // the values of VecOp, except then one read from EIOp0.
12660 // Build a new shuffle mask.
12661 std::vector<Constant*> Mask;
12662 if (isa<UndefValue>(VecOp))
12663 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12665 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12666 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12669 Mask[InsertedIdx] =
12670 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12671 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12672 Context->getConstantVector(Mask));
12675 // If this insertelement isn't used by some other insertelement, turn it
12676 // (and any insertelements it points to), into one big shuffle.
12677 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12678 std::vector<Constant*> Mask;
12680 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12681 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12682 // We now have a shuffle of LHS, RHS, Mask.
12683 return new ShuffleVectorInst(LHS, RHS,
12684 Context->getConstantVector(Mask));
12689 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12690 APInt UndefElts(VWidth, 0);
12691 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12692 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12699 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12700 Value *LHS = SVI.getOperand(0);
12701 Value *RHS = SVI.getOperand(1);
12702 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12704 bool MadeChange = false;
12706 // Undefined shuffle mask -> undefined value.
12707 if (isa<UndefValue>(SVI.getOperand(2)))
12708 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12710 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12712 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12715 APInt UndefElts(VWidth, 0);
12716 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12717 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12718 LHS = SVI.getOperand(0);
12719 RHS = SVI.getOperand(1);
12723 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12724 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12725 if (LHS == RHS || isa<UndefValue>(LHS)) {
12726 if (isa<UndefValue>(LHS) && LHS == RHS) {
12727 // shuffle(undef,undef,mask) -> undef.
12728 return ReplaceInstUsesWith(SVI, LHS);
12731 // Remap any references to RHS to use LHS.
12732 std::vector<Constant*> Elts;
12733 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12734 if (Mask[i] >= 2*e)
12735 Elts.push_back(Context->getUndef(Type::Int32Ty));
12737 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12738 (Mask[i] < e && isa<UndefValue>(LHS))) {
12739 Mask[i] = 2*e; // Turn into undef.
12740 Elts.push_back(Context->getUndef(Type::Int32Ty));
12742 Mask[i] = Mask[i] % e; // Force to LHS.
12743 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12747 SVI.setOperand(0, SVI.getOperand(1));
12748 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12749 SVI.setOperand(2, Context->getConstantVector(Elts));
12750 LHS = SVI.getOperand(0);
12751 RHS = SVI.getOperand(1);
12755 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12756 bool isLHSID = true, isRHSID = true;
12758 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12759 if (Mask[i] >= e*2) continue; // Ignore undef values.
12760 // Is this an identity shuffle of the LHS value?
12761 isLHSID &= (Mask[i] == i);
12763 // Is this an identity shuffle of the RHS value?
12764 isRHSID &= (Mask[i]-e == i);
12767 // Eliminate identity shuffles.
12768 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12769 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12771 // If the LHS is a shufflevector itself, see if we can combine it with this
12772 // one without producing an unusual shuffle. Here we are really conservative:
12773 // we are absolutely afraid of producing a shuffle mask not in the input
12774 // program, because the code gen may not be smart enough to turn a merged
12775 // shuffle into two specific shuffles: it may produce worse code. As such,
12776 // we only merge two shuffles if the result is one of the two input shuffle
12777 // masks. In this case, merging the shuffles just removes one instruction,
12778 // which we know is safe. This is good for things like turning:
12779 // (splat(splat)) -> splat.
12780 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12781 if (isa<UndefValue>(RHS)) {
12782 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12784 std::vector<unsigned> NewMask;
12785 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12786 if (Mask[i] >= 2*e)
12787 NewMask.push_back(2*e);
12789 NewMask.push_back(LHSMask[Mask[i]]);
12791 // If the result mask is equal to the src shuffle or this shuffle mask, do
12792 // the replacement.
12793 if (NewMask == LHSMask || NewMask == Mask) {
12794 unsigned LHSInNElts =
12795 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12796 std::vector<Constant*> Elts;
12797 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12798 if (NewMask[i] >= LHSInNElts*2) {
12799 Elts.push_back(Context->getUndef(Type::Int32Ty));
12801 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12804 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12805 LHSSVI->getOperand(1),
12806 Context->getConstantVector(Elts));
12811 return MadeChange ? &SVI : 0;
12817 /// TryToSinkInstruction - Try to move the specified instruction from its
12818 /// current block into the beginning of DestBlock, which can only happen if it's
12819 /// safe to move the instruction past all of the instructions between it and the
12820 /// end of its block.
12821 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12822 assert(I->hasOneUse() && "Invariants didn't hold!");
12824 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12825 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12828 // Do not sink alloca instructions out of the entry block.
12829 if (isa<AllocaInst>(I) && I->getParent() ==
12830 &DestBlock->getParent()->getEntryBlock())
12833 // We can only sink load instructions if there is nothing between the load and
12834 // the end of block that could change the value.
12835 if (I->mayReadFromMemory()) {
12836 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12838 if (Scan->mayWriteToMemory())
12842 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12844 CopyPrecedingStopPoint(I, InsertPos);
12845 I->moveBefore(InsertPos);
12851 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12852 /// all reachable code to the worklist.
12854 /// This has a couple of tricks to make the code faster and more powerful. In
12855 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12856 /// them to the worklist (this significantly speeds up instcombine on code where
12857 /// many instructions are dead or constant). Additionally, if we find a branch
12858 /// whose condition is a known constant, we only visit the reachable successors.
12860 static void AddReachableCodeToWorklist(BasicBlock *BB,
12861 SmallPtrSet<BasicBlock*, 64> &Visited,
12863 const TargetData *TD) {
12864 SmallVector<BasicBlock*, 256> Worklist;
12865 Worklist.push_back(BB);
12867 while (!Worklist.empty()) {
12868 BB = Worklist.back();
12869 Worklist.pop_back();
12871 // We have now visited this block! If we've already been here, ignore it.
12872 if (!Visited.insert(BB)) continue;
12874 DbgInfoIntrinsic *DBI_Prev = NULL;
12875 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12876 Instruction *Inst = BBI++;
12878 // DCE instruction if trivially dead.
12879 if (isInstructionTriviallyDead(Inst)) {
12881 DOUT << "IC: DCE: " << *Inst;
12882 Inst->eraseFromParent();
12886 // ConstantProp instruction if trivially constant.
12887 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12888 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12889 Inst->replaceAllUsesWith(C);
12891 Inst->eraseFromParent();
12895 // If there are two consecutive llvm.dbg.stoppoint calls then
12896 // it is likely that the optimizer deleted code in between these
12898 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12901 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12902 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12903 IC.RemoveFromWorkList(DBI_Prev);
12904 DBI_Prev->eraseFromParent();
12906 DBI_Prev = DBI_Next;
12911 IC.AddToWorkList(Inst);
12914 // Recursively visit successors. If this is a branch or switch on a
12915 // constant, only visit the reachable successor.
12916 TerminatorInst *TI = BB->getTerminator();
12917 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12918 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12919 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12920 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12921 Worklist.push_back(ReachableBB);
12924 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12925 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12926 // See if this is an explicit destination.
12927 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12928 if (SI->getCaseValue(i) == Cond) {
12929 BasicBlock *ReachableBB = SI->getSuccessor(i);
12930 Worklist.push_back(ReachableBB);
12934 // Otherwise it is the default destination.
12935 Worklist.push_back(SI->getSuccessor(0));
12940 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12941 Worklist.push_back(TI->getSuccessor(i));
12945 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12946 bool Changed = false;
12947 TD = &getAnalysis<TargetData>();
12949 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12950 << F.getNameStr() << "\n");
12953 // Do a depth-first traversal of the function, populate the worklist with
12954 // the reachable instructions. Ignore blocks that are not reachable. Keep
12955 // track of which blocks we visit.
12956 SmallPtrSet<BasicBlock*, 64> Visited;
12957 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12959 // Do a quick scan over the function. If we find any blocks that are
12960 // unreachable, remove any instructions inside of them. This prevents
12961 // the instcombine code from having to deal with some bad special cases.
12962 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12963 if (!Visited.count(BB)) {
12964 Instruction *Term = BB->getTerminator();
12965 while (Term != BB->begin()) { // Remove instrs bottom-up
12966 BasicBlock::iterator I = Term; --I;
12968 DOUT << "IC: DCE: " << *I;
12969 // A debug intrinsic shouldn't force another iteration if we weren't
12970 // going to do one without it.
12971 if (!isa<DbgInfoIntrinsic>(I)) {
12975 if (!I->use_empty())
12976 I->replaceAllUsesWith(Context->getUndef(I->getType()));
12977 I->eraseFromParent();
12982 while (!Worklist.empty()) {
12983 Instruction *I = RemoveOneFromWorkList();
12984 if (I == 0) continue; // skip null values.
12986 // Check to see if we can DCE the instruction.
12987 if (isInstructionTriviallyDead(I)) {
12988 // Add operands to the worklist.
12989 if (I->getNumOperands() < 4)
12990 AddUsesToWorkList(*I);
12993 DOUT << "IC: DCE: " << *I;
12995 I->eraseFromParent();
12996 RemoveFromWorkList(I);
13001 // Instruction isn't dead, see if we can constant propagate it.
13002 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13003 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13005 // Add operands to the worklist.
13006 AddUsesToWorkList(*I);
13007 ReplaceInstUsesWith(*I, C);
13010 I->eraseFromParent();
13011 RemoveFromWorkList(I);
13017 (I->getType()->getTypeID() == Type::VoidTyID ||
13018 I->isTrapping())) {
13019 // See if we can constant fold its operands.
13020 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13021 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13022 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13023 F.getContext(), TD))
13030 // See if we can trivially sink this instruction to a successor basic block.
13031 if (I->hasOneUse()) {
13032 BasicBlock *BB = I->getParent();
13033 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13034 if (UserParent != BB) {
13035 bool UserIsSuccessor = false;
13036 // See if the user is one of our successors.
13037 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13038 if (*SI == UserParent) {
13039 UserIsSuccessor = true;
13043 // If the user is one of our immediate successors, and if that successor
13044 // only has us as a predecessors (we'd have to split the critical edge
13045 // otherwise), we can keep going.
13046 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13047 next(pred_begin(UserParent)) == pred_end(UserParent))
13048 // Okay, the CFG is simple enough, try to sink this instruction.
13049 Changed |= TryToSinkInstruction(I, UserParent);
13053 // Now that we have an instruction, try combining it to simplify it...
13057 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13058 if (Instruction *Result = visit(*I)) {
13060 // Should we replace the old instruction with a new one?
13062 DOUT << "IC: Old = " << *I
13063 << " New = " << *Result;
13065 // Everything uses the new instruction now.
13066 I->replaceAllUsesWith(Result);
13068 // Push the new instruction and any users onto the worklist.
13069 AddToWorkList(Result);
13070 AddUsersToWorkList(*Result);
13072 // Move the name to the new instruction first.
13073 Result->takeName(I);
13075 // Insert the new instruction into the basic block...
13076 BasicBlock *InstParent = I->getParent();
13077 BasicBlock::iterator InsertPos = I;
13079 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13080 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13083 InstParent->getInstList().insert(InsertPos, Result);
13085 // Make sure that we reprocess all operands now that we reduced their
13087 AddUsesToWorkList(*I);
13089 // Instructions can end up on the worklist more than once. Make sure
13090 // we do not process an instruction that has been deleted.
13091 RemoveFromWorkList(I);
13093 // Erase the old instruction.
13094 InstParent->getInstList().erase(I);
13097 DOUT << "IC: Mod = " << OrigI
13098 << " New = " << *I;
13101 // If the instruction was modified, it's possible that it is now dead.
13102 // if so, remove it.
13103 if (isInstructionTriviallyDead(I)) {
13104 // Make sure we process all operands now that we are reducing their
13106 AddUsesToWorkList(*I);
13108 // Instructions may end up in the worklist more than once. Erase all
13109 // occurrences of this instruction.
13110 RemoveFromWorkList(I);
13111 I->eraseFromParent();
13114 AddUsersToWorkList(*I);
13121 assert(WorklistMap.empty() && "Worklist empty, but map not?");
13123 // Do an explicit clear, this shrinks the map if needed.
13124 WorklistMap.clear();
13129 bool InstCombiner::runOnFunction(Function &F) {
13130 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13132 bool EverMadeChange = false;
13134 // Iterate while there is work to do.
13135 unsigned Iteration = 0;
13136 while (DoOneIteration(F, Iteration++))
13137 EverMadeChange = true;
13138 return EverMadeChange;
13141 FunctionPass *llvm::createInstructionCombiningPass() {
13142 return new InstCombiner();