1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG. This pass is where
12 // algebraic simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/MallocHelper.h"
46 #include "llvm/Analysis/ValueTracking.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Support/CallSite.h"
51 #include "llvm/Support/ConstantRange.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/GetElementPtrTypeIterator.h"
55 #include "llvm/Support/InstVisitor.h"
56 #include "llvm/Support/IRBuilder.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/PatternMatch.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/ADT/DenseMap.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/ADT/SmallPtrSet.h"
63 #include "llvm/ADT/Statistic.h"
64 #include "llvm/ADT/STLExtras.h"
68 using namespace llvm::PatternMatch;
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74 STATISTIC(NumSunkInst , "Number of instructions sunk");
77 /// InstCombineWorklist - This is the worklist management logic for
79 class InstCombineWorklist {
80 SmallVector<Instruction*, 256> Worklist;
81 DenseMap<Instruction*, unsigned> WorklistMap;
83 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
84 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
86 InstCombineWorklist() {}
88 bool isEmpty() const { return Worklist.empty(); }
90 /// Add - Add the specified instruction to the worklist if it isn't already
92 void Add(Instruction *I) {
93 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
94 DEBUG(errs() << "IC: ADD: " << *I << '\n');
95 Worklist.push_back(I);
99 void AddValue(Value *V) {
100 if (Instruction *I = dyn_cast<Instruction>(V))
104 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
105 /// which should only be done when the worklist is empty and when the group
106 /// has no duplicates.
107 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
108 assert(Worklist.empty() && "Worklist must be empty to add initial group");
109 Worklist.reserve(NumEntries+16);
110 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
111 for (; NumEntries; --NumEntries) {
112 Instruction *I = List[NumEntries-1];
113 WorklistMap.insert(std::make_pair(I, Worklist.size()));
114 Worklist.push_back(I);
118 // Remove - remove I from the worklist if it exists.
119 void Remove(Instruction *I) {
120 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
121 if (It == WorklistMap.end()) return; // Not in worklist.
123 // Don't bother moving everything down, just null out the slot.
124 Worklist[It->second] = 0;
126 WorklistMap.erase(It);
129 Instruction *RemoveOne() {
130 Instruction *I = Worklist.back();
132 WorklistMap.erase(I);
136 /// AddUsersToWorkList - When an instruction is simplified, add all users of
137 /// the instruction to the work lists because they might get more simplified
140 void AddUsersToWorkList(Instruction &I) {
141 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
143 Add(cast<Instruction>(*UI));
147 /// Zap - check that the worklist is empty and nuke the backing store for
148 /// the map if it is large.
150 assert(WorklistMap.empty() && "Worklist empty, but map not?");
152 // Do an explicit clear, this shrinks the map if needed.
156 } // end anonymous namespace.
160 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
161 /// just like the normal insertion helper, but also adds any new instructions
162 /// to the instcombine worklist.
163 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
164 InstCombineWorklist &Worklist;
166 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
168 void InsertHelper(Instruction *I, const Twine &Name,
169 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
170 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
174 } // end anonymous namespace
178 class InstCombiner : public FunctionPass,
179 public InstVisitor<InstCombiner, Instruction*> {
181 bool MustPreserveLCSSA;
184 /// Worklist - All of the instructions that need to be simplified.
185 InstCombineWorklist Worklist;
187 /// Builder - This is an IRBuilder that automatically inserts new
188 /// instructions into the worklist when they are created.
189 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
192 static char ID; // Pass identification, replacement for typeid
193 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
195 LLVMContext *Context;
196 LLVMContext *getContext() const { return Context; }
199 virtual bool runOnFunction(Function &F);
201 bool DoOneIteration(Function &F, unsigned ItNum);
203 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
204 AU.addPreservedID(LCSSAID);
205 AU.setPreservesCFG();
208 TargetData *getTargetData() const { return TD; }
210 // Visitation implementation - Implement instruction combining for different
211 // instruction types. The semantics are as follows:
213 // null - No change was made
214 // I - Change was made, I is still valid, I may be dead though
215 // otherwise - Change was made, replace I with returned instruction
217 Instruction *visitAdd(BinaryOperator &I);
218 Instruction *visitFAdd(BinaryOperator &I);
219 Instruction *visitSub(BinaryOperator &I);
220 Instruction *visitFSub(BinaryOperator &I);
221 Instruction *visitMul(BinaryOperator &I);
222 Instruction *visitFMul(BinaryOperator &I);
223 Instruction *visitURem(BinaryOperator &I);
224 Instruction *visitSRem(BinaryOperator &I);
225 Instruction *visitFRem(BinaryOperator &I);
226 bool SimplifyDivRemOfSelect(BinaryOperator &I);
227 Instruction *commonRemTransforms(BinaryOperator &I);
228 Instruction *commonIRemTransforms(BinaryOperator &I);
229 Instruction *commonDivTransforms(BinaryOperator &I);
230 Instruction *commonIDivTransforms(BinaryOperator &I);
231 Instruction *visitUDiv(BinaryOperator &I);
232 Instruction *visitSDiv(BinaryOperator &I);
233 Instruction *visitFDiv(BinaryOperator &I);
234 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
235 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
236 Instruction *visitAnd(BinaryOperator &I);
237 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
238 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
239 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
240 Value *A, Value *B, Value *C);
241 Instruction *visitOr (BinaryOperator &I);
242 Instruction *visitXor(BinaryOperator &I);
243 Instruction *visitShl(BinaryOperator &I);
244 Instruction *visitAShr(BinaryOperator &I);
245 Instruction *visitLShr(BinaryOperator &I);
246 Instruction *commonShiftTransforms(BinaryOperator &I);
247 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
249 Instruction *visitFCmpInst(FCmpInst &I);
250 Instruction *visitICmpInst(ICmpInst &I);
251 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
252 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
255 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
256 ConstantInt *DivRHS);
258 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
259 ICmpInst::Predicate Cond, Instruction &I);
260 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
262 Instruction *commonCastTransforms(CastInst &CI);
263 Instruction *commonIntCastTransforms(CastInst &CI);
264 Instruction *commonPointerCastTransforms(CastInst &CI);
265 Instruction *visitTrunc(TruncInst &CI);
266 Instruction *visitZExt(ZExtInst &CI);
267 Instruction *visitSExt(SExtInst &CI);
268 Instruction *visitFPTrunc(FPTruncInst &CI);
269 Instruction *visitFPExt(CastInst &CI);
270 Instruction *visitFPToUI(FPToUIInst &FI);
271 Instruction *visitFPToSI(FPToSIInst &FI);
272 Instruction *visitUIToFP(CastInst &CI);
273 Instruction *visitSIToFP(CastInst &CI);
274 Instruction *visitPtrToInt(PtrToIntInst &CI);
275 Instruction *visitIntToPtr(IntToPtrInst &CI);
276 Instruction *visitBitCast(BitCastInst &CI);
277 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
279 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
280 Instruction *visitSelectInst(SelectInst &SI);
281 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
282 Instruction *visitCallInst(CallInst &CI);
283 Instruction *visitInvokeInst(InvokeInst &II);
284 Instruction *visitPHINode(PHINode &PN);
285 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
286 Instruction *visitAllocationInst(AllocationInst &AI);
287 Instruction *visitFreeInst(FreeInst &FI);
288 Instruction *visitLoadInst(LoadInst &LI);
289 Instruction *visitStoreInst(StoreInst &SI);
290 Instruction *visitBranchInst(BranchInst &BI);
291 Instruction *visitSwitchInst(SwitchInst &SI);
292 Instruction *visitInsertElementInst(InsertElementInst &IE);
293 Instruction *visitExtractElementInst(ExtractElementInst &EI);
294 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
295 Instruction *visitExtractValueInst(ExtractValueInst &EV);
297 // visitInstruction - Specify what to return for unhandled instructions...
298 Instruction *visitInstruction(Instruction &I) { return 0; }
301 Instruction *visitCallSite(CallSite CS);
302 bool transformConstExprCastCall(CallSite CS);
303 Instruction *transformCallThroughTrampoline(CallSite CS);
304 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
305 bool DoXform = true);
306 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
307 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
311 // InsertNewInstBefore - insert an instruction New before instruction Old
312 // in the program. Add the new instruction to the worklist.
314 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
315 assert(New && New->getParent() == 0 &&
316 "New instruction already inserted into a basic block!");
317 BasicBlock *BB = Old.getParent();
318 BB->getInstList().insert(&Old, New); // Insert inst
323 // ReplaceInstUsesWith - This method is to be used when an instruction is
324 // found to be dead, replacable with another preexisting expression. Here
325 // we add all uses of I to the worklist, replace all uses of I with the new
326 // value, then return I, so that the inst combiner will know that I was
329 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
330 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
332 // If we are replacing the instruction with itself, this must be in a
333 // segment of unreachable code, so just clobber the instruction.
335 V = UndefValue::get(I.getType());
337 I.replaceAllUsesWith(V);
341 // EraseInstFromFunction - When dealing with an instruction that has side
342 // effects or produces a void value, we can't rely on DCE to delete the
343 // instruction. Instead, visit methods should return the value returned by
345 Instruction *EraseInstFromFunction(Instruction &I) {
346 DEBUG(errs() << "IC: ERASE " << I << '\n');
348 assert(I.use_empty() && "Cannot erase instruction that is used!");
349 // Make sure that we reprocess all operands now that we reduced their
351 if (I.getNumOperands() < 8) {
352 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
353 if (Instruction *Op = dyn_cast<Instruction>(*i))
359 return 0; // Don't do anything with FI
362 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
363 APInt &KnownOne, unsigned Depth = 0) const {
364 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
367 bool MaskedValueIsZero(Value *V, const APInt &Mask,
368 unsigned Depth = 0) const {
369 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
371 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
372 return llvm::ComputeNumSignBits(Op, TD, Depth);
377 /// SimplifyCommutative - This performs a few simplifications for
378 /// commutative operators.
379 bool SimplifyCommutative(BinaryOperator &I);
381 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
382 /// most-complex to least-complex order.
383 bool SimplifyCompare(CmpInst &I);
385 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
386 /// based on the demanded bits.
387 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
388 APInt& KnownZero, APInt& KnownOne,
390 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
391 APInt& KnownZero, APInt& KnownOne,
394 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
395 /// SimplifyDemandedBits knows about. See if the instruction has any
396 /// properties that allow us to simplify its operands.
397 bool SimplifyDemandedInstructionBits(Instruction &Inst);
399 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
400 APInt& UndefElts, unsigned Depth = 0);
402 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
403 // which has a PHI node as operand #0, see if we can fold the instruction
404 // into the PHI (which is only possible if all operands to the PHI are
407 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
408 // that would normally be unprofitable because they strongly encourage jump
410 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
412 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
413 // operator and they all are only used by the PHI, PHI together their
414 // inputs, and do the operation once, to the result of the PHI.
415 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
416 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
417 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
420 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
421 ConstantInt *AndRHS, BinaryOperator &TheAnd);
423 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
424 bool isSub, Instruction &I);
425 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
426 bool isSigned, bool Inside, Instruction &IB);
427 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
428 Instruction *MatchBSwap(BinaryOperator &I);
429 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
430 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
431 Instruction *SimplifyMemSet(MemSetInst *MI);
434 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
436 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
437 unsigned CastOpc, int &NumCastsRemoved);
438 unsigned GetOrEnforceKnownAlignment(Value *V,
439 unsigned PrefAlign = 0);
442 } // end anonymous namespace
444 char InstCombiner::ID = 0;
445 static RegisterPass<InstCombiner>
446 X("instcombine", "Combine redundant instructions");
448 // getComplexity: Assign a complexity or rank value to LLVM Values...
449 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
450 static unsigned getComplexity(Value *V) {
451 if (isa<Instruction>(V)) {
452 if (BinaryOperator::isNeg(V) ||
453 BinaryOperator::isFNeg(V) ||
454 BinaryOperator::isNot(V))
458 if (isa<Argument>(V)) return 3;
459 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
462 // isOnlyUse - Return true if this instruction will be deleted if we stop using
464 static bool isOnlyUse(Value *V) {
465 return V->hasOneUse() || isa<Constant>(V);
468 // getPromotedType - Return the specified type promoted as it would be to pass
469 // though a va_arg area...
470 static const Type *getPromotedType(const Type *Ty) {
471 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
472 if (ITy->getBitWidth() < 32)
473 return Type::getInt32Ty(Ty->getContext());
478 /// getBitCastOperand - If the specified operand is a CastInst, a constant
479 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
480 /// operand value, otherwise return null.
481 static Value *getBitCastOperand(Value *V) {
482 if (Operator *O = dyn_cast<Operator>(V)) {
483 if (O->getOpcode() == Instruction::BitCast)
484 return O->getOperand(0);
485 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
486 if (GEP->hasAllZeroIndices())
487 return GEP->getPointerOperand();
492 /// This function is a wrapper around CastInst::isEliminableCastPair. It
493 /// simply extracts arguments and returns what that function returns.
494 static Instruction::CastOps
495 isEliminableCastPair(
496 const CastInst *CI, ///< The first cast instruction
497 unsigned opcode, ///< The opcode of the second cast instruction
498 const Type *DstTy, ///< The target type for the second cast instruction
499 TargetData *TD ///< The target data for pointer size
502 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
503 const Type *MidTy = CI->getType(); // B from above
505 // Get the opcodes of the two Cast instructions
506 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
507 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
509 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
511 TD ? TD->getIntPtrType(CI->getContext()) : 0);
513 // We don't want to form an inttoptr or ptrtoint that converts to an integer
514 // type that differs from the pointer size.
515 if ((Res == Instruction::IntToPtr &&
516 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
517 (Res == Instruction::PtrToInt &&
518 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
521 return Instruction::CastOps(Res);
524 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
525 /// in any code being generated. It does not require codegen if V is simple
526 /// enough or if the cast can be folded into other casts.
527 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
528 const Type *Ty, TargetData *TD) {
529 if (V->getType() == Ty || isa<Constant>(V)) return false;
531 // If this is another cast that can be eliminated, it isn't codegen either.
532 if (const CastInst *CI = dyn_cast<CastInst>(V))
533 if (isEliminableCastPair(CI, opcode, Ty, TD))
538 // SimplifyCommutative - This performs a few simplifications for commutative
541 // 1. Order operands such that they are listed from right (least complex) to
542 // left (most complex). This puts constants before unary operators before
545 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
546 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
548 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
549 bool Changed = false;
550 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
551 Changed = !I.swapOperands();
553 if (!I.isAssociative()) return Changed;
554 Instruction::BinaryOps Opcode = I.getOpcode();
555 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
556 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
557 if (isa<Constant>(I.getOperand(1))) {
558 Constant *Folded = ConstantExpr::get(I.getOpcode(),
559 cast<Constant>(I.getOperand(1)),
560 cast<Constant>(Op->getOperand(1)));
561 I.setOperand(0, Op->getOperand(0));
562 I.setOperand(1, Folded);
564 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
565 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
566 isOnlyUse(Op) && isOnlyUse(Op1)) {
567 Constant *C1 = cast<Constant>(Op->getOperand(1));
568 Constant *C2 = cast<Constant>(Op1->getOperand(1));
570 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
571 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
572 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
576 I.setOperand(0, New);
577 I.setOperand(1, Folded);
584 /// SimplifyCompare - For a CmpInst this function just orders the operands
585 /// so that theyare listed from right (least complex) to left (most complex).
586 /// This puts constants before unary operators before binary operators.
587 bool InstCombiner::SimplifyCompare(CmpInst &I) {
588 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
591 // Compare instructions are not associative so there's nothing else we can do.
595 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
596 // if the LHS is a constant zero (which is the 'negate' form).
598 static inline Value *dyn_castNegVal(Value *V) {
599 if (BinaryOperator::isNeg(V))
600 return BinaryOperator::getNegArgument(V);
602 // Constants can be considered to be negated values if they can be folded.
603 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
604 return ConstantExpr::getNeg(C);
606 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
607 if (C->getType()->getElementType()->isInteger())
608 return ConstantExpr::getNeg(C);
613 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
614 // instruction if the LHS is a constant negative zero (which is the 'negate'
617 static inline Value *dyn_castFNegVal(Value *V) {
618 if (BinaryOperator::isFNeg(V))
619 return BinaryOperator::getFNegArgument(V);
621 // Constants can be considered to be negated values if they can be folded.
622 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
623 return ConstantExpr::getFNeg(C);
625 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
626 if (C->getType()->getElementType()->isFloatingPoint())
627 return ConstantExpr::getFNeg(C);
632 static inline Value *dyn_castNotVal(Value *V) {
633 if (BinaryOperator::isNot(V))
634 return BinaryOperator::getNotArgument(V);
636 // Constants can be considered to be not'ed values...
637 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
638 return ConstantInt::get(C->getType(), ~C->getValue());
642 // dyn_castFoldableMul - If this value is a multiply that can be folded into
643 // other computations (because it has a constant operand), return the
644 // non-constant operand of the multiply, and set CST to point to the multiplier.
645 // Otherwise, return null.
647 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
648 if (V->hasOneUse() && V->getType()->isInteger())
649 if (Instruction *I = dyn_cast<Instruction>(V)) {
650 if (I->getOpcode() == Instruction::Mul)
651 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
652 return I->getOperand(0);
653 if (I->getOpcode() == Instruction::Shl)
654 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
655 // The multiplier is really 1 << CST.
656 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
657 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
658 CST = ConstantInt::get(V->getType()->getContext(),
659 APInt(BitWidth, 1).shl(CSTVal));
660 return I->getOperand(0);
666 /// AddOne - Add one to a ConstantInt
667 static Constant *AddOne(Constant *C) {
668 return ConstantExpr::getAdd(C,
669 ConstantInt::get(C->getType(), 1));
671 /// SubOne - Subtract one from a ConstantInt
672 static Constant *SubOne(ConstantInt *C) {
673 return ConstantExpr::getSub(C,
674 ConstantInt::get(C->getType(), 1));
676 /// MultiplyOverflows - True if the multiply can not be expressed in an int
678 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
679 uint32_t W = C1->getBitWidth();
680 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
689 APInt MulExt = LHSExt * RHSExt;
692 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
693 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
694 return MulExt.slt(Min) || MulExt.sgt(Max);
696 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
700 /// ShrinkDemandedConstant - Check to see if the specified operand of the
701 /// specified instruction is a constant integer. If so, check to see if there
702 /// are any bits set in the constant that are not demanded. If so, shrink the
703 /// constant and return true.
704 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
706 assert(I && "No instruction?");
707 assert(OpNo < I->getNumOperands() && "Operand index too large");
709 // If the operand is not a constant integer, nothing to do.
710 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
711 if (!OpC) return false;
713 // If there are no bits set that aren't demanded, nothing to do.
714 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
715 if ((~Demanded & OpC->getValue()) == 0)
718 // This instruction is producing bits that are not demanded. Shrink the RHS.
719 Demanded &= OpC->getValue();
720 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
724 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
725 // set of known zero and one bits, compute the maximum and minimum values that
726 // could have the specified known zero and known one bits, returning them in
728 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
729 const APInt& KnownOne,
730 APInt& Min, APInt& Max) {
731 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
732 KnownZero.getBitWidth() == Min.getBitWidth() &&
733 KnownZero.getBitWidth() == Max.getBitWidth() &&
734 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
735 APInt UnknownBits = ~(KnownZero|KnownOne);
737 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
738 // bit if it is unknown.
740 Max = KnownOne|UnknownBits;
742 if (UnknownBits.isNegative()) { // Sign bit is unknown
743 Min.set(Min.getBitWidth()-1);
744 Max.clear(Max.getBitWidth()-1);
748 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
749 // a set of known zero and one bits, compute the maximum and minimum values that
750 // could have the specified known zero and known one bits, returning them in
752 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
753 const APInt &KnownOne,
754 APInt &Min, APInt &Max) {
755 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
756 KnownZero.getBitWidth() == Min.getBitWidth() &&
757 KnownZero.getBitWidth() == Max.getBitWidth() &&
758 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
759 APInt UnknownBits = ~(KnownZero|KnownOne);
761 // The minimum value is when the unknown bits are all zeros.
763 // The maximum value is when the unknown bits are all ones.
764 Max = KnownOne|UnknownBits;
767 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
768 /// SimplifyDemandedBits knows about. See if the instruction has any
769 /// properties that allow us to simplify its operands.
770 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
771 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
772 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
773 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
775 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
776 KnownZero, KnownOne, 0);
777 if (V == 0) return false;
778 if (V == &Inst) return true;
779 ReplaceInstUsesWith(Inst, V);
783 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
784 /// specified instruction operand if possible, updating it in place. It returns
785 /// true if it made any change and false otherwise.
786 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
787 APInt &KnownZero, APInt &KnownOne,
789 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
790 KnownZero, KnownOne, Depth);
791 if (NewVal == 0) return false;
797 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
798 /// value based on the demanded bits. When this function is called, it is known
799 /// that only the bits set in DemandedMask of the result of V are ever used
800 /// downstream. Consequently, depending on the mask and V, it may be possible
801 /// to replace V with a constant or one of its operands. In such cases, this
802 /// function does the replacement and returns true. In all other cases, it
803 /// returns false after analyzing the expression and setting KnownOne and known
804 /// to be one in the expression. KnownZero contains all the bits that are known
805 /// to be zero in the expression. These are provided to potentially allow the
806 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
807 /// the expression. KnownOne and KnownZero always follow the invariant that
808 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
809 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
810 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
811 /// and KnownOne must all be the same.
813 /// This returns null if it did not change anything and it permits no
814 /// simplification. This returns V itself if it did some simplification of V's
815 /// operands based on the information about what bits are demanded. This returns
816 /// some other non-null value if it found out that V is equal to another value
817 /// in the context where the specified bits are demanded, but not for all users.
818 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
819 APInt &KnownZero, APInt &KnownOne,
821 assert(V != 0 && "Null pointer of Value???");
822 assert(Depth <= 6 && "Limit Search Depth");
823 uint32_t BitWidth = DemandedMask.getBitWidth();
824 const Type *VTy = V->getType();
825 assert((TD || !isa<PointerType>(VTy)) &&
826 "SimplifyDemandedBits needs to know bit widths!");
827 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
828 (!VTy->isIntOrIntVector() ||
829 VTy->getScalarSizeInBits() == BitWidth) &&
830 KnownZero.getBitWidth() == BitWidth &&
831 KnownOne.getBitWidth() == BitWidth &&
832 "Value *V, DemandedMask, KnownZero and KnownOne "
833 "must have same BitWidth");
834 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
835 // We know all of the bits for a constant!
836 KnownOne = CI->getValue() & DemandedMask;
837 KnownZero = ~KnownOne & DemandedMask;
840 if (isa<ConstantPointerNull>(V)) {
841 // We know all of the bits for a constant!
843 KnownZero = DemandedMask;
849 if (DemandedMask == 0) { // Not demanding any bits from V.
850 if (isa<UndefValue>(V))
852 return UndefValue::get(VTy);
855 if (Depth == 6) // Limit search depth.
858 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
859 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
861 Instruction *I = dyn_cast<Instruction>(V);
863 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
864 return 0; // Only analyze instructions.
867 // If there are multiple uses of this value and we aren't at the root, then
868 // we can't do any simplifications of the operands, because DemandedMask
869 // only reflects the bits demanded by *one* of the users.
870 if (Depth != 0 && !I->hasOneUse()) {
871 // Despite the fact that we can't simplify this instruction in all User's
872 // context, we can at least compute the knownzero/knownone bits, and we can
873 // do simplifications that apply to *just* the one user if we know that
874 // this instruction has a simpler value in that context.
875 if (I->getOpcode() == Instruction::And) {
876 // If either the LHS or the RHS are Zero, the result is zero.
877 ComputeMaskedBits(I->getOperand(1), DemandedMask,
878 RHSKnownZero, RHSKnownOne, Depth+1);
879 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
880 LHSKnownZero, LHSKnownOne, Depth+1);
882 // If all of the demanded bits are known 1 on one side, return the other.
883 // These bits cannot contribute to the result of the 'and' in this
885 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
886 (DemandedMask & ~LHSKnownZero))
887 return I->getOperand(0);
888 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
889 (DemandedMask & ~RHSKnownZero))
890 return I->getOperand(1);
892 // If all of the demanded bits in the inputs are known zeros, return zero.
893 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
894 return Constant::getNullValue(VTy);
896 } else if (I->getOpcode() == Instruction::Or) {
897 // We can simplify (X|Y) -> X or Y in the user's context if we know that
898 // only bits from X or Y are demanded.
900 // If either the LHS or the RHS are One, the result is One.
901 ComputeMaskedBits(I->getOperand(1), DemandedMask,
902 RHSKnownZero, RHSKnownOne, Depth+1);
903 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
904 LHSKnownZero, LHSKnownOne, Depth+1);
906 // If all of the demanded bits are known zero on one side, return the
907 // other. These bits cannot contribute to the result of the 'or' in this
909 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
910 (DemandedMask & ~LHSKnownOne))
911 return I->getOperand(0);
912 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
913 (DemandedMask & ~RHSKnownOne))
914 return I->getOperand(1);
916 // If all of the potentially set bits on one side are known to be set on
917 // the other side, just use the 'other' side.
918 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
919 (DemandedMask & (~RHSKnownZero)))
920 return I->getOperand(0);
921 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
922 (DemandedMask & (~LHSKnownZero)))
923 return I->getOperand(1);
926 // Compute the KnownZero/KnownOne bits to simplify things downstream.
927 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
931 // If this is the root being simplified, allow it to have multiple uses,
932 // just set the DemandedMask to all bits so that we can try to simplify the
933 // operands. This allows visitTruncInst (for example) to simplify the
934 // operand of a trunc without duplicating all the logic below.
935 if (Depth == 0 && !V->hasOneUse())
936 DemandedMask = APInt::getAllOnesValue(BitWidth);
938 switch (I->getOpcode()) {
940 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
942 case Instruction::And:
943 // If either the LHS or the RHS are Zero, the result is zero.
944 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
945 RHSKnownZero, RHSKnownOne, Depth+1) ||
946 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
947 LHSKnownZero, LHSKnownOne, Depth+1))
949 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
950 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
952 // If all of the demanded bits are known 1 on one side, return the other.
953 // These bits cannot contribute to the result of the 'and'.
954 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
955 (DemandedMask & ~LHSKnownZero))
956 return I->getOperand(0);
957 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
958 (DemandedMask & ~RHSKnownZero))
959 return I->getOperand(1);
961 // If all of the demanded bits in the inputs are known zeros, return zero.
962 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
963 return Constant::getNullValue(VTy);
965 // If the RHS is a constant, see if we can simplify it.
966 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
969 // Output known-1 bits are only known if set in both the LHS & RHS.
970 RHSKnownOne &= LHSKnownOne;
971 // Output known-0 are known to be clear if zero in either the LHS | RHS.
972 RHSKnownZero |= LHSKnownZero;
974 case Instruction::Or:
975 // If either the LHS or the RHS are One, the result is One.
976 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
977 RHSKnownZero, RHSKnownOne, Depth+1) ||
978 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
979 LHSKnownZero, LHSKnownOne, Depth+1))
981 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
982 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
984 // If all of the demanded bits are known zero on one side, return the other.
985 // These bits cannot contribute to the result of the 'or'.
986 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
987 (DemandedMask & ~LHSKnownOne))
988 return I->getOperand(0);
989 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
990 (DemandedMask & ~RHSKnownOne))
991 return I->getOperand(1);
993 // If all of the potentially set bits on one side are known to be set on
994 // the other side, just use the 'other' side.
995 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
996 (DemandedMask & (~RHSKnownZero)))
997 return I->getOperand(0);
998 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
999 (DemandedMask & (~LHSKnownZero)))
1000 return I->getOperand(1);
1002 // If the RHS is a constant, see if we can simplify it.
1003 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1006 // Output known-0 bits are only known if clear in both the LHS & RHS.
1007 RHSKnownZero &= LHSKnownZero;
1008 // Output known-1 are known to be set if set in either the LHS | RHS.
1009 RHSKnownOne |= LHSKnownOne;
1011 case Instruction::Xor: {
1012 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1013 RHSKnownZero, RHSKnownOne, Depth+1) ||
1014 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1015 LHSKnownZero, LHSKnownOne, Depth+1))
1017 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1018 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1020 // If all of the demanded bits are known zero on one side, return the other.
1021 // These bits cannot contribute to the result of the 'xor'.
1022 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1023 return I->getOperand(0);
1024 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1025 return I->getOperand(1);
1027 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1028 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1029 (RHSKnownOne & LHSKnownOne);
1030 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1031 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1032 (RHSKnownOne & LHSKnownZero);
1034 // If all of the demanded bits are known to be zero on one side or the
1035 // other, turn this into an *inclusive* or.
1036 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1037 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1039 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1041 return InsertNewInstBefore(Or, *I);
1044 // If all of the demanded bits on one side are known, and all of the set
1045 // bits on that side are also known to be set on the other side, turn this
1046 // into an AND, as we know the bits will be cleared.
1047 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1048 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1050 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1051 Constant *AndC = Constant::getIntegerValue(VTy,
1052 ~RHSKnownOne & DemandedMask);
1054 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1055 return InsertNewInstBefore(And, *I);
1059 // If the RHS is a constant, see if we can simplify it.
1060 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1061 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1064 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1065 // are flipping are known to be set, then the xor is just resetting those
1066 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1067 // simplifying both of them.
1068 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1069 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1070 isa<ConstantInt>(I->getOperand(1)) &&
1071 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1072 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1073 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1074 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1075 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1078 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1079 Instruction *NewAnd =
1080 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1081 InsertNewInstBefore(NewAnd, *I);
1084 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1085 Instruction *NewXor =
1086 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1087 return InsertNewInstBefore(NewXor, *I);
1091 RHSKnownZero = KnownZeroOut;
1092 RHSKnownOne = KnownOneOut;
1095 case Instruction::Select:
1096 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1097 RHSKnownZero, RHSKnownOne, Depth+1) ||
1098 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1099 LHSKnownZero, LHSKnownOne, Depth+1))
1101 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1102 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1104 // If the operands are constants, see if we can simplify them.
1105 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1106 ShrinkDemandedConstant(I, 2, DemandedMask))
1109 // Only known if known in both the LHS and RHS.
1110 RHSKnownOne &= LHSKnownOne;
1111 RHSKnownZero &= LHSKnownZero;
1113 case Instruction::Trunc: {
1114 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1115 DemandedMask.zext(truncBf);
1116 RHSKnownZero.zext(truncBf);
1117 RHSKnownOne.zext(truncBf);
1118 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1119 RHSKnownZero, RHSKnownOne, Depth+1))
1121 DemandedMask.trunc(BitWidth);
1122 RHSKnownZero.trunc(BitWidth);
1123 RHSKnownOne.trunc(BitWidth);
1124 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1127 case Instruction::BitCast:
1128 if (!I->getOperand(0)->getType()->isIntOrIntVector())
1129 return false; // vector->int or fp->int?
1131 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1132 if (const VectorType *SrcVTy =
1133 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1134 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1135 // Don't touch a bitcast between vectors of different element counts.
1138 // Don't touch a scalar-to-vector bitcast.
1140 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1141 // Don't touch a vector-to-scalar bitcast.
1144 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1145 RHSKnownZero, RHSKnownOne, Depth+1))
1147 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1149 case Instruction::ZExt: {
1150 // Compute the bits in the result that are not present in the input.
1151 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1153 DemandedMask.trunc(SrcBitWidth);
1154 RHSKnownZero.trunc(SrcBitWidth);
1155 RHSKnownOne.trunc(SrcBitWidth);
1156 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1157 RHSKnownZero, RHSKnownOne, Depth+1))
1159 DemandedMask.zext(BitWidth);
1160 RHSKnownZero.zext(BitWidth);
1161 RHSKnownOne.zext(BitWidth);
1162 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1163 // The top bits are known to be zero.
1164 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1167 case Instruction::SExt: {
1168 // Compute the bits in the result that are not present in the input.
1169 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1171 APInt InputDemandedBits = DemandedMask &
1172 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1174 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1175 // If any of the sign extended bits are demanded, we know that the sign
1177 if ((NewBits & DemandedMask) != 0)
1178 InputDemandedBits.set(SrcBitWidth-1);
1180 InputDemandedBits.trunc(SrcBitWidth);
1181 RHSKnownZero.trunc(SrcBitWidth);
1182 RHSKnownOne.trunc(SrcBitWidth);
1183 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1184 RHSKnownZero, RHSKnownOne, Depth+1))
1186 InputDemandedBits.zext(BitWidth);
1187 RHSKnownZero.zext(BitWidth);
1188 RHSKnownOne.zext(BitWidth);
1189 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1191 // If the sign bit of the input is known set or clear, then we know the
1192 // top bits of the result.
1194 // If the input sign bit is known zero, or if the NewBits are not demanded
1195 // convert this into a zero extension.
1196 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1197 // Convert to ZExt cast
1198 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1199 return InsertNewInstBefore(NewCast, *I);
1200 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1201 RHSKnownOne |= NewBits;
1205 case Instruction::Add: {
1206 // Figure out what the input bits are. If the top bits of the and result
1207 // are not demanded, then the add doesn't demand them from its input
1209 unsigned NLZ = DemandedMask.countLeadingZeros();
1211 // If there is a constant on the RHS, there are a variety of xformations
1213 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1214 // If null, this should be simplified elsewhere. Some of the xforms here
1215 // won't work if the RHS is zero.
1219 // If the top bit of the output is demanded, demand everything from the
1220 // input. Otherwise, we demand all the input bits except NLZ top bits.
1221 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1223 // Find information about known zero/one bits in the input.
1224 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1225 LHSKnownZero, LHSKnownOne, Depth+1))
1228 // If the RHS of the add has bits set that can't affect the input, reduce
1230 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1233 // Avoid excess work.
1234 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1237 // Turn it into OR if input bits are zero.
1238 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1240 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1242 return InsertNewInstBefore(Or, *I);
1245 // We can say something about the output known-zero and known-one bits,
1246 // depending on potential carries from the input constant and the
1247 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1248 // bits set and the RHS constant is 0x01001, then we know we have a known
1249 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1251 // To compute this, we first compute the potential carry bits. These are
1252 // the bits which may be modified. I'm not aware of a better way to do
1254 const APInt &RHSVal = RHS->getValue();
1255 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1257 // Now that we know which bits have carries, compute the known-1/0 sets.
1259 // Bits are known one if they are known zero in one operand and one in the
1260 // other, and there is no input carry.
1261 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1262 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1264 // Bits are known zero if they are known zero in both operands and there
1265 // is no input carry.
1266 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1268 // If the high-bits of this ADD are not demanded, then it does not demand
1269 // the high bits of its LHS or RHS.
1270 if (DemandedMask[BitWidth-1] == 0) {
1271 // Right fill the mask of bits for this ADD to demand the most
1272 // significant bit and all those below it.
1273 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1274 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1275 LHSKnownZero, LHSKnownOne, Depth+1) ||
1276 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1277 LHSKnownZero, LHSKnownOne, Depth+1))
1283 case Instruction::Sub:
1284 // If the high-bits of this SUB are not demanded, then it does not demand
1285 // the high bits of its LHS or RHS.
1286 if (DemandedMask[BitWidth-1] == 0) {
1287 // Right fill the mask of bits for this SUB to demand the most
1288 // significant bit and all those below it.
1289 uint32_t NLZ = DemandedMask.countLeadingZeros();
1290 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1291 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1292 LHSKnownZero, LHSKnownOne, Depth+1) ||
1293 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1294 LHSKnownZero, LHSKnownOne, Depth+1))
1297 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1298 // the known zeros and ones.
1299 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1301 case Instruction::Shl:
1302 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1303 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1304 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1305 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1306 RHSKnownZero, RHSKnownOne, Depth+1))
1308 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1309 RHSKnownZero <<= ShiftAmt;
1310 RHSKnownOne <<= ShiftAmt;
1311 // low bits known zero.
1313 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1316 case Instruction::LShr:
1317 // For a logical shift right
1318 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1319 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1321 // Unsigned shift right.
1322 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1323 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1324 RHSKnownZero, RHSKnownOne, Depth+1))
1326 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1327 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1328 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1330 // Compute the new bits that are at the top now.
1331 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1332 RHSKnownZero |= HighBits; // high bits known zero.
1336 case Instruction::AShr:
1337 // If this is an arithmetic shift right and only the low-bit is set, we can
1338 // always convert this into a logical shr, even if the shift amount is
1339 // variable. The low bit of the shift cannot be an input sign bit unless
1340 // the shift amount is >= the size of the datatype, which is undefined.
1341 if (DemandedMask == 1) {
1342 // Perform the logical shift right.
1343 Instruction *NewVal = BinaryOperator::CreateLShr(
1344 I->getOperand(0), I->getOperand(1), I->getName());
1345 return InsertNewInstBefore(NewVal, *I);
1348 // If the sign bit is the only bit demanded by this ashr, then there is no
1349 // need to do it, the shift doesn't change the high bit.
1350 if (DemandedMask.isSignBit())
1351 return I->getOperand(0);
1353 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1354 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1356 // Signed shift right.
1357 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1358 // If any of the "high bits" are demanded, we should set the sign bit as
1360 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1361 DemandedMaskIn.set(BitWidth-1);
1362 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1363 RHSKnownZero, RHSKnownOne, Depth+1))
1365 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1366 // Compute the new bits that are at the top now.
1367 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1368 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1369 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1371 // Handle the sign bits.
1372 APInt SignBit(APInt::getSignBit(BitWidth));
1373 // Adjust to where it is now in the mask.
1374 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1376 // If the input sign bit is known to be zero, or if none of the top bits
1377 // are demanded, turn this into an unsigned shift right.
1378 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1379 (HighBits & ~DemandedMask) == HighBits) {
1380 // Perform the logical shift right.
1381 Instruction *NewVal = BinaryOperator::CreateLShr(
1382 I->getOperand(0), SA, I->getName());
1383 return InsertNewInstBefore(NewVal, *I);
1384 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1385 RHSKnownOne |= HighBits;
1389 case Instruction::SRem:
1390 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1391 APInt RA = Rem->getValue().abs();
1392 if (RA.isPowerOf2()) {
1393 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
1394 return I->getOperand(0);
1396 APInt LowBits = RA - 1;
1397 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1398 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1399 LHSKnownZero, LHSKnownOne, Depth+1))
1402 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1403 LHSKnownZero |= ~LowBits;
1405 KnownZero |= LHSKnownZero & DemandedMask;
1407 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
1411 case Instruction::URem: {
1412 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1413 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1414 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1415 KnownZero2, KnownOne2, Depth+1) ||
1416 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1417 KnownZero2, KnownOne2, Depth+1))
1420 unsigned Leaders = KnownZero2.countLeadingOnes();
1421 Leaders = std::max(Leaders,
1422 KnownZero2.countLeadingOnes());
1423 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1426 case Instruction::Call:
1427 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1428 switch (II->getIntrinsicID()) {
1430 case Intrinsic::bswap: {
1431 // If the only bits demanded come from one byte of the bswap result,
1432 // just shift the input byte into position to eliminate the bswap.
1433 unsigned NLZ = DemandedMask.countLeadingZeros();
1434 unsigned NTZ = DemandedMask.countTrailingZeros();
1436 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1437 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1438 // have 14 leading zeros, round to 8.
1441 // If we need exactly one byte, we can do this transformation.
1442 if (BitWidth-NLZ-NTZ == 8) {
1443 unsigned ResultBit = NTZ;
1444 unsigned InputBit = BitWidth-NTZ-8;
1446 // Replace this with either a left or right shift to get the byte into
1448 Instruction *NewVal;
1449 if (InputBit > ResultBit)
1450 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1451 ConstantInt::get(I->getType(), InputBit-ResultBit));
1453 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1454 ConstantInt::get(I->getType(), ResultBit-InputBit));
1455 NewVal->takeName(I);
1456 return InsertNewInstBefore(NewVal, *I);
1459 // TODO: Could compute known zero/one bits based on the input.
1464 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1468 // If the client is only demanding bits that we know, return the known
1470 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1471 return Constant::getIntegerValue(VTy, RHSKnownOne);
1476 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1477 /// any number of elements. DemandedElts contains the set of elements that are
1478 /// actually used by the caller. This method analyzes which elements of the
1479 /// operand are undef and returns that information in UndefElts.
1481 /// If the information about demanded elements can be used to simplify the
1482 /// operation, the operation is simplified, then the resultant value is
1483 /// returned. This returns null if no change was made.
1484 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1487 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1488 APInt EltMask(APInt::getAllOnesValue(VWidth));
1489 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1491 if (isa<UndefValue>(V)) {
1492 // If the entire vector is undefined, just return this info.
1493 UndefElts = EltMask;
1495 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1496 UndefElts = EltMask;
1497 return UndefValue::get(V->getType());
1501 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1502 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1503 Constant *Undef = UndefValue::get(EltTy);
1505 std::vector<Constant*> Elts;
1506 for (unsigned i = 0; i != VWidth; ++i)
1507 if (!DemandedElts[i]) { // If not demanded, set to undef.
1508 Elts.push_back(Undef);
1510 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1511 Elts.push_back(Undef);
1513 } else { // Otherwise, defined.
1514 Elts.push_back(CP->getOperand(i));
1517 // If we changed the constant, return it.
1518 Constant *NewCP = ConstantVector::get(Elts);
1519 return NewCP != CP ? NewCP : 0;
1520 } else if (isa<ConstantAggregateZero>(V)) {
1521 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1524 // Check if this is identity. If so, return 0 since we are not simplifying
1526 if (DemandedElts == ((1ULL << VWidth) -1))
1529 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1530 Constant *Zero = Constant::getNullValue(EltTy);
1531 Constant *Undef = UndefValue::get(EltTy);
1532 std::vector<Constant*> Elts;
1533 for (unsigned i = 0; i != VWidth; ++i) {
1534 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1535 Elts.push_back(Elt);
1537 UndefElts = DemandedElts ^ EltMask;
1538 return ConstantVector::get(Elts);
1541 // Limit search depth.
1545 // If multiple users are using the root value, procede with
1546 // simplification conservatively assuming that all elements
1548 if (!V->hasOneUse()) {
1549 // Quit if we find multiple users of a non-root value though.
1550 // They'll be handled when it's their turn to be visited by
1551 // the main instcombine process.
1553 // TODO: Just compute the UndefElts information recursively.
1556 // Conservatively assume that all elements are needed.
1557 DemandedElts = EltMask;
1560 Instruction *I = dyn_cast<Instruction>(V);
1561 if (!I) return 0; // Only analyze instructions.
1563 bool MadeChange = false;
1564 APInt UndefElts2(VWidth, 0);
1566 switch (I->getOpcode()) {
1569 case Instruction::InsertElement: {
1570 // If this is a variable index, we don't know which element it overwrites.
1571 // demand exactly the same input as we produce.
1572 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1574 // Note that we can't propagate undef elt info, because we don't know
1575 // which elt is getting updated.
1576 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1577 UndefElts2, Depth+1);
1578 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1582 // If this is inserting an element that isn't demanded, remove this
1584 unsigned IdxNo = Idx->getZExtValue();
1585 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1587 return I->getOperand(0);
1590 // Otherwise, the element inserted overwrites whatever was there, so the
1591 // input demanded set is simpler than the output set.
1592 APInt DemandedElts2 = DemandedElts;
1593 DemandedElts2.clear(IdxNo);
1594 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1595 UndefElts, Depth+1);
1596 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1598 // The inserted element is defined.
1599 UndefElts.clear(IdxNo);
1602 case Instruction::ShuffleVector: {
1603 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1604 uint64_t LHSVWidth =
1605 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1606 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1607 for (unsigned i = 0; i < VWidth; i++) {
1608 if (DemandedElts[i]) {
1609 unsigned MaskVal = Shuffle->getMaskValue(i);
1610 if (MaskVal != -1u) {
1611 assert(MaskVal < LHSVWidth * 2 &&
1612 "shufflevector mask index out of range!");
1613 if (MaskVal < LHSVWidth)
1614 LeftDemanded.set(MaskVal);
1616 RightDemanded.set(MaskVal - LHSVWidth);
1621 APInt UndefElts4(LHSVWidth, 0);
1622 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1623 UndefElts4, Depth+1);
1624 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1626 APInt UndefElts3(LHSVWidth, 0);
1627 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1628 UndefElts3, Depth+1);
1629 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1631 bool NewUndefElts = false;
1632 for (unsigned i = 0; i < VWidth; i++) {
1633 unsigned MaskVal = Shuffle->getMaskValue(i);
1634 if (MaskVal == -1u) {
1636 } else if (MaskVal < LHSVWidth) {
1637 if (UndefElts4[MaskVal]) {
1638 NewUndefElts = true;
1642 if (UndefElts3[MaskVal - LHSVWidth]) {
1643 NewUndefElts = true;
1650 // Add additional discovered undefs.
1651 std::vector<Constant*> Elts;
1652 for (unsigned i = 0; i < VWidth; ++i) {
1654 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1656 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1657 Shuffle->getMaskValue(i)));
1659 I->setOperand(2, ConstantVector::get(Elts));
1664 case Instruction::BitCast: {
1665 // Vector->vector casts only.
1666 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1668 unsigned InVWidth = VTy->getNumElements();
1669 APInt InputDemandedElts(InVWidth, 0);
1672 if (VWidth == InVWidth) {
1673 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1674 // elements as are demanded of us.
1676 InputDemandedElts = DemandedElts;
1677 } else if (VWidth > InVWidth) {
1681 // If there are more elements in the result than there are in the source,
1682 // then an input element is live if any of the corresponding output
1683 // elements are live.
1684 Ratio = VWidth/InVWidth;
1685 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1686 if (DemandedElts[OutIdx])
1687 InputDemandedElts.set(OutIdx/Ratio);
1693 // If there are more elements in the source than there are in the result,
1694 // then an input element is live if the corresponding output element is
1696 Ratio = InVWidth/VWidth;
1697 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1698 if (DemandedElts[InIdx/Ratio])
1699 InputDemandedElts.set(InIdx);
1702 // div/rem demand all inputs, because they don't want divide by zero.
1703 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1704 UndefElts2, Depth+1);
1706 I->setOperand(0, TmpV);
1710 UndefElts = UndefElts2;
1711 if (VWidth > InVWidth) {
1712 llvm_unreachable("Unimp");
1713 // If there are more elements in the result than there are in the source,
1714 // then an output element is undef if the corresponding input element is
1716 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1717 if (UndefElts2[OutIdx/Ratio])
1718 UndefElts.set(OutIdx);
1719 } else if (VWidth < InVWidth) {
1720 llvm_unreachable("Unimp");
1721 // If there are more elements in the source than there are in the result,
1722 // then a result element is undef if all of the corresponding input
1723 // elements are undef.
1724 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1725 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1726 if (!UndefElts2[InIdx]) // Not undef?
1727 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
1731 case Instruction::And:
1732 case Instruction::Or:
1733 case Instruction::Xor:
1734 case Instruction::Add:
1735 case Instruction::Sub:
1736 case Instruction::Mul:
1737 // div/rem demand all inputs, because they don't want divide by zero.
1738 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1739 UndefElts, Depth+1);
1740 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1741 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1742 UndefElts2, Depth+1);
1743 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1745 // Output elements are undefined if both are undefined. Consider things
1746 // like undef&0. The result is known zero, not undef.
1747 UndefElts &= UndefElts2;
1750 case Instruction::Call: {
1751 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1753 switch (II->getIntrinsicID()) {
1756 // Binary vector operations that work column-wise. A dest element is a
1757 // function of the corresponding input elements from the two inputs.
1758 case Intrinsic::x86_sse_sub_ss:
1759 case Intrinsic::x86_sse_mul_ss:
1760 case Intrinsic::x86_sse_min_ss:
1761 case Intrinsic::x86_sse_max_ss:
1762 case Intrinsic::x86_sse2_sub_sd:
1763 case Intrinsic::x86_sse2_mul_sd:
1764 case Intrinsic::x86_sse2_min_sd:
1765 case Intrinsic::x86_sse2_max_sd:
1766 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1767 UndefElts, Depth+1);
1768 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1769 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1770 UndefElts2, Depth+1);
1771 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1773 // If only the low elt is demanded and this is a scalarizable intrinsic,
1774 // scalarize it now.
1775 if (DemandedElts == 1) {
1776 switch (II->getIntrinsicID()) {
1778 case Intrinsic::x86_sse_sub_ss:
1779 case Intrinsic::x86_sse_mul_ss:
1780 case Intrinsic::x86_sse2_sub_sd:
1781 case Intrinsic::x86_sse2_mul_sd:
1782 // TODO: Lower MIN/MAX/ABS/etc
1783 Value *LHS = II->getOperand(1);
1784 Value *RHS = II->getOperand(2);
1785 // Extract the element as scalars.
1786 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
1787 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1788 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1789 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1791 switch (II->getIntrinsicID()) {
1792 default: llvm_unreachable("Case stmts out of sync!");
1793 case Intrinsic::x86_sse_sub_ss:
1794 case Intrinsic::x86_sse2_sub_sd:
1795 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1796 II->getName()), *II);
1798 case Intrinsic::x86_sse_mul_ss:
1799 case Intrinsic::x86_sse2_mul_sd:
1800 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1801 II->getName()), *II);
1806 InsertElementInst::Create(
1807 UndefValue::get(II->getType()), TmpV,
1808 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1809 InsertNewInstBefore(New, *II);
1814 // Output elements are undefined if both are undefined. Consider things
1815 // like undef&0. The result is known zero, not undef.
1816 UndefElts &= UndefElts2;
1822 return MadeChange ? I : 0;
1826 /// AssociativeOpt - Perform an optimization on an associative operator. This
1827 /// function is designed to check a chain of associative operators for a
1828 /// potential to apply a certain optimization. Since the optimization may be
1829 /// applicable if the expression was reassociated, this checks the chain, then
1830 /// reassociates the expression as necessary to expose the optimization
1831 /// opportunity. This makes use of a special Functor, which must define
1832 /// 'shouldApply' and 'apply' methods.
1834 template<typename Functor>
1835 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1836 unsigned Opcode = Root.getOpcode();
1837 Value *LHS = Root.getOperand(0);
1839 // Quick check, see if the immediate LHS matches...
1840 if (F.shouldApply(LHS))
1841 return F.apply(Root);
1843 // Otherwise, if the LHS is not of the same opcode as the root, return.
1844 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1845 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1846 // Should we apply this transform to the RHS?
1847 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1849 // If not to the RHS, check to see if we should apply to the LHS...
1850 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1851 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1855 // If the functor wants to apply the optimization to the RHS of LHSI,
1856 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1858 // Now all of the instructions are in the current basic block, go ahead
1859 // and perform the reassociation.
1860 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1862 // First move the selected RHS to the LHS of the root...
1863 Root.setOperand(0, LHSI->getOperand(1));
1865 // Make what used to be the LHS of the root be the user of the root...
1866 Value *ExtraOperand = TmpLHSI->getOperand(1);
1867 if (&Root == TmpLHSI) {
1868 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1871 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1872 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1873 BasicBlock::iterator ARI = &Root; ++ARI;
1874 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1877 // Now propagate the ExtraOperand down the chain of instructions until we
1879 while (TmpLHSI != LHSI) {
1880 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1881 // Move the instruction to immediately before the chain we are
1882 // constructing to avoid breaking dominance properties.
1883 NextLHSI->moveBefore(ARI);
1886 Value *NextOp = NextLHSI->getOperand(1);
1887 NextLHSI->setOperand(1, ExtraOperand);
1889 ExtraOperand = NextOp;
1892 // Now that the instructions are reassociated, have the functor perform
1893 // the transformation...
1894 return F.apply(Root);
1897 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1904 // AddRHS - Implements: X + X --> X << 1
1907 explicit AddRHS(Value *rhs) : RHS(rhs) {}
1908 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1909 Instruction *apply(BinaryOperator &Add) const {
1910 return BinaryOperator::CreateShl(Add.getOperand(0),
1911 ConstantInt::get(Add.getType(), 1));
1915 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1917 struct AddMaskingAnd {
1919 explicit AddMaskingAnd(Constant *c) : C2(c) {}
1920 bool shouldApply(Value *LHS) const {
1922 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1923 ConstantExpr::getAnd(C1, C2)->isNullValue();
1925 Instruction *apply(BinaryOperator &Add) const {
1926 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1932 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1934 if (CastInst *CI = dyn_cast<CastInst>(&I))
1935 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1937 // Figure out if the constant is the left or the right argument.
1938 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1939 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1941 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1943 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1944 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1947 Value *Op0 = SO, *Op1 = ConstOperand;
1949 std::swap(Op0, Op1);
1951 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1952 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1953 SO->getName()+".op");
1954 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1955 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1956 SO->getName()+".cmp");
1957 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1958 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1959 SO->getName()+".cmp");
1960 llvm_unreachable("Unknown binary instruction type!");
1963 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1964 // constant as the other operand, try to fold the binary operator into the
1965 // select arguments. This also works for Cast instructions, which obviously do
1966 // not have a second operand.
1967 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1969 // Don't modify shared select instructions
1970 if (!SI->hasOneUse()) return 0;
1971 Value *TV = SI->getOperand(1);
1972 Value *FV = SI->getOperand(2);
1974 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1975 // Bool selects with constant operands can be folded to logical ops.
1976 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1978 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1979 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1981 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1988 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1989 /// has a PHI node as operand #0, see if we can fold the instruction into the
1990 /// PHI (which is only possible if all operands to the PHI are constants).
1992 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1993 /// that would normally be unprofitable because they strongly encourage jump
1995 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1996 bool AllowAggressive) {
1997 AllowAggressive = false;
1998 PHINode *PN = cast<PHINode>(I.getOperand(0));
1999 unsigned NumPHIValues = PN->getNumIncomingValues();
2000 if (NumPHIValues == 0 ||
2001 // We normally only transform phis with a single use, unless we're trying
2002 // hard to make jump threading happen.
2003 (!PN->hasOneUse() && !AllowAggressive))
2007 // Check to see if all of the operands of the PHI are simple constants
2008 // (constantint/constantfp/undef). If there is one non-constant value,
2009 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2010 // bail out. We don't do arbitrary constant expressions here because moving
2011 // their computation can be expensive without a cost model.
2012 BasicBlock *NonConstBB = 0;
2013 for (unsigned i = 0; i != NumPHIValues; ++i)
2014 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2015 isa<ConstantExpr>(PN->getIncomingValue(i))) {
2016 if (NonConstBB) return 0; // More than one non-const value.
2017 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2018 NonConstBB = PN->getIncomingBlock(i);
2020 // If the incoming non-constant value is in I's block, we have an infinite
2022 if (NonConstBB == I.getParent())
2026 // If there is exactly one non-constant value, we can insert a copy of the
2027 // operation in that block. However, if this is a critical edge, we would be
2028 // inserting the computation one some other paths (e.g. inside a loop). Only
2029 // do this if the pred block is unconditionally branching into the phi block.
2030 if (NonConstBB != 0 && !AllowAggressive) {
2031 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2032 if (!BI || !BI->isUnconditional()) return 0;
2035 // Okay, we can do the transformation: create the new PHI node.
2036 PHINode *NewPN = PHINode::Create(I.getType(), "");
2037 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2038 InsertNewInstBefore(NewPN, *PN);
2039 NewPN->takeName(PN);
2041 // Next, add all of the operands to the PHI.
2042 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2043 // We only currently try to fold the condition of a select when it is a phi,
2044 // not the true/false values.
2045 Value *TrueV = SI->getTrueValue();
2046 Value *FalseV = SI->getFalseValue();
2047 BasicBlock *PhiTransBB = PN->getParent();
2048 for (unsigned i = 0; i != NumPHIValues; ++i) {
2049 BasicBlock *ThisBB = PN->getIncomingBlock(i);
2050 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2051 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2053 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2054 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2056 assert(PN->getIncomingBlock(i) == NonConstBB);
2057 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2059 "phitmp", NonConstBB->getTerminator());
2060 Worklist.Add(cast<Instruction>(InV));
2062 NewPN->addIncoming(InV, ThisBB);
2064 } else if (I.getNumOperands() == 2) {
2065 Constant *C = cast<Constant>(I.getOperand(1));
2066 for (unsigned i = 0; i != NumPHIValues; ++i) {
2068 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2069 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2070 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2072 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2074 assert(PN->getIncomingBlock(i) == NonConstBB);
2075 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2076 InV = BinaryOperator::Create(BO->getOpcode(),
2077 PN->getIncomingValue(i), C, "phitmp",
2078 NonConstBB->getTerminator());
2079 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2080 InV = CmpInst::Create(CI->getOpcode(),
2082 PN->getIncomingValue(i), C, "phitmp",
2083 NonConstBB->getTerminator());
2085 llvm_unreachable("Unknown binop!");
2087 Worklist.Add(cast<Instruction>(InV));
2089 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2092 CastInst *CI = cast<CastInst>(&I);
2093 const Type *RetTy = CI->getType();
2094 for (unsigned i = 0; i != NumPHIValues; ++i) {
2096 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2097 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2099 assert(PN->getIncomingBlock(i) == NonConstBB);
2100 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2101 I.getType(), "phitmp",
2102 NonConstBB->getTerminator());
2103 Worklist.Add(cast<Instruction>(InV));
2105 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2108 return ReplaceInstUsesWith(I, NewPN);
2112 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2113 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2114 /// This basically requires proving that the add in the original type would not
2115 /// overflow to change the sign bit or have a carry out.
2116 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2117 // There are different heuristics we can use for this. Here are some simple
2120 // Add has the property that adding any two 2's complement numbers can only
2121 // have one carry bit which can change a sign. As such, if LHS and RHS each
2122 // have at least two sign bits, we know that the addition of the two values will
2123 // sign extend fine.
2124 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2128 // If one of the operands only has one non-zero bit, and if the other operand
2129 // has a known-zero bit in a more significant place than it (not including the
2130 // sign bit) the ripple may go up to and fill the zero, but won't change the
2131 // sign. For example, (X & ~4) + 1.
2139 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2140 bool Changed = SimplifyCommutative(I);
2141 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2143 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2144 // X + undef -> undef
2145 if (isa<UndefValue>(RHS))
2146 return ReplaceInstUsesWith(I, RHS);
2149 if (RHSC->isNullValue())
2150 return ReplaceInstUsesWith(I, LHS);
2152 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2153 // X + (signbit) --> X ^ signbit
2154 const APInt& Val = CI->getValue();
2155 uint32_t BitWidth = Val.getBitWidth();
2156 if (Val == APInt::getSignBit(BitWidth))
2157 return BinaryOperator::CreateXor(LHS, RHS);
2159 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2160 // (X & 254)+1 -> (X&254)|1
2161 if (SimplifyDemandedInstructionBits(I))
2164 // zext(bool) + C -> bool ? C + 1 : C
2165 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2166 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2167 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2170 if (isa<PHINode>(LHS))
2171 if (Instruction *NV = FoldOpIntoPhi(I))
2174 ConstantInt *XorRHS = 0;
2176 if (isa<ConstantInt>(RHSC) &&
2177 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2178 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2179 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2181 uint32_t Size = TySizeBits / 2;
2182 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2183 APInt CFF80Val(-C0080Val);
2185 if (TySizeBits > Size) {
2186 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2187 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2188 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2189 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2190 // This is a sign extend if the top bits are known zero.
2191 if (!MaskedValueIsZero(XorLHS,
2192 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2193 Size = 0; // Not a sign ext, but can't be any others either.
2198 C0080Val = APIntOps::lshr(C0080Val, Size);
2199 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2200 } while (Size >= 1);
2202 // FIXME: This shouldn't be necessary. When the backends can handle types
2203 // with funny bit widths then this switch statement should be removed. It
2204 // is just here to get the size of the "middle" type back up to something
2205 // that the back ends can handle.
2206 const Type *MiddleType = 0;
2209 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2210 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2211 case 8: MiddleType = Type::getInt8Ty(*Context); break;
2214 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2215 return new SExtInst(NewTrunc, I.getType(), I.getName());
2220 if (I.getType() == Type::getInt1Ty(*Context))
2221 return BinaryOperator::CreateXor(LHS, RHS);
2224 if (I.getType()->isInteger()) {
2225 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2228 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2229 if (RHSI->getOpcode() == Instruction::Sub)
2230 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2231 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2233 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2234 if (LHSI->getOpcode() == Instruction::Sub)
2235 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2236 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2241 // -A + -B --> -(A + B)
2242 if (Value *LHSV = dyn_castNegVal(LHS)) {
2243 if (LHS->getType()->isIntOrIntVector()) {
2244 if (Value *RHSV = dyn_castNegVal(RHS)) {
2245 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2246 return BinaryOperator::CreateNeg(NewAdd);
2250 return BinaryOperator::CreateSub(RHS, LHSV);
2254 if (!isa<Constant>(RHS))
2255 if (Value *V = dyn_castNegVal(RHS))
2256 return BinaryOperator::CreateSub(LHS, V);
2260 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2261 if (X == RHS) // X*C + X --> X * (C+1)
2262 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2264 // X*C1 + X*C2 --> X * (C1+C2)
2266 if (X == dyn_castFoldableMul(RHS, C1))
2267 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2270 // X + X*C --> X * (C+1)
2271 if (dyn_castFoldableMul(RHS, C2) == LHS)
2272 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2274 // X + ~X --> -1 since ~X = -X-1
2275 if (dyn_castNotVal(LHS) == RHS ||
2276 dyn_castNotVal(RHS) == LHS)
2277 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2280 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2281 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2282 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2285 // A+B --> A|B iff A and B have no bits set in common.
2286 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2287 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2288 APInt LHSKnownOne(IT->getBitWidth(), 0);
2289 APInt LHSKnownZero(IT->getBitWidth(), 0);
2290 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2291 if (LHSKnownZero != 0) {
2292 APInt RHSKnownOne(IT->getBitWidth(), 0);
2293 APInt RHSKnownZero(IT->getBitWidth(), 0);
2294 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2296 // No bits in common -> bitwise or.
2297 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2298 return BinaryOperator::CreateOr(LHS, RHS);
2302 // W*X + Y*Z --> W * (X+Z) iff W == Y
2303 if (I.getType()->isIntOrIntVector()) {
2304 Value *W, *X, *Y, *Z;
2305 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2306 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2310 } else if (Y == X) {
2312 } else if (X == Z) {
2319 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2320 return BinaryOperator::CreateMul(W, NewAdd);
2325 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2327 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2328 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2330 // (X & FF00) + xx00 -> (X+xx00) & FF00
2331 if (LHS->hasOneUse() &&
2332 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2333 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2334 if (Anded == CRHS) {
2335 // See if all bits from the first bit set in the Add RHS up are included
2336 // in the mask. First, get the rightmost bit.
2337 const APInt& AddRHSV = CRHS->getValue();
2339 // Form a mask of all bits from the lowest bit added through the top.
2340 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2342 // See if the and mask includes all of these bits.
2343 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2345 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2346 // Okay, the xform is safe. Insert the new add pronto.
2347 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2348 return BinaryOperator::CreateAnd(NewAdd, C2);
2353 // Try to fold constant add into select arguments.
2354 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2355 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2359 // add (select X 0 (sub n A)) A --> select X A n
2361 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2364 SI = dyn_cast<SelectInst>(RHS);
2367 if (SI && SI->hasOneUse()) {
2368 Value *TV = SI->getTrueValue();
2369 Value *FV = SI->getFalseValue();
2372 // Can we fold the add into the argument of the select?
2373 // We check both true and false select arguments for a matching subtract.
2374 if (match(FV, m_Zero()) &&
2375 match(TV, m_Sub(m_Value(N), m_Specific(A))))
2376 // Fold the add into the true select value.
2377 return SelectInst::Create(SI->getCondition(), N, A);
2378 if (match(TV, m_Zero()) &&
2379 match(FV, m_Sub(m_Value(N), m_Specific(A))))
2380 // Fold the add into the false select value.
2381 return SelectInst::Create(SI->getCondition(), A, N);
2385 // Check for (add (sext x), y), see if we can merge this into an
2386 // integer add followed by a sext.
2387 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2388 // (add (sext x), cst) --> (sext (add x, cst'))
2389 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2391 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2392 if (LHSConv->hasOneUse() &&
2393 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2394 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2395 // Insert the new, smaller add.
2396 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2398 return new SExtInst(NewAdd, I.getType());
2402 // (add (sext x), (sext y)) --> (sext (add int x, y))
2403 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2404 // Only do this if x/y have the same type, if at last one of them has a
2405 // single use (so we don't increase the number of sexts), and if the
2406 // integer add will not overflow.
2407 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2408 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2409 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2410 RHSConv->getOperand(0))) {
2411 // Insert the new integer add.
2412 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2413 RHSConv->getOperand(0), "addconv");
2414 return new SExtInst(NewAdd, I.getType());
2419 return Changed ? &I : 0;
2422 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2423 bool Changed = SimplifyCommutative(I);
2424 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2426 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2428 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2429 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2430 (I.getType())->getValueAPF()))
2431 return ReplaceInstUsesWith(I, LHS);
2434 if (isa<PHINode>(LHS))
2435 if (Instruction *NV = FoldOpIntoPhi(I))
2440 // -A + -B --> -(A + B)
2441 if (Value *LHSV = dyn_castFNegVal(LHS))
2442 return BinaryOperator::CreateFSub(RHS, LHSV);
2445 if (!isa<Constant>(RHS))
2446 if (Value *V = dyn_castFNegVal(RHS))
2447 return BinaryOperator::CreateFSub(LHS, V);
2449 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2450 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2451 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2452 return ReplaceInstUsesWith(I, LHS);
2454 // Check for (add double (sitofp x), y), see if we can merge this into an
2455 // integer add followed by a promotion.
2456 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2457 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2458 // ... if the constant fits in the integer value. This is useful for things
2459 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2460 // requires a constant pool load, and generally allows the add to be better
2462 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2464 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2465 if (LHSConv->hasOneUse() &&
2466 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2467 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2468 // Insert the new integer add.
2469 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2471 return new SIToFPInst(NewAdd, I.getType());
2475 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2476 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2477 // Only do this if x/y have the same type, if at last one of them has a
2478 // single use (so we don't increase the number of int->fp conversions),
2479 // and if the integer add will not overflow.
2480 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2481 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2482 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2483 RHSConv->getOperand(0))) {
2484 // Insert the new integer add.
2485 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2486 RHSConv->getOperand(0), "addconv");
2487 return new SIToFPInst(NewAdd, I.getType());
2492 return Changed ? &I : 0;
2495 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2496 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2498 if (Op0 == Op1) // sub X, X -> 0
2499 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2501 // If this is a 'B = x-(-A)', change to B = x+A...
2502 if (Value *V = dyn_castNegVal(Op1))
2503 return BinaryOperator::CreateAdd(Op0, V);
2505 if (isa<UndefValue>(Op0))
2506 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2507 if (isa<UndefValue>(Op1))
2508 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2510 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2511 // Replace (-1 - A) with (~A)...
2512 if (C->isAllOnesValue())
2513 return BinaryOperator::CreateNot(Op1);
2515 // C - ~X == X + (1+C)
2517 if (match(Op1, m_Not(m_Value(X))))
2518 return BinaryOperator::CreateAdd(X, AddOne(C));
2520 // -(X >>u 31) -> (X >>s 31)
2521 // -(X >>s 31) -> (X >>u 31)
2523 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2524 if (SI->getOpcode() == Instruction::LShr) {
2525 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2526 // Check to see if we are shifting out everything but the sign bit.
2527 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2528 SI->getType()->getPrimitiveSizeInBits()-1) {
2529 // Ok, the transformation is safe. Insert AShr.
2530 return BinaryOperator::Create(Instruction::AShr,
2531 SI->getOperand(0), CU, SI->getName());
2535 else if (SI->getOpcode() == Instruction::AShr) {
2536 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2537 // Check to see if we are shifting out everything but the sign bit.
2538 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2539 SI->getType()->getPrimitiveSizeInBits()-1) {
2540 // Ok, the transformation is safe. Insert LShr.
2541 return BinaryOperator::CreateLShr(
2542 SI->getOperand(0), CU, SI->getName());
2549 // Try to fold constant sub into select arguments.
2550 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2551 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2554 // C - zext(bool) -> bool ? C - 1 : C
2555 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2556 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2557 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2560 if (I.getType() == Type::getInt1Ty(*Context))
2561 return BinaryOperator::CreateXor(Op0, Op1);
2563 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2564 if (Op1I->getOpcode() == Instruction::Add) {
2565 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2566 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2568 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2569 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2571 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2572 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2573 // C1-(X+C2) --> (C1-C2)-X
2574 return BinaryOperator::CreateSub(
2575 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2579 if (Op1I->hasOneUse()) {
2580 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2581 // is not used by anyone else...
2583 if (Op1I->getOpcode() == Instruction::Sub) {
2584 // Swap the two operands of the subexpr...
2585 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2586 Op1I->setOperand(0, IIOp1);
2587 Op1I->setOperand(1, IIOp0);
2589 // Create the new top level add instruction...
2590 return BinaryOperator::CreateAdd(Op0, Op1);
2593 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2595 if (Op1I->getOpcode() == Instruction::And &&
2596 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2597 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2599 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2600 return BinaryOperator::CreateAnd(Op0, NewNot);
2603 // 0 - (X sdiv C) -> (X sdiv -C)
2604 if (Op1I->getOpcode() == Instruction::SDiv)
2605 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2607 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2608 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2609 ConstantExpr::getNeg(DivRHS));
2611 // X - X*C --> X * (1-C)
2612 ConstantInt *C2 = 0;
2613 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2615 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2617 return BinaryOperator::CreateMul(Op0, CP1);
2622 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2623 if (Op0I->getOpcode() == Instruction::Add) {
2624 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2625 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2626 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2627 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2628 } else if (Op0I->getOpcode() == Instruction::Sub) {
2629 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2630 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2636 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2637 if (X == Op1) // X*C - X --> X * (C-1)
2638 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2640 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2641 if (X == dyn_castFoldableMul(Op1, C2))
2642 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2647 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2648 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2650 // If this is a 'B = x-(-A)', change to B = x+A...
2651 if (Value *V = dyn_castFNegVal(Op1))
2652 return BinaryOperator::CreateFAdd(Op0, V);
2654 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2655 if (Op1I->getOpcode() == Instruction::FAdd) {
2656 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2657 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2659 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2660 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2668 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2669 /// comparison only checks the sign bit. If it only checks the sign bit, set
2670 /// TrueIfSigned if the result of the comparison is true when the input value is
2672 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2673 bool &TrueIfSigned) {
2675 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2676 TrueIfSigned = true;
2677 return RHS->isZero();
2678 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2679 TrueIfSigned = true;
2680 return RHS->isAllOnesValue();
2681 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2682 TrueIfSigned = false;
2683 return RHS->isAllOnesValue();
2684 case ICmpInst::ICMP_UGT:
2685 // True if LHS u> RHS and RHS == high-bit-mask - 1
2686 TrueIfSigned = true;
2687 return RHS->getValue() ==
2688 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2689 case ICmpInst::ICMP_UGE:
2690 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2691 TrueIfSigned = true;
2692 return RHS->getValue().isSignBit();
2698 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2699 bool Changed = SimplifyCommutative(I);
2700 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2702 if (isa<UndefValue>(Op1)) // undef * X -> 0
2703 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2705 // Simplify mul instructions with a constant RHS.
2706 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2707 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
2709 // ((X << C1)*C2) == (X * (C2 << C1))
2710 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2711 if (SI->getOpcode() == Instruction::Shl)
2712 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2713 return BinaryOperator::CreateMul(SI->getOperand(0),
2714 ConstantExpr::getShl(CI, ShOp));
2717 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
2718 if (CI->equalsInt(1)) // X * 1 == X
2719 return ReplaceInstUsesWith(I, Op0);
2720 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2721 return BinaryOperator::CreateNeg(Op0, I.getName());
2723 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2724 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2725 return BinaryOperator::CreateShl(Op0,
2726 ConstantInt::get(Op0->getType(), Val.logBase2()));
2728 } else if (isa<VectorType>(Op1C->getType())) {
2729 if (Op1C->isNullValue())
2730 return ReplaceInstUsesWith(I, Op1C);
2732 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2733 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2734 return BinaryOperator::CreateNeg(Op0, I.getName());
2736 // As above, vector X*splat(1.0) -> X in all defined cases.
2737 if (Constant *Splat = Op1V->getSplatValue()) {
2738 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2739 if (CI->equalsInt(1))
2740 return ReplaceInstUsesWith(I, Op0);
2745 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2746 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2747 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
2748 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2749 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2750 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
2751 return BinaryOperator::CreateAdd(Add, C1C2);
2755 // Try to fold constant mul into select arguments.
2756 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2757 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2760 if (isa<PHINode>(Op0))
2761 if (Instruction *NV = FoldOpIntoPhi(I))
2765 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2766 if (Value *Op1v = dyn_castNegVal(Op1))
2767 return BinaryOperator::CreateMul(Op0v, Op1v);
2769 // (X / Y) * Y = X - (X % Y)
2770 // (X / Y) * -Y = (X % Y) - X
2773 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2775 (BO->getOpcode() != Instruction::UDiv &&
2776 BO->getOpcode() != Instruction::SDiv)) {
2778 BO = dyn_cast<BinaryOperator>(Op1);
2780 Value *Neg = dyn_castNegVal(Op1C);
2781 if (BO && BO->hasOneUse() &&
2782 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
2783 (BO->getOpcode() == Instruction::UDiv ||
2784 BO->getOpcode() == Instruction::SDiv)) {
2785 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2787 // If the division is exact, X % Y is zero.
2788 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2789 if (SDiv->isExact()) {
2791 return ReplaceInstUsesWith(I, Op0BO);
2792 return BinaryOperator::CreateNeg(Op0BO);
2796 if (BO->getOpcode() == Instruction::UDiv)
2797 Rem = Builder->CreateURem(Op0BO, Op1BO);
2799 Rem = Builder->CreateSRem(Op0BO, Op1BO);
2803 return BinaryOperator::CreateSub(Op0BO, Rem);
2804 return BinaryOperator::CreateSub(Rem, Op0BO);
2808 /// i1 mul -> i1 and.
2809 if (I.getType() == Type::getInt1Ty(*Context))
2810 return BinaryOperator::CreateAnd(Op0, Op1);
2812 // X*(1 << Y) --> X << Y
2813 // (1 << Y)*X --> X << Y
2816 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
2817 return BinaryOperator::CreateShl(Op1, Y);
2818 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
2819 return BinaryOperator::CreateShl(Op0, Y);
2822 // If one of the operands of the multiply is a cast from a boolean value, then
2823 // we know the bool is either zero or one, so this is a 'masking' multiply.
2824 // X * Y (where Y is 0 or 1) -> X & (0-Y)
2825 if (!isa<VectorType>(I.getType())) {
2826 // -2 is "-1 << 1" so it is all bits set except the low one.
2827 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
2829 Value *BoolCast = 0, *OtherOp = 0;
2830 if (MaskedValueIsZero(Op0, Negative2))
2831 BoolCast = Op0, OtherOp = Op1;
2832 else if (MaskedValueIsZero(Op1, Negative2))
2833 BoolCast = Op1, OtherOp = Op0;
2836 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2838 return BinaryOperator::CreateAnd(V, OtherOp);
2842 return Changed ? &I : 0;
2845 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2846 bool Changed = SimplifyCommutative(I);
2847 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2849 // Simplify mul instructions with a constant RHS...
2850 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2851 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
2852 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2853 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2854 if (Op1F->isExactlyValue(1.0))
2855 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2856 } else if (isa<VectorType>(Op1C->getType())) {
2857 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2858 // As above, vector X*splat(1.0) -> X in all defined cases.
2859 if (Constant *Splat = Op1V->getSplatValue()) {
2860 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2861 if (F->isExactlyValue(1.0))
2862 return ReplaceInstUsesWith(I, Op0);
2867 // Try to fold constant mul into select arguments.
2868 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2869 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2872 if (isa<PHINode>(Op0))
2873 if (Instruction *NV = FoldOpIntoPhi(I))
2877 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2878 if (Value *Op1v = dyn_castFNegVal(Op1))
2879 return BinaryOperator::CreateFMul(Op0v, Op1v);
2881 return Changed ? &I : 0;
2884 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2886 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2887 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2889 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2890 int NonNullOperand = -1;
2891 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2892 if (ST->isNullValue())
2894 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2895 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2896 if (ST->isNullValue())
2899 if (NonNullOperand == -1)
2902 Value *SelectCond = SI->getOperand(0);
2904 // Change the div/rem to use 'Y' instead of the select.
2905 I.setOperand(1, SI->getOperand(NonNullOperand));
2907 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2908 // problem. However, the select, or the condition of the select may have
2909 // multiple uses. Based on our knowledge that the operand must be non-zero,
2910 // propagate the known value for the select into other uses of it, and
2911 // propagate a known value of the condition into its other users.
2913 // If the select and condition only have a single use, don't bother with this,
2915 if (SI->use_empty() && SelectCond->hasOneUse())
2918 // Scan the current block backward, looking for other uses of SI.
2919 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2921 while (BBI != BBFront) {
2923 // If we found a call to a function, we can't assume it will return, so
2924 // information from below it cannot be propagated above it.
2925 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2928 // Replace uses of the select or its condition with the known values.
2929 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2932 *I = SI->getOperand(NonNullOperand);
2934 } else if (*I == SelectCond) {
2935 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2936 ConstantInt::getFalse(*Context);
2941 // If we past the instruction, quit looking for it.
2944 if (&*BBI == SelectCond)
2947 // If we ran out of things to eliminate, break out of the loop.
2948 if (SelectCond == 0 && SI == 0)
2956 /// This function implements the transforms on div instructions that work
2957 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2958 /// used by the visitors to those instructions.
2959 /// @brief Transforms common to all three div instructions
2960 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2961 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2963 // undef / X -> 0 for integer.
2964 // undef / X -> undef for FP (the undef could be a snan).
2965 if (isa<UndefValue>(Op0)) {
2966 if (Op0->getType()->isFPOrFPVector())
2967 return ReplaceInstUsesWith(I, Op0);
2968 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2971 // X / undef -> undef
2972 if (isa<UndefValue>(Op1))
2973 return ReplaceInstUsesWith(I, Op1);
2978 /// This function implements the transforms common to both integer division
2979 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2980 /// division instructions.
2981 /// @brief Common integer divide transforms
2982 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2983 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2985 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2987 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2988 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2989 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2990 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2993 Constant *CI = ConstantInt::get(I.getType(), 1);
2994 return ReplaceInstUsesWith(I, CI);
2997 if (Instruction *Common = commonDivTransforms(I))
3000 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3001 // This does not apply for fdiv.
3002 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3005 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3007 if (RHS->equalsInt(1))
3008 return ReplaceInstUsesWith(I, Op0);
3010 // (X / C1) / C2 -> X / (C1*C2)
3011 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3012 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3013 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3014 if (MultiplyOverflows(RHS, LHSRHS,
3015 I.getOpcode()==Instruction::SDiv))
3016 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3018 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3019 ConstantExpr::getMul(RHS, LHSRHS));
3022 if (!RHS->isZero()) { // avoid X udiv 0
3023 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3024 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3026 if (isa<PHINode>(Op0))
3027 if (Instruction *NV = FoldOpIntoPhi(I))
3032 // 0 / X == 0, we don't need to preserve faults!
3033 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3034 if (LHS->equalsInt(0))
3035 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3037 // It can't be division by zero, hence it must be division by one.
3038 if (I.getType() == Type::getInt1Ty(*Context))
3039 return ReplaceInstUsesWith(I, Op0);
3041 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3042 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3045 return ReplaceInstUsesWith(I, Op0);
3051 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3052 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3054 // Handle the integer div common cases
3055 if (Instruction *Common = commonIDivTransforms(I))
3058 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3059 // X udiv C^2 -> X >> C
3060 // Check to see if this is an unsigned division with an exact power of 2,
3061 // if so, convert to a right shift.
3062 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3063 return BinaryOperator::CreateLShr(Op0,
3064 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3066 // X udiv C, where C >= signbit
3067 if (C->getValue().isNegative()) {
3068 Value *IC = Builder->CreateICmpULT( Op0, C);
3069 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3070 ConstantInt::get(I.getType(), 1));
3074 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3075 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3076 if (RHSI->getOpcode() == Instruction::Shl &&
3077 isa<ConstantInt>(RHSI->getOperand(0))) {
3078 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3079 if (C1.isPowerOf2()) {
3080 Value *N = RHSI->getOperand(1);
3081 const Type *NTy = N->getType();
3082 if (uint32_t C2 = C1.logBase2())
3083 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3084 return BinaryOperator::CreateLShr(Op0, N);
3089 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3090 // where C1&C2 are powers of two.
3091 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3092 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3093 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3094 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3095 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3096 // Compute the shift amounts
3097 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3098 // Construct the "on true" case of the select
3099 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3100 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3102 // Construct the "on false" case of the select
3103 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3104 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
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(Op0);
3125 // sdiv X, C --> ashr X, log2(C)
3126 if (cast<SDivOperator>(&I)->isExact() &&
3127 RHS->getValue().isNonNegative() &&
3128 RHS->getValue().isPowerOf2()) {
3129 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3130 RHS->getValue().exactLogBase2());
3131 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3134 // -X/C --> X/-C provided the negation doesn't overflow.
3135 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3136 if (isa<Constant>(Sub->getOperand(0)) &&
3137 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3138 Sub->hasNoSignedWrap())
3139 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3140 ConstantExpr::getNeg(RHS));
3143 // If the sign bits of both operands are zero (i.e. we can prove they are
3144 // unsigned inputs), turn this into a udiv.
3145 if (I.getType()->isInteger()) {
3146 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3147 if (MaskedValueIsZero(Op0, Mask)) {
3148 if (MaskedValueIsZero(Op1, Mask)) {
3149 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3150 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3152 ConstantInt *ShiftedInt;
3153 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3154 ShiftedInt->getValue().isPowerOf2()) {
3155 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3156 // Safe because the only negative value (1 << Y) can take on is
3157 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3158 // the sign bit set.
3159 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3167 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3168 return commonDivTransforms(I);
3171 /// This function implements the transforms on rem instructions that work
3172 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3173 /// is used by the visitors to those instructions.
3174 /// @brief Transforms common to all three rem instructions
3175 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3176 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3178 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3179 if (I.getType()->isFPOrFPVector())
3180 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3181 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3183 if (isa<UndefValue>(Op1))
3184 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3186 // Handle cases involving: rem X, (select Cond, Y, Z)
3187 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3193 /// This function implements the transforms common to both integer remainder
3194 /// instructions (urem and srem). It is called by the visitors to those integer
3195 /// remainder instructions.
3196 /// @brief Common integer remainder transforms
3197 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3198 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3200 if (Instruction *common = commonRemTransforms(I))
3203 // 0 % X == 0 for integer, we don't need to preserve faults!
3204 if (Constant *LHS = dyn_cast<Constant>(Op0))
3205 if (LHS->isNullValue())
3206 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3208 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3209 // X % 0 == undef, we don't need to preserve faults!
3210 if (RHS->equalsInt(0))
3211 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3213 if (RHS->equalsInt(1)) // X % 1 == 0
3214 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3216 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3217 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3218 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3220 } else if (isa<PHINode>(Op0I)) {
3221 if (Instruction *NV = FoldOpIntoPhi(I))
3225 // See if we can fold away this rem instruction.
3226 if (SimplifyDemandedInstructionBits(I))
3234 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3235 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3237 if (Instruction *common = commonIRemTransforms(I))
3240 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3241 // X urem C^2 -> X and C
3242 // Check to see if this is an unsigned remainder with an exact power of 2,
3243 // if so, convert to a bitwise and.
3244 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3245 if (C->getValue().isPowerOf2())
3246 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3249 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3250 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3251 if (RHSI->getOpcode() == Instruction::Shl &&
3252 isa<ConstantInt>(RHSI->getOperand(0))) {
3253 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3254 Constant *N1 = Constant::getAllOnesValue(I.getType());
3255 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3256 return BinaryOperator::CreateAnd(Op0, Add);
3261 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3262 // where C1&C2 are powers of two.
3263 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3264 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3265 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3266 // STO == 0 and SFO == 0 handled above.
3267 if ((STO->getValue().isPowerOf2()) &&
3268 (SFO->getValue().isPowerOf2())) {
3269 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3270 SI->getName()+".t");
3271 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3272 SI->getName()+".f");
3273 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3281 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3282 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3284 // Handle the integer rem common cases
3285 if (Instruction *Common = commonIRemTransforms(I))
3288 if (Value *RHSNeg = dyn_castNegVal(Op1))
3289 if (!isa<Constant>(RHSNeg) ||
3290 (isa<ConstantInt>(RHSNeg) &&
3291 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3293 Worklist.AddValue(I.getOperand(1));
3294 I.setOperand(1, RHSNeg);
3298 // If the sign bits of both operands are zero (i.e. we can prove they are
3299 // unsigned inputs), turn this into a urem.
3300 if (I.getType()->isInteger()) {
3301 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3302 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3303 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3304 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3308 // If it's a constant vector, flip any negative values positive.
3309 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3310 unsigned VWidth = RHSV->getNumOperands();
3312 bool hasNegative = false;
3313 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3314 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3315 if (RHS->getValue().isNegative())
3319 std::vector<Constant *> Elts(VWidth);
3320 for (unsigned i = 0; i != VWidth; ++i) {
3321 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3322 if (RHS->getValue().isNegative())
3323 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3329 Constant *NewRHSV = ConstantVector::get(Elts);
3330 if (NewRHSV != RHSV) {
3331 Worklist.AddValue(I.getOperand(1));
3332 I.setOperand(1, NewRHSV);
3341 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3342 return commonRemTransforms(I);
3345 // isOneBitSet - Return true if there is exactly one bit set in the specified
3347 static bool isOneBitSet(const ConstantInt *CI) {
3348 return CI->getValue().isPowerOf2();
3351 // isHighOnes - Return true if the constant is of the form 1+0+.
3352 // This is the same as lowones(~X).
3353 static bool isHighOnes(const ConstantInt *CI) {
3354 return (~CI->getValue() + 1).isPowerOf2();
3357 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3358 /// are carefully arranged to allow folding of expressions such as:
3360 /// (A < B) | (A > B) --> (A != B)
3362 /// Note that this is only valid if the first and second predicates have the
3363 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3365 /// Three bits are used to represent the condition, as follows:
3370 /// <=> Value Definition
3371 /// 000 0 Always false
3378 /// 111 7 Always true
3380 static unsigned getICmpCode(const ICmpInst *ICI) {
3381 switch (ICI->getPredicate()) {
3383 case ICmpInst::ICMP_UGT: return 1; // 001
3384 case ICmpInst::ICMP_SGT: return 1; // 001
3385 case ICmpInst::ICMP_EQ: return 2; // 010
3386 case ICmpInst::ICMP_UGE: return 3; // 011
3387 case ICmpInst::ICMP_SGE: return 3; // 011
3388 case ICmpInst::ICMP_ULT: return 4; // 100
3389 case ICmpInst::ICMP_SLT: return 4; // 100
3390 case ICmpInst::ICMP_NE: return 5; // 101
3391 case ICmpInst::ICMP_ULE: return 6; // 110
3392 case ICmpInst::ICMP_SLE: return 6; // 110
3395 llvm_unreachable("Invalid ICmp predicate!");
3400 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3401 /// predicate into a three bit mask. It also returns whether it is an ordered
3402 /// predicate by reference.
3403 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3406 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3407 case FCmpInst::FCMP_UNO: return 0; // 000
3408 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3409 case FCmpInst::FCMP_UGT: return 1; // 001
3410 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3411 case FCmpInst::FCMP_UEQ: return 2; // 010
3412 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3413 case FCmpInst::FCMP_UGE: return 3; // 011
3414 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3415 case FCmpInst::FCMP_ULT: return 4; // 100
3416 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3417 case FCmpInst::FCMP_UNE: return 5; // 101
3418 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3419 case FCmpInst::FCMP_ULE: return 6; // 110
3422 // Not expecting FCMP_FALSE and FCMP_TRUE;
3423 llvm_unreachable("Unexpected FCmp predicate!");
3428 /// getICmpValue - This is the complement of getICmpCode, which turns an
3429 /// opcode and two operands into either a constant true or false, or a brand
3430 /// new ICmp instruction. The sign is passed in to determine which kind
3431 /// of predicate to use in the new icmp instruction.
3432 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3433 LLVMContext *Context) {
3435 default: llvm_unreachable("Illegal ICmp code!");
3436 case 0: return ConstantInt::getFalse(*Context);
3439 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3441 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3442 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3445 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3447 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3450 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3452 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3453 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3456 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3458 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3459 case 7: return ConstantInt::getTrue(*Context);
3463 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3464 /// opcode and two operands into either a FCmp instruction. isordered is passed
3465 /// in to determine which kind of predicate to use in the new fcmp instruction.
3466 static Value *getFCmpValue(bool isordered, unsigned code,
3467 Value *LHS, Value *RHS, LLVMContext *Context) {
3469 default: llvm_unreachable("Illegal FCmp code!");
3472 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3474 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3477 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3479 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3482 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3484 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3487 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3489 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3492 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3494 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3497 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3499 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3502 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3504 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3505 case 7: return ConstantInt::getTrue(*Context);
3509 /// PredicatesFoldable - Return true if both predicates match sign or if at
3510 /// least one of them is an equality comparison (which is signless).
3511 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3512 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3513 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3514 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3518 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3519 struct FoldICmpLogical {
3522 ICmpInst::Predicate pred;
3523 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3524 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3525 pred(ICI->getPredicate()) {}
3526 bool shouldApply(Value *V) const {
3527 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3528 if (PredicatesFoldable(pred, ICI->getPredicate()))
3529 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3530 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3533 Instruction *apply(Instruction &Log) const {
3534 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3535 if (ICI->getOperand(0) != LHS) {
3536 assert(ICI->getOperand(1) == LHS);
3537 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3540 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3541 unsigned LHSCode = getICmpCode(ICI);
3542 unsigned RHSCode = getICmpCode(RHSICI);
3544 switch (Log.getOpcode()) {
3545 case Instruction::And: Code = LHSCode & RHSCode; break;
3546 case Instruction::Or: Code = LHSCode | RHSCode; break;
3547 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3548 default: llvm_unreachable("Illegal logical opcode!"); return 0;
3551 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3552 ICmpInst::isSignedPredicate(ICI->getPredicate());
3554 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3555 if (Instruction *I = dyn_cast<Instruction>(RV))
3557 // Otherwise, it's a constant boolean value...
3558 return IC.ReplaceInstUsesWith(Log, RV);
3561 } // end anonymous namespace
3563 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3564 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3565 // guaranteed to be a binary operator.
3566 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3568 ConstantInt *AndRHS,
3569 BinaryOperator &TheAnd) {
3570 Value *X = Op->getOperand(0);
3571 Constant *Together = 0;
3573 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3575 switch (Op->getOpcode()) {
3576 case Instruction::Xor:
3577 if (Op->hasOneUse()) {
3578 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3579 Value *And = Builder->CreateAnd(X, AndRHS);
3581 return BinaryOperator::CreateXor(And, Together);
3584 case Instruction::Or:
3585 if (Together == AndRHS) // (X | C) & C --> C
3586 return ReplaceInstUsesWith(TheAnd, AndRHS);
3588 if (Op->hasOneUse() && Together != OpRHS) {
3589 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3590 Value *Or = Builder->CreateOr(X, Together);
3592 return BinaryOperator::CreateAnd(Or, AndRHS);
3595 case Instruction::Add:
3596 if (Op->hasOneUse()) {
3597 // Adding a one to a single bit bit-field should be turned into an XOR
3598 // of the bit. First thing to check is to see if this AND is with a
3599 // single bit constant.
3600 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3602 // If there is only one bit set...
3603 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3604 // Ok, at this point, we know that we are masking the result of the
3605 // ADD down to exactly one bit. If the constant we are adding has
3606 // no bits set below this bit, then we can eliminate the ADD.
3607 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3609 // Check to see if any bits below the one bit set in AndRHSV are set.
3610 if ((AddRHS & (AndRHSV-1)) == 0) {
3611 // If not, the only thing that can effect the output of the AND is
3612 // the bit specified by AndRHSV. If that bit is set, the effect of
3613 // the XOR is to toggle the bit. If it is clear, then the ADD has
3615 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3616 TheAnd.setOperand(0, X);
3619 // Pull the XOR out of the AND.
3620 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3621 NewAnd->takeName(Op);
3622 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3629 case Instruction::Shl: {
3630 // We know that the AND will not produce any of the bits shifted in, so if
3631 // the anded constant includes them, clear them now!
3633 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3634 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3635 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3636 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3638 if (CI->getValue() == ShlMask) {
3639 // Masking out bits that the shift already masks
3640 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3641 } else if (CI != AndRHS) { // Reducing bits set in and.
3642 TheAnd.setOperand(1, CI);
3647 case Instruction::LShr:
3649 // We know that the AND will not produce any of the bits shifted in, so if
3650 // the anded constant includes them, clear them now! This only applies to
3651 // unsigned shifts, because a signed shr may bring in set bits!
3653 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3654 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3655 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3656 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3658 if (CI->getValue() == ShrMask) {
3659 // Masking out bits that the shift already masks.
3660 return ReplaceInstUsesWith(TheAnd, Op);
3661 } else if (CI != AndRHS) {
3662 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3667 case Instruction::AShr:
3669 // See if this is shifting in some sign extension, then masking it out
3671 if (Op->hasOneUse()) {
3672 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3673 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3674 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3675 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3676 if (C == AndRHS) { // Masking out bits shifted in.
3677 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3678 // Make the argument unsigned.
3679 Value *ShVal = Op->getOperand(0);
3680 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3681 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3690 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3691 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3692 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3693 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3694 /// insert new instructions.
3695 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3696 bool isSigned, bool Inside,
3698 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3699 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3700 "Lo is not <= Hi in range emission code!");
3703 if (Lo == Hi) // Trivially false.
3704 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3706 // V >= Min && V < Hi --> V < Hi
3707 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3708 ICmpInst::Predicate pred = (isSigned ?
3709 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3710 return new ICmpInst(pred, V, Hi);
3713 // Emit V-Lo <u Hi-Lo
3714 Constant *NegLo = ConstantExpr::getNeg(Lo);
3715 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3716 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3717 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3720 if (Lo == Hi) // Trivially true.
3721 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3723 // V < Min || V >= Hi -> V > Hi-1
3724 Hi = SubOne(cast<ConstantInt>(Hi));
3725 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3726 ICmpInst::Predicate pred = (isSigned ?
3727 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3728 return new ICmpInst(pred, V, Hi);
3731 // Emit V-Lo >u Hi-1-Lo
3732 // Note that Hi has already had one subtracted from it, above.
3733 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3734 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3735 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3736 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3739 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3740 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3741 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3742 // not, since all 1s are not contiguous.
3743 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3744 const APInt& V = Val->getValue();
3745 uint32_t BitWidth = Val->getType()->getBitWidth();
3746 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3748 // look for the first zero bit after the run of ones
3749 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3750 // look for the first non-zero bit
3751 ME = V.getActiveBits();
3755 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3756 /// where isSub determines whether the operator is a sub. If we can fold one of
3757 /// the following xforms:
3759 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3760 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3761 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3763 /// return (A +/- B).
3765 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3766 ConstantInt *Mask, bool isSub,
3768 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3769 if (!LHSI || LHSI->getNumOperands() != 2 ||
3770 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3772 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3774 switch (LHSI->getOpcode()) {
3776 case Instruction::And:
3777 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3778 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3779 if ((Mask->getValue().countLeadingZeros() +
3780 Mask->getValue().countPopulation()) ==
3781 Mask->getValue().getBitWidth())
3784 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3785 // part, we don't need any explicit masks to take them out of A. If that
3786 // is all N is, ignore it.
3787 uint32_t MB = 0, ME = 0;
3788 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3789 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3790 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3791 if (MaskedValueIsZero(RHS, Mask))
3796 case Instruction::Or:
3797 case Instruction::Xor:
3798 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3799 if ((Mask->getValue().countLeadingZeros() +
3800 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3801 && ConstantExpr::getAnd(N, Mask)->isNullValue())
3807 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3808 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3811 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3812 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3813 ICmpInst *LHS, ICmpInst *RHS) {
3815 ConstantInt *LHSCst, *RHSCst;
3816 ICmpInst::Predicate LHSCC, RHSCC;
3818 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3819 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3820 m_ConstantInt(LHSCst))) ||
3821 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3822 m_ConstantInt(RHSCst))))
3825 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3826 // where C is a power of 2
3827 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3828 LHSCst->getValue().isPowerOf2()) {
3829 Value *NewOr = Builder->CreateOr(Val, Val2);
3830 return new ICmpInst(LHSCC, NewOr, LHSCst);
3833 // From here on, we only handle:
3834 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3835 if (Val != Val2) return 0;
3837 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3838 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3839 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3840 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3841 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3844 // We can't fold (ugt x, C) & (sgt x, C2).
3845 if (!PredicatesFoldable(LHSCC, RHSCC))
3848 // Ensure that the larger constant is on the RHS.
3850 if (ICmpInst::isSignedPredicate(LHSCC) ||
3851 (ICmpInst::isEquality(LHSCC) &&
3852 ICmpInst::isSignedPredicate(RHSCC)))
3853 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3855 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3858 std::swap(LHS, RHS);
3859 std::swap(LHSCst, RHSCst);
3860 std::swap(LHSCC, RHSCC);
3863 // At this point, we know we have have two icmp instructions
3864 // comparing a value against two constants and and'ing the result
3865 // together. Because of the above check, we know that we only have
3866 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3867 // (from the FoldICmpLogical check above), that the two constants
3868 // are not equal and that the larger constant is on the RHS
3869 assert(LHSCst != RHSCst && "Compares not folded above?");
3872 default: llvm_unreachable("Unknown integer condition code!");
3873 case ICmpInst::ICMP_EQ:
3875 default: llvm_unreachable("Unknown integer condition code!");
3876 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3877 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3878 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3879 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3880 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3881 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3882 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3883 return ReplaceInstUsesWith(I, LHS);
3885 case ICmpInst::ICMP_NE:
3887 default: llvm_unreachable("Unknown integer condition code!");
3888 case ICmpInst::ICMP_ULT:
3889 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3890 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3891 break; // (X != 13 & X u< 15) -> no change
3892 case ICmpInst::ICMP_SLT:
3893 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3894 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3895 break; // (X != 13 & X s< 15) -> no change
3896 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3897 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3898 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3899 return ReplaceInstUsesWith(I, RHS);
3900 case ICmpInst::ICMP_NE:
3901 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3902 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3903 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3904 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3905 ConstantInt::get(Add->getType(), 1));
3907 break; // (X != 13 & X != 15) -> no change
3910 case ICmpInst::ICMP_ULT:
3912 default: llvm_unreachable("Unknown integer condition code!");
3913 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3914 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3915 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3916 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3918 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3919 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3920 return ReplaceInstUsesWith(I, LHS);
3921 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3925 case ICmpInst::ICMP_SLT:
3927 default: llvm_unreachable("Unknown integer condition code!");
3928 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3929 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3930 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3931 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3933 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3934 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3935 return ReplaceInstUsesWith(I, LHS);
3936 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3940 case ICmpInst::ICMP_UGT:
3942 default: llvm_unreachable("Unknown integer condition code!");
3943 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3944 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3945 return ReplaceInstUsesWith(I, RHS);
3946 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3948 case ICmpInst::ICMP_NE:
3949 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3950 return new ICmpInst(LHSCC, Val, RHSCst);
3951 break; // (X u> 13 & X != 15) -> no change
3952 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3953 return InsertRangeTest(Val, AddOne(LHSCst),
3954 RHSCst, false, true, I);
3955 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3959 case ICmpInst::ICMP_SGT:
3961 default: llvm_unreachable("Unknown integer condition code!");
3962 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3963 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3964 return ReplaceInstUsesWith(I, RHS);
3965 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3967 case ICmpInst::ICMP_NE:
3968 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3969 return new ICmpInst(LHSCC, Val, RHSCst);
3970 break; // (X s> 13 & X != 15) -> no change
3971 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3972 return InsertRangeTest(Val, AddOne(LHSCst),
3973 RHSCst, true, true, I);
3974 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3983 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3986 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3987 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3988 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3989 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3990 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3991 // If either of the constants are nans, then the whole thing returns
3993 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3994 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3995 return new FCmpInst(FCmpInst::FCMP_ORD,
3996 LHS->getOperand(0), RHS->getOperand(0));
3999 // Handle vector zeros. This occurs because the canonical form of
4000 // "fcmp ord x,x" is "fcmp ord x, 0".
4001 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4002 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4003 return new FCmpInst(FCmpInst::FCMP_ORD,
4004 LHS->getOperand(0), RHS->getOperand(0));
4008 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4009 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4010 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4013 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4014 // Swap RHS operands to match LHS.
4015 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4016 std::swap(Op1LHS, Op1RHS);
4019 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4020 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4022 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4024 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4025 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4026 if (Op0CC == FCmpInst::FCMP_TRUE)
4027 return ReplaceInstUsesWith(I, RHS);
4028 if (Op1CC == FCmpInst::FCMP_TRUE)
4029 return ReplaceInstUsesWith(I, LHS);
4033 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4034 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4036 std::swap(LHS, RHS);
4037 std::swap(Op0Pred, Op1Pred);
4038 std::swap(Op0Ordered, Op1Ordered);
4041 // uno && ueq -> uno && (uno || eq) -> ueq
4042 // ord && olt -> ord && (ord && lt) -> olt
4043 if (Op0Ordered == Op1Ordered)
4044 return ReplaceInstUsesWith(I, RHS);
4046 // uno && oeq -> uno && (ord && eq) -> false
4047 // uno && ord -> false
4049 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4050 // ord && ueq -> ord && (uno || eq) -> oeq
4051 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4052 Op0LHS, Op0RHS, Context));
4060 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4061 bool Changed = SimplifyCommutative(I);
4062 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4064 if (isa<UndefValue>(Op1)) // X & undef -> 0
4065 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4069 return ReplaceInstUsesWith(I, Op1);
4071 // See if we can simplify any instructions used by the instruction whose sole
4072 // purpose is to compute bits we don't care about.
4073 if (SimplifyDemandedInstructionBits(I))
4075 if (isa<VectorType>(I.getType())) {
4076 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4077 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4078 return ReplaceInstUsesWith(I, I.getOperand(0));
4079 } else if (isa<ConstantAggregateZero>(Op1)) {
4080 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4084 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4085 const APInt &AndRHSMask = AndRHS->getValue();
4086 APInt NotAndRHS(~AndRHSMask);
4088 // Optimize a variety of ((val OP C1) & C2) combinations...
4089 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4090 Value *Op0LHS = Op0I->getOperand(0);
4091 Value *Op0RHS = Op0I->getOperand(1);
4092 switch (Op0I->getOpcode()) {
4094 case Instruction::Xor:
4095 case Instruction::Or:
4096 // If the mask is only needed on one incoming arm, push it up.
4097 if (!Op0I->hasOneUse()) break;
4099 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4100 // Not masking anything out for the LHS, move to RHS.
4101 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4102 Op0RHS->getName()+".masked");
4103 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4105 if (!isa<Constant>(Op0RHS) &&
4106 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4107 // Not masking anything out for the RHS, move to LHS.
4108 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4109 Op0LHS->getName()+".masked");
4110 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4114 case Instruction::Add:
4115 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4116 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4117 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4118 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4119 return BinaryOperator::CreateAnd(V, AndRHS);
4120 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4121 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4124 case Instruction::Sub:
4125 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4126 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4127 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4128 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4129 return BinaryOperator::CreateAnd(V, AndRHS);
4131 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4132 // has 1's for all bits that the subtraction with A might affect.
4133 if (Op0I->hasOneUse()) {
4134 uint32_t BitWidth = AndRHSMask.getBitWidth();
4135 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4136 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4138 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4139 if (!(A && A->isZero()) && // avoid infinite recursion.
4140 MaskedValueIsZero(Op0LHS, Mask)) {
4141 Value *NewNeg = Builder->CreateNeg(Op0RHS);
4142 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4147 case Instruction::Shl:
4148 case Instruction::LShr:
4149 // (1 << x) & 1 --> zext(x == 0)
4150 // (1 >> x) & 1 --> zext(x == 0)
4151 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4153 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4154 return new ZExtInst(NewICmp, I.getType());
4159 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4160 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4162 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4163 // If this is an integer truncation or change from signed-to-unsigned, and
4164 // if the source is an and/or with immediate, transform it. This
4165 // frequently occurs for bitfield accesses.
4166 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4167 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4168 CastOp->getNumOperands() == 2)
4169 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4170 if (CastOp->getOpcode() == Instruction::And) {
4171 // Change: and (cast (and X, C1) to T), C2
4172 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4173 // This will fold the two constants together, which may allow
4174 // other simplifications.
4175 Value *NewCast = Builder->CreateTruncOrBitCast(
4176 CastOp->getOperand(0), I.getType(),
4177 CastOp->getName()+".shrunk");
4178 // trunc_or_bitcast(C1)&C2
4179 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4180 C3 = ConstantExpr::getAnd(C3, AndRHS);
4181 return BinaryOperator::CreateAnd(NewCast, C3);
4182 } else if (CastOp->getOpcode() == Instruction::Or) {
4183 // Change: and (cast (or X, C1) to T), C2
4184 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4185 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4186 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4188 return ReplaceInstUsesWith(I, AndRHS);
4194 // Try to fold constant and into select arguments.
4195 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4196 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4198 if (isa<PHINode>(Op0))
4199 if (Instruction *NV = FoldOpIntoPhi(I))
4203 Value *Op0NotVal = dyn_castNotVal(Op0);
4204 Value *Op1NotVal = dyn_castNotVal(Op1);
4206 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4207 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4209 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4210 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4211 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4212 I.getName()+".demorgan");
4213 return BinaryOperator::CreateNot(Or);
4217 Value *A = 0, *B = 0, *C = 0, *D = 0;
4218 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4219 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4220 return ReplaceInstUsesWith(I, Op1);
4222 // (A|B) & ~(A&B) -> A^B
4223 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4224 if ((A == C && B == D) || (A == D && B == C))
4225 return BinaryOperator::CreateXor(A, B);
4229 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4230 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4231 return ReplaceInstUsesWith(I, Op0);
4233 // ~(A&B) & (A|B) -> A^B
4234 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4235 if ((A == C && B == D) || (A == D && B == C))
4236 return BinaryOperator::CreateXor(A, B);
4240 if (Op0->hasOneUse() &&
4241 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4242 if (A == Op1) { // (A^B)&A -> A&(A^B)
4243 I.swapOperands(); // Simplify below
4244 std::swap(Op0, Op1);
4245 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4246 cast<BinaryOperator>(Op0)->swapOperands();
4247 I.swapOperands(); // Simplify below
4248 std::swap(Op0, Op1);
4252 if (Op1->hasOneUse() &&
4253 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4254 if (B == Op0) { // B&(A^B) -> B&(B^A)
4255 cast<BinaryOperator>(Op1)->swapOperands();
4258 if (A == Op0) // A&(A^B) -> A & ~B
4259 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4262 // (A&((~A)|B)) -> A&B
4263 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4264 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4265 return BinaryOperator::CreateAnd(A, Op1);
4266 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4267 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4268 return BinaryOperator::CreateAnd(A, Op0);
4271 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4272 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4273 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4276 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4277 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4281 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4282 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4283 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4284 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4285 const Type *SrcTy = Op0C->getOperand(0)->getType();
4286 if (SrcTy == Op1C->getOperand(0)->getType() &&
4287 SrcTy->isIntOrIntVector() &&
4288 // Only do this if the casts both really cause code to be generated.
4289 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4291 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4293 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4294 Op1C->getOperand(0), I.getName());
4295 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4299 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4300 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4301 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4302 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4303 SI0->getOperand(1) == SI1->getOperand(1) &&
4304 (SI0->hasOneUse() || SI1->hasOneUse())) {
4306 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4308 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4309 SI1->getOperand(1));
4313 // If and'ing two fcmp, try combine them into one.
4314 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4315 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4316 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4320 return Changed ? &I : 0;
4323 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4324 /// capable of providing pieces of a bswap. The subexpression provides pieces
4325 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4326 /// the expression came from the corresponding "byte swapped" byte in some other
4327 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4328 /// we know that the expression deposits the low byte of %X into the high byte
4329 /// of the bswap result and that all other bytes are zero. This expression is
4330 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4333 /// This function returns true if the match was unsuccessful and false if so.
4334 /// On entry to the function the "OverallLeftShift" is a signed integer value
4335 /// indicating the number of bytes that the subexpression is later shifted. For
4336 /// example, if the expression is later right shifted by 16 bits, the
4337 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4338 /// byte of ByteValues is actually being set.
4340 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4341 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4342 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4343 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4344 /// always in the local (OverallLeftShift) coordinate space.
4346 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4347 SmallVector<Value*, 8> &ByteValues) {
4348 if (Instruction *I = dyn_cast<Instruction>(V)) {
4349 // If this is an or instruction, it may be an inner node of the bswap.
4350 if (I->getOpcode() == Instruction::Or) {
4351 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4353 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4357 // If this is a logical shift by a constant multiple of 8, recurse with
4358 // OverallLeftShift and ByteMask adjusted.
4359 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4361 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4362 // Ensure the shift amount is defined and of a byte value.
4363 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4366 unsigned ByteShift = ShAmt >> 3;
4367 if (I->getOpcode() == Instruction::Shl) {
4368 // X << 2 -> collect(X, +2)
4369 OverallLeftShift += ByteShift;
4370 ByteMask >>= ByteShift;
4372 // X >>u 2 -> collect(X, -2)
4373 OverallLeftShift -= ByteShift;
4374 ByteMask <<= ByteShift;
4375 ByteMask &= (~0U >> (32-ByteValues.size()));
4378 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4379 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4381 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4385 // If this is a logical 'and' with a mask that clears bytes, clear the
4386 // corresponding bytes in ByteMask.
4387 if (I->getOpcode() == Instruction::And &&
4388 isa<ConstantInt>(I->getOperand(1))) {
4389 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4390 unsigned NumBytes = ByteValues.size();
4391 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4392 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4394 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4395 // If this byte is masked out by a later operation, we don't care what
4397 if ((ByteMask & (1 << i)) == 0)
4400 // If the AndMask is all zeros for this byte, clear the bit.
4401 APInt MaskB = AndMask & Byte;
4403 ByteMask &= ~(1U << i);
4407 // If the AndMask is not all ones for this byte, it's not a bytezap.
4411 // Otherwise, this byte is kept.
4414 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4419 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4420 // the input value to the bswap. Some observations: 1) if more than one byte
4421 // is demanded from this input, then it could not be successfully assembled
4422 // into a byteswap. At least one of the two bytes would not be aligned with
4423 // their ultimate destination.
4424 if (!isPowerOf2_32(ByteMask)) return true;
4425 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4427 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4428 // is demanded, it needs to go into byte 0 of the result. This means that the
4429 // byte needs to be shifted until it lands in the right byte bucket. The
4430 // shift amount depends on the position: if the byte is coming from the high
4431 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4432 // low part, it must be shifted left.
4433 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4434 if (InputByteNo < ByteValues.size()/2) {
4435 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4438 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4442 // If the destination byte value is already defined, the values are or'd
4443 // together, which isn't a bswap (unless it's an or of the same bits).
4444 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4446 ByteValues[DestByteNo] = V;
4450 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4451 /// If so, insert the new bswap intrinsic and return it.
4452 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4453 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4454 if (!ITy || ITy->getBitWidth() % 16 ||
4455 // ByteMask only allows up to 32-byte values.
4456 ITy->getBitWidth() > 32*8)
4457 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4459 /// ByteValues - For each byte of the result, we keep track of which value
4460 /// defines each byte.
4461 SmallVector<Value*, 8> ByteValues;
4462 ByteValues.resize(ITy->getBitWidth()/8);
4464 // Try to find all the pieces corresponding to the bswap.
4465 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4466 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4469 // Check to see if all of the bytes come from the same value.
4470 Value *V = ByteValues[0];
4471 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4473 // Check to make sure that all of the bytes come from the same value.
4474 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4475 if (ByteValues[i] != V)
4477 const Type *Tys[] = { ITy };
4478 Module *M = I.getParent()->getParent()->getParent();
4479 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4480 return CallInst::Create(F, V);
4483 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4484 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4485 /// we can simplify this expression to "cond ? C : D or B".
4486 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4488 LLVMContext *Context) {
4489 // If A is not a select of -1/0, this cannot match.
4491 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4494 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4495 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4496 return SelectInst::Create(Cond, C, B);
4497 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4498 return SelectInst::Create(Cond, C, B);
4499 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4500 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4501 return SelectInst::Create(Cond, C, D);
4502 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4503 return SelectInst::Create(Cond, C, D);
4507 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4508 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4509 ICmpInst *LHS, ICmpInst *RHS) {
4511 ConstantInt *LHSCst, *RHSCst;
4512 ICmpInst::Predicate LHSCC, RHSCC;
4514 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4515 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4516 m_ConstantInt(LHSCst))) ||
4517 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4518 m_ConstantInt(RHSCst))))
4521 // From here on, we only handle:
4522 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4523 if (Val != Val2) return 0;
4525 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4526 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4527 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4528 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4529 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4532 // We can't fold (ugt x, C) | (sgt x, C2).
4533 if (!PredicatesFoldable(LHSCC, RHSCC))
4536 // Ensure that the larger constant is on the RHS.
4538 if (ICmpInst::isSignedPredicate(LHSCC) ||
4539 (ICmpInst::isEquality(LHSCC) &&
4540 ICmpInst::isSignedPredicate(RHSCC)))
4541 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4543 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4546 std::swap(LHS, RHS);
4547 std::swap(LHSCst, RHSCst);
4548 std::swap(LHSCC, RHSCC);
4551 // At this point, we know we have have two icmp instructions
4552 // comparing a value against two constants and or'ing the result
4553 // together. Because of the above check, we know that we only have
4554 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4555 // FoldICmpLogical check above), that the two constants are not
4557 assert(LHSCst != RHSCst && "Compares not folded above?");
4560 default: llvm_unreachable("Unknown integer condition code!");
4561 case ICmpInst::ICMP_EQ:
4563 default: llvm_unreachable("Unknown integer condition code!");
4564 case ICmpInst::ICMP_EQ:
4565 if (LHSCst == SubOne(RHSCst)) {
4566 // (X == 13 | X == 14) -> X-13 <u 2
4567 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4568 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4569 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4570 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4572 break; // (X == 13 | X == 15) -> no change
4573 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4574 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4576 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4577 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4578 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4579 return ReplaceInstUsesWith(I, RHS);
4582 case ICmpInst::ICMP_NE:
4584 default: llvm_unreachable("Unknown integer condition code!");
4585 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4586 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4587 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4588 return ReplaceInstUsesWith(I, LHS);
4589 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4590 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4591 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4592 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4595 case ICmpInst::ICMP_ULT:
4597 default: llvm_unreachable("Unknown integer condition code!");
4598 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4600 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4601 // If RHSCst is [us]MAXINT, it is always false. Not handling
4602 // this can cause overflow.
4603 if (RHSCst->isMaxValue(false))
4604 return ReplaceInstUsesWith(I, LHS);
4605 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4607 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4609 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4610 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4611 return ReplaceInstUsesWith(I, RHS);
4612 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4616 case ICmpInst::ICMP_SLT:
4618 default: llvm_unreachable("Unknown integer condition code!");
4619 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4621 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4622 // If RHSCst is [us]MAXINT, it is always false. Not handling
4623 // this can cause overflow.
4624 if (RHSCst->isMaxValue(true))
4625 return ReplaceInstUsesWith(I, LHS);
4626 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4628 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4630 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4631 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4632 return ReplaceInstUsesWith(I, RHS);
4633 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4637 case ICmpInst::ICMP_UGT:
4639 default: llvm_unreachable("Unknown integer condition code!");
4640 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4641 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4642 return ReplaceInstUsesWith(I, LHS);
4643 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4645 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4646 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4647 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4648 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4652 case ICmpInst::ICMP_SGT:
4654 default: llvm_unreachable("Unknown integer condition code!");
4655 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4656 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4657 return ReplaceInstUsesWith(I, LHS);
4658 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4660 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4661 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4662 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4663 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4671 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4673 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4674 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4675 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4676 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4677 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4678 // If either of the constants are nans, then the whole thing returns
4680 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4681 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4683 // Otherwise, no need to compare the two constants, compare the
4685 return new FCmpInst(FCmpInst::FCMP_UNO,
4686 LHS->getOperand(0), RHS->getOperand(0));
4689 // Handle vector zeros. This occurs because the canonical form of
4690 // "fcmp uno x,x" is "fcmp uno x, 0".
4691 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4692 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4693 return new FCmpInst(FCmpInst::FCMP_UNO,
4694 LHS->getOperand(0), RHS->getOperand(0));
4699 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4700 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4701 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4703 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4704 // Swap RHS operands to match LHS.
4705 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4706 std::swap(Op1LHS, Op1RHS);
4708 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4709 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4711 return new FCmpInst((FCmpInst::Predicate)Op0CC,
4713 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4714 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4715 if (Op0CC == FCmpInst::FCMP_FALSE)
4716 return ReplaceInstUsesWith(I, RHS);
4717 if (Op1CC == FCmpInst::FCMP_FALSE)
4718 return ReplaceInstUsesWith(I, LHS);
4721 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4722 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4723 if (Op0Ordered == Op1Ordered) {
4724 // If both are ordered or unordered, return a new fcmp with
4725 // or'ed predicates.
4726 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4727 Op0LHS, Op0RHS, Context);
4728 if (Instruction *I = dyn_cast<Instruction>(RV))
4730 // Otherwise, it's a constant boolean value...
4731 return ReplaceInstUsesWith(I, RV);
4737 /// FoldOrWithConstants - This helper function folds:
4739 /// ((A | B) & C1) | (B & C2)
4745 /// when the XOR of the two constants is "all ones" (-1).
4746 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4747 Value *A, Value *B, Value *C) {
4748 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4752 ConstantInt *CI2 = 0;
4753 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4755 APInt Xor = CI1->getValue() ^ CI2->getValue();
4756 if (!Xor.isAllOnesValue()) return 0;
4758 if (V1 == A || V1 == B) {
4759 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4760 return BinaryOperator::CreateOr(NewOp, V1);
4766 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4767 bool Changed = SimplifyCommutative(I);
4768 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4770 if (isa<UndefValue>(Op1)) // X | undef -> -1
4771 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4775 return ReplaceInstUsesWith(I, Op0);
4777 // See if we can simplify any instructions used by the instruction whose sole
4778 // purpose is to compute bits we don't care about.
4779 if (SimplifyDemandedInstructionBits(I))
4781 if (isa<VectorType>(I.getType())) {
4782 if (isa<ConstantAggregateZero>(Op1)) {
4783 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4784 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4785 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4786 return ReplaceInstUsesWith(I, I.getOperand(1));
4791 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4792 ConstantInt *C1 = 0; Value *X = 0;
4793 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4794 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4796 Value *Or = Builder->CreateOr(X, RHS);
4798 return BinaryOperator::CreateAnd(Or,
4799 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4802 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4803 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4805 Value *Or = Builder->CreateOr(X, RHS);
4807 return BinaryOperator::CreateXor(Or,
4808 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4811 // Try to fold constant and into select arguments.
4812 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4813 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4815 if (isa<PHINode>(Op0))
4816 if (Instruction *NV = FoldOpIntoPhi(I))
4820 Value *A = 0, *B = 0;
4821 ConstantInt *C1 = 0, *C2 = 0;
4823 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4824 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4825 return ReplaceInstUsesWith(I, Op1);
4826 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4827 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4828 return ReplaceInstUsesWith(I, Op0);
4830 // (A | B) | C and A | (B | C) -> bswap if possible.
4831 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4832 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4833 match(Op1, m_Or(m_Value(), m_Value())) ||
4834 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4835 match(Op1, m_Shift(m_Value(), m_Value())))) {
4836 if (Instruction *BSwap = MatchBSwap(I))
4840 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4841 if (Op0->hasOneUse() &&
4842 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4843 MaskedValueIsZero(Op1, C1->getValue())) {
4844 Value *NOr = Builder->CreateOr(A, Op1);
4846 return BinaryOperator::CreateXor(NOr, C1);
4849 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4850 if (Op1->hasOneUse() &&
4851 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4852 MaskedValueIsZero(Op0, C1->getValue())) {
4853 Value *NOr = Builder->CreateOr(A, Op0);
4855 return BinaryOperator::CreateXor(NOr, C1);
4859 Value *C = 0, *D = 0;
4860 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4861 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4862 Value *V1 = 0, *V2 = 0, *V3 = 0;
4863 C1 = dyn_cast<ConstantInt>(C);
4864 C2 = dyn_cast<ConstantInt>(D);
4865 if (C1 && C2) { // (A & C1)|(B & C2)
4866 // If we have: ((V + N) & C1) | (V & C2)
4867 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4868 // replace with V+N.
4869 if (C1->getValue() == ~C2->getValue()) {
4870 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4871 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4872 // Add commutes, try both ways.
4873 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4874 return ReplaceInstUsesWith(I, A);
4875 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4876 return ReplaceInstUsesWith(I, A);
4878 // Or commutes, try both ways.
4879 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4880 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4881 // Add commutes, try both ways.
4882 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4883 return ReplaceInstUsesWith(I, B);
4884 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4885 return ReplaceInstUsesWith(I, B);
4888 V1 = 0; V2 = 0; V3 = 0;
4891 // Check to see if we have any common things being and'ed. If so, find the
4892 // terms for V1 & (V2|V3).
4893 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4894 if (A == B) // (A & C)|(A & D) == A & (C|D)
4895 V1 = A, V2 = C, V3 = D;
4896 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4897 V1 = A, V2 = B, V3 = C;
4898 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4899 V1 = C, V2 = A, V3 = D;
4900 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4901 V1 = C, V2 = A, V3 = B;
4904 Value *Or = Builder->CreateOr(V2, V3, "tmp");
4905 return BinaryOperator::CreateAnd(V1, Or);
4909 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4910 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4912 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4914 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4916 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4919 // ((A&~B)|(~A&B)) -> A^B
4920 if ((match(C, m_Not(m_Specific(D))) &&
4921 match(B, m_Not(m_Specific(A)))))
4922 return BinaryOperator::CreateXor(A, D);
4923 // ((~B&A)|(~A&B)) -> A^B
4924 if ((match(A, m_Not(m_Specific(D))) &&
4925 match(B, m_Not(m_Specific(C)))))
4926 return BinaryOperator::CreateXor(C, D);
4927 // ((A&~B)|(B&~A)) -> A^B
4928 if ((match(C, m_Not(m_Specific(B))) &&
4929 match(D, m_Not(m_Specific(A)))))
4930 return BinaryOperator::CreateXor(A, B);
4931 // ((~B&A)|(B&~A)) -> A^B
4932 if ((match(A, m_Not(m_Specific(B))) &&
4933 match(D, m_Not(m_Specific(C)))))
4934 return BinaryOperator::CreateXor(C, B);
4937 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4938 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4939 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4940 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4941 SI0->getOperand(1) == SI1->getOperand(1) &&
4942 (SI0->hasOneUse() || SI1->hasOneUse())) {
4943 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4945 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4946 SI1->getOperand(1));
4950 // ((A|B)&1)|(B&-2) -> (A&1) | B
4951 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4952 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4953 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4954 if (Ret) return Ret;
4956 // (B&-2)|((A|B)&1) -> (A&1) | B
4957 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4958 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4959 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4960 if (Ret) return Ret;
4963 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4964 if (A == Op1) // ~A | A == -1
4965 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4969 // Note, A is still live here!
4970 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4972 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4974 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4975 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4976 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4977 return BinaryOperator::CreateNot(And);
4981 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4982 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4983 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4986 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4987 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4991 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4992 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4993 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4994 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4995 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4996 !isa<ICmpInst>(Op1C->getOperand(0))) {
4997 const Type *SrcTy = Op0C->getOperand(0)->getType();
4998 if (SrcTy == Op1C->getOperand(0)->getType() &&
4999 SrcTy->isIntOrIntVector() &&
5000 // Only do this if the casts both really cause code to be
5002 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5004 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5006 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5007 Op1C->getOperand(0), I.getName());
5008 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5015 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5016 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5017 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5018 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5022 return Changed ? &I : 0;
5027 // XorSelf - Implements: X ^ X --> 0
5030 XorSelf(Value *rhs) : RHS(rhs) {}
5031 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5032 Instruction *apply(BinaryOperator &Xor) const {
5039 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5040 bool Changed = SimplifyCommutative(I);
5041 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5043 if (isa<UndefValue>(Op1)) {
5044 if (isa<UndefValue>(Op0))
5045 // Handle undef ^ undef -> 0 special case. This is a common
5047 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5048 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
5051 // xor X, X = 0, even if X is nested in a sequence of Xor's.
5052 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5053 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5054 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5057 // See if we can simplify any instructions used by the instruction whose sole
5058 // purpose is to compute bits we don't care about.
5059 if (SimplifyDemandedInstructionBits(I))
5061 if (isa<VectorType>(I.getType()))
5062 if (isa<ConstantAggregateZero>(Op1))
5063 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
5065 // Is this a ~ operation?
5066 if (Value *NotOp = dyn_castNotVal(&I)) {
5067 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5068 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5069 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5070 if (Op0I->getOpcode() == Instruction::And ||
5071 Op0I->getOpcode() == Instruction::Or) {
5072 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5073 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5075 Builder->CreateNot(Op0I->getOperand(1),
5076 Op0I->getOperand(1)->getName()+".not");
5077 if (Op0I->getOpcode() == Instruction::And)
5078 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5079 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5086 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5087 if (RHS->isOne() && Op0->hasOneUse()) {
5088 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5089 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5090 return new ICmpInst(ICI->getInversePredicate(),
5091 ICI->getOperand(0), ICI->getOperand(1));
5093 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5094 return new FCmpInst(FCI->getInversePredicate(),
5095 FCI->getOperand(0), FCI->getOperand(1));
5098 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5099 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5100 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5101 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5102 Instruction::CastOps Opcode = Op0C->getOpcode();
5103 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5104 (RHS == ConstantExpr::getCast(Opcode,
5105 ConstantInt::getTrue(*Context),
5106 Op0C->getDestTy()))) {
5107 CI->setPredicate(CI->getInversePredicate());
5108 return CastInst::Create(Opcode, CI, Op0C->getType());
5114 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5115 // ~(c-X) == X-c-1 == X+(-c-1)
5116 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5117 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5118 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5119 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5120 ConstantInt::get(I.getType(), 1));
5121 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5124 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5125 if (Op0I->getOpcode() == Instruction::Add) {
5126 // ~(X-c) --> (-c-1)-X
5127 if (RHS->isAllOnesValue()) {
5128 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5129 return BinaryOperator::CreateSub(
5130 ConstantExpr::getSub(NegOp0CI,
5131 ConstantInt::get(I.getType(), 1)),
5132 Op0I->getOperand(0));
5133 } else if (RHS->getValue().isSignBit()) {
5134 // (X + C) ^ signbit -> (X + C + signbit)
5135 Constant *C = ConstantInt::get(*Context,
5136 RHS->getValue() + Op0CI->getValue());
5137 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5140 } else if (Op0I->getOpcode() == Instruction::Or) {
5141 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5142 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5143 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5144 // Anything in both C1 and C2 is known to be zero, remove it from
5146 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5147 NewRHS = ConstantExpr::getAnd(NewRHS,
5148 ConstantExpr::getNot(CommonBits));
5150 I.setOperand(0, Op0I->getOperand(0));
5151 I.setOperand(1, NewRHS);
5158 // Try to fold constant and into select arguments.
5159 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5160 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5162 if (isa<PHINode>(Op0))
5163 if (Instruction *NV = FoldOpIntoPhi(I))
5167 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5169 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5171 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5173 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5176 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5179 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5180 if (A == Op0) { // B^(B|A) == (A|B)^B
5181 Op1I->swapOperands();
5183 std::swap(Op0, Op1);
5184 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5185 I.swapOperands(); // Simplified below.
5186 std::swap(Op0, Op1);
5188 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5189 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5190 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5191 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5192 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
5194 if (A == Op0) { // A^(A&B) -> A^(B&A)
5195 Op1I->swapOperands();
5198 if (B == Op0) { // A^(B&A) -> (B&A)^A
5199 I.swapOperands(); // Simplified below.
5200 std::swap(Op0, Op1);
5205 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5208 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5209 Op0I->hasOneUse()) {
5210 if (A == Op1) // (B|A)^B == (A|B)^B
5212 if (B == Op1) // (A|B)^B == A & ~B
5213 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5214 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5215 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5216 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5217 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5218 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5220 if (A == Op1) // (A&B)^A -> (B&A)^A
5222 if (B == Op1 && // (B&A)^A == ~B & A
5223 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5224 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5229 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5230 if (Op0I && Op1I && Op0I->isShift() &&
5231 Op0I->getOpcode() == Op1I->getOpcode() &&
5232 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5233 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5235 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5237 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5238 Op1I->getOperand(1));
5242 Value *A, *B, *C, *D;
5243 // (A & B)^(A | B) -> A ^ B
5244 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5245 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5246 if ((A == C && B == D) || (A == D && B == C))
5247 return BinaryOperator::CreateXor(A, B);
5249 // (A | B)^(A & B) -> A ^ B
5250 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5251 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5252 if ((A == C && B == D) || (A == D && B == C))
5253 return BinaryOperator::CreateXor(A, B);
5257 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5258 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5259 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5260 // (X & Y)^(X & Y) -> (Y^Z) & X
5261 Value *X = 0, *Y = 0, *Z = 0;
5263 X = A, Y = B, Z = D;
5265 X = A, Y = B, Z = C;
5267 X = B, Y = A, Z = D;
5269 X = B, Y = A, Z = C;
5272 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5273 return BinaryOperator::CreateAnd(NewOp, X);
5278 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5279 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5280 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5283 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5284 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5285 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5286 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5287 const Type *SrcTy = Op0C->getOperand(0)->getType();
5288 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5289 // Only do this if the casts both really cause code to be generated.
5290 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5292 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5294 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5295 Op1C->getOperand(0), I.getName());
5296 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5301 return Changed ? &I : 0;
5304 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5305 LLVMContext *Context) {
5306 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5309 static bool HasAddOverflow(ConstantInt *Result,
5310 ConstantInt *In1, ConstantInt *In2,
5313 if (In2->getValue().isNegative())
5314 return Result->getValue().sgt(In1->getValue());
5316 return Result->getValue().slt(In1->getValue());
5318 return Result->getValue().ult(In1->getValue());
5321 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5322 /// overflowed for this type.
5323 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5324 Constant *In2, LLVMContext *Context,
5325 bool IsSigned = false) {
5326 Result = ConstantExpr::getAdd(In1, In2);
5328 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5329 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5330 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5331 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5332 ExtractElement(In1, Idx, Context),
5333 ExtractElement(In2, Idx, Context),
5340 return HasAddOverflow(cast<ConstantInt>(Result),
5341 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5345 static bool HasSubOverflow(ConstantInt *Result,
5346 ConstantInt *In1, ConstantInt *In2,
5349 if (In2->getValue().isNegative())
5350 return Result->getValue().slt(In1->getValue());
5352 return Result->getValue().sgt(In1->getValue());
5354 return Result->getValue().ugt(In1->getValue());
5357 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5358 /// overflowed for this type.
5359 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5360 Constant *In2, LLVMContext *Context,
5361 bool IsSigned = false) {
5362 Result = ConstantExpr::getSub(In1, In2);
5364 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5365 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5366 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5367 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5368 ExtractElement(In1, Idx, Context),
5369 ExtractElement(In2, Idx, Context),
5376 return HasSubOverflow(cast<ConstantInt>(Result),
5377 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5381 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5382 /// code necessary to compute the offset from the base pointer (without adding
5383 /// in the base pointer). Return the result as a signed integer of intptr size.
5384 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5385 TargetData &TD = *IC.getTargetData();
5386 gep_type_iterator GTI = gep_type_begin(GEP);
5387 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5388 Value *Result = Constant::getNullValue(IntPtrTy);
5390 // Build a mask for high order bits.
5391 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5392 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5394 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5397 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5398 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5399 if (OpC->isZero()) continue;
5401 // Handle a struct index, which adds its field offset to the pointer.
5402 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5403 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5405 Result = IC.Builder->CreateAdd(Result,
5406 ConstantInt::get(IntPtrTy, Size),
5407 GEP->getName()+".offs");
5411 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5413 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5414 Scale = ConstantExpr::getMul(OC, Scale);
5415 // Emit an add instruction.
5416 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5419 // Convert to correct type.
5420 if (Op->getType() != IntPtrTy)
5421 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5423 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5424 // We'll let instcombine(mul) convert this to a shl if possible.
5425 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5428 // Emit an add instruction.
5429 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5435 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5436 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5437 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5438 /// be complex, and scales are involved. The above expression would also be
5439 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5440 /// This later form is less amenable to optimization though, and we are allowed
5441 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5443 /// If we can't emit an optimized form for this expression, this returns null.
5445 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5447 TargetData &TD = *IC.getTargetData();
5448 gep_type_iterator GTI = gep_type_begin(GEP);
5450 // Check to see if this gep only has a single variable index. If so, and if
5451 // any constant indices are a multiple of its scale, then we can compute this
5452 // in terms of the scale of the variable index. For example, if the GEP
5453 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5454 // because the expression will cross zero at the same point.
5455 unsigned i, e = GEP->getNumOperands();
5457 for (i = 1; i != e; ++i, ++GTI) {
5458 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5459 // Compute the aggregate offset of constant indices.
5460 if (CI->isZero()) continue;
5462 // Handle a struct index, which adds its field offset to the pointer.
5463 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5464 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5466 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5467 Offset += Size*CI->getSExtValue();
5470 // Found our variable index.
5475 // If there are no variable indices, we must have a constant offset, just
5476 // evaluate it the general way.
5477 if (i == e) return 0;
5479 Value *VariableIdx = GEP->getOperand(i);
5480 // Determine the scale factor of the variable element. For example, this is
5481 // 4 if the variable index is into an array of i32.
5482 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5484 // Verify that there are no other variable indices. If so, emit the hard way.
5485 for (++i, ++GTI; i != e; ++i, ++GTI) {
5486 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5489 // Compute the aggregate offset of constant indices.
5490 if (CI->isZero()) continue;
5492 // Handle a struct index, which adds its field offset to the pointer.
5493 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5494 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5496 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5497 Offset += Size*CI->getSExtValue();
5501 // Okay, we know we have a single variable index, which must be a
5502 // pointer/array/vector index. If there is no offset, life is simple, return
5504 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5506 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5507 // we don't need to bother extending: the extension won't affect where the
5508 // computation crosses zero.
5509 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5510 VariableIdx = new TruncInst(VariableIdx,
5511 TD.getIntPtrType(VariableIdx->getContext()),
5512 VariableIdx->getName(), &I);
5516 // Otherwise, there is an index. The computation we will do will be modulo
5517 // the pointer size, so get it.
5518 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5520 Offset &= PtrSizeMask;
5521 VariableScale &= PtrSizeMask;
5523 // To do this transformation, any constant index must be a multiple of the
5524 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5525 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5526 // multiple of the variable scale.
5527 int64_t NewOffs = Offset / (int64_t)VariableScale;
5528 if (Offset != NewOffs*(int64_t)VariableScale)
5531 // Okay, we can do this evaluation. Start by converting the index to intptr.
5532 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5533 if (VariableIdx->getType() != IntPtrTy)
5534 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5536 VariableIdx->getName(), &I);
5537 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5538 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5542 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5543 /// else. At this point we know that the GEP is on the LHS of the comparison.
5544 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5545 ICmpInst::Predicate Cond,
5547 // Look through bitcasts.
5548 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5549 RHS = BCI->getOperand(0);
5551 Value *PtrBase = GEPLHS->getOperand(0);
5552 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5553 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5554 // This transformation (ignoring the base and scales) is valid because we
5555 // know pointers can't overflow since the gep is inbounds. See if we can
5556 // output an optimized form.
5557 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5559 // If not, synthesize the offset the hard way.
5561 Offset = EmitGEPOffset(GEPLHS, I, *this);
5562 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5563 Constant::getNullValue(Offset->getType()));
5564 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5565 // If the base pointers are different, but the indices are the same, just
5566 // compare the base pointer.
5567 if (PtrBase != GEPRHS->getOperand(0)) {
5568 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5569 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5570 GEPRHS->getOperand(0)->getType();
5572 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5573 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5574 IndicesTheSame = false;
5578 // If all indices are the same, just compare the base pointers.
5580 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5581 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5583 // Otherwise, the base pointers are different and the indices are
5584 // different, bail out.
5588 // If one of the GEPs has all zero indices, recurse.
5589 bool AllZeros = true;
5590 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5591 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5592 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5597 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5598 ICmpInst::getSwappedPredicate(Cond), I);
5600 // If the other GEP has all zero indices, recurse.
5602 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5603 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5604 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5609 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5611 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5612 // If the GEPs only differ by one index, compare it.
5613 unsigned NumDifferences = 0; // Keep track of # differences.
5614 unsigned DiffOperand = 0; // The operand that differs.
5615 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5616 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5617 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5618 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5619 // Irreconcilable differences.
5623 if (NumDifferences++) break;
5628 if (NumDifferences == 0) // SAME GEP?
5629 return ReplaceInstUsesWith(I, // No comparison is needed here.
5630 ConstantInt::get(Type::getInt1Ty(*Context),
5631 ICmpInst::isTrueWhenEqual(Cond)));
5633 else if (NumDifferences == 1) {
5634 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5635 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5636 // Make sure we do a signed comparison here.
5637 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5641 // Only lower this if the icmp is the only user of the GEP or if we expect
5642 // the result to fold to a constant!
5644 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5645 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5646 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5647 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5648 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5649 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5655 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5657 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5660 if (!isa<ConstantFP>(RHSC)) return 0;
5661 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5663 // Get the width of the mantissa. We don't want to hack on conversions that
5664 // might lose information from the integer, e.g. "i64 -> float"
5665 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5666 if (MantissaWidth == -1) return 0; // Unknown.
5668 // Check to see that the input is converted from an integer type that is small
5669 // enough that preserves all bits. TODO: check here for "known" sign bits.
5670 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5671 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5673 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5674 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5678 // If the conversion would lose info, don't hack on this.
5679 if ((int)InputSize > MantissaWidth)
5682 // Otherwise, we can potentially simplify the comparison. We know that it
5683 // will always come through as an integer value and we know the constant is
5684 // not a NAN (it would have been previously simplified).
5685 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5687 ICmpInst::Predicate Pred;
5688 switch (I.getPredicate()) {
5689 default: llvm_unreachable("Unexpected predicate!");
5690 case FCmpInst::FCMP_UEQ:
5691 case FCmpInst::FCMP_OEQ:
5692 Pred = ICmpInst::ICMP_EQ;
5694 case FCmpInst::FCMP_UGT:
5695 case FCmpInst::FCMP_OGT:
5696 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5698 case FCmpInst::FCMP_UGE:
5699 case FCmpInst::FCMP_OGE:
5700 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5702 case FCmpInst::FCMP_ULT:
5703 case FCmpInst::FCMP_OLT:
5704 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5706 case FCmpInst::FCMP_ULE:
5707 case FCmpInst::FCMP_OLE:
5708 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5710 case FCmpInst::FCMP_UNE:
5711 case FCmpInst::FCMP_ONE:
5712 Pred = ICmpInst::ICMP_NE;
5714 case FCmpInst::FCMP_ORD:
5715 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5716 case FCmpInst::FCMP_UNO:
5717 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5720 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5722 // Now we know that the APFloat is a normal number, zero or inf.
5724 // See if the FP constant is too large for the integer. For example,
5725 // comparing an i8 to 300.0.
5726 unsigned IntWidth = IntTy->getScalarSizeInBits();
5729 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5730 // and large values.
5731 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5732 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5733 APFloat::rmNearestTiesToEven);
5734 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5735 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5736 Pred == ICmpInst::ICMP_SLE)
5737 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5738 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5741 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5742 // +INF and large values.
5743 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5744 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5745 APFloat::rmNearestTiesToEven);
5746 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5747 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5748 Pred == ICmpInst::ICMP_ULE)
5749 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5750 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5755 // See if the RHS value is < SignedMin.
5756 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5757 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5758 APFloat::rmNearestTiesToEven);
5759 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5760 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5761 Pred == ICmpInst::ICMP_SGE)
5762 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5763 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5767 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5768 // [0, UMAX], but it may still be fractional. See if it is fractional by
5769 // casting the FP value to the integer value and back, checking for equality.
5770 // Don't do this for zero, because -0.0 is not fractional.
5771 Constant *RHSInt = LHSUnsigned
5772 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5773 : ConstantExpr::getFPToSI(RHSC, IntTy);
5774 if (!RHS.isZero()) {
5775 bool Equal = LHSUnsigned
5776 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5777 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5779 // If we had a comparison against a fractional value, we have to adjust
5780 // the compare predicate and sometimes the value. RHSC is rounded towards
5781 // zero at this point.
5783 default: llvm_unreachable("Unexpected integer comparison!");
5784 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5785 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5786 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5787 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5788 case ICmpInst::ICMP_ULE:
5789 // (float)int <= 4.4 --> int <= 4
5790 // (float)int <= -4.4 --> false
5791 if (RHS.isNegative())
5792 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5794 case ICmpInst::ICMP_SLE:
5795 // (float)int <= 4.4 --> int <= 4
5796 // (float)int <= -4.4 --> int < -4
5797 if (RHS.isNegative())
5798 Pred = ICmpInst::ICMP_SLT;
5800 case ICmpInst::ICMP_ULT:
5801 // (float)int < -4.4 --> false
5802 // (float)int < 4.4 --> int <= 4
5803 if (RHS.isNegative())
5804 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5805 Pred = ICmpInst::ICMP_ULE;
5807 case ICmpInst::ICMP_SLT:
5808 // (float)int < -4.4 --> int < -4
5809 // (float)int < 4.4 --> int <= 4
5810 if (!RHS.isNegative())
5811 Pred = ICmpInst::ICMP_SLE;
5813 case ICmpInst::ICMP_UGT:
5814 // (float)int > 4.4 --> int > 4
5815 // (float)int > -4.4 --> true
5816 if (RHS.isNegative())
5817 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5819 case ICmpInst::ICMP_SGT:
5820 // (float)int > 4.4 --> int > 4
5821 // (float)int > -4.4 --> int >= -4
5822 if (RHS.isNegative())
5823 Pred = ICmpInst::ICMP_SGE;
5825 case ICmpInst::ICMP_UGE:
5826 // (float)int >= -4.4 --> true
5827 // (float)int >= 4.4 --> int > 4
5828 if (!RHS.isNegative())
5829 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5830 Pred = ICmpInst::ICMP_UGT;
5832 case ICmpInst::ICMP_SGE:
5833 // (float)int >= -4.4 --> int >= -4
5834 // (float)int >= 4.4 --> int > 4
5835 if (!RHS.isNegative())
5836 Pred = ICmpInst::ICMP_SGT;
5842 // Lower this FP comparison into an appropriate integer version of the
5844 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5847 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5848 bool Changed = SimplifyCompare(I);
5849 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5851 // Fold trivial predicates.
5852 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5853 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5854 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5855 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5857 // Simplify 'fcmp pred X, X'
5859 switch (I.getPredicate()) {
5860 default: llvm_unreachable("Unknown predicate!");
5861 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5862 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5863 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5864 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5865 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5866 case FCmpInst::FCMP_OLT: // True if ordered and less than
5867 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5868 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5870 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5871 case FCmpInst::FCMP_ULT: // True if unordered or less than
5872 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5873 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5874 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5875 I.setPredicate(FCmpInst::FCMP_UNO);
5876 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5879 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5880 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5881 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5882 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5883 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5884 I.setPredicate(FCmpInst::FCMP_ORD);
5885 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5890 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5891 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5893 // Handle fcmp with constant RHS
5894 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5895 // If the constant is a nan, see if we can fold the comparison based on it.
5896 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5897 if (CFP->getValueAPF().isNaN()) {
5898 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5899 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5900 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5901 "Comparison must be either ordered or unordered!");
5902 // True if unordered.
5903 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5907 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5908 switch (LHSI->getOpcode()) {
5909 case Instruction::PHI:
5910 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5911 // block. If in the same block, we're encouraging jump threading. If
5912 // not, we are just pessimizing the code by making an i1 phi.
5913 if (LHSI->getParent() == I.getParent())
5914 if (Instruction *NV = FoldOpIntoPhi(I, true))
5917 case Instruction::SIToFP:
5918 case Instruction::UIToFP:
5919 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5922 case Instruction::Select:
5923 // If either operand of the select is a constant, we can fold the
5924 // comparison into the select arms, which will cause one to be
5925 // constant folded and the select turned into a bitwise or.
5926 Value *Op1 = 0, *Op2 = 0;
5927 if (LHSI->hasOneUse()) {
5928 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5929 // Fold the known value into the constant operand.
5930 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5931 // Insert a new FCmp of the other select operand.
5932 Op2 = Builder->CreateFCmp(I.getPredicate(),
5933 LHSI->getOperand(2), RHSC, I.getName());
5934 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5935 // Fold the known value into the constant operand.
5936 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5937 // Insert a new FCmp of the other select operand.
5938 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5944 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5949 return Changed ? &I : 0;
5952 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5953 bool Changed = SimplifyCompare(I);
5954 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5955 const Type *Ty = Op0->getType();
5959 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
5960 I.isTrueWhenEqual()));
5962 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5963 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5965 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5966 // addresses never equal each other! We already know that Op0 != Op1.
5967 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5968 isa<ConstantPointerNull>(Op0)) &&
5969 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5970 isa<ConstantPointerNull>(Op1)))
5971 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
5972 !I.isTrueWhenEqual()));
5974 // icmp's with boolean values can always be turned into bitwise operations
5975 if (Ty == Type::getInt1Ty(*Context)) {
5976 switch (I.getPredicate()) {
5977 default: llvm_unreachable("Invalid icmp instruction!");
5978 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5979 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5980 return BinaryOperator::CreateNot(Xor);
5982 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5983 return BinaryOperator::CreateXor(Op0, Op1);
5985 case ICmpInst::ICMP_UGT:
5986 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5988 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5989 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5990 return BinaryOperator::CreateAnd(Not, Op1);
5992 case ICmpInst::ICMP_SGT:
5993 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
5995 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5996 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5997 return BinaryOperator::CreateAnd(Not, Op0);
5999 case ICmpInst::ICMP_UGE:
6000 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6002 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
6003 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6004 return BinaryOperator::CreateOr(Not, Op1);
6006 case ICmpInst::ICMP_SGE:
6007 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6009 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
6010 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6011 return BinaryOperator::CreateOr(Not, Op0);
6016 unsigned BitWidth = 0;
6018 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6019 else if (Ty->isIntOrIntVector())
6020 BitWidth = Ty->getScalarSizeInBits();
6022 bool isSignBit = false;
6024 // See if we are doing a comparison with a constant.
6025 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6026 Value *A = 0, *B = 0;
6028 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6029 if (I.isEquality() && CI->isNullValue() &&
6030 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6031 // (icmp cond A B) if cond is equality
6032 return new ICmpInst(I.getPredicate(), A, B);
6035 // If we have an icmp le or icmp ge instruction, turn it into the
6036 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6037 // them being folded in the code below.
6038 switch (I.getPredicate()) {
6040 case ICmpInst::ICMP_ULE:
6041 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
6042 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6043 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6045 case ICmpInst::ICMP_SLE:
6046 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
6047 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6048 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6050 case ICmpInst::ICMP_UGE:
6051 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6052 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6053 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6055 case ICmpInst::ICMP_SGE:
6056 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6057 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6058 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6062 // If this comparison is a normal comparison, it demands all
6063 // bits, if it is a sign bit comparison, it only demands the sign bit.
6065 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6068 // See if we can fold the comparison based on range information we can get
6069 // by checking whether bits are known to be zero or one in the input.
6070 if (BitWidth != 0) {
6071 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6072 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6074 if (SimplifyDemandedBits(I.getOperandUse(0),
6075 isSignBit ? APInt::getSignBit(BitWidth)
6076 : APInt::getAllOnesValue(BitWidth),
6077 Op0KnownZero, Op0KnownOne, 0))
6079 if (SimplifyDemandedBits(I.getOperandUse(1),
6080 APInt::getAllOnesValue(BitWidth),
6081 Op1KnownZero, Op1KnownOne, 0))
6084 // Given the known and unknown bits, compute a range that the LHS could be
6085 // in. Compute the Min, Max and RHS values based on the known bits. For the
6086 // EQ and NE we use unsigned values.
6087 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6088 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6089 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6090 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6092 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6095 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6097 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6101 // If Min and Max are known to be the same, then SimplifyDemandedBits
6102 // figured out that the LHS is a constant. Just constant fold this now so
6103 // that code below can assume that Min != Max.
6104 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6105 return new ICmpInst(I.getPredicate(),
6106 ConstantInt::get(*Context, Op0Min), Op1);
6107 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6108 return new ICmpInst(I.getPredicate(), Op0,
6109 ConstantInt::get(*Context, Op1Min));
6111 // Based on the range information we know about the LHS, see if we can
6112 // simplify this comparison. For example, (x&4) < 8 is always true.
6113 switch (I.getPredicate()) {
6114 default: llvm_unreachable("Unknown icmp opcode!");
6115 case ICmpInst::ICMP_EQ:
6116 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6117 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6119 case ICmpInst::ICMP_NE:
6120 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6121 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6123 case ICmpInst::ICMP_ULT:
6124 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6125 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6126 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6127 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6128 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6129 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6130 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6131 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6132 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6135 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6136 if (CI->isMinValue(true))
6137 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6138 Constant::getAllOnesValue(Op0->getType()));
6141 case ICmpInst::ICMP_UGT:
6142 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6143 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6144 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6145 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6147 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6148 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6149 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6150 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6151 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6154 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6155 if (CI->isMaxValue(true))
6156 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6157 Constant::getNullValue(Op0->getType()));
6160 case ICmpInst::ICMP_SLT:
6161 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6162 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6163 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6164 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6165 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6166 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6167 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6168 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6169 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6173 case ICmpInst::ICMP_SGT:
6174 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6175 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6176 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6177 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6179 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6180 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6181 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6182 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6183 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6187 case ICmpInst::ICMP_SGE:
6188 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6189 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6190 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6191 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6192 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6194 case ICmpInst::ICMP_SLE:
6195 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6196 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6197 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6198 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6199 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6201 case ICmpInst::ICMP_UGE:
6202 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6203 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6204 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6205 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6206 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6208 case ICmpInst::ICMP_ULE:
6209 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6210 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6211 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6212 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6213 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6217 // Turn a signed comparison into an unsigned one if both operands
6218 // are known to have the same sign.
6219 if (I.isSignedPredicate() &&
6220 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6221 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6222 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6225 // Test if the ICmpInst instruction is used exclusively by a select as
6226 // part of a minimum or maximum operation. If so, refrain from doing
6227 // any other folding. This helps out other analyses which understand
6228 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6229 // and CodeGen. And in this case, at least one of the comparison
6230 // operands has at least one user besides the compare (the select),
6231 // which would often largely negate the benefit of folding anyway.
6233 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6234 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6235 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6238 // See if we are doing a comparison between a constant and an instruction that
6239 // can be folded into the comparison.
6240 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6241 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6242 // instruction, see if that instruction also has constants so that the
6243 // instruction can be folded into the icmp
6244 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6245 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6249 // Handle icmp with constant (but not simple integer constant) RHS
6250 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6251 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6252 switch (LHSI->getOpcode()) {
6253 case Instruction::GetElementPtr:
6254 if (RHSC->isNullValue()) {
6255 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6256 bool isAllZeros = true;
6257 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6258 if (!isa<Constant>(LHSI->getOperand(i)) ||
6259 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6264 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6265 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6269 case Instruction::PHI:
6270 // Only fold icmp into the PHI if the phi and icmp are in the same
6271 // block. If in the same block, we're encouraging jump threading. If
6272 // not, we are just pessimizing the code by making an i1 phi.
6273 if (LHSI->getParent() == I.getParent())
6274 if (Instruction *NV = FoldOpIntoPhi(I, true))
6277 case Instruction::Select: {
6278 // If either operand of the select is a constant, we can fold the
6279 // comparison into the select arms, which will cause one to be
6280 // constant folded and the select turned into a bitwise or.
6281 Value *Op1 = 0, *Op2 = 0;
6282 if (LHSI->hasOneUse()) {
6283 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6284 // Fold the known value into the constant operand.
6285 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6286 // Insert a new ICmp of the other select operand.
6287 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6289 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6290 // Fold the known value into the constant operand.
6291 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6292 // Insert a new ICmp of the other select operand.
6293 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6299 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6302 case Instruction::Malloc:
6303 // If we have (malloc != null), and if the malloc has a single use, we
6304 // can assume it is successful and remove the malloc.
6305 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6307 return ReplaceInstUsesWith(I,
6308 ConstantInt::get(Type::getInt1Ty(*Context),
6309 !I.isTrueWhenEqual()));
6312 case Instruction::Call:
6313 // If we have (malloc != null), and if the malloc has a single use, we
6314 // can assume it is successful and remove the malloc.
6315 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6316 isa<ConstantPointerNull>(RHSC)) {
6318 return ReplaceInstUsesWith(I,
6319 ConstantInt::get(Type::getInt1Ty(*Context),
6320 !I.isTrueWhenEqual()));
6326 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6327 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6328 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6330 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6331 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6332 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6335 // Test to see if the operands of the icmp are casted versions of other
6336 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6338 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6339 if (isa<PointerType>(Op0->getType()) &&
6340 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6341 // We keep moving the cast from the left operand over to the right
6342 // operand, where it can often be eliminated completely.
6343 Op0 = CI->getOperand(0);
6345 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6346 // so eliminate it as well.
6347 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6348 Op1 = CI2->getOperand(0);
6350 // If Op1 is a constant, we can fold the cast into the constant.
6351 if (Op0->getType() != Op1->getType()) {
6352 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6353 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6355 // Otherwise, cast the RHS right before the icmp
6356 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6359 return new ICmpInst(I.getPredicate(), Op0, Op1);
6363 if (isa<CastInst>(Op0)) {
6364 // Handle the special case of: icmp (cast bool to X), <cst>
6365 // This comes up when you have code like
6368 // For generality, we handle any zero-extension of any operand comparison
6369 // with a constant or another cast from the same type.
6370 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6371 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6375 // See if it's the same type of instruction on the left and right.
6376 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6377 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6378 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6379 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6380 switch (Op0I->getOpcode()) {
6382 case Instruction::Add:
6383 case Instruction::Sub:
6384 case Instruction::Xor:
6385 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6386 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6387 Op1I->getOperand(0));
6388 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6389 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6390 if (CI->getValue().isSignBit()) {
6391 ICmpInst::Predicate Pred = I.isSignedPredicate()
6392 ? I.getUnsignedPredicate()
6393 : I.getSignedPredicate();
6394 return new ICmpInst(Pred, Op0I->getOperand(0),
6395 Op1I->getOperand(0));
6398 if (CI->getValue().isMaxSignedValue()) {
6399 ICmpInst::Predicate Pred = I.isSignedPredicate()
6400 ? I.getUnsignedPredicate()
6401 : I.getSignedPredicate();
6402 Pred = I.getSwappedPredicate(Pred);
6403 return new ICmpInst(Pred, Op0I->getOperand(0),
6404 Op1I->getOperand(0));
6408 case Instruction::Mul:
6409 if (!I.isEquality())
6412 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6413 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6414 // Mask = -1 >> count-trailing-zeros(Cst).
6415 if (!CI->isZero() && !CI->isOne()) {
6416 const APInt &AP = CI->getValue();
6417 ConstantInt *Mask = ConstantInt::get(*Context,
6418 APInt::getLowBitsSet(AP.getBitWidth(),
6420 AP.countTrailingZeros()));
6421 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6422 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6423 return new ICmpInst(I.getPredicate(), And1, And2);
6432 // ~x < ~y --> y < x
6434 if (match(Op0, m_Not(m_Value(A))) &&
6435 match(Op1, m_Not(m_Value(B))))
6436 return new ICmpInst(I.getPredicate(), B, A);
6439 if (I.isEquality()) {
6440 Value *A, *B, *C, *D;
6442 // -x == -y --> x == y
6443 if (match(Op0, m_Neg(m_Value(A))) &&
6444 match(Op1, m_Neg(m_Value(B))))
6445 return new ICmpInst(I.getPredicate(), A, B);
6447 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6448 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6449 Value *OtherVal = A == Op1 ? B : A;
6450 return new ICmpInst(I.getPredicate(), OtherVal,
6451 Constant::getNullValue(A->getType()));
6454 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6455 // A^c1 == C^c2 --> A == C^(c1^c2)
6456 ConstantInt *C1, *C2;
6457 if (match(B, m_ConstantInt(C1)) &&
6458 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6460 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6461 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6462 return new ICmpInst(I.getPredicate(), A, Xor);
6465 // A^B == A^D -> B == D
6466 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6467 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6468 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6469 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6473 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6474 (A == Op0 || B == Op0)) {
6475 // A == (A^B) -> B == 0
6476 Value *OtherVal = A == Op0 ? B : A;
6477 return new ICmpInst(I.getPredicate(), OtherVal,
6478 Constant::getNullValue(A->getType()));
6481 // (A-B) == A -> B == 0
6482 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6483 return new ICmpInst(I.getPredicate(), B,
6484 Constant::getNullValue(B->getType()));
6486 // A == (A-B) -> B == 0
6487 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6488 return new ICmpInst(I.getPredicate(), B,
6489 Constant::getNullValue(B->getType()));
6491 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6492 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6493 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6494 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6495 Value *X = 0, *Y = 0, *Z = 0;
6498 X = B; Y = D; Z = A;
6499 } else if (A == D) {
6500 X = B; Y = C; Z = A;
6501 } else if (B == C) {
6502 X = A; Y = D; Z = B;
6503 } else if (B == D) {
6504 X = A; Y = C; Z = B;
6507 if (X) { // Build (X^Y) & Z
6508 Op1 = Builder->CreateXor(X, Y, "tmp");
6509 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6510 I.setOperand(0, Op1);
6511 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6516 return Changed ? &I : 0;
6520 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6521 /// and CmpRHS are both known to be integer constants.
6522 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6523 ConstantInt *DivRHS) {
6524 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6525 const APInt &CmpRHSV = CmpRHS->getValue();
6527 // FIXME: If the operand types don't match the type of the divide
6528 // then don't attempt this transform. The code below doesn't have the
6529 // logic to deal with a signed divide and an unsigned compare (and
6530 // vice versa). This is because (x /s C1) <s C2 produces different
6531 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6532 // (x /u C1) <u C2. Simply casting the operands and result won't
6533 // work. :( The if statement below tests that condition and bails
6535 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6536 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6538 if (DivRHS->isZero())
6539 return 0; // The ProdOV computation fails on divide by zero.
6540 if (DivIsSigned && DivRHS->isAllOnesValue())
6541 return 0; // The overflow computation also screws up here
6542 if (DivRHS->isOne())
6543 return 0; // Not worth bothering, and eliminates some funny cases
6546 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6547 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6548 // C2 (CI). By solving for X we can turn this into a range check
6549 // instead of computing a divide.
6550 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6552 // Determine if the product overflows by seeing if the product is
6553 // not equal to the divide. Make sure we do the same kind of divide
6554 // as in the LHS instruction that we're folding.
6555 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6556 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6558 // Get the ICmp opcode
6559 ICmpInst::Predicate Pred = ICI.getPredicate();
6561 // Figure out the interval that is being checked. For example, a comparison
6562 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6563 // Compute this interval based on the constants involved and the signedness of
6564 // the compare/divide. This computes a half-open interval, keeping track of
6565 // whether either value in the interval overflows. After analysis each
6566 // overflow variable is set to 0 if it's corresponding bound variable is valid
6567 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6568 int LoOverflow = 0, HiOverflow = 0;
6569 Constant *LoBound = 0, *HiBound = 0;
6571 if (!DivIsSigned) { // udiv
6572 // e.g. X/5 op 3 --> [15, 20)
6574 HiOverflow = LoOverflow = ProdOV;
6576 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6577 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6578 if (CmpRHSV == 0) { // (X / pos) op 0
6579 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6580 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6582 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6583 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6584 HiOverflow = LoOverflow = ProdOV;
6586 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6587 } else { // (X / pos) op neg
6588 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6589 HiBound = AddOne(Prod);
6590 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6592 ConstantInt* DivNeg =
6593 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6594 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6598 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6599 if (CmpRHSV == 0) { // (X / neg) op 0
6600 // e.g. X/-5 op 0 --> [-4, 5)
6601 LoBound = AddOne(DivRHS);
6602 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6603 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6604 HiOverflow = 1; // [INTMIN+1, overflow)
6605 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6607 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6608 // e.g. X/-5 op 3 --> [-19, -14)
6609 HiBound = AddOne(Prod);
6610 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6612 LoOverflow = AddWithOverflow(LoBound, HiBound,
6613 DivRHS, Context, true) ? -1 : 0;
6614 } else { // (X / neg) op neg
6615 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6616 LoOverflow = HiOverflow = ProdOV;
6618 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6621 // Dividing by a negative swaps the condition. LT <-> GT
6622 Pred = ICmpInst::getSwappedPredicate(Pred);
6625 Value *X = DivI->getOperand(0);
6627 default: llvm_unreachable("Unhandled icmp opcode!");
6628 case ICmpInst::ICMP_EQ:
6629 if (LoOverflow && HiOverflow)
6630 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6631 else if (HiOverflow)
6632 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6633 ICmpInst::ICMP_UGE, X, LoBound);
6634 else if (LoOverflow)
6635 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6636 ICmpInst::ICMP_ULT, X, HiBound);
6638 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6639 case ICmpInst::ICMP_NE:
6640 if (LoOverflow && HiOverflow)
6641 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6642 else if (HiOverflow)
6643 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6644 ICmpInst::ICMP_ULT, X, LoBound);
6645 else if (LoOverflow)
6646 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6647 ICmpInst::ICMP_UGE, X, HiBound);
6649 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6650 case ICmpInst::ICMP_ULT:
6651 case ICmpInst::ICMP_SLT:
6652 if (LoOverflow == +1) // Low bound is greater than input range.
6653 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6654 if (LoOverflow == -1) // Low bound is less than input range.
6655 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6656 return new ICmpInst(Pred, X, LoBound);
6657 case ICmpInst::ICMP_UGT:
6658 case ICmpInst::ICMP_SGT:
6659 if (HiOverflow == +1) // High bound greater than input range.
6660 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6661 else if (HiOverflow == -1) // High bound less than input range.
6662 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6663 if (Pred == ICmpInst::ICMP_UGT)
6664 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6666 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6671 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6673 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6676 const APInt &RHSV = RHS->getValue();
6678 switch (LHSI->getOpcode()) {
6679 case Instruction::Trunc:
6680 if (ICI.isEquality() && LHSI->hasOneUse()) {
6681 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6682 // of the high bits truncated out of x are known.
6683 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6684 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6685 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6686 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6687 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6689 // If all the high bits are known, we can do this xform.
6690 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6691 // Pull in the high bits from known-ones set.
6692 APInt NewRHS(RHS->getValue());
6693 NewRHS.zext(SrcBits);
6695 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6696 ConstantInt::get(*Context, NewRHS));
6701 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6702 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6703 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6705 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6706 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6707 Value *CompareVal = LHSI->getOperand(0);
6709 // If the sign bit of the XorCST is not set, there is no change to
6710 // the operation, just stop using the Xor.
6711 if (!XorCST->getValue().isNegative()) {
6712 ICI.setOperand(0, CompareVal);
6717 // Was the old condition true if the operand is positive?
6718 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6720 // If so, the new one isn't.
6721 isTrueIfPositive ^= true;
6723 if (isTrueIfPositive)
6724 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6727 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6731 if (LHSI->hasOneUse()) {
6732 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6733 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6734 const APInt &SignBit = XorCST->getValue();
6735 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6736 ? ICI.getUnsignedPredicate()
6737 : ICI.getSignedPredicate();
6738 return new ICmpInst(Pred, LHSI->getOperand(0),
6739 ConstantInt::get(*Context, RHSV ^ SignBit));
6742 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6743 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6744 const APInt &NotSignBit = XorCST->getValue();
6745 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6746 ? ICI.getUnsignedPredicate()
6747 : ICI.getSignedPredicate();
6748 Pred = ICI.getSwappedPredicate(Pred);
6749 return new ICmpInst(Pred, LHSI->getOperand(0),
6750 ConstantInt::get(*Context, RHSV ^ NotSignBit));
6755 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6756 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6757 LHSI->getOperand(0)->hasOneUse()) {
6758 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6760 // If the LHS is an AND of a truncating cast, we can widen the
6761 // and/compare to be the input width without changing the value
6762 // produced, eliminating a cast.
6763 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6764 // We can do this transformation if either the AND constant does not
6765 // have its sign bit set or if it is an equality comparison.
6766 // Extending a relational comparison when we're checking the sign
6767 // bit would not work.
6768 if (Cast->hasOneUse() &&
6769 (ICI.isEquality() ||
6770 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6772 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6773 APInt NewCST = AndCST->getValue();
6774 NewCST.zext(BitWidth);
6776 NewCI.zext(BitWidth);
6778 Builder->CreateAnd(Cast->getOperand(0),
6779 ConstantInt::get(*Context, NewCST), LHSI->getName());
6780 return new ICmpInst(ICI.getPredicate(), NewAnd,
6781 ConstantInt::get(*Context, NewCI));
6785 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6786 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6787 // happens a LOT in code produced by the C front-end, for bitfield
6789 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6790 if (Shift && !Shift->isShift())
6794 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6795 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6796 const Type *AndTy = AndCST->getType(); // Type of the and.
6798 // We can fold this as long as we can't shift unknown bits
6799 // into the mask. This can only happen with signed shift
6800 // rights, as they sign-extend.
6802 bool CanFold = Shift->isLogicalShift();
6804 // To test for the bad case of the signed shr, see if any
6805 // of the bits shifted in could be tested after the mask.
6806 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6807 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6809 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6810 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6811 AndCST->getValue()) == 0)
6817 if (Shift->getOpcode() == Instruction::Shl)
6818 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6820 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6822 // Check to see if we are shifting out any of the bits being
6824 if (ConstantExpr::get(Shift->getOpcode(),
6825 NewCst, ShAmt) != RHS) {
6826 // If we shifted bits out, the fold is not going to work out.
6827 // As a special case, check to see if this means that the
6828 // result is always true or false now.
6829 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6830 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6831 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6832 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6834 ICI.setOperand(1, NewCst);
6835 Constant *NewAndCST;
6836 if (Shift->getOpcode() == Instruction::Shl)
6837 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6839 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6840 LHSI->setOperand(1, NewAndCST);
6841 LHSI->setOperand(0, Shift->getOperand(0));
6842 Worklist.Add(Shift); // Shift is dead.
6848 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6849 // preferable because it allows the C<<Y expression to be hoisted out
6850 // of a loop if Y is invariant and X is not.
6851 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6852 ICI.isEquality() && !Shift->isArithmeticShift() &&
6853 !isa<Constant>(Shift->getOperand(0))) {
6856 if (Shift->getOpcode() == Instruction::LShr) {
6857 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6859 // Insert a logical shift.
6860 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6863 // Compute X & (C << Y).
6865 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6867 ICI.setOperand(0, NewAnd);
6873 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6874 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6877 uint32_t TypeBits = RHSV.getBitWidth();
6879 // Check that the shift amount is in range. If not, don't perform
6880 // undefined shifts. When the shift is visited it will be
6882 if (ShAmt->uge(TypeBits))
6885 if (ICI.isEquality()) {
6886 // If we are comparing against bits always shifted out, the
6887 // comparison cannot succeed.
6889 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6891 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6892 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6893 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6894 return ReplaceInstUsesWith(ICI, Cst);
6897 if (LHSI->hasOneUse()) {
6898 // Otherwise strength reduce the shift into an and.
6899 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6901 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
6902 TypeBits-ShAmtVal));
6905 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6906 return new ICmpInst(ICI.getPredicate(), And,
6907 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6911 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6912 bool TrueIfSigned = false;
6913 if (LHSI->hasOneUse() &&
6914 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6915 // (X << 31) <s 0 --> (X&1) != 0
6916 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6917 (TypeBits-ShAmt->getZExtValue()-1));
6919 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6920 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6921 And, Constant::getNullValue(And->getType()));
6926 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6927 case Instruction::AShr: {
6928 // Only handle equality comparisons of shift-by-constant.
6929 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6930 if (!ShAmt || !ICI.isEquality()) break;
6932 // Check that the shift amount is in range. If not, don't perform
6933 // undefined shifts. When the shift is visited it will be
6935 uint32_t TypeBits = RHSV.getBitWidth();
6936 if (ShAmt->uge(TypeBits))
6939 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6941 // If we are comparing against bits always shifted out, the
6942 // comparison cannot succeed.
6943 APInt Comp = RHSV << ShAmtVal;
6944 if (LHSI->getOpcode() == Instruction::LShr)
6945 Comp = Comp.lshr(ShAmtVal);
6947 Comp = Comp.ashr(ShAmtVal);
6949 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6950 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6951 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6952 return ReplaceInstUsesWith(ICI, Cst);
6955 // Otherwise, check to see if the bits shifted out are known to be zero.
6956 // If so, we can compare against the unshifted value:
6957 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6958 if (LHSI->hasOneUse() &&
6959 MaskedValueIsZero(LHSI->getOperand(0),
6960 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6961 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6962 ConstantExpr::getShl(RHS, ShAmt));
6965 if (LHSI->hasOneUse()) {
6966 // Otherwise strength reduce the shift into an and.
6967 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6968 Constant *Mask = ConstantInt::get(*Context, Val);
6970 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6971 Mask, LHSI->getName()+".mask");
6972 return new ICmpInst(ICI.getPredicate(), And,
6973 ConstantExpr::getShl(RHS, ShAmt));
6978 case Instruction::SDiv:
6979 case Instruction::UDiv:
6980 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6981 // Fold this div into the comparison, producing a range check.
6982 // Determine, based on the divide type, what the range is being
6983 // checked. If there is an overflow on the low or high side, remember
6984 // it, otherwise compute the range [low, hi) bounding the new value.
6985 // See: InsertRangeTest above for the kinds of replacements possible.
6986 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6987 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6992 case Instruction::Add:
6993 // Fold: icmp pred (add, X, C1), C2
6995 if (!ICI.isEquality()) {
6996 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6998 const APInt &LHSV = LHSC->getValue();
7000 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7003 if (ICI.isSignedPredicate()) {
7004 if (CR.getLower().isSignBit()) {
7005 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7006 ConstantInt::get(*Context, CR.getUpper()));
7007 } else if (CR.getUpper().isSignBit()) {
7008 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7009 ConstantInt::get(*Context, CR.getLower()));
7012 if (CR.getLower().isMinValue()) {
7013 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7014 ConstantInt::get(*Context, CR.getUpper()));
7015 } else if (CR.getUpper().isMinValue()) {
7016 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7017 ConstantInt::get(*Context, CR.getLower()));
7024 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7025 if (ICI.isEquality()) {
7026 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7028 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7029 // the second operand is a constant, simplify a bit.
7030 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7031 switch (BO->getOpcode()) {
7032 case Instruction::SRem:
7033 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7034 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7035 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7036 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7038 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7040 return new ICmpInst(ICI.getPredicate(), NewRem,
7041 Constant::getNullValue(BO->getType()));
7045 case Instruction::Add:
7046 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7047 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7048 if (BO->hasOneUse())
7049 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7050 ConstantExpr::getSub(RHS, BOp1C));
7051 } else if (RHSV == 0) {
7052 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7053 // efficiently invertible, or if the add has just this one use.
7054 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7056 if (Value *NegVal = dyn_castNegVal(BOp1))
7057 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7058 else if (Value *NegVal = dyn_castNegVal(BOp0))
7059 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7060 else if (BO->hasOneUse()) {
7061 Value *Neg = Builder->CreateNeg(BOp1);
7063 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7067 case Instruction::Xor:
7068 // For the xor case, we can xor two constants together, eliminating
7069 // the explicit xor.
7070 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7071 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7072 ConstantExpr::getXor(RHS, BOC));
7075 case Instruction::Sub:
7076 // Replace (([sub|xor] A, B) != 0) with (A != B)
7078 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7082 case Instruction::Or:
7083 // If bits are being or'd in that are not present in the constant we
7084 // are comparing against, then the comparison could never succeed!
7085 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7086 Constant *NotCI = ConstantExpr::getNot(RHS);
7087 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7088 return ReplaceInstUsesWith(ICI,
7089 ConstantInt::get(Type::getInt1Ty(*Context),
7094 case Instruction::And:
7095 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7096 // If bits are being compared against that are and'd out, then the
7097 // comparison can never succeed!
7098 if ((RHSV & ~BOC->getValue()) != 0)
7099 return ReplaceInstUsesWith(ICI,
7100 ConstantInt::get(Type::getInt1Ty(*Context),
7103 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7104 if (RHS == BOC && RHSV.isPowerOf2())
7105 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7106 ICmpInst::ICMP_NE, LHSI,
7107 Constant::getNullValue(RHS->getType()));
7109 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7110 if (BOC->getValue().isSignBit()) {
7111 Value *X = BO->getOperand(0);
7112 Constant *Zero = Constant::getNullValue(X->getType());
7113 ICmpInst::Predicate pred = isICMP_NE ?
7114 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7115 return new ICmpInst(pred, X, Zero);
7118 // ((X & ~7) == 0) --> X < 8
7119 if (RHSV == 0 && isHighOnes(BOC)) {
7120 Value *X = BO->getOperand(0);
7121 Constant *NegX = ConstantExpr::getNeg(BOC);
7122 ICmpInst::Predicate pred = isICMP_NE ?
7123 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7124 return new ICmpInst(pred, X, NegX);
7129 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7130 // Handle icmp {eq|ne} <intrinsic>, intcst.
7131 if (II->getIntrinsicID() == Intrinsic::bswap) {
7133 ICI.setOperand(0, II->getOperand(1));
7134 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7142 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7143 /// We only handle extending casts so far.
7145 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7146 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7147 Value *LHSCIOp = LHSCI->getOperand(0);
7148 const Type *SrcTy = LHSCIOp->getType();
7149 const Type *DestTy = LHSCI->getType();
7152 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7153 // integer type is the same size as the pointer type.
7154 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7155 TD->getPointerSizeInBits() ==
7156 cast<IntegerType>(DestTy)->getBitWidth()) {
7158 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7159 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7160 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7161 RHSOp = RHSC->getOperand(0);
7162 // If the pointer types don't match, insert a bitcast.
7163 if (LHSCIOp->getType() != RHSOp->getType())
7164 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7168 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7171 // The code below only handles extension cast instructions, so far.
7173 if (LHSCI->getOpcode() != Instruction::ZExt &&
7174 LHSCI->getOpcode() != Instruction::SExt)
7177 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7178 bool isSignedCmp = ICI.isSignedPredicate();
7180 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7181 // Not an extension from the same type?
7182 RHSCIOp = CI->getOperand(0);
7183 if (RHSCIOp->getType() != LHSCIOp->getType())
7186 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7187 // and the other is a zext), then we can't handle this.
7188 if (CI->getOpcode() != LHSCI->getOpcode())
7191 // Deal with equality cases early.
7192 if (ICI.isEquality())
7193 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7195 // A signed comparison of sign extended values simplifies into a
7196 // signed comparison.
7197 if (isSignedCmp && isSignedExt)
7198 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7200 // The other three cases all fold into an unsigned comparison.
7201 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7204 // If we aren't dealing with a constant on the RHS, exit early
7205 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7209 // Compute the constant that would happen if we truncated to SrcTy then
7210 // reextended to DestTy.
7211 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7212 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7215 // If the re-extended constant didn't change...
7217 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7218 // For example, we might have:
7219 // %A = sext i16 %X to i32
7220 // %B = icmp ugt i32 %A, 1330
7221 // It is incorrect to transform this into
7222 // %B = icmp ugt i16 %X, 1330
7223 // because %A may have negative value.
7225 // However, we allow this when the compare is EQ/NE, because they are
7227 if (isSignedExt == isSignedCmp || ICI.isEquality())
7228 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7232 // The re-extended constant changed so the constant cannot be represented
7233 // in the shorter type. Consequently, we cannot emit a simple comparison.
7235 // First, handle some easy cases. We know the result cannot be equal at this
7236 // point so handle the ICI.isEquality() cases
7237 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7238 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7239 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7240 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7242 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7243 // should have been folded away previously and not enter in here.
7246 // We're performing a signed comparison.
7247 if (cast<ConstantInt>(CI)->getValue().isNegative())
7248 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
7250 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
7252 // We're performing an unsigned comparison.
7254 // We're performing an unsigned comp with a sign extended value.
7255 // This is true if the input is >= 0. [aka >s -1]
7256 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7257 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7259 // Unsigned extend & unsigned compare -> always true.
7260 Result = ConstantInt::getTrue(*Context);
7264 // Finally, return the value computed.
7265 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7266 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7267 return ReplaceInstUsesWith(ICI, Result);
7269 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7270 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7271 "ICmp should be folded!");
7272 if (Constant *CI = dyn_cast<Constant>(Result))
7273 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7274 return BinaryOperator::CreateNot(Result);
7277 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7278 return commonShiftTransforms(I);
7281 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7282 return commonShiftTransforms(I);
7285 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7286 if (Instruction *R = commonShiftTransforms(I))
7289 Value *Op0 = I.getOperand(0);
7291 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7292 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7293 if (CSI->isAllOnesValue())
7294 return ReplaceInstUsesWith(I, CSI);
7296 // See if we can turn a signed shr into an unsigned shr.
7297 if (MaskedValueIsZero(Op0,
7298 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7299 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7301 // Arithmetic shifting an all-sign-bit value is a no-op.
7302 unsigned NumSignBits = ComputeNumSignBits(Op0);
7303 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7304 return ReplaceInstUsesWith(I, Op0);
7309 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7310 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7311 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7313 // shl X, 0 == X and shr X, 0 == X
7314 // shl 0, X == 0 and shr 0, X == 0
7315 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7316 Op0 == Constant::getNullValue(Op0->getType()))
7317 return ReplaceInstUsesWith(I, Op0);
7319 if (isa<UndefValue>(Op0)) {
7320 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7321 return ReplaceInstUsesWith(I, Op0);
7322 else // undef << X -> 0, undef >>u X -> 0
7323 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7325 if (isa<UndefValue>(Op1)) {
7326 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7327 return ReplaceInstUsesWith(I, Op0);
7328 else // X << undef, X >>u undef -> 0
7329 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7332 // See if we can fold away this shift.
7333 if (SimplifyDemandedInstructionBits(I))
7336 // Try to fold constant and into select arguments.
7337 if (isa<Constant>(Op0))
7338 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7339 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7342 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7343 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7348 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7349 BinaryOperator &I) {
7350 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7352 // See if we can simplify any instructions used by the instruction whose sole
7353 // purpose is to compute bits we don't care about.
7354 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7356 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7359 if (Op1->uge(TypeBits)) {
7360 if (I.getOpcode() != Instruction::AShr)
7361 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7363 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7368 // ((X*C1) << C2) == (X * (C1 << C2))
7369 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7370 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7371 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7372 return BinaryOperator::CreateMul(BO->getOperand(0),
7373 ConstantExpr::getShl(BOOp, Op1));
7375 // Try to fold constant and into select arguments.
7376 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7377 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7379 if (isa<PHINode>(Op0))
7380 if (Instruction *NV = FoldOpIntoPhi(I))
7383 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7384 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7385 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7386 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7387 // place. Don't try to do this transformation in this case. Also, we
7388 // require that the input operand is a shift-by-constant so that we have
7389 // confidence that the shifts will get folded together. We could do this
7390 // xform in more cases, but it is unlikely to be profitable.
7391 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7392 isa<ConstantInt>(TrOp->getOperand(1))) {
7393 // Okay, we'll do this xform. Make the shift of shift.
7394 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7395 // (shift2 (shift1 & 0x00FF), c2)
7396 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7398 // For logical shifts, the truncation has the effect of making the high
7399 // part of the register be zeros. Emulate this by inserting an AND to
7400 // clear the top bits as needed. This 'and' will usually be zapped by
7401 // other xforms later if dead.
7402 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7403 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7404 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7406 // The mask we constructed says what the trunc would do if occurring
7407 // between the shifts. We want to know the effect *after* the second
7408 // shift. We know that it is a logical shift by a constant, so adjust the
7409 // mask as appropriate.
7410 if (I.getOpcode() == Instruction::Shl)
7411 MaskV <<= Op1->getZExtValue();
7413 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7414 MaskV = MaskV.lshr(Op1->getZExtValue());
7418 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7421 // Return the value truncated to the interesting size.
7422 return new TruncInst(And, I.getType());
7426 if (Op0->hasOneUse()) {
7427 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7428 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7431 switch (Op0BO->getOpcode()) {
7433 case Instruction::Add:
7434 case Instruction::And:
7435 case Instruction::Or:
7436 case Instruction::Xor: {
7437 // These operators commute.
7438 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7439 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7440 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7441 m_Specific(Op1)))) {
7442 Value *YS = // (Y << C)
7443 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7445 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7446 Op0BO->getOperand(1)->getName());
7447 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7448 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7449 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7452 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7453 Value *Op0BOOp1 = Op0BO->getOperand(1);
7454 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7456 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7457 m_ConstantInt(CC))) &&
7458 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7459 Value *YS = // (Y << C)
7460 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7463 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7464 V1->getName()+".mask");
7465 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7470 case Instruction::Sub: {
7471 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7472 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7473 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7474 m_Specific(Op1)))) {
7475 Value *YS = // (Y << C)
7476 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7478 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7479 Op0BO->getOperand(0)->getName());
7480 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7481 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7482 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7485 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7486 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7487 match(Op0BO->getOperand(0),
7488 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7489 m_ConstantInt(CC))) && V2 == Op1 &&
7490 cast<BinaryOperator>(Op0BO->getOperand(0))
7491 ->getOperand(0)->hasOneUse()) {
7492 Value *YS = // (Y << C)
7493 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7495 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7496 V1->getName()+".mask");
7498 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7506 // If the operand is an bitwise operator with a constant RHS, and the
7507 // shift is the only use, we can pull it out of the shift.
7508 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7509 bool isValid = true; // Valid only for And, Or, Xor
7510 bool highBitSet = false; // Transform if high bit of constant set?
7512 switch (Op0BO->getOpcode()) {
7513 default: isValid = false; break; // Do not perform transform!
7514 case Instruction::Add:
7515 isValid = isLeftShift;
7517 case Instruction::Or:
7518 case Instruction::Xor:
7521 case Instruction::And:
7526 // If this is a signed shift right, and the high bit is modified
7527 // by the logical operation, do not perform the transformation.
7528 // The highBitSet boolean indicates the value of the high bit of
7529 // the constant which would cause it to be modified for this
7532 if (isValid && I.getOpcode() == Instruction::AShr)
7533 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7536 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7539 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7540 NewShift->takeName(Op0BO);
7542 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7549 // Find out if this is a shift of a shift by a constant.
7550 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7551 if (ShiftOp && !ShiftOp->isShift())
7554 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7555 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7556 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7557 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7558 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7559 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7560 Value *X = ShiftOp->getOperand(0);
7562 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7564 const IntegerType *Ty = cast<IntegerType>(I.getType());
7566 // Check for (X << c1) << c2 and (X >> c1) >> c2
7567 if (I.getOpcode() == ShiftOp->getOpcode()) {
7568 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7570 if (AmtSum >= TypeBits) {
7571 if (I.getOpcode() != Instruction::AShr)
7572 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7573 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7576 return BinaryOperator::Create(I.getOpcode(), X,
7577 ConstantInt::get(Ty, AmtSum));
7580 if (ShiftOp->getOpcode() == Instruction::LShr &&
7581 I.getOpcode() == Instruction::AShr) {
7582 if (AmtSum >= TypeBits)
7583 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7585 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7586 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7589 if (ShiftOp->getOpcode() == Instruction::AShr &&
7590 I.getOpcode() == Instruction::LShr) {
7591 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7592 if (AmtSum >= TypeBits)
7593 AmtSum = TypeBits-1;
7595 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7597 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7598 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7601 // Okay, if we get here, one shift must be left, and the other shift must be
7602 // right. See if the amounts are equal.
7603 if (ShiftAmt1 == ShiftAmt2) {
7604 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7605 if (I.getOpcode() == Instruction::Shl) {
7606 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7607 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7609 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7610 if (I.getOpcode() == Instruction::LShr) {
7611 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7612 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7614 // We can simplify ((X << C) >>s C) into a trunc + sext.
7615 // NOTE: we could do this for any C, but that would make 'unusual' integer
7616 // types. For now, just stick to ones well-supported by the code
7618 const Type *SExtType = 0;
7619 switch (Ty->getBitWidth() - ShiftAmt1) {
7626 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7631 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7632 // Otherwise, we can't handle it yet.
7633 } else if (ShiftAmt1 < ShiftAmt2) {
7634 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7636 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7637 if (I.getOpcode() == Instruction::Shl) {
7638 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7639 ShiftOp->getOpcode() == Instruction::AShr);
7640 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7642 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7643 return BinaryOperator::CreateAnd(Shift,
7644 ConstantInt::get(*Context, Mask));
7647 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7648 if (I.getOpcode() == Instruction::LShr) {
7649 assert(ShiftOp->getOpcode() == Instruction::Shl);
7650 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7652 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7653 return BinaryOperator::CreateAnd(Shift,
7654 ConstantInt::get(*Context, Mask));
7657 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7659 assert(ShiftAmt2 < ShiftAmt1);
7660 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7662 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7663 if (I.getOpcode() == Instruction::Shl) {
7664 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7665 ShiftOp->getOpcode() == Instruction::AShr);
7666 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7667 ConstantInt::get(Ty, ShiftDiff));
7669 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7670 return BinaryOperator::CreateAnd(Shift,
7671 ConstantInt::get(*Context, Mask));
7674 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7675 if (I.getOpcode() == Instruction::LShr) {
7676 assert(ShiftOp->getOpcode() == Instruction::Shl);
7677 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7679 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7680 return BinaryOperator::CreateAnd(Shift,
7681 ConstantInt::get(*Context, Mask));
7684 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7691 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7692 /// expression. If so, decompose it, returning some value X, such that Val is
7695 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7696 int &Offset, LLVMContext *Context) {
7697 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7698 "Unexpected allocation size type!");
7699 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7700 Offset = CI->getZExtValue();
7702 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7703 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7704 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7705 if (I->getOpcode() == Instruction::Shl) {
7706 // This is a value scaled by '1 << the shift amt'.
7707 Scale = 1U << RHS->getZExtValue();
7709 return I->getOperand(0);
7710 } else if (I->getOpcode() == Instruction::Mul) {
7711 // This value is scaled by 'RHS'.
7712 Scale = RHS->getZExtValue();
7714 return I->getOperand(0);
7715 } else if (I->getOpcode() == Instruction::Add) {
7716 // We have X+C. Check to see if we really have (X*C2)+C1,
7717 // where C1 is divisible by C2.
7720 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7722 Offset += RHS->getZExtValue();
7729 // Otherwise, we can't look past this.
7736 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7737 /// try to eliminate the cast by moving the type information into the alloc.
7738 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7739 AllocationInst &AI) {
7740 const PointerType *PTy = cast<PointerType>(CI.getType());
7742 BuilderTy AllocaBuilder(*Builder);
7743 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7745 // Remove any uses of AI that are dead.
7746 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7748 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7749 Instruction *User = cast<Instruction>(*UI++);
7750 if (isInstructionTriviallyDead(User)) {
7751 while (UI != E && *UI == User)
7752 ++UI; // If this instruction uses AI more than once, don't break UI.
7755 DEBUG(errs() << "IC: DCE: " << *User << '\n');
7756 EraseInstFromFunction(*User);
7760 // This requires TargetData to get the alloca alignment and size information.
7763 // Get the type really allocated and the type casted to.
7764 const Type *AllocElTy = AI.getAllocatedType();
7765 const Type *CastElTy = PTy->getElementType();
7766 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7768 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7769 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7770 if (CastElTyAlign < AllocElTyAlign) return 0;
7772 // If the allocation has multiple uses, only promote it if we are strictly
7773 // increasing the alignment of the resultant allocation. If we keep it the
7774 // same, we open the door to infinite loops of various kinds. (A reference
7775 // from a dbg.declare doesn't count as a use for this purpose.)
7776 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7777 CastElTyAlign == AllocElTyAlign) return 0;
7779 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7780 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7781 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7783 // See if we can satisfy the modulus by pulling a scale out of the array
7785 unsigned ArraySizeScale;
7787 Value *NumElements = // See if the array size is a decomposable linear expr.
7788 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7789 ArrayOffset, Context);
7791 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7793 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7794 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7796 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7801 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7802 // Insert before the alloca, not before the cast.
7803 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7806 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7807 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7808 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7811 AllocationInst *New;
7812 if (isa<MallocInst>(AI))
7813 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
7815 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7816 New->setAlignment(AI.getAlignment());
7819 // If the allocation has one real use plus a dbg.declare, just remove the
7821 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7822 EraseInstFromFunction(*DI);
7824 // If the allocation has multiple real uses, insert a cast and change all
7825 // things that used it to use the new cast. This will also hack on CI, but it
7827 else if (!AI.hasOneUse()) {
7828 // New is the allocation instruction, pointer typed. AI is the original
7829 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7830 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7831 AI.replaceAllUsesWith(NewCast);
7833 return ReplaceInstUsesWith(CI, New);
7836 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7837 /// and return it as type Ty without inserting any new casts and without
7838 /// changing the computed value. This is used by code that tries to decide
7839 /// whether promoting or shrinking integer operations to wider or smaller types
7840 /// will allow us to eliminate a truncate or extend.
7842 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7843 /// extension operation if Ty is larger.
7845 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7846 /// should return true if trunc(V) can be computed by computing V in the smaller
7847 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7848 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7849 /// efficiently truncated.
7851 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7852 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7853 /// the final result.
7854 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7856 int &NumCastsRemoved){
7857 // We can always evaluate constants in another type.
7858 if (isa<Constant>(V))
7861 Instruction *I = dyn_cast<Instruction>(V);
7862 if (!I) return false;
7864 const Type *OrigTy = V->getType();
7866 // If this is an extension or truncate, we can often eliminate it.
7867 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7868 // If this is a cast from the destination type, we can trivially eliminate
7869 // it, and this will remove a cast overall.
7870 if (I->getOperand(0)->getType() == Ty) {
7871 // If the first operand is itself a cast, and is eliminable, do not count
7872 // this as an eliminable cast. We would prefer to eliminate those two
7874 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7880 // We can't extend or shrink something that has multiple uses: doing so would
7881 // require duplicating the instruction in general, which isn't profitable.
7882 if (!I->hasOneUse()) return false;
7884 unsigned Opc = I->getOpcode();
7886 case Instruction::Add:
7887 case Instruction::Sub:
7888 case Instruction::Mul:
7889 case Instruction::And:
7890 case Instruction::Or:
7891 case Instruction::Xor:
7892 // These operators can all arbitrarily be extended or truncated.
7893 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7895 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7898 case Instruction::UDiv:
7899 case Instruction::URem: {
7900 // UDiv and URem can be truncated if all the truncated bits are zero.
7901 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7902 uint32_t BitWidth = Ty->getScalarSizeInBits();
7903 if (BitWidth < OrigBitWidth) {
7904 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7905 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7906 MaskedValueIsZero(I->getOperand(1), Mask)) {
7907 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7909 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7915 case Instruction::Shl:
7916 // If we are truncating the result of this SHL, and if it's a shift of a
7917 // constant amount, we can always perform a SHL in a smaller type.
7918 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7919 uint32_t BitWidth = Ty->getScalarSizeInBits();
7920 if (BitWidth < OrigTy->getScalarSizeInBits() &&
7921 CI->getLimitedValue(BitWidth) < BitWidth)
7922 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7926 case Instruction::LShr:
7927 // If this is a truncate of a logical shr, we can truncate it to a smaller
7928 // lshr iff we know that the bits we would otherwise be shifting in are
7930 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7931 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7932 uint32_t BitWidth = Ty->getScalarSizeInBits();
7933 if (BitWidth < OrigBitWidth &&
7934 MaskedValueIsZero(I->getOperand(0),
7935 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7936 CI->getLimitedValue(BitWidth) < BitWidth) {
7937 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7942 case Instruction::ZExt:
7943 case Instruction::SExt:
7944 case Instruction::Trunc:
7945 // If this is the same kind of case as our original (e.g. zext+zext), we
7946 // can safely replace it. Note that replacing it does not reduce the number
7947 // of casts in the input.
7951 // sext (zext ty1), ty2 -> zext ty2
7952 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7955 case Instruction::Select: {
7956 SelectInst *SI = cast<SelectInst>(I);
7957 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7959 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7962 case Instruction::PHI: {
7963 // We can change a phi if we can change all operands.
7964 PHINode *PN = cast<PHINode>(I);
7965 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7966 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7972 // TODO: Can handle more cases here.
7979 /// EvaluateInDifferentType - Given an expression that
7980 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7981 /// evaluate the expression.
7982 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7984 if (Constant *C = dyn_cast<Constant>(V))
7985 return ConstantExpr::getIntegerCast(C, Ty,
7986 isSigned /*Sext or ZExt*/);
7988 // Otherwise, it must be an instruction.
7989 Instruction *I = cast<Instruction>(V);
7990 Instruction *Res = 0;
7991 unsigned Opc = I->getOpcode();
7993 case Instruction::Add:
7994 case Instruction::Sub:
7995 case Instruction::Mul:
7996 case Instruction::And:
7997 case Instruction::Or:
7998 case Instruction::Xor:
7999 case Instruction::AShr:
8000 case Instruction::LShr:
8001 case Instruction::Shl:
8002 case Instruction::UDiv:
8003 case Instruction::URem: {
8004 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8005 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8006 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8009 case Instruction::Trunc:
8010 case Instruction::ZExt:
8011 case Instruction::SExt:
8012 // If the source type of the cast is the type we're trying for then we can
8013 // just return the source. There's no need to insert it because it is not
8015 if (I->getOperand(0)->getType() == Ty)
8016 return I->getOperand(0);
8018 // Otherwise, must be the same type of cast, so just reinsert a new one.
8019 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8022 case Instruction::Select: {
8023 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8024 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8025 Res = SelectInst::Create(I->getOperand(0), True, False);
8028 case Instruction::PHI: {
8029 PHINode *OPN = cast<PHINode>(I);
8030 PHINode *NPN = PHINode::Create(Ty);
8031 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8032 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8033 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8039 // TODO: Can handle more cases here.
8040 llvm_unreachable("Unreachable!");
8045 return InsertNewInstBefore(Res, *I);
8048 /// @brief Implement the transforms common to all CastInst visitors.
8049 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8050 Value *Src = CI.getOperand(0);
8052 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8053 // eliminate it now.
8054 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8055 if (Instruction::CastOps opc =
8056 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8057 // The first cast (CSrc) is eliminable so we need to fix up or replace
8058 // the second cast (CI). CSrc will then have a good chance of being dead.
8059 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8063 // If we are casting a select then fold the cast into the select
8064 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8065 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8068 // If we are casting a PHI then fold the cast into the PHI
8069 if (isa<PHINode>(Src))
8070 if (Instruction *NV = FoldOpIntoPhi(CI))
8076 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8077 /// or not there is a sequence of GEP indices into the type that will land us at
8078 /// the specified offset. If so, fill them into NewIndices and return the
8079 /// resultant element type, otherwise return null.
8080 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8081 SmallVectorImpl<Value*> &NewIndices,
8082 const TargetData *TD,
8083 LLVMContext *Context) {
8085 if (!Ty->isSized()) return 0;
8087 // Start with the index over the outer type. Note that the type size
8088 // might be zero (even if the offset isn't zero) if the indexed type
8089 // is something like [0 x {int, int}]
8090 const Type *IntPtrTy = TD->getIntPtrType(*Context);
8091 int64_t FirstIdx = 0;
8092 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8093 FirstIdx = Offset/TySize;
8094 Offset -= FirstIdx*TySize;
8096 // Handle hosts where % returns negative instead of values [0..TySize).
8100 assert(Offset >= 0);
8102 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8105 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8107 // Index into the types. If we fail, set OrigBase to null.
8109 // Indexing into tail padding between struct/array elements.
8110 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8113 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8114 const StructLayout *SL = TD->getStructLayout(STy);
8115 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8116 "Offset must stay within the indexed type");
8118 unsigned Elt = SL->getElementContainingOffset(Offset);
8119 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8121 Offset -= SL->getElementOffset(Elt);
8122 Ty = STy->getElementType(Elt);
8123 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8124 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8125 assert(EltSize && "Cannot index into a zero-sized array");
8126 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8128 Ty = AT->getElementType();
8130 // Otherwise, we can't index into the middle of this atomic type, bail.
8138 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8139 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8140 Value *Src = CI.getOperand(0);
8142 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8143 // If casting the result of a getelementptr instruction with no offset, turn
8144 // this into a cast of the original pointer!
8145 if (GEP->hasAllZeroIndices()) {
8146 // Changing the cast operand is usually not a good idea but it is safe
8147 // here because the pointer operand is being replaced with another
8148 // pointer operand so the opcode doesn't need to change.
8150 CI.setOperand(0, GEP->getOperand(0));
8154 // If the GEP has a single use, and the base pointer is a bitcast, and the
8155 // GEP computes a constant offset, see if we can convert these three
8156 // instructions into fewer. This typically happens with unions and other
8157 // non-type-safe code.
8158 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8159 if (GEP->hasAllConstantIndices()) {
8160 // We are guaranteed to get a constant from EmitGEPOffset.
8161 ConstantInt *OffsetV =
8162 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8163 int64_t Offset = OffsetV->getSExtValue();
8165 // Get the base pointer input of the bitcast, and the type it points to.
8166 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8167 const Type *GEPIdxTy =
8168 cast<PointerType>(OrigBase->getType())->getElementType();
8169 SmallVector<Value*, 8> NewIndices;
8170 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8171 // If we were able to index down into an element, create the GEP
8172 // and bitcast the result. This eliminates one bitcast, potentially
8174 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8175 Builder->CreateInBoundsGEP(OrigBase,
8176 NewIndices.begin(), NewIndices.end()) :
8177 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8178 NGEP->takeName(GEP);
8180 if (isa<BitCastInst>(CI))
8181 return new BitCastInst(NGEP, CI.getType());
8182 assert(isa<PtrToIntInst>(CI));
8183 return new PtrToIntInst(NGEP, CI.getType());
8189 return commonCastTransforms(CI);
8192 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8193 /// type like i42. We don't want to introduce operations on random non-legal
8194 /// integer types where they don't already exist in the code. In the future,
8195 /// we should consider making this based off target-data, so that 32-bit targets
8196 /// won't get i64 operations etc.
8197 static bool isSafeIntegerType(const Type *Ty) {
8198 switch (Ty->getPrimitiveSizeInBits()) {
8209 /// commonIntCastTransforms - This function implements the common transforms
8210 /// for trunc, zext, and sext.
8211 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8212 if (Instruction *Result = commonCastTransforms(CI))
8215 Value *Src = CI.getOperand(0);
8216 const Type *SrcTy = Src->getType();
8217 const Type *DestTy = CI.getType();
8218 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8219 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8221 // See if we can simplify any instructions used by the LHS whose sole
8222 // purpose is to compute bits we don't care about.
8223 if (SimplifyDemandedInstructionBits(CI))
8226 // If the source isn't an instruction or has more than one use then we
8227 // can't do anything more.
8228 Instruction *SrcI = dyn_cast<Instruction>(Src);
8229 if (!SrcI || !Src->hasOneUse())
8232 // Attempt to propagate the cast into the instruction for int->int casts.
8233 int NumCastsRemoved = 0;
8234 // Only do this if the dest type is a simple type, don't convert the
8235 // expression tree to something weird like i93 unless the source is also
8237 if ((isSafeIntegerType(DestTy->getScalarType()) ||
8238 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8239 CanEvaluateInDifferentType(SrcI, DestTy,
8240 CI.getOpcode(), NumCastsRemoved)) {
8241 // If this cast is a truncate, evaluting in a different type always
8242 // eliminates the cast, so it is always a win. If this is a zero-extension,
8243 // we need to do an AND to maintain the clear top-part of the computation,
8244 // so we require that the input have eliminated at least one cast. If this
8245 // is a sign extension, we insert two new casts (to do the extension) so we
8246 // require that two casts have been eliminated.
8247 bool DoXForm = false;
8248 bool JustReplace = false;
8249 switch (CI.getOpcode()) {
8251 // All the others use floating point so we shouldn't actually
8252 // get here because of the check above.
8253 llvm_unreachable("Unknown cast type");
8254 case Instruction::Trunc:
8257 case Instruction::ZExt: {
8258 DoXForm = NumCastsRemoved >= 1;
8259 if (!DoXForm && 0) {
8260 // If it's unnecessary to issue an AND to clear the high bits, it's
8261 // always profitable to do this xform.
8262 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8263 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8264 if (MaskedValueIsZero(TryRes, Mask))
8265 return ReplaceInstUsesWith(CI, TryRes);
8267 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8268 if (TryI->use_empty())
8269 EraseInstFromFunction(*TryI);
8273 case Instruction::SExt: {
8274 DoXForm = NumCastsRemoved >= 2;
8275 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8276 // If we do not have to emit the truncate + sext pair, then it's always
8277 // profitable to do this xform.
8279 // It's not safe to eliminate the trunc + sext pair if one of the
8280 // eliminated cast is a truncate. e.g.
8281 // t2 = trunc i32 t1 to i16
8282 // t3 = sext i16 t2 to i32
8285 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8286 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8287 if (NumSignBits > (DestBitSize - SrcBitSize))
8288 return ReplaceInstUsesWith(CI, TryRes);
8290 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8291 if (TryI->use_empty())
8292 EraseInstFromFunction(*TryI);
8299 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8300 " to avoid cast: " << CI);
8301 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8302 CI.getOpcode() == Instruction::SExt);
8304 // Just replace this cast with the result.
8305 return ReplaceInstUsesWith(CI, Res);
8307 assert(Res->getType() == DestTy);
8308 switch (CI.getOpcode()) {
8309 default: llvm_unreachable("Unknown cast type!");
8310 case Instruction::Trunc:
8311 // Just replace this cast with the result.
8312 return ReplaceInstUsesWith(CI, Res);
8313 case Instruction::ZExt: {
8314 assert(SrcBitSize < DestBitSize && "Not a zext?");
8316 // If the high bits are already zero, just replace this cast with the
8318 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8319 if (MaskedValueIsZero(Res, Mask))
8320 return ReplaceInstUsesWith(CI, Res);
8322 // We need to emit an AND to clear the high bits.
8323 Constant *C = ConstantInt::get(*Context,
8324 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8325 return BinaryOperator::CreateAnd(Res, C);
8327 case Instruction::SExt: {
8328 // If the high bits are already filled with sign bit, just replace this
8329 // cast with the result.
8330 unsigned NumSignBits = ComputeNumSignBits(Res);
8331 if (NumSignBits > (DestBitSize - SrcBitSize))
8332 return ReplaceInstUsesWith(CI, Res);
8334 // We need to emit a cast to truncate, then a cast to sext.
8335 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8341 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8342 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8344 switch (SrcI->getOpcode()) {
8345 case Instruction::Add:
8346 case Instruction::Mul:
8347 case Instruction::And:
8348 case Instruction::Or:
8349 case Instruction::Xor:
8350 // If we are discarding information, rewrite.
8351 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8352 // Don't insert two casts unless at least one can be eliminated.
8353 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8354 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8355 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8356 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8357 return BinaryOperator::Create(
8358 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8362 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8363 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8364 SrcI->getOpcode() == Instruction::Xor &&
8365 Op1 == ConstantInt::getTrue(*Context) &&
8366 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8367 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8368 return BinaryOperator::CreateXor(New,
8369 ConstantInt::get(CI.getType(), 1));
8373 case Instruction::Shl: {
8374 // Canonicalize trunc inside shl, if we can.
8375 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8376 if (CI && DestBitSize < SrcBitSize &&
8377 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8378 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8379 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8380 return BinaryOperator::CreateShl(Op0c, Op1c);
8388 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8389 if (Instruction *Result = commonIntCastTransforms(CI))
8392 Value *Src = CI.getOperand(0);
8393 const Type *Ty = CI.getType();
8394 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8395 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8397 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8398 if (DestBitWidth == 1) {
8399 Constant *One = ConstantInt::get(Src->getType(), 1);
8400 Src = Builder->CreateAnd(Src, One, "tmp");
8401 Value *Zero = Constant::getNullValue(Src->getType());
8402 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8405 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8406 ConstantInt *ShAmtV = 0;
8408 if (Src->hasOneUse() &&
8409 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8410 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8412 // Get a mask for the bits shifting in.
8413 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8414 if (MaskedValueIsZero(ShiftOp, Mask)) {
8415 if (ShAmt >= DestBitWidth) // All zeros.
8416 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8418 // Okay, we can shrink this. Truncate the input, then return a new
8420 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8421 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8422 return BinaryOperator::CreateLShr(V1, V2);
8429 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8430 /// in order to eliminate the icmp.
8431 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8433 // If we are just checking for a icmp eq of a single bit and zext'ing it
8434 // to an integer, then shift the bit to the appropriate place and then
8435 // cast to integer to avoid the comparison.
8436 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8437 const APInt &Op1CV = Op1C->getValue();
8439 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8440 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8441 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8442 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8443 if (!DoXform) return ICI;
8445 Value *In = ICI->getOperand(0);
8446 Value *Sh = ConstantInt::get(In->getType(),
8447 In->getType()->getScalarSizeInBits()-1);
8448 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8449 if (In->getType() != CI.getType())
8450 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8452 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8453 Constant *One = ConstantInt::get(In->getType(), 1);
8454 In = Builder->CreateXor(In, One, In->getName()+".not");
8457 return ReplaceInstUsesWith(CI, In);
8462 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8463 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8464 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8465 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8466 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8467 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8468 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8469 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8470 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8471 // This only works for EQ and NE
8472 ICI->isEquality()) {
8473 // If Op1C some other power of two, convert:
8474 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8475 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8476 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8477 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8479 APInt KnownZeroMask(~KnownZero);
8480 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8481 if (!DoXform) return ICI;
8483 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8484 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8485 // (X&4) == 2 --> false
8486 // (X&4) != 2 --> true
8487 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8488 Res = ConstantExpr::getZExt(Res, CI.getType());
8489 return ReplaceInstUsesWith(CI, Res);
8492 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8493 Value *In = ICI->getOperand(0);
8495 // Perform a logical shr by shiftamt.
8496 // Insert the shift to put the result in the low bit.
8497 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8498 In->getName()+".lobit");
8501 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8502 Constant *One = ConstantInt::get(In->getType(), 1);
8503 In = Builder->CreateXor(In, One, "tmp");
8506 if (CI.getType() == In->getType())
8507 return ReplaceInstUsesWith(CI, In);
8509 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8517 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8518 // If one of the common conversion will work ..
8519 if (Instruction *Result = commonIntCastTransforms(CI))
8522 Value *Src = CI.getOperand(0);
8524 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8525 // types and if the sizes are just right we can convert this into a logical
8526 // 'and' which will be much cheaper than the pair of casts.
8527 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8528 // Get the sizes of the types involved. We know that the intermediate type
8529 // will be smaller than A or C, but don't know the relation between A and C.
8530 Value *A = CSrc->getOperand(0);
8531 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8532 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8533 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8534 // If we're actually extending zero bits, then if
8535 // SrcSize < DstSize: zext(a & mask)
8536 // SrcSize == DstSize: a & mask
8537 // SrcSize > DstSize: trunc(a) & mask
8538 if (SrcSize < DstSize) {
8539 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8540 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8541 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8542 return new ZExtInst(And, CI.getType());
8545 if (SrcSize == DstSize) {
8546 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8547 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8550 if (SrcSize > DstSize) {
8551 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8552 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8553 return BinaryOperator::CreateAnd(Trunc,
8554 ConstantInt::get(Trunc->getType(),
8559 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8560 return transformZExtICmp(ICI, CI);
8562 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8563 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8564 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8565 // of the (zext icmp) will be transformed.
8566 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8567 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8568 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8569 (transformZExtICmp(LHS, CI, false) ||
8570 transformZExtICmp(RHS, CI, false))) {
8571 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8572 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8573 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8577 // zext(trunc(t) & C) -> (t & zext(C)).
8578 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8579 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8580 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8581 Value *TI0 = TI->getOperand(0);
8582 if (TI0->getType() == CI.getType())
8584 BinaryOperator::CreateAnd(TI0,
8585 ConstantExpr::getZExt(C, CI.getType()));
8588 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8589 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8590 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8591 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8592 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8593 And->getOperand(1) == C)
8594 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8595 Value *TI0 = TI->getOperand(0);
8596 if (TI0->getType() == CI.getType()) {
8597 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8598 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8599 return BinaryOperator::CreateXor(NewAnd, ZC);
8606 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8607 if (Instruction *I = commonIntCastTransforms(CI))
8610 Value *Src = CI.getOperand(0);
8612 // Canonicalize sign-extend from i1 to a select.
8613 if (Src->getType() == Type::getInt1Ty(*Context))
8614 return SelectInst::Create(Src,
8615 Constant::getAllOnesValue(CI.getType()),
8616 Constant::getNullValue(CI.getType()));
8618 // See if the value being truncated is already sign extended. If so, just
8619 // eliminate the trunc/sext pair.
8620 if (Operator::getOpcode(Src) == Instruction::Trunc) {
8621 Value *Op = cast<User>(Src)->getOperand(0);
8622 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8623 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8624 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8625 unsigned NumSignBits = ComputeNumSignBits(Op);
8627 if (OpBits == DestBits) {
8628 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8629 // bits, it is already ready.
8630 if (NumSignBits > DestBits-MidBits)
8631 return ReplaceInstUsesWith(CI, Op);
8632 } else if (OpBits < DestBits) {
8633 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8634 // bits, just sext from i32.
8635 if (NumSignBits > OpBits-MidBits)
8636 return new SExtInst(Op, CI.getType(), "tmp");
8638 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8639 // bits, just truncate to i32.
8640 if (NumSignBits > OpBits-MidBits)
8641 return new TruncInst(Op, CI.getType(), "tmp");
8645 // If the input is a shl/ashr pair of a same constant, then this is a sign
8646 // extension from a smaller value. If we could trust arbitrary bitwidth
8647 // integers, we could turn this into a truncate to the smaller bit and then
8648 // use a sext for the whole extension. Since we don't, look deeper and check
8649 // for a truncate. If the source and dest are the same type, eliminate the
8650 // trunc and extend and just do shifts. For example, turn:
8651 // %a = trunc i32 %i to i8
8652 // %b = shl i8 %a, 6
8653 // %c = ashr i8 %b, 6
8654 // %d = sext i8 %c to i32
8656 // %a = shl i32 %i, 30
8657 // %d = ashr i32 %a, 30
8659 ConstantInt *BA = 0, *CA = 0;
8660 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8661 m_ConstantInt(CA))) &&
8662 BA == CA && isa<TruncInst>(A)) {
8663 Value *I = cast<TruncInst>(A)->getOperand(0);
8664 if (I->getType() == CI.getType()) {
8665 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8666 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8667 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8668 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8669 I = Builder->CreateShl(I, ShAmtV, CI.getName());
8670 return BinaryOperator::CreateAShr(I, ShAmtV);
8677 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8678 /// in the specified FP type without changing its value.
8679 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8680 LLVMContext *Context) {
8682 APFloat F = CFP->getValueAPF();
8683 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8685 return ConstantFP::get(*Context, F);
8689 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8690 /// through it until we get the source value.
8691 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8692 if (Instruction *I = dyn_cast<Instruction>(V))
8693 if (I->getOpcode() == Instruction::FPExt)
8694 return LookThroughFPExtensions(I->getOperand(0), Context);
8696 // If this value is a constant, return the constant in the smallest FP type
8697 // that can accurately represent it. This allows us to turn
8698 // (float)((double)X+2.0) into x+2.0f.
8699 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8700 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8701 return V; // No constant folding of this.
8702 // See if the value can be truncated to float and then reextended.
8703 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8705 if (CFP->getType() == Type::getDoubleTy(*Context))
8706 return V; // Won't shrink.
8707 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8709 // Don't try to shrink to various long double types.
8715 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8716 if (Instruction *I = commonCastTransforms(CI))
8719 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8720 // smaller than the destination type, we can eliminate the truncate by doing
8721 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8722 // many builtins (sqrt, etc).
8723 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8724 if (OpI && OpI->hasOneUse()) {
8725 switch (OpI->getOpcode()) {
8727 case Instruction::FAdd:
8728 case Instruction::FSub:
8729 case Instruction::FMul:
8730 case Instruction::FDiv:
8731 case Instruction::FRem:
8732 const Type *SrcTy = OpI->getType();
8733 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8734 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8735 if (LHSTrunc->getType() != SrcTy &&
8736 RHSTrunc->getType() != SrcTy) {
8737 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8738 // If the source types were both smaller than the destination type of
8739 // the cast, do this xform.
8740 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8741 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8742 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8743 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8744 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8753 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8754 return commonCastTransforms(CI);
8757 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8758 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8760 return commonCastTransforms(FI);
8762 // fptoui(uitofp(X)) --> X
8763 // fptoui(sitofp(X)) --> X
8764 // This is safe if the intermediate type has enough bits in its mantissa to
8765 // accurately represent all values of X. For example, do not do this with
8766 // i64->float->i64. This is also safe for sitofp case, because any negative
8767 // 'X' value would cause an undefined result for the fptoui.
8768 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8769 OpI->getOperand(0)->getType() == FI.getType() &&
8770 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8771 OpI->getType()->getFPMantissaWidth())
8772 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8774 return commonCastTransforms(FI);
8777 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8778 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8780 return commonCastTransforms(FI);
8782 // fptosi(sitofp(X)) --> X
8783 // fptosi(uitofp(X)) --> X
8784 // This is safe if the intermediate type has enough bits in its mantissa to
8785 // accurately represent all values of X. For example, do not do this with
8786 // i64->float->i64. This is also safe for sitofp case, because any negative
8787 // 'X' value would cause an undefined result for the fptoui.
8788 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8789 OpI->getOperand(0)->getType() == FI.getType() &&
8790 (int)FI.getType()->getScalarSizeInBits() <=
8791 OpI->getType()->getFPMantissaWidth())
8792 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8794 return commonCastTransforms(FI);
8797 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8798 return commonCastTransforms(CI);
8801 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8802 return commonCastTransforms(CI);
8805 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8806 // If the destination integer type is smaller than the intptr_t type for
8807 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8808 // trunc to be exposed to other transforms. Don't do this for extending
8809 // ptrtoint's, because we don't know if the target sign or zero extends its
8812 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8813 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8814 TD->getIntPtrType(CI.getContext()),
8816 return new TruncInst(P, CI.getType());
8819 return commonPointerCastTransforms(CI);
8822 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8823 // If the source integer type is larger than the intptr_t type for
8824 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8825 // allows the trunc to be exposed to other transforms. Don't do this for
8826 // extending inttoptr's, because we don't know if the target sign or zero
8827 // extends to pointers.
8828 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8829 TD->getPointerSizeInBits()) {
8830 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8831 TD->getIntPtrType(CI.getContext()), "tmp");
8832 return new IntToPtrInst(P, CI.getType());
8835 if (Instruction *I = commonCastTransforms(CI))
8841 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8842 // If the operands are integer typed then apply the integer transforms,
8843 // otherwise just apply the common ones.
8844 Value *Src = CI.getOperand(0);
8845 const Type *SrcTy = Src->getType();
8846 const Type *DestTy = CI.getType();
8848 if (isa<PointerType>(SrcTy)) {
8849 if (Instruction *I = commonPointerCastTransforms(CI))
8852 if (Instruction *Result = commonCastTransforms(CI))
8857 // Get rid of casts from one type to the same type. These are useless and can
8858 // be replaced by the operand.
8859 if (DestTy == Src->getType())
8860 return ReplaceInstUsesWith(CI, Src);
8862 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8863 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8864 const Type *DstElTy = DstPTy->getElementType();
8865 const Type *SrcElTy = SrcPTy->getElementType();
8867 // If the address spaces don't match, don't eliminate the bitcast, which is
8868 // required for changing types.
8869 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8872 // If we are casting a alloca to a pointer to a type of the same
8873 // size, rewrite the allocation instruction to allocate the "right" type.
8874 // There is no need to modify malloc calls because it is their bitcast that
8875 // needs to be cleaned up.
8876 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8877 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8880 // If the source and destination are pointers, and this cast is equivalent
8881 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8882 // This can enhance SROA and other transforms that want type-safe pointers.
8883 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8884 unsigned NumZeros = 0;
8885 while (SrcElTy != DstElTy &&
8886 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8887 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8888 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8892 // If we found a path from the src to dest, create the getelementptr now.
8893 if (SrcElTy == DstElTy) {
8894 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8895 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8896 ((Instruction*) NULL));
8900 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8901 if (DestVTy->getNumElements() == 1) {
8902 if (!isa<VectorType>(SrcTy)) {
8903 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8904 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8905 Constant::getNullValue(Type::getInt32Ty(*Context)));
8907 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8911 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8912 if (SrcVTy->getNumElements() == 1) {
8913 if (!isa<VectorType>(DestTy)) {
8915 Builder->CreateExtractElement(Src,
8916 Constant::getNullValue(Type::getInt32Ty(*Context)));
8917 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8922 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8923 if (SVI->hasOneUse()) {
8924 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8925 // a bitconvert to a vector with the same # elts.
8926 if (isa<VectorType>(DestTy) &&
8927 cast<VectorType>(DestTy)->getNumElements() ==
8928 SVI->getType()->getNumElements() &&
8929 SVI->getType()->getNumElements() ==
8930 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8932 // If either of the operands is a cast from CI.getType(), then
8933 // evaluating the shuffle in the casted destination's type will allow
8934 // us to eliminate at least one cast.
8935 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8936 Tmp->getOperand(0)->getType() == DestTy) ||
8937 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8938 Tmp->getOperand(0)->getType() == DestTy)) {
8939 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8940 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8941 // Return a new shuffle vector. Use the same element ID's, as we
8942 // know the vector types match #elts.
8943 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8951 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8953 /// %D = select %cond, %C, %A
8955 /// %C = select %cond, %B, 0
8958 /// Assuming that the specified instruction is an operand to the select, return
8959 /// a bitmask indicating which operands of this instruction are foldable if they
8960 /// equal the other incoming value of the select.
8962 static unsigned GetSelectFoldableOperands(Instruction *I) {
8963 switch (I->getOpcode()) {
8964 case Instruction::Add:
8965 case Instruction::Mul:
8966 case Instruction::And:
8967 case Instruction::Or:
8968 case Instruction::Xor:
8969 return 3; // Can fold through either operand.
8970 case Instruction::Sub: // Can only fold on the amount subtracted.
8971 case Instruction::Shl: // Can only fold on the shift amount.
8972 case Instruction::LShr:
8973 case Instruction::AShr:
8976 return 0; // Cannot fold
8980 /// GetSelectFoldableConstant - For the same transformation as the previous
8981 /// function, return the identity constant that goes into the select.
8982 static Constant *GetSelectFoldableConstant(Instruction *I,
8983 LLVMContext *Context) {
8984 switch (I->getOpcode()) {
8985 default: llvm_unreachable("This cannot happen!");
8986 case Instruction::Add:
8987 case Instruction::Sub:
8988 case Instruction::Or:
8989 case Instruction::Xor:
8990 case Instruction::Shl:
8991 case Instruction::LShr:
8992 case Instruction::AShr:
8993 return Constant::getNullValue(I->getType());
8994 case Instruction::And:
8995 return Constant::getAllOnesValue(I->getType());
8996 case Instruction::Mul:
8997 return ConstantInt::get(I->getType(), 1);
9001 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9002 /// have the same opcode and only one use each. Try to simplify this.
9003 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9005 if (TI->getNumOperands() == 1) {
9006 // If this is a non-volatile load or a cast from the same type,
9009 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9012 return 0; // unknown unary op.
9015 // Fold this by inserting a select from the input values.
9016 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9017 FI->getOperand(0), SI.getName()+".v");
9018 InsertNewInstBefore(NewSI, SI);
9019 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
9023 // Only handle binary operators here.
9024 if (!isa<BinaryOperator>(TI))
9027 // Figure out if the operations have any operands in common.
9028 Value *MatchOp, *OtherOpT, *OtherOpF;
9030 if (TI->getOperand(0) == FI->getOperand(0)) {
9031 MatchOp = TI->getOperand(0);
9032 OtherOpT = TI->getOperand(1);
9033 OtherOpF = FI->getOperand(1);
9034 MatchIsOpZero = true;
9035 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9036 MatchOp = TI->getOperand(1);
9037 OtherOpT = TI->getOperand(0);
9038 OtherOpF = FI->getOperand(0);
9039 MatchIsOpZero = false;
9040 } else if (!TI->isCommutative()) {
9042 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9043 MatchOp = TI->getOperand(0);
9044 OtherOpT = TI->getOperand(1);
9045 OtherOpF = FI->getOperand(0);
9046 MatchIsOpZero = true;
9047 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9048 MatchOp = TI->getOperand(1);
9049 OtherOpT = TI->getOperand(0);
9050 OtherOpF = FI->getOperand(1);
9051 MatchIsOpZero = true;
9056 // If we reach here, they do have operations in common.
9057 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9058 OtherOpF, SI.getName()+".v");
9059 InsertNewInstBefore(NewSI, SI);
9061 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9063 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9065 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9067 llvm_unreachable("Shouldn't get here");
9071 static bool isSelect01(Constant *C1, Constant *C2) {
9072 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9075 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9078 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9081 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9082 /// facilitate further optimization.
9083 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9085 // See the comment above GetSelectFoldableOperands for a description of the
9086 // transformation we are doing here.
9087 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9088 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9089 !isa<Constant>(FalseVal)) {
9090 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9091 unsigned OpToFold = 0;
9092 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9094 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9099 Constant *C = GetSelectFoldableConstant(TVI, Context);
9100 Value *OOp = TVI->getOperand(2-OpToFold);
9101 // Avoid creating select between 2 constants unless it's selecting
9103 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9104 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9105 InsertNewInstBefore(NewSel, SI);
9106 NewSel->takeName(TVI);
9107 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9108 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9109 llvm_unreachable("Unknown instruction!!");
9116 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9117 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9118 !isa<Constant>(TrueVal)) {
9119 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9120 unsigned OpToFold = 0;
9121 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9123 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9128 Constant *C = GetSelectFoldableConstant(FVI, Context);
9129 Value *OOp = FVI->getOperand(2-OpToFold);
9130 // Avoid creating select between 2 constants unless it's selecting
9132 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9133 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9134 InsertNewInstBefore(NewSel, SI);
9135 NewSel->takeName(FVI);
9136 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9137 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9138 llvm_unreachable("Unknown instruction!!");
9148 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9149 /// ICmpInst as its first operand.
9151 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9153 bool Changed = false;
9154 ICmpInst::Predicate Pred = ICI->getPredicate();
9155 Value *CmpLHS = ICI->getOperand(0);
9156 Value *CmpRHS = ICI->getOperand(1);
9157 Value *TrueVal = SI.getTrueValue();
9158 Value *FalseVal = SI.getFalseValue();
9160 // Check cases where the comparison is with a constant that
9161 // can be adjusted to fit the min/max idiom. We may edit ICI in
9162 // place here, so make sure the select is the only user.
9163 if (ICI->hasOneUse())
9164 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9167 case ICmpInst::ICMP_ULT:
9168 case ICmpInst::ICMP_SLT: {
9169 // X < MIN ? T : F --> F
9170 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9171 return ReplaceInstUsesWith(SI, FalseVal);
9172 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9173 Constant *AdjustedRHS = SubOne(CI);
9174 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9175 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9176 Pred = ICmpInst::getSwappedPredicate(Pred);
9177 CmpRHS = AdjustedRHS;
9178 std::swap(FalseVal, TrueVal);
9179 ICI->setPredicate(Pred);
9180 ICI->setOperand(1, CmpRHS);
9181 SI.setOperand(1, TrueVal);
9182 SI.setOperand(2, FalseVal);
9187 case ICmpInst::ICMP_UGT:
9188 case ICmpInst::ICMP_SGT: {
9189 // X > MAX ? T : F --> F
9190 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9191 return ReplaceInstUsesWith(SI, FalseVal);
9192 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9193 Constant *AdjustedRHS = AddOne(CI);
9194 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9195 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9196 Pred = ICmpInst::getSwappedPredicate(Pred);
9197 CmpRHS = AdjustedRHS;
9198 std::swap(FalseVal, TrueVal);
9199 ICI->setPredicate(Pred);
9200 ICI->setOperand(1, CmpRHS);
9201 SI.setOperand(1, TrueVal);
9202 SI.setOperand(2, FalseVal);
9209 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9210 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9211 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9212 if (match(TrueVal, m_ConstantInt<-1>()) &&
9213 match(FalseVal, m_ConstantInt<0>()))
9214 Pred = ICI->getPredicate();
9215 else if (match(TrueVal, m_ConstantInt<0>()) &&
9216 match(FalseVal, m_ConstantInt<-1>()))
9217 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9219 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9220 // If we are just checking for a icmp eq of a single bit and zext'ing it
9221 // to an integer, then shift the bit to the appropriate place and then
9222 // cast to integer to avoid the comparison.
9223 const APInt &Op1CV = CI->getValue();
9225 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9226 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9227 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9228 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9229 Value *In = ICI->getOperand(0);
9230 Value *Sh = ConstantInt::get(In->getType(),
9231 In->getType()->getScalarSizeInBits()-1);
9232 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9233 In->getName()+".lobit"),
9235 if (In->getType() != SI.getType())
9236 In = CastInst::CreateIntegerCast(In, SI.getType(),
9237 true/*SExt*/, "tmp", ICI);
9239 if (Pred == ICmpInst::ICMP_SGT)
9240 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9241 In->getName()+".not"), *ICI);
9243 return ReplaceInstUsesWith(SI, In);
9248 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9249 // Transform (X == Y) ? X : Y -> Y
9250 if (Pred == ICmpInst::ICMP_EQ)
9251 return ReplaceInstUsesWith(SI, FalseVal);
9252 // Transform (X != Y) ? X : Y -> X
9253 if (Pred == ICmpInst::ICMP_NE)
9254 return ReplaceInstUsesWith(SI, TrueVal);
9255 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9257 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9258 // Transform (X == Y) ? Y : X -> X
9259 if (Pred == ICmpInst::ICMP_EQ)
9260 return ReplaceInstUsesWith(SI, FalseVal);
9261 // Transform (X != Y) ? Y : X -> Y
9262 if (Pred == ICmpInst::ICMP_NE)
9263 return ReplaceInstUsesWith(SI, TrueVal);
9264 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9267 /// NOTE: if we wanted to, this is where to detect integer ABS
9269 return Changed ? &SI : 0;
9272 /// isDefinedInBB - Return true if the value is an instruction defined in the
9273 /// specified basicblock.
9274 static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9275 const Instruction *I = dyn_cast<Instruction>(V);
9276 return I != 0 && I->getParent() == BB;
9280 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9281 Value *CondVal = SI.getCondition();
9282 Value *TrueVal = SI.getTrueValue();
9283 Value *FalseVal = SI.getFalseValue();
9285 // select true, X, Y -> X
9286 // select false, X, Y -> Y
9287 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9288 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9290 // select C, X, X -> X
9291 if (TrueVal == FalseVal)
9292 return ReplaceInstUsesWith(SI, TrueVal);
9294 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9295 return ReplaceInstUsesWith(SI, FalseVal);
9296 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9297 return ReplaceInstUsesWith(SI, TrueVal);
9298 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9299 if (isa<Constant>(TrueVal))
9300 return ReplaceInstUsesWith(SI, TrueVal);
9302 return ReplaceInstUsesWith(SI, FalseVal);
9305 if (SI.getType() == Type::getInt1Ty(*Context)) {
9306 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9307 if (C->getZExtValue()) {
9308 // Change: A = select B, true, C --> A = or B, C
9309 return BinaryOperator::CreateOr(CondVal, FalseVal);
9311 // Change: A = select B, false, C --> A = and !B, C
9313 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9314 "not."+CondVal->getName()), SI);
9315 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9317 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9318 if (C->getZExtValue() == false) {
9319 // Change: A = select B, C, false --> A = and B, C
9320 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9322 // Change: A = select B, C, true --> A = or !B, C
9324 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9325 "not."+CondVal->getName()), SI);
9326 return BinaryOperator::CreateOr(NotCond, TrueVal);
9330 // select a, b, a -> a&b
9331 // select a, a, b -> a|b
9332 if (CondVal == TrueVal)
9333 return BinaryOperator::CreateOr(CondVal, FalseVal);
9334 else if (CondVal == FalseVal)
9335 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9338 // Selecting between two integer constants?
9339 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9340 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9341 // select C, 1, 0 -> zext C to int
9342 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9343 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9344 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9345 // select C, 0, 1 -> zext !C to int
9347 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9348 "not."+CondVal->getName()), SI);
9349 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9352 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9353 // If one of the constants is zero (we know they can't both be) and we
9354 // have an icmp instruction with zero, and we have an 'and' with the
9355 // non-constant value, eliminate this whole mess. This corresponds to
9356 // cases like this: ((X & 27) ? 27 : 0)
9357 if (TrueValC->isZero() || FalseValC->isZero())
9358 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9359 cast<Constant>(IC->getOperand(1))->isNullValue())
9360 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9361 if (ICA->getOpcode() == Instruction::And &&
9362 isa<ConstantInt>(ICA->getOperand(1)) &&
9363 (ICA->getOperand(1) == TrueValC ||
9364 ICA->getOperand(1) == FalseValC) &&
9365 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9366 // Okay, now we know that everything is set up, we just don't
9367 // know whether we have a icmp_ne or icmp_eq and whether the
9368 // true or false val is the zero.
9369 bool ShouldNotVal = !TrueValC->isZero();
9370 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9373 V = InsertNewInstBefore(BinaryOperator::Create(
9374 Instruction::Xor, V, ICA->getOperand(1)), SI);
9375 return ReplaceInstUsesWith(SI, V);
9380 // See if we are selecting two values based on a comparison of the two values.
9381 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9382 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9383 // Transform (X == Y) ? X : Y -> Y
9384 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9385 // This is not safe in general for floating point:
9386 // consider X== -0, Y== +0.
9387 // It becomes safe if either operand is a nonzero constant.
9388 ConstantFP *CFPt, *CFPf;
9389 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9390 !CFPt->getValueAPF().isZero()) ||
9391 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9392 !CFPf->getValueAPF().isZero()))
9393 return ReplaceInstUsesWith(SI, FalseVal);
9395 // Transform (X != Y) ? X : Y -> X
9396 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9397 return ReplaceInstUsesWith(SI, TrueVal);
9398 // NOTE: if we wanted to, this is where to detect MIN/MAX
9400 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9401 // Transform (X == Y) ? Y : X -> X
9402 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9403 // This is not safe in general for floating point:
9404 // consider X== -0, Y== +0.
9405 // It becomes safe if either operand is a nonzero constant.
9406 ConstantFP *CFPt, *CFPf;
9407 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9408 !CFPt->getValueAPF().isZero()) ||
9409 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9410 !CFPf->getValueAPF().isZero()))
9411 return ReplaceInstUsesWith(SI, FalseVal);
9413 // Transform (X != Y) ? Y : X -> Y
9414 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9415 return ReplaceInstUsesWith(SI, TrueVal);
9416 // NOTE: if we wanted to, this is where to detect MIN/MAX
9418 // NOTE: if we wanted to, this is where to detect ABS
9421 // See if we are selecting two values based on a comparison of the two values.
9422 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9423 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9426 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9427 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9428 if (TI->hasOneUse() && FI->hasOneUse()) {
9429 Instruction *AddOp = 0, *SubOp = 0;
9431 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9432 if (TI->getOpcode() == FI->getOpcode())
9433 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9436 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9437 // even legal for FP.
9438 if ((TI->getOpcode() == Instruction::Sub &&
9439 FI->getOpcode() == Instruction::Add) ||
9440 (TI->getOpcode() == Instruction::FSub &&
9441 FI->getOpcode() == Instruction::FAdd)) {
9442 AddOp = FI; SubOp = TI;
9443 } else if ((FI->getOpcode() == Instruction::Sub &&
9444 TI->getOpcode() == Instruction::Add) ||
9445 (FI->getOpcode() == Instruction::FSub &&
9446 TI->getOpcode() == Instruction::FAdd)) {
9447 AddOp = TI; SubOp = FI;
9451 Value *OtherAddOp = 0;
9452 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9453 OtherAddOp = AddOp->getOperand(1);
9454 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9455 OtherAddOp = AddOp->getOperand(0);
9459 // So at this point we know we have (Y -> OtherAddOp):
9460 // select C, (add X, Y), (sub X, Z)
9461 Value *NegVal; // Compute -Z
9462 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9463 NegVal = ConstantExpr::getNeg(C);
9465 NegVal = InsertNewInstBefore(
9466 BinaryOperator::CreateNeg(SubOp->getOperand(1),
9470 Value *NewTrueOp = OtherAddOp;
9471 Value *NewFalseOp = NegVal;
9473 std::swap(NewTrueOp, NewFalseOp);
9474 Instruction *NewSel =
9475 SelectInst::Create(CondVal, NewTrueOp,
9476 NewFalseOp, SI.getName() + ".p");
9478 NewSel = InsertNewInstBefore(NewSel, SI);
9479 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9484 // See if we can fold the select into one of our operands.
9485 if (SI.getType()->isInteger()) {
9486 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9491 // See if we can fold the select into a phi node. The true/false values have
9492 // to be live in the predecessor blocks. If they are instructions in SI's
9493 // block, we can't map to the predecessor.
9494 if (isa<PHINode>(SI.getCondition()) &&
9495 (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9496 isa<PHINode>(SI.getTrueValue())) &&
9497 (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9498 isa<PHINode>(SI.getFalseValue())))
9499 if (Instruction *NV = FoldOpIntoPhi(SI))
9502 if (BinaryOperator::isNot(CondVal)) {
9503 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9504 SI.setOperand(1, FalseVal);
9505 SI.setOperand(2, TrueVal);
9512 /// EnforceKnownAlignment - If the specified pointer points to an object that
9513 /// we control, modify the object's alignment to PrefAlign. This isn't
9514 /// often possible though. If alignment is important, a more reliable approach
9515 /// is to simply align all global variables and allocation instructions to
9516 /// their preferred alignment from the beginning.
9518 static unsigned EnforceKnownAlignment(Value *V,
9519 unsigned Align, unsigned PrefAlign) {
9521 User *U = dyn_cast<User>(V);
9522 if (!U) return Align;
9524 switch (Operator::getOpcode(U)) {
9526 case Instruction::BitCast:
9527 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9528 case Instruction::GetElementPtr: {
9529 // If all indexes are zero, it is just the alignment of the base pointer.
9530 bool AllZeroOperands = true;
9531 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9532 if (!isa<Constant>(*i) ||
9533 !cast<Constant>(*i)->isNullValue()) {
9534 AllZeroOperands = false;
9538 if (AllZeroOperands) {
9539 // Treat this like a bitcast.
9540 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9546 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9547 // If there is a large requested alignment and we can, bump up the alignment
9549 if (!GV->isDeclaration()) {
9550 if (GV->getAlignment() >= PrefAlign)
9551 Align = GV->getAlignment();
9553 GV->setAlignment(PrefAlign);
9557 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9558 // If there is a requested alignment and if this is an alloca, round up.
9559 if (AI->getAlignment() >= PrefAlign)
9560 Align = AI->getAlignment();
9562 AI->setAlignment(PrefAlign);
9570 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9571 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9572 /// and it is more than the alignment of the ultimate object, see if we can
9573 /// increase the alignment of the ultimate object, making this check succeed.
9574 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9575 unsigned PrefAlign) {
9576 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9577 sizeof(PrefAlign) * CHAR_BIT;
9578 APInt Mask = APInt::getAllOnesValue(BitWidth);
9579 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9580 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9581 unsigned TrailZ = KnownZero.countTrailingOnes();
9582 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9584 if (PrefAlign > Align)
9585 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9587 // We don't need to make any adjustment.
9591 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9592 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9593 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9594 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9595 unsigned CopyAlign = MI->getAlignment();
9597 if (CopyAlign < MinAlign) {
9598 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9603 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9605 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9606 if (MemOpLength == 0) return 0;
9608 // Source and destination pointer types are always "i8*" for intrinsic. See
9609 // if the size is something we can handle with a single primitive load/store.
9610 // A single load+store correctly handles overlapping memory in the memmove
9612 unsigned Size = MemOpLength->getZExtValue();
9613 if (Size == 0) return MI; // Delete this mem transfer.
9615 if (Size > 8 || (Size&(Size-1)))
9616 return 0; // If not 1/2/4/8 bytes, exit.
9618 // Use an integer load+store unless we can find something better.
9620 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9622 // Memcpy forces the use of i8* for the source and destination. That means
9623 // that if you're using memcpy to move one double around, you'll get a cast
9624 // from double* to i8*. We'd much rather use a double load+store rather than
9625 // an i64 load+store, here because this improves the odds that the source or
9626 // dest address will be promotable. See if we can find a better type than the
9627 // integer datatype.
9628 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9629 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9630 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9631 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9632 // down through these levels if so.
9633 while (!SrcETy->isSingleValueType()) {
9634 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9635 if (STy->getNumElements() == 1)
9636 SrcETy = STy->getElementType(0);
9639 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9640 if (ATy->getNumElements() == 1)
9641 SrcETy = ATy->getElementType();
9648 if (SrcETy->isSingleValueType())
9649 NewPtrTy = PointerType::getUnqual(SrcETy);
9654 // If the memcpy/memmove provides better alignment info than we can
9656 SrcAlign = std::max(SrcAlign, CopyAlign);
9657 DstAlign = std::max(DstAlign, CopyAlign);
9659 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9660 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9661 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9662 InsertNewInstBefore(L, *MI);
9663 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9665 // Set the size of the copy to 0, it will be deleted on the next iteration.
9666 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9670 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9671 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9672 if (MI->getAlignment() < Alignment) {
9673 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9678 // Extract the length and alignment and fill if they are constant.
9679 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9680 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9681 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9683 uint64_t Len = LenC->getZExtValue();
9684 Alignment = MI->getAlignment();
9686 // If the length is zero, this is a no-op
9687 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9689 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9690 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9691 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
9693 Value *Dest = MI->getDest();
9694 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9696 // Alignment 0 is identity for alignment 1 for memset, but not store.
9697 if (Alignment == 0) Alignment = 1;
9699 // Extract the fill value and store.
9700 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9701 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9702 Dest, false, Alignment), *MI);
9704 // Set the size of the copy to 0, it will be deleted on the next iteration.
9705 MI->setLength(Constant::getNullValue(LenC->getType()));
9713 /// visitCallInst - CallInst simplification. This mostly only handles folding
9714 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9715 /// the heavy lifting.
9717 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9718 // If the caller function is nounwind, mark the call as nounwind, even if the
9720 if (CI.getParent()->getParent()->doesNotThrow() &&
9721 !CI.doesNotThrow()) {
9722 CI.setDoesNotThrow();
9726 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9727 if (!II) return visitCallSite(&CI);
9729 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9731 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9732 bool Changed = false;
9734 // memmove/cpy/set of zero bytes is a noop.
9735 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9736 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9738 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9739 if (CI->getZExtValue() == 1) {
9740 // Replace the instruction with just byte operations. We would
9741 // transform other cases to loads/stores, but we don't know if
9742 // alignment is sufficient.
9746 // If we have a memmove and the source operation is a constant global,
9747 // then the source and dest pointers can't alias, so we can change this
9748 // into a call to memcpy.
9749 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9750 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9751 if (GVSrc->isConstant()) {
9752 Module *M = CI.getParent()->getParent()->getParent();
9753 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9755 Tys[0] = CI.getOperand(3)->getType();
9757 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9761 // memmove(x,x,size) -> noop.
9762 if (MMI->getSource() == MMI->getDest())
9763 return EraseInstFromFunction(CI);
9766 // If we can determine a pointer alignment that is bigger than currently
9767 // set, update the alignment.
9768 if (isa<MemTransferInst>(MI)) {
9769 if (Instruction *I = SimplifyMemTransfer(MI))
9771 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9772 if (Instruction *I = SimplifyMemSet(MSI))
9776 if (Changed) return II;
9779 switch (II->getIntrinsicID()) {
9781 case Intrinsic::bswap:
9782 // bswap(bswap(x)) -> x
9783 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9784 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9785 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9787 case Intrinsic::ppc_altivec_lvx:
9788 case Intrinsic::ppc_altivec_lvxl:
9789 case Intrinsic::x86_sse_loadu_ps:
9790 case Intrinsic::x86_sse2_loadu_pd:
9791 case Intrinsic::x86_sse2_loadu_dq:
9792 // Turn PPC lvx -> load if the pointer is known aligned.
9793 // Turn X86 loadups -> load if the pointer is known aligned.
9794 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9795 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9796 PointerType::getUnqual(II->getType()));
9797 return new LoadInst(Ptr);
9800 case Intrinsic::ppc_altivec_stvx:
9801 case Intrinsic::ppc_altivec_stvxl:
9802 // Turn stvx -> store if the pointer is known aligned.
9803 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9804 const Type *OpPtrTy =
9805 PointerType::getUnqual(II->getOperand(1)->getType());
9806 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9807 return new StoreInst(II->getOperand(1), Ptr);
9810 case Intrinsic::x86_sse_storeu_ps:
9811 case Intrinsic::x86_sse2_storeu_pd:
9812 case Intrinsic::x86_sse2_storeu_dq:
9813 // Turn X86 storeu -> store if the pointer is known aligned.
9814 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9815 const Type *OpPtrTy =
9816 PointerType::getUnqual(II->getOperand(2)->getType());
9817 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9818 return new StoreInst(II->getOperand(2), Ptr);
9822 case Intrinsic::x86_sse_cvttss2si: {
9823 // These intrinsics only demands the 0th element of its input vector. If
9824 // we can simplify the input based on that, do so now.
9826 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9827 APInt DemandedElts(VWidth, 1);
9828 APInt UndefElts(VWidth, 0);
9829 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9831 II->setOperand(1, V);
9837 case Intrinsic::ppc_altivec_vperm:
9838 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9839 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9840 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9842 // Check that all of the elements are integer constants or undefs.
9843 bool AllEltsOk = true;
9844 for (unsigned i = 0; i != 16; ++i) {
9845 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9846 !isa<UndefValue>(Mask->getOperand(i))) {
9853 // Cast the input vectors to byte vectors.
9854 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9855 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9856 Value *Result = UndefValue::get(Op0->getType());
9858 // Only extract each element once.
9859 Value *ExtractedElts[32];
9860 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9862 for (unsigned i = 0; i != 16; ++i) {
9863 if (isa<UndefValue>(Mask->getOperand(i)))
9865 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9866 Idx &= 31; // Match the hardware behavior.
9868 if (ExtractedElts[Idx] == 0) {
9869 ExtractedElts[Idx] =
9870 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9871 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9875 // Insert this value into the result vector.
9876 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9877 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9880 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9885 case Intrinsic::stackrestore: {
9886 // If the save is right next to the restore, remove the restore. This can
9887 // happen when variable allocas are DCE'd.
9888 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9889 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9890 BasicBlock::iterator BI = SS;
9892 return EraseInstFromFunction(CI);
9896 // Scan down this block to see if there is another stack restore in the
9897 // same block without an intervening call/alloca.
9898 BasicBlock::iterator BI = II;
9899 TerminatorInst *TI = II->getParent()->getTerminator();
9900 bool CannotRemove = false;
9901 for (++BI; &*BI != TI; ++BI) {
9902 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
9903 CannotRemove = true;
9906 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9907 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9908 // If there is a stackrestore below this one, remove this one.
9909 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9910 return EraseInstFromFunction(CI);
9911 // Otherwise, ignore the intrinsic.
9913 // If we found a non-intrinsic call, we can't remove the stack
9915 CannotRemove = true;
9921 // If the stack restore is in a return/unwind block and if there are no
9922 // allocas or calls between the restore and the return, nuke the restore.
9923 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9924 return EraseInstFromFunction(CI);
9929 return visitCallSite(II);
9932 // InvokeInst simplification
9934 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9935 return visitCallSite(&II);
9938 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
9939 /// passed through the varargs area, we can eliminate the use of the cast.
9940 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9941 const CastInst * const CI,
9942 const TargetData * const TD,
9944 if (!CI->isLosslessCast())
9947 // The size of ByVal arguments is derived from the type, so we
9948 // can't change to a type with a different size. If the size were
9949 // passed explicitly we could avoid this check.
9950 if (!CS.paramHasAttr(ix, Attribute::ByVal))
9954 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9955 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9956 if (!SrcTy->isSized() || !DstTy->isSized())
9958 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9963 // visitCallSite - Improvements for call and invoke instructions.
9965 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9966 bool Changed = false;
9968 // If the callee is a constexpr cast of a function, attempt to move the cast
9969 // to the arguments of the call/invoke.
9970 if (transformConstExprCastCall(CS)) return 0;
9972 Value *Callee = CS.getCalledValue();
9974 if (Function *CalleeF = dyn_cast<Function>(Callee))
9975 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9976 Instruction *OldCall = CS.getInstruction();
9977 // If the call and callee calling conventions don't match, this call must
9978 // be unreachable, as the call is undefined.
9979 new StoreInst(ConstantInt::getTrue(*Context),
9980 UndefValue::get(Type::getInt1PtrTy(*Context)),
9982 if (!OldCall->use_empty())
9983 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9984 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9985 return EraseInstFromFunction(*OldCall);
9989 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9990 // This instruction is not reachable, just remove it. We insert a store to
9991 // undef so that we know that this code is not reachable, despite the fact
9992 // that we can't modify the CFG here.
9993 new StoreInst(ConstantInt::getTrue(*Context),
9994 UndefValue::get(Type::getInt1PtrTy(*Context)),
9995 CS.getInstruction());
9997 if (!CS.getInstruction()->use_empty())
9998 CS.getInstruction()->
9999 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10001 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10002 // Don't break the CFG, insert a dummy cond branch.
10003 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10004 ConstantInt::getTrue(*Context), II);
10006 return EraseInstFromFunction(*CS.getInstruction());
10009 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10010 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10011 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10012 return transformCallThroughTrampoline(CS);
10014 const PointerType *PTy = cast<PointerType>(Callee->getType());
10015 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10016 if (FTy->isVarArg()) {
10017 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10018 // See if we can optimize any arguments passed through the varargs area of
10020 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10021 E = CS.arg_end(); I != E; ++I, ++ix) {
10022 CastInst *CI = dyn_cast<CastInst>(*I);
10023 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10024 *I = CI->getOperand(0);
10030 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10031 // Inline asm calls cannot throw - mark them 'nounwind'.
10032 CS.setDoesNotThrow();
10036 return Changed ? CS.getInstruction() : 0;
10039 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10040 // attempt to move the cast to the arguments of the call/invoke.
10042 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10043 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10044 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10045 if (CE->getOpcode() != Instruction::BitCast ||
10046 !isa<Function>(CE->getOperand(0)))
10048 Function *Callee = cast<Function>(CE->getOperand(0));
10049 Instruction *Caller = CS.getInstruction();
10050 const AttrListPtr &CallerPAL = CS.getAttributes();
10052 // Okay, this is a cast from a function to a different type. Unless doing so
10053 // would cause a type conversion of one of our arguments, change this call to
10054 // be a direct call with arguments casted to the appropriate types.
10056 const FunctionType *FT = Callee->getFunctionType();
10057 const Type *OldRetTy = Caller->getType();
10058 const Type *NewRetTy = FT->getReturnType();
10060 if (isa<StructType>(NewRetTy))
10061 return false; // TODO: Handle multiple return values.
10063 // Check to see if we are changing the return type...
10064 if (OldRetTy != NewRetTy) {
10065 if (Callee->isDeclaration() &&
10066 // Conversion is ok if changing from one pointer type to another or from
10067 // a pointer to an integer of the same size.
10068 !((isa<PointerType>(OldRetTy) || !TD ||
10069 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10070 (isa<PointerType>(NewRetTy) || !TD ||
10071 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10072 return false; // Cannot transform this return value.
10074 if (!Caller->use_empty() &&
10075 // void -> non-void is handled specially
10076 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
10077 return false; // Cannot transform this return value.
10079 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10080 Attributes RAttrs = CallerPAL.getRetAttributes();
10081 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10082 return false; // Attribute not compatible with transformed value.
10085 // If the callsite is an invoke instruction, and the return value is used by
10086 // a PHI node in a successor, we cannot change the return type of the call
10087 // because there is no place to put the cast instruction (without breaking
10088 // the critical edge). Bail out in this case.
10089 if (!Caller->use_empty())
10090 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10091 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10093 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10094 if (PN->getParent() == II->getNormalDest() ||
10095 PN->getParent() == II->getUnwindDest())
10099 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10100 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10102 CallSite::arg_iterator AI = CS.arg_begin();
10103 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10104 const Type *ParamTy = FT->getParamType(i);
10105 const Type *ActTy = (*AI)->getType();
10107 if (!CastInst::isCastable(ActTy, ParamTy))
10108 return false; // Cannot transform this parameter value.
10110 if (CallerPAL.getParamAttributes(i + 1)
10111 & Attribute::typeIncompatible(ParamTy))
10112 return false; // Attribute not compatible with transformed value.
10114 // Converting from one pointer type to another or between a pointer and an
10115 // integer of the same size is safe even if we do not have a body.
10116 bool isConvertible = ActTy == ParamTy ||
10117 (TD && ((isa<PointerType>(ParamTy) ||
10118 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10119 (isa<PointerType>(ActTy) ||
10120 ActTy == TD->getIntPtrType(Caller->getContext()))));
10121 if (Callee->isDeclaration() && !isConvertible) return false;
10124 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10125 Callee->isDeclaration())
10126 return false; // Do not delete arguments unless we have a function body.
10128 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10129 !CallerPAL.isEmpty())
10130 // In this case we have more arguments than the new function type, but we
10131 // won't be dropping them. Check that these extra arguments have attributes
10132 // that are compatible with being a vararg call argument.
10133 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10134 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10136 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10137 if (PAttrs & Attribute::VarArgsIncompatible)
10141 // Okay, we decided that this is a safe thing to do: go ahead and start
10142 // inserting cast instructions as necessary...
10143 std::vector<Value*> Args;
10144 Args.reserve(NumActualArgs);
10145 SmallVector<AttributeWithIndex, 8> attrVec;
10146 attrVec.reserve(NumCommonArgs);
10148 // Get any return attributes.
10149 Attributes RAttrs = CallerPAL.getRetAttributes();
10151 // If the return value is not being used, the type may not be compatible
10152 // with the existing attributes. Wipe out any problematic attributes.
10153 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10155 // Add the new return attributes.
10157 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10159 AI = CS.arg_begin();
10160 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10161 const Type *ParamTy = FT->getParamType(i);
10162 if ((*AI)->getType() == ParamTy) {
10163 Args.push_back(*AI);
10165 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10166 false, ParamTy, false);
10167 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10170 // Add any parameter attributes.
10171 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10172 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10175 // If the function takes more arguments than the call was taking, add them
10177 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10178 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10180 // If we are removing arguments to the function, emit an obnoxious warning.
10181 if (FT->getNumParams() < NumActualArgs) {
10182 if (!FT->isVarArg()) {
10183 errs() << "WARNING: While resolving call to function '"
10184 << Callee->getName() << "' arguments were dropped!\n";
10186 // Add all of the arguments in their promoted form to the arg list.
10187 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10188 const Type *PTy = getPromotedType((*AI)->getType());
10189 if (PTy != (*AI)->getType()) {
10190 // Must promote to pass through va_arg area!
10191 Instruction::CastOps opcode =
10192 CastInst::getCastOpcode(*AI, false, PTy, false);
10193 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10195 Args.push_back(*AI);
10198 // Add any parameter attributes.
10199 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10200 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10205 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10206 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10208 if (NewRetTy == Type::getVoidTy(*Context))
10209 Caller->setName(""); // Void type should not have a name.
10211 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10215 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10216 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10217 Args.begin(), Args.end(),
10218 Caller->getName(), Caller);
10219 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10220 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10222 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10223 Caller->getName(), Caller);
10224 CallInst *CI = cast<CallInst>(Caller);
10225 if (CI->isTailCall())
10226 cast<CallInst>(NC)->setTailCall();
10227 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10228 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10231 // Insert a cast of the return type as necessary.
10233 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10234 if (NV->getType() != Type::getVoidTy(*Context)) {
10235 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10237 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10239 // If this is an invoke instruction, we should insert it after the first
10240 // non-phi, instruction in the normal successor block.
10241 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10242 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10243 InsertNewInstBefore(NC, *I);
10245 // Otherwise, it's a call, just insert cast right after the call instr
10246 InsertNewInstBefore(NC, *Caller);
10248 Worklist.AddUsersToWorkList(*Caller);
10250 NV = UndefValue::get(Caller->getType());
10255 if (!Caller->use_empty())
10256 Caller->replaceAllUsesWith(NV);
10258 EraseInstFromFunction(*Caller);
10262 // transformCallThroughTrampoline - Turn a call to a function created by the
10263 // init_trampoline intrinsic into a direct call to the underlying function.
10265 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10266 Value *Callee = CS.getCalledValue();
10267 const PointerType *PTy = cast<PointerType>(Callee->getType());
10268 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10269 const AttrListPtr &Attrs = CS.getAttributes();
10271 // If the call already has the 'nest' attribute somewhere then give up -
10272 // otherwise 'nest' would occur twice after splicing in the chain.
10273 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10276 IntrinsicInst *Tramp =
10277 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10279 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10280 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10281 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10283 const AttrListPtr &NestAttrs = NestF->getAttributes();
10284 if (!NestAttrs.isEmpty()) {
10285 unsigned NestIdx = 1;
10286 const Type *NestTy = 0;
10287 Attributes NestAttr = Attribute::None;
10289 // Look for a parameter marked with the 'nest' attribute.
10290 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10291 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10292 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10293 // Record the parameter type and any other attributes.
10295 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10300 Instruction *Caller = CS.getInstruction();
10301 std::vector<Value*> NewArgs;
10302 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10304 SmallVector<AttributeWithIndex, 8> NewAttrs;
10305 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10307 // Insert the nest argument into the call argument list, which may
10308 // mean appending it. Likewise for attributes.
10310 // Add any result attributes.
10311 if (Attributes Attr = Attrs.getRetAttributes())
10312 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10316 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10318 if (Idx == NestIdx) {
10319 // Add the chain argument and attributes.
10320 Value *NestVal = Tramp->getOperand(3);
10321 if (NestVal->getType() != NestTy)
10322 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10323 NewArgs.push_back(NestVal);
10324 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10330 // Add the original argument and attributes.
10331 NewArgs.push_back(*I);
10332 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10334 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10340 // Add any function attributes.
10341 if (Attributes Attr = Attrs.getFnAttributes())
10342 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10344 // The trampoline may have been bitcast to a bogus type (FTy).
10345 // Handle this by synthesizing a new function type, equal to FTy
10346 // with the chain parameter inserted.
10348 std::vector<const Type*> NewTypes;
10349 NewTypes.reserve(FTy->getNumParams()+1);
10351 // Insert the chain's type into the list of parameter types, which may
10352 // mean appending it.
10355 FunctionType::param_iterator I = FTy->param_begin(),
10356 E = FTy->param_end();
10359 if (Idx == NestIdx)
10360 // Add the chain's type.
10361 NewTypes.push_back(NestTy);
10366 // Add the original type.
10367 NewTypes.push_back(*I);
10373 // Replace the trampoline call with a direct call. Let the generic
10374 // code sort out any function type mismatches.
10375 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
10377 Constant *NewCallee =
10378 NestF->getType() == PointerType::getUnqual(NewFTy) ?
10379 NestF : ConstantExpr::getBitCast(NestF,
10380 PointerType::getUnqual(NewFTy));
10381 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10384 Instruction *NewCaller;
10385 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10386 NewCaller = InvokeInst::Create(NewCallee,
10387 II->getNormalDest(), II->getUnwindDest(),
10388 NewArgs.begin(), NewArgs.end(),
10389 Caller->getName(), Caller);
10390 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10391 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10393 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10394 Caller->getName(), Caller);
10395 if (cast<CallInst>(Caller)->isTailCall())
10396 cast<CallInst>(NewCaller)->setTailCall();
10397 cast<CallInst>(NewCaller)->
10398 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10399 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10401 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10402 Caller->replaceAllUsesWith(NewCaller);
10403 Caller->eraseFromParent();
10404 Worklist.Remove(Caller);
10409 // Replace the trampoline call with a direct call. Since there is no 'nest'
10410 // parameter, there is no need to adjust the argument list. Let the generic
10411 // code sort out any function type mismatches.
10412 Constant *NewCallee =
10413 NestF->getType() == PTy ? NestF :
10414 ConstantExpr::getBitCast(NestF, PTy);
10415 CS.setCalledFunction(NewCallee);
10416 return CS.getInstruction();
10419 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10420 /// and if a/b/c and the add's all have a single use, turn this into a phi
10421 /// and a single binop.
10422 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10423 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10424 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10425 unsigned Opc = FirstInst->getOpcode();
10426 Value *LHSVal = FirstInst->getOperand(0);
10427 Value *RHSVal = FirstInst->getOperand(1);
10429 const Type *LHSType = LHSVal->getType();
10430 const Type *RHSType = RHSVal->getType();
10432 // Scan to see if all operands are the same opcode, and all have one use.
10433 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10434 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10435 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10436 // Verify type of the LHS matches so we don't fold cmp's of different
10437 // types or GEP's with different index types.
10438 I->getOperand(0)->getType() != LHSType ||
10439 I->getOperand(1)->getType() != RHSType)
10442 // If they are CmpInst instructions, check their predicates
10443 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10444 if (cast<CmpInst>(I)->getPredicate() !=
10445 cast<CmpInst>(FirstInst)->getPredicate())
10448 // Keep track of which operand needs a phi node.
10449 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10450 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10453 // If both LHS and RHS would need a PHI, don't do this transformation,
10454 // because it would increase the number of PHIs entering the block,
10455 // which leads to higher register pressure. This is especially
10456 // bad when the PHIs are in the header of a loop.
10457 if (!LHSVal && !RHSVal)
10460 // Otherwise, this is safe to transform!
10462 Value *InLHS = FirstInst->getOperand(0);
10463 Value *InRHS = FirstInst->getOperand(1);
10464 PHINode *NewLHS = 0, *NewRHS = 0;
10466 NewLHS = PHINode::Create(LHSType,
10467 FirstInst->getOperand(0)->getName() + ".pn");
10468 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10469 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10470 InsertNewInstBefore(NewLHS, PN);
10475 NewRHS = PHINode::Create(RHSType,
10476 FirstInst->getOperand(1)->getName() + ".pn");
10477 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10478 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10479 InsertNewInstBefore(NewRHS, PN);
10483 // Add all operands to the new PHIs.
10484 if (NewLHS || NewRHS) {
10485 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10486 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10488 Value *NewInLHS = InInst->getOperand(0);
10489 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10492 Value *NewInRHS = InInst->getOperand(1);
10493 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10498 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10499 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10500 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10501 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10505 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10506 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10508 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10509 FirstInst->op_end());
10510 // This is true if all GEP bases are allocas and if all indices into them are
10512 bool AllBasePointersAreAllocas = true;
10514 // We don't want to replace this phi if the replacement would require
10515 // more than one phi, which leads to higher register pressure. This is
10516 // especially bad when the PHIs are in the header of a loop.
10517 bool NeededPhi = false;
10519 // Scan to see if all operands are the same opcode, and all have one use.
10520 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10521 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10522 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10523 GEP->getNumOperands() != FirstInst->getNumOperands())
10526 // Keep track of whether or not all GEPs are of alloca pointers.
10527 if (AllBasePointersAreAllocas &&
10528 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10529 !GEP->hasAllConstantIndices()))
10530 AllBasePointersAreAllocas = false;
10532 // Compare the operand lists.
10533 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10534 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10537 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10538 // if one of the PHIs has a constant for the index. The index may be
10539 // substantially cheaper to compute for the constants, so making it a
10540 // variable index could pessimize the path. This also handles the case
10541 // for struct indices, which must always be constant.
10542 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10543 isa<ConstantInt>(GEP->getOperand(op)))
10546 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10549 // If we already needed a PHI for an earlier operand, and another operand
10550 // also requires a PHI, we'd be introducing more PHIs than we're
10551 // eliminating, which increases register pressure on entry to the PHI's
10556 FixedOperands[op] = 0; // Needs a PHI.
10561 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10562 // bother doing this transformation. At best, this will just save a bit of
10563 // offset calculation, but all the predecessors will have to materialize the
10564 // stack address into a register anyway. We'd actually rather *clone* the
10565 // load up into the predecessors so that we have a load of a gep of an alloca,
10566 // which can usually all be folded into the load.
10567 if (AllBasePointersAreAllocas)
10570 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10571 // that is variable.
10572 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10574 bool HasAnyPHIs = false;
10575 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10576 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10577 Value *FirstOp = FirstInst->getOperand(i);
10578 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10579 FirstOp->getName()+".pn");
10580 InsertNewInstBefore(NewPN, PN);
10582 NewPN->reserveOperandSpace(e);
10583 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10584 OperandPhis[i] = NewPN;
10585 FixedOperands[i] = NewPN;
10590 // Add all operands to the new PHIs.
10592 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10593 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10594 BasicBlock *InBB = PN.getIncomingBlock(i);
10596 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10597 if (PHINode *OpPhi = OperandPhis[op])
10598 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10602 Value *Base = FixedOperands[0];
10603 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10604 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10605 FixedOperands.end()) :
10606 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10607 FixedOperands.end());
10611 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10612 /// sink the load out of the block that defines it. This means that it must be
10613 /// obvious the value of the load is not changed from the point of the load to
10614 /// the end of the block it is in.
10616 /// Finally, it is safe, but not profitable, to sink a load targetting a
10617 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10619 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10620 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10622 for (++BBI; BBI != E; ++BBI)
10623 if (BBI->mayWriteToMemory())
10626 // Check for non-address taken alloca. If not address-taken already, it isn't
10627 // profitable to do this xform.
10628 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10629 bool isAddressTaken = false;
10630 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10632 if (isa<LoadInst>(UI)) continue;
10633 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10634 // If storing TO the alloca, then the address isn't taken.
10635 if (SI->getOperand(1) == AI) continue;
10637 isAddressTaken = true;
10641 if (!isAddressTaken && AI->isStaticAlloca())
10645 // If this load is a load from a GEP with a constant offset from an alloca,
10646 // then we don't want to sink it. In its present form, it will be
10647 // load [constant stack offset]. Sinking it will cause us to have to
10648 // materialize the stack addresses in each predecessor in a register only to
10649 // do a shared load from register in the successor.
10650 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10651 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10652 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10659 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10660 // operator and they all are only used by the PHI, PHI together their
10661 // inputs, and do the operation once, to the result of the PHI.
10662 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10663 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10665 // Scan the instruction, looking for input operations that can be folded away.
10666 // If all input operands to the phi are the same instruction (e.g. a cast from
10667 // the same type or "+42") we can pull the operation through the PHI, reducing
10668 // code size and simplifying code.
10669 Constant *ConstantOp = 0;
10670 const Type *CastSrcTy = 0;
10671 bool isVolatile = false;
10672 if (isa<CastInst>(FirstInst)) {
10673 CastSrcTy = FirstInst->getOperand(0)->getType();
10674 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10675 // Can fold binop, compare or shift here if the RHS is a constant,
10676 // otherwise call FoldPHIArgBinOpIntoPHI.
10677 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10678 if (ConstantOp == 0)
10679 return FoldPHIArgBinOpIntoPHI(PN);
10680 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10681 isVolatile = LI->isVolatile();
10682 // We can't sink the load if the loaded value could be modified between the
10683 // load and the PHI.
10684 if (LI->getParent() != PN.getIncomingBlock(0) ||
10685 !isSafeAndProfitableToSinkLoad(LI))
10688 // If the PHI is of volatile loads and the load block has multiple
10689 // successors, sinking it would remove a load of the volatile value from
10690 // the path through the other successor.
10692 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10695 } else if (isa<GetElementPtrInst>(FirstInst)) {
10696 return FoldPHIArgGEPIntoPHI(PN);
10698 return 0; // Cannot fold this operation.
10701 // Check to see if all arguments are the same operation.
10702 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10703 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10704 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10705 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10708 if (I->getOperand(0)->getType() != CastSrcTy)
10709 return 0; // Cast operation must match.
10710 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10711 // We can't sink the load if the loaded value could be modified between
10712 // the load and the PHI.
10713 if (LI->isVolatile() != isVolatile ||
10714 LI->getParent() != PN.getIncomingBlock(i) ||
10715 !isSafeAndProfitableToSinkLoad(LI))
10718 // If the PHI is of volatile loads and the load block has multiple
10719 // successors, sinking it would remove a load of the volatile value from
10720 // the path through the other successor.
10722 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10725 } else if (I->getOperand(1) != ConstantOp) {
10730 // Okay, they are all the same operation. Create a new PHI node of the
10731 // correct type, and PHI together all of the LHS's of the instructions.
10732 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10733 PN.getName()+".in");
10734 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10736 Value *InVal = FirstInst->getOperand(0);
10737 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10739 // Add all operands to the new PHI.
10740 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10741 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10742 if (NewInVal != InVal)
10744 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10749 // The new PHI unions all of the same values together. This is really
10750 // common, so we handle it intelligently here for compile-time speed.
10754 InsertNewInstBefore(NewPN, PN);
10758 // Insert and return the new operation.
10759 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10760 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10761 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10762 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10763 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10764 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10765 PhiVal, ConstantOp);
10766 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10768 // If this was a volatile load that we are merging, make sure to loop through
10769 // and mark all the input loads as non-volatile. If we don't do this, we will
10770 // insert a new volatile load and the old ones will not be deletable.
10772 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10773 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10775 return new LoadInst(PhiVal, "", isVolatile);
10778 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10780 static bool DeadPHICycle(PHINode *PN,
10781 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10782 if (PN->use_empty()) return true;
10783 if (!PN->hasOneUse()) return false;
10785 // Remember this node, and if we find the cycle, return.
10786 if (!PotentiallyDeadPHIs.insert(PN))
10789 // Don't scan crazily complex things.
10790 if (PotentiallyDeadPHIs.size() == 16)
10793 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10794 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10799 /// PHIsEqualValue - Return true if this phi node is always equal to
10800 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10801 /// z = some value; x = phi (y, z); y = phi (x, z)
10802 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10803 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10804 // See if we already saw this PHI node.
10805 if (!ValueEqualPHIs.insert(PN))
10808 // Don't scan crazily complex things.
10809 if (ValueEqualPHIs.size() == 16)
10812 // Scan the operands to see if they are either phi nodes or are equal to
10814 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10815 Value *Op = PN->getIncomingValue(i);
10816 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10817 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10819 } else if (Op != NonPhiInVal)
10827 // PHINode simplification
10829 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10830 // If LCSSA is around, don't mess with Phi nodes
10831 if (MustPreserveLCSSA) return 0;
10833 if (Value *V = PN.hasConstantValue())
10834 return ReplaceInstUsesWith(PN, V);
10836 // If all PHI operands are the same operation, pull them through the PHI,
10837 // reducing code size.
10838 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10839 isa<Instruction>(PN.getIncomingValue(1)) &&
10840 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10841 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10842 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10843 // than themselves more than once.
10844 PN.getIncomingValue(0)->hasOneUse())
10845 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10848 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10849 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10850 // PHI)... break the cycle.
10851 if (PN.hasOneUse()) {
10852 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10853 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10854 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10855 PotentiallyDeadPHIs.insert(&PN);
10856 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10857 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10860 // If this phi has a single use, and if that use just computes a value for
10861 // the next iteration of a loop, delete the phi. This occurs with unused
10862 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10863 // common case here is good because the only other things that catch this
10864 // are induction variable analysis (sometimes) and ADCE, which is only run
10866 if (PHIUser->hasOneUse() &&
10867 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10868 PHIUser->use_back() == &PN) {
10869 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10873 // We sometimes end up with phi cycles that non-obviously end up being the
10874 // same value, for example:
10875 // z = some value; x = phi (y, z); y = phi (x, z)
10876 // where the phi nodes don't necessarily need to be in the same block. Do a
10877 // quick check to see if the PHI node only contains a single non-phi value, if
10878 // so, scan to see if the phi cycle is actually equal to that value.
10880 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10881 // Scan for the first non-phi operand.
10882 while (InValNo != NumOperandVals &&
10883 isa<PHINode>(PN.getIncomingValue(InValNo)))
10886 if (InValNo != NumOperandVals) {
10887 Value *NonPhiInVal = PN.getOperand(InValNo);
10889 // Scan the rest of the operands to see if there are any conflicts, if so
10890 // there is no need to recursively scan other phis.
10891 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10892 Value *OpVal = PN.getIncomingValue(InValNo);
10893 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10897 // If we scanned over all operands, then we have one unique value plus
10898 // phi values. Scan PHI nodes to see if they all merge in each other or
10900 if (InValNo == NumOperandVals) {
10901 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10902 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10903 return ReplaceInstUsesWith(PN, NonPhiInVal);
10910 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10911 Value *PtrOp = GEP.getOperand(0);
10912 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10913 if (GEP.getNumOperands() == 1)
10914 return ReplaceInstUsesWith(GEP, PtrOp);
10916 if (isa<UndefValue>(GEP.getOperand(0)))
10917 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10919 bool HasZeroPointerIndex = false;
10920 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10921 HasZeroPointerIndex = C->isNullValue();
10923 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10924 return ReplaceInstUsesWith(GEP, PtrOp);
10926 // Eliminate unneeded casts for indices.
10928 bool MadeChange = false;
10929 unsigned PtrSize = TD->getPointerSizeInBits();
10931 gep_type_iterator GTI = gep_type_begin(GEP);
10932 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10933 I != E; ++I, ++GTI) {
10934 if (!isa<SequentialType>(*GTI)) continue;
10936 // If we are using a wider index than needed for this platform, shrink it
10937 // to what we need. If narrower, sign-extend it to what we need. This
10938 // explicit cast can make subsequent optimizations more obvious.
10939 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10940 if (OpBits == PtrSize)
10943 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10946 if (MadeChange) return &GEP;
10949 // Combine Indices - If the source pointer to this getelementptr instruction
10950 // is a getelementptr instruction, combine the indices of the two
10951 // getelementptr instructions into a single instruction.
10953 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10954 // Note that if our source is a gep chain itself that we wait for that
10955 // chain to be resolved before we perform this transformation. This
10956 // avoids us creating a TON of code in some cases.
10958 if (GetElementPtrInst *SrcGEP =
10959 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10960 if (SrcGEP->getNumOperands() == 2)
10961 return 0; // Wait until our source is folded to completion.
10963 SmallVector<Value*, 8> Indices;
10965 // Find out whether the last index in the source GEP is a sequential idx.
10966 bool EndsWithSequential = false;
10967 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10969 EndsWithSequential = !isa<StructType>(*I);
10971 // Can we combine the two pointer arithmetics offsets?
10972 if (EndsWithSequential) {
10973 // Replace: gep (gep %P, long B), long A, ...
10974 // With: T = long A+B; gep %P, T, ...
10977 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10978 Value *GO1 = GEP.getOperand(1);
10979 if (SO1 == Constant::getNullValue(SO1->getType())) {
10981 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10984 // If they aren't the same type, then the input hasn't been processed
10985 // by the loop above yet (which canonicalizes sequential index types to
10986 // intptr_t). Just avoid transforming this until the input has been
10988 if (SO1->getType() != GO1->getType())
10990 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10993 // Update the GEP in place if possible.
10994 if (Src->getNumOperands() == 2) {
10995 GEP.setOperand(0, Src->getOperand(0));
10996 GEP.setOperand(1, Sum);
10999 Indices.append(Src->op_begin()+1, Src->op_end()-1);
11000 Indices.push_back(Sum);
11001 Indices.append(GEP.op_begin()+2, GEP.op_end());
11002 } else if (isa<Constant>(*GEP.idx_begin()) &&
11003 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11004 Src->getNumOperands() != 1) {
11005 // Otherwise we can do the fold if the first index of the GEP is a zero
11006 Indices.append(Src->op_begin()+1, Src->op_end());
11007 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11010 if (!Indices.empty())
11011 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11012 Src->isInBounds()) ?
11013 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11014 Indices.end(), GEP.getName()) :
11015 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11016 Indices.end(), GEP.getName());
11019 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11020 if (Value *X = getBitCastOperand(PtrOp)) {
11021 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11023 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11024 // want to change the gep until the bitcasts are eliminated.
11025 if (getBitCastOperand(X)) {
11026 Worklist.AddValue(PtrOp);
11030 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11031 // into : GEP [10 x i8]* X, i32 0, ...
11033 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11034 // into : GEP i8* X, ...
11036 // This occurs when the program declares an array extern like "int X[];"
11037 if (HasZeroPointerIndex) {
11038 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11039 const PointerType *XTy = cast<PointerType>(X->getType());
11040 if (const ArrayType *CATy =
11041 dyn_cast<ArrayType>(CPTy->getElementType())) {
11042 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11043 if (CATy->getElementType() == XTy->getElementType()) {
11044 // -> GEP i8* X, ...
11045 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11046 return cast<GEPOperator>(&GEP)->isInBounds() ?
11047 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11049 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11053 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11054 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11055 if (CATy->getElementType() == XATy->getElementType()) {
11056 // -> GEP [10 x i8]* X, i32 0, ...
11057 // At this point, we know that the cast source type is a pointer
11058 // to an array of the same type as the destination pointer
11059 // array. Because the array type is never stepped over (there
11060 // is a leading zero) we can fold the cast into this GEP.
11061 GEP.setOperand(0, X);
11066 } else if (GEP.getNumOperands() == 2) {
11067 // Transform things like:
11068 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11069 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11070 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11071 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11072 if (TD && isa<ArrayType>(SrcElTy) &&
11073 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11074 TD->getTypeAllocSize(ResElTy)) {
11076 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11077 Idx[1] = GEP.getOperand(1);
11078 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11079 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11080 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11081 // V and GEP are both pointer types --> BitCast
11082 return new BitCastInst(NewGEP, GEP.getType());
11085 // Transform things like:
11086 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11087 // (where tmp = 8*tmp2) into:
11088 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11090 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11091 uint64_t ArrayEltSize =
11092 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11094 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11095 // allow either a mul, shift, or constant here.
11097 ConstantInt *Scale = 0;
11098 if (ArrayEltSize == 1) {
11099 NewIdx = GEP.getOperand(1);
11100 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11101 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11102 NewIdx = ConstantInt::get(CI->getType(), 1);
11104 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11105 if (Inst->getOpcode() == Instruction::Shl &&
11106 isa<ConstantInt>(Inst->getOperand(1))) {
11107 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11108 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11109 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11111 NewIdx = Inst->getOperand(0);
11112 } else if (Inst->getOpcode() == Instruction::Mul &&
11113 isa<ConstantInt>(Inst->getOperand(1))) {
11114 Scale = cast<ConstantInt>(Inst->getOperand(1));
11115 NewIdx = Inst->getOperand(0);
11119 // If the index will be to exactly the right offset with the scale taken
11120 // out, perform the transformation. Note, we don't know whether Scale is
11121 // signed or not. We'll use unsigned version of division/modulo
11122 // operation after making sure Scale doesn't have the sign bit set.
11123 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11124 Scale->getZExtValue() % ArrayEltSize == 0) {
11125 Scale = ConstantInt::get(Scale->getType(),
11126 Scale->getZExtValue() / ArrayEltSize);
11127 if (Scale->getZExtValue() != 1) {
11128 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11130 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11133 // Insert the new GEP instruction.
11135 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11137 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11138 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11139 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11140 // The NewGEP must be pointer typed, so must the old one -> BitCast
11141 return new BitCastInst(NewGEP, GEP.getType());
11147 /// See if we can simplify:
11148 /// X = bitcast A* to B*
11149 /// Y = gep X, <...constant indices...>
11150 /// into a gep of the original struct. This is important for SROA and alias
11151 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11152 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11154 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11155 // Determine how much the GEP moves the pointer. We are guaranteed to get
11156 // a constant back from EmitGEPOffset.
11157 ConstantInt *OffsetV =
11158 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11159 int64_t Offset = OffsetV->getSExtValue();
11161 // If this GEP instruction doesn't move the pointer, just replace the GEP
11162 // with a bitcast of the real input to the dest type.
11164 // If the bitcast is of an allocation, and the allocation will be
11165 // converted to match the type of the cast, don't touch this.
11166 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11167 isMalloc(BCI->getOperand(0))) {
11168 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11169 if (Instruction *I = visitBitCast(*BCI)) {
11172 BCI->getParent()->getInstList().insert(BCI, I);
11173 ReplaceInstUsesWith(*BCI, I);
11178 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11181 // Otherwise, if the offset is non-zero, we need to find out if there is a
11182 // field at Offset in 'A's type. If so, we can pull the cast through the
11184 SmallVector<Value*, 8> NewIndices;
11186 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11187 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11188 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11189 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11190 NewIndices.end()) :
11191 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11194 if (NGEP->getType() == GEP.getType())
11195 return ReplaceInstUsesWith(GEP, NGEP);
11196 NGEP->takeName(&GEP);
11197 return new BitCastInst(NGEP, GEP.getType());
11205 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11206 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11207 if (AI.isArrayAllocation()) { // Check C != 1
11208 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11209 const Type *NewTy =
11210 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11211 AllocationInst *New = 0;
11213 // Create and insert the replacement instruction...
11214 if (isa<MallocInst>(AI))
11215 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
11217 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11218 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11220 New->setAlignment(AI.getAlignment());
11222 // Scan to the end of the allocation instructions, to skip over a block of
11223 // allocas if possible...also skip interleaved debug info
11225 BasicBlock::iterator It = New;
11226 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11228 // Now that I is pointing to the first non-allocation-inst in the block,
11229 // insert our getelementptr instruction...
11231 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11235 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11236 New->getName()+".sub", It);
11238 // Now make everything use the getelementptr instead of the original
11240 return ReplaceInstUsesWith(AI, V);
11241 } else if (isa<UndefValue>(AI.getArraySize())) {
11242 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11246 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11247 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11248 // Note that we only do this for alloca's, because malloc should allocate
11249 // and return a unique pointer, even for a zero byte allocation.
11250 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11251 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11253 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11254 if (AI.getAlignment() == 0)
11255 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11261 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11262 Value *Op = FI.getOperand(0);
11264 // free undef -> unreachable.
11265 if (isa<UndefValue>(Op)) {
11266 // Insert a new store to null because we cannot modify the CFG here.
11267 new StoreInst(ConstantInt::getTrue(*Context),
11268 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11269 return EraseInstFromFunction(FI);
11272 // If we have 'free null' delete the instruction. This can happen in stl code
11273 // when lots of inlining happens.
11274 if (isa<ConstantPointerNull>(Op))
11275 return EraseInstFromFunction(FI);
11277 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11278 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11279 FI.setOperand(0, CI->getOperand(0));
11283 // Change free (gep X, 0,0,0,0) into free(X)
11284 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11285 if (GEPI->hasAllZeroIndices()) {
11286 Worklist.Add(GEPI);
11287 FI.setOperand(0, GEPI->getOperand(0));
11292 // Change free(malloc) into nothing, if the malloc has a single use.
11293 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11294 if (MI->hasOneUse()) {
11295 EraseInstFromFunction(FI);
11296 return EraseInstFromFunction(*MI);
11298 if (isMalloc(Op)) {
11299 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11300 if (Op->hasOneUse() && CI->hasOneUse()) {
11301 EraseInstFromFunction(FI);
11302 EraseInstFromFunction(*CI);
11303 return EraseInstFromFunction(*cast<Instruction>(Op));
11306 // Op is a call to malloc
11307 if (Op->hasOneUse()) {
11308 EraseInstFromFunction(FI);
11309 return EraseInstFromFunction(*cast<Instruction>(Op));
11318 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11319 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11320 const TargetData *TD) {
11321 User *CI = cast<User>(LI.getOperand(0));
11322 Value *CastOp = CI->getOperand(0);
11323 LLVMContext *Context = IC.getContext();
11326 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11327 // Instead of loading constant c string, use corresponding integer value
11328 // directly if string length is small enough.
11330 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11331 unsigned len = Str.length();
11332 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11333 unsigned numBits = Ty->getPrimitiveSizeInBits();
11334 // Replace LI with immediate integer store.
11335 if ((numBits >> 3) == len + 1) {
11336 APInt StrVal(numBits, 0);
11337 APInt SingleChar(numBits, 0);
11338 if (TD->isLittleEndian()) {
11339 for (signed i = len-1; i >= 0; i--) {
11340 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11341 StrVal = (StrVal << 8) | SingleChar;
11344 for (unsigned i = 0; i < len; i++) {
11345 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11346 StrVal = (StrVal << 8) | SingleChar;
11348 // Append NULL at the end.
11350 StrVal = (StrVal << 8) | SingleChar;
11352 Value *NL = ConstantInt::get(*Context, StrVal);
11353 return IC.ReplaceInstUsesWith(LI, NL);
11359 const PointerType *DestTy = cast<PointerType>(CI->getType());
11360 const Type *DestPTy = DestTy->getElementType();
11361 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11363 // If the address spaces don't match, don't eliminate the cast.
11364 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11367 const Type *SrcPTy = SrcTy->getElementType();
11369 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11370 isa<VectorType>(DestPTy)) {
11371 // If the source is an array, the code below will not succeed. Check to
11372 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11374 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11375 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11376 if (ASrcTy->getNumElements() != 0) {
11378 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11379 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11380 SrcTy = cast<PointerType>(CastOp->getType());
11381 SrcPTy = SrcTy->getElementType();
11384 if (IC.getTargetData() &&
11385 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11386 isa<VectorType>(SrcPTy)) &&
11387 // Do not allow turning this into a load of an integer, which is then
11388 // casted to a pointer, this pessimizes pointer analysis a lot.
11389 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11390 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11391 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11393 // Okay, we are casting from one integer or pointer type to another of
11394 // the same size. Instead of casting the pointer before the load, cast
11395 // the result of the loaded value.
11397 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11398 // Now cast the result of the load.
11399 return new BitCastInst(NewLoad, LI.getType());
11406 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11407 Value *Op = LI.getOperand(0);
11409 // Attempt to improve the alignment.
11411 unsigned KnownAlign =
11412 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11414 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11415 LI.getAlignment()))
11416 LI.setAlignment(KnownAlign);
11419 // load (cast X) --> cast (load X) iff safe.
11420 if (isa<CastInst>(Op))
11421 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11424 // None of the following transforms are legal for volatile loads.
11425 if (LI.isVolatile()) return 0;
11427 // Do really simple store-to-load forwarding and load CSE, to catch cases
11428 // where there are several consequtive memory accesses to the same location,
11429 // separated by a few arithmetic operations.
11430 BasicBlock::iterator BBI = &LI;
11431 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11432 return ReplaceInstUsesWith(LI, AvailableVal);
11434 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11435 const Value *GEPI0 = GEPI->getOperand(0);
11436 // TODO: Consider a target hook for valid address spaces for this xform.
11437 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11438 // Insert a new store to null instruction before the load to indicate
11439 // that this code is not reachable. We do this instead of inserting
11440 // an unreachable instruction directly because we cannot modify the
11442 new StoreInst(UndefValue::get(LI.getType()),
11443 Constant::getNullValue(Op->getType()), &LI);
11444 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11448 if (Constant *C = dyn_cast<Constant>(Op)) {
11449 // load null/undef -> undef
11450 // TODO: Consider a target hook for valid address spaces for this xform.
11451 if (isa<UndefValue>(C) ||
11452 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11453 // Insert a new store to null instruction before the load to indicate that
11454 // this code is not reachable. We do this instead of inserting an
11455 // unreachable instruction directly because we cannot modify the CFG.
11456 new StoreInst(UndefValue::get(LI.getType()),
11457 Constant::getNullValue(Op->getType()), &LI);
11458 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11461 // Instcombine load (constant global) into the value loaded.
11462 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11463 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11464 return ReplaceInstUsesWith(LI, GV->getInitializer());
11466 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11467 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11468 if (CE->getOpcode() == Instruction::GetElementPtr) {
11469 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11470 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11472 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11473 return ReplaceInstUsesWith(LI, V);
11474 if (CE->getOperand(0)->isNullValue()) {
11475 // Insert a new store to null instruction before the load to indicate
11476 // that this code is not reachable. We do this instead of inserting
11477 // an unreachable instruction directly because we cannot modify the
11479 new StoreInst(UndefValue::get(LI.getType()),
11480 Constant::getNullValue(Op->getType()), &LI);
11481 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11484 } else if (CE->isCast()) {
11485 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11491 // If this load comes from anywhere in a constant global, and if the global
11492 // is all undef or zero, we know what it loads.
11493 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11494 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11495 if (GV->getInitializer()->isNullValue())
11496 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11497 else if (isa<UndefValue>(GV->getInitializer()))
11498 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11502 if (Op->hasOneUse()) {
11503 // Change select and PHI nodes to select values instead of addresses: this
11504 // helps alias analysis out a lot, allows many others simplifications, and
11505 // exposes redundancy in the code.
11507 // Note that we cannot do the transformation unless we know that the
11508 // introduced loads cannot trap! Something like this is valid as long as
11509 // the condition is always false: load (select bool %C, int* null, int* %G),
11510 // but it would not be valid if we transformed it to load from null
11511 // unconditionally.
11513 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11514 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11515 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11516 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11517 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11518 SI->getOperand(1)->getName()+".val");
11519 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11520 SI->getOperand(2)->getName()+".val");
11521 return SelectInst::Create(SI->getCondition(), V1, V2);
11524 // load (select (cond, null, P)) -> load P
11525 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11526 if (C->isNullValue()) {
11527 LI.setOperand(0, SI->getOperand(2));
11531 // load (select (cond, P, null)) -> load P
11532 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11533 if (C->isNullValue()) {
11534 LI.setOperand(0, SI->getOperand(1));
11542 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11543 /// when possible. This makes it generally easy to do alias analysis and/or
11544 /// SROA/mem2reg of the memory object.
11545 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11546 User *CI = cast<User>(SI.getOperand(1));
11547 Value *CastOp = CI->getOperand(0);
11549 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11550 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11551 if (SrcTy == 0) return 0;
11553 const Type *SrcPTy = SrcTy->getElementType();
11555 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11558 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11559 /// to its first element. This allows us to handle things like:
11560 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11561 /// on 32-bit hosts.
11562 SmallVector<Value*, 4> NewGEPIndices;
11564 // If the source is an array, the code below will not succeed. Check to
11565 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11567 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11568 // Index through pointer.
11569 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11570 NewGEPIndices.push_back(Zero);
11573 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11574 if (!STy->getNumElements()) /* Struct can be empty {} */
11576 NewGEPIndices.push_back(Zero);
11577 SrcPTy = STy->getElementType(0);
11578 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11579 NewGEPIndices.push_back(Zero);
11580 SrcPTy = ATy->getElementType();
11586 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11589 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11592 // If the pointers point into different address spaces or if they point to
11593 // values with different sizes, we can't do the transformation.
11594 if (!IC.getTargetData() ||
11595 SrcTy->getAddressSpace() !=
11596 cast<PointerType>(CI->getType())->getAddressSpace() ||
11597 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11598 IC.getTargetData()->getTypeSizeInBits(DestPTy))
11601 // Okay, we are casting from one integer or pointer type to another of
11602 // the same size. Instead of casting the pointer before
11603 // the store, cast the value to be stored.
11605 Value *SIOp0 = SI.getOperand(0);
11606 Instruction::CastOps opcode = Instruction::BitCast;
11607 const Type* CastSrcTy = SIOp0->getType();
11608 const Type* CastDstTy = SrcPTy;
11609 if (isa<PointerType>(CastDstTy)) {
11610 if (CastSrcTy->isInteger())
11611 opcode = Instruction::IntToPtr;
11612 } else if (isa<IntegerType>(CastDstTy)) {
11613 if (isa<PointerType>(SIOp0->getType()))
11614 opcode = Instruction::PtrToInt;
11617 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11618 // emit a GEP to index into its first field.
11619 if (!NewGEPIndices.empty())
11620 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11621 NewGEPIndices.end());
11623 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11624 SIOp0->getName()+".c");
11625 return new StoreInst(NewCast, CastOp);
11628 /// equivalentAddressValues - Test if A and B will obviously have the same
11629 /// value. This includes recognizing that %t0 and %t1 will have the same
11630 /// value in code like this:
11631 /// %t0 = getelementptr \@a, 0, 3
11632 /// store i32 0, i32* %t0
11633 /// %t1 = getelementptr \@a, 0, 3
11634 /// %t2 = load i32* %t1
11636 static bool equivalentAddressValues(Value *A, Value *B) {
11637 // Test if the values are trivially equivalent.
11638 if (A == B) return true;
11640 // Test if the values come form identical arithmetic instructions.
11641 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11642 // its only used to compare two uses within the same basic block, which
11643 // means that they'll always either have the same value or one of them
11644 // will have an undefined value.
11645 if (isa<BinaryOperator>(A) ||
11646 isa<CastInst>(A) ||
11648 isa<GetElementPtrInst>(A))
11649 if (Instruction *BI = dyn_cast<Instruction>(B))
11650 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11653 // Otherwise they may not be equivalent.
11657 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11658 // return the llvm.dbg.declare.
11659 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11660 if (!V->hasNUses(2))
11662 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11664 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11666 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11667 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11674 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11675 Value *Val = SI.getOperand(0);
11676 Value *Ptr = SI.getOperand(1);
11678 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11679 EraseInstFromFunction(SI);
11684 // If the RHS is an alloca with a single use, zapify the store, making the
11686 // If the RHS is an alloca with a two uses, the other one being a
11687 // llvm.dbg.declare, zapify the store and the declare, making the
11688 // alloca dead. We must do this to prevent declare's from affecting
11690 if (!SI.isVolatile()) {
11691 if (Ptr->hasOneUse()) {
11692 if (isa<AllocaInst>(Ptr)) {
11693 EraseInstFromFunction(SI);
11697 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11698 if (isa<AllocaInst>(GEP->getOperand(0))) {
11699 if (GEP->getOperand(0)->hasOneUse()) {
11700 EraseInstFromFunction(SI);
11704 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11705 EraseInstFromFunction(*DI);
11706 EraseInstFromFunction(SI);
11713 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11714 EraseInstFromFunction(*DI);
11715 EraseInstFromFunction(SI);
11721 // Attempt to improve the alignment.
11723 unsigned KnownAlign =
11724 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11726 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11727 SI.getAlignment()))
11728 SI.setAlignment(KnownAlign);
11731 // Do really simple DSE, to catch cases where there are several consecutive
11732 // stores to the same location, separated by a few arithmetic operations. This
11733 // situation often occurs with bitfield accesses.
11734 BasicBlock::iterator BBI = &SI;
11735 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11738 // Don't count debug info directives, lest they affect codegen,
11739 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11740 // It is necessary for correctness to skip those that feed into a
11741 // llvm.dbg.declare, as these are not present when debugging is off.
11742 if (isa<DbgInfoIntrinsic>(BBI) ||
11743 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11748 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11749 // Prev store isn't volatile, and stores to the same location?
11750 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11751 SI.getOperand(1))) {
11754 EraseInstFromFunction(*PrevSI);
11760 // If this is a load, we have to stop. However, if the loaded value is from
11761 // the pointer we're loading and is producing the pointer we're storing,
11762 // then *this* store is dead (X = load P; store X -> P).
11763 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11764 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11765 !SI.isVolatile()) {
11766 EraseInstFromFunction(SI);
11770 // Otherwise, this is a load from some other location. Stores before it
11771 // may not be dead.
11775 // Don't skip over loads or things that can modify memory.
11776 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11781 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11783 // store X, null -> turns into 'unreachable' in SimplifyCFG
11784 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11785 if (!isa<UndefValue>(Val)) {
11786 SI.setOperand(0, UndefValue::get(Val->getType()));
11787 if (Instruction *U = dyn_cast<Instruction>(Val))
11788 Worklist.Add(U); // Dropped a use.
11791 return 0; // Do not modify these!
11794 // store undef, Ptr -> noop
11795 if (isa<UndefValue>(Val)) {
11796 EraseInstFromFunction(SI);
11801 // If the pointer destination is a cast, see if we can fold the cast into the
11803 if (isa<CastInst>(Ptr))
11804 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11806 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11808 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11812 // If this store is the last instruction in the basic block (possibly
11813 // excepting debug info instructions and the pointer bitcasts that feed
11814 // into them), and if the block ends with an unconditional branch, try
11815 // to move it to the successor block.
11819 } while (isa<DbgInfoIntrinsic>(BBI) ||
11820 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11821 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11822 if (BI->isUnconditional())
11823 if (SimplifyStoreAtEndOfBlock(SI))
11824 return 0; // xform done!
11829 /// SimplifyStoreAtEndOfBlock - Turn things like:
11830 /// if () { *P = v1; } else { *P = v2 }
11831 /// into a phi node with a store in the successor.
11833 /// Simplify things like:
11834 /// *P = v1; if () { *P = v2; }
11835 /// into a phi node with a store in the successor.
11837 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11838 BasicBlock *StoreBB = SI.getParent();
11840 // Check to see if the successor block has exactly two incoming edges. If
11841 // so, see if the other predecessor contains a store to the same location.
11842 // if so, insert a PHI node (if needed) and move the stores down.
11843 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11845 // Determine whether Dest has exactly two predecessors and, if so, compute
11846 // the other predecessor.
11847 pred_iterator PI = pred_begin(DestBB);
11848 BasicBlock *OtherBB = 0;
11849 if (*PI != StoreBB)
11852 if (PI == pred_end(DestBB))
11855 if (*PI != StoreBB) {
11860 if (++PI != pred_end(DestBB))
11863 // Bail out if all the relevant blocks aren't distinct (this can happen,
11864 // for example, if SI is in an infinite loop)
11865 if (StoreBB == DestBB || OtherBB == DestBB)
11868 // Verify that the other block ends in a branch and is not otherwise empty.
11869 BasicBlock::iterator BBI = OtherBB->getTerminator();
11870 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11871 if (!OtherBr || BBI == OtherBB->begin())
11874 // If the other block ends in an unconditional branch, check for the 'if then
11875 // else' case. there is an instruction before the branch.
11876 StoreInst *OtherStore = 0;
11877 if (OtherBr->isUnconditional()) {
11879 // Skip over debugging info.
11880 while (isa<DbgInfoIntrinsic>(BBI) ||
11881 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11882 if (BBI==OtherBB->begin())
11886 // If this isn't a store, or isn't a store to the same location, bail out.
11887 OtherStore = dyn_cast<StoreInst>(BBI);
11888 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11891 // Otherwise, the other block ended with a conditional branch. If one of the
11892 // destinations is StoreBB, then we have the if/then case.
11893 if (OtherBr->getSuccessor(0) != StoreBB &&
11894 OtherBr->getSuccessor(1) != StoreBB)
11897 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11898 // if/then triangle. See if there is a store to the same ptr as SI that
11899 // lives in OtherBB.
11901 // Check to see if we find the matching store.
11902 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11903 if (OtherStore->getOperand(1) != SI.getOperand(1))
11907 // If we find something that may be using or overwriting the stored
11908 // value, or if we run out of instructions, we can't do the xform.
11909 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11910 BBI == OtherBB->begin())
11914 // In order to eliminate the store in OtherBr, we have to
11915 // make sure nothing reads or overwrites the stored value in
11917 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11918 // FIXME: This should really be AA driven.
11919 if (I->mayReadFromMemory() || I->mayWriteToMemory())
11924 // Insert a PHI node now if we need it.
11925 Value *MergedVal = OtherStore->getOperand(0);
11926 if (MergedVal != SI.getOperand(0)) {
11927 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11928 PN->reserveOperandSpace(2);
11929 PN->addIncoming(SI.getOperand(0), SI.getParent());
11930 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11931 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11934 // Advance to a place where it is safe to insert the new store and
11936 BBI = DestBB->getFirstNonPHI();
11937 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11938 OtherStore->isVolatile()), *BBI);
11940 // Nuke the old stores.
11941 EraseInstFromFunction(SI);
11942 EraseInstFromFunction(*OtherStore);
11948 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11949 // Change br (not X), label True, label False to: br X, label False, True
11951 BasicBlock *TrueDest;
11952 BasicBlock *FalseDest;
11953 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11954 !isa<Constant>(X)) {
11955 // Swap Destinations and condition...
11956 BI.setCondition(X);
11957 BI.setSuccessor(0, FalseDest);
11958 BI.setSuccessor(1, TrueDest);
11962 // Cannonicalize fcmp_one -> fcmp_oeq
11963 FCmpInst::Predicate FPred; Value *Y;
11964 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11965 TrueDest, FalseDest)) &&
11966 BI.getCondition()->hasOneUse())
11967 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11968 FPred == FCmpInst::FCMP_OGE) {
11969 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11970 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11972 // Swap Destinations and condition.
11973 BI.setSuccessor(0, FalseDest);
11974 BI.setSuccessor(1, TrueDest);
11975 Worklist.Add(Cond);
11979 // Cannonicalize icmp_ne -> icmp_eq
11980 ICmpInst::Predicate IPred;
11981 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11982 TrueDest, FalseDest)) &&
11983 BI.getCondition()->hasOneUse())
11984 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11985 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11986 IPred == ICmpInst::ICMP_SGE) {
11987 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11988 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11989 // Swap Destinations and condition.
11990 BI.setSuccessor(0, FalseDest);
11991 BI.setSuccessor(1, TrueDest);
11992 Worklist.Add(Cond);
11999 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12000 Value *Cond = SI.getCondition();
12001 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12002 if (I->getOpcode() == Instruction::Add)
12003 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12004 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12005 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12007 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12009 SI.setOperand(0, I->getOperand(0));
12017 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12018 Value *Agg = EV.getAggregateOperand();
12020 if (!EV.hasIndices())
12021 return ReplaceInstUsesWith(EV, Agg);
12023 if (Constant *C = dyn_cast<Constant>(Agg)) {
12024 if (isa<UndefValue>(C))
12025 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12027 if (isa<ConstantAggregateZero>(C))
12028 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12030 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12031 // Extract the element indexed by the first index out of the constant
12032 Value *V = C->getOperand(*EV.idx_begin());
12033 if (EV.getNumIndices() > 1)
12034 // Extract the remaining indices out of the constant indexed by the
12036 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12038 return ReplaceInstUsesWith(EV, V);
12040 return 0; // Can't handle other constants
12042 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12043 // We're extracting from an insertvalue instruction, compare the indices
12044 const unsigned *exti, *exte, *insi, *inse;
12045 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12046 exte = EV.idx_end(), inse = IV->idx_end();
12047 exti != exte && insi != inse;
12049 if (*insi != *exti)
12050 // The insert and extract both reference distinctly different elements.
12051 // This means the extract is not influenced by the insert, and we can
12052 // replace the aggregate operand of the extract with the aggregate
12053 // operand of the insert. i.e., replace
12054 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12055 // %E = extractvalue { i32, { i32 } } %I, 0
12057 // %E = extractvalue { i32, { i32 } } %A, 0
12058 return ExtractValueInst::Create(IV->getAggregateOperand(),
12059 EV.idx_begin(), EV.idx_end());
12061 if (exti == exte && insi == inse)
12062 // Both iterators are at the end: Index lists are identical. Replace
12063 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12064 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12066 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12067 if (exti == exte) {
12068 // The extract list is a prefix of the insert list. i.e. replace
12069 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12070 // %E = extractvalue { i32, { i32 } } %I, 1
12072 // %X = extractvalue { i32, { i32 } } %A, 1
12073 // %E = insertvalue { i32 } %X, i32 42, 0
12074 // by switching the order of the insert and extract (though the
12075 // insertvalue should be left in, since it may have other uses).
12076 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12077 EV.idx_begin(), EV.idx_end());
12078 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12082 // The insert list is a prefix of the extract list
12083 // We can simply remove the common indices from the extract and make it
12084 // operate on the inserted value instead of the insertvalue result.
12086 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12087 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12089 // %E extractvalue { i32 } { i32 42 }, 0
12090 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12093 // Can't simplify extracts from other values. Note that nested extracts are
12094 // already simplified implicitely by the above (extract ( extract (insert) )
12095 // will be translated into extract ( insert ( extract ) ) first and then just
12096 // the value inserted, if appropriate).
12100 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12101 /// is to leave as a vector operation.
12102 static bool CheapToScalarize(Value *V, bool isConstant) {
12103 if (isa<ConstantAggregateZero>(V))
12105 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12106 if (isConstant) return true;
12107 // If all elts are the same, we can extract.
12108 Constant *Op0 = C->getOperand(0);
12109 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12110 if (C->getOperand(i) != Op0)
12114 Instruction *I = dyn_cast<Instruction>(V);
12115 if (!I) return false;
12117 // Insert element gets simplified to the inserted element or is deleted if
12118 // this is constant idx extract element and its a constant idx insertelt.
12119 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12120 isa<ConstantInt>(I->getOperand(2)))
12122 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12124 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12125 if (BO->hasOneUse() &&
12126 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12127 CheapToScalarize(BO->getOperand(1), isConstant)))
12129 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12130 if (CI->hasOneUse() &&
12131 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12132 CheapToScalarize(CI->getOperand(1), isConstant)))
12138 /// Read and decode a shufflevector mask.
12140 /// It turns undef elements into values that are larger than the number of
12141 /// elements in the input.
12142 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12143 unsigned NElts = SVI->getType()->getNumElements();
12144 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12145 return std::vector<unsigned>(NElts, 0);
12146 if (isa<UndefValue>(SVI->getOperand(2)))
12147 return std::vector<unsigned>(NElts, 2*NElts);
12149 std::vector<unsigned> Result;
12150 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12151 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12152 if (isa<UndefValue>(*i))
12153 Result.push_back(NElts*2); // undef -> 8
12155 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12159 /// FindScalarElement - Given a vector and an element number, see if the scalar
12160 /// value is already around as a register, for example if it were inserted then
12161 /// extracted from the vector.
12162 static Value *FindScalarElement(Value *V, unsigned EltNo,
12163 LLVMContext *Context) {
12164 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12165 const VectorType *PTy = cast<VectorType>(V->getType());
12166 unsigned Width = PTy->getNumElements();
12167 if (EltNo >= Width) // Out of range access.
12168 return UndefValue::get(PTy->getElementType());
12170 if (isa<UndefValue>(V))
12171 return UndefValue::get(PTy->getElementType());
12172 else if (isa<ConstantAggregateZero>(V))
12173 return Constant::getNullValue(PTy->getElementType());
12174 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12175 return CP->getOperand(EltNo);
12176 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12177 // If this is an insert to a variable element, we don't know what it is.
12178 if (!isa<ConstantInt>(III->getOperand(2)))
12180 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12182 // If this is an insert to the element we are looking for, return the
12184 if (EltNo == IIElt)
12185 return III->getOperand(1);
12187 // Otherwise, the insertelement doesn't modify the value, recurse on its
12189 return FindScalarElement(III->getOperand(0), EltNo, Context);
12190 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12191 unsigned LHSWidth =
12192 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12193 unsigned InEl = getShuffleMask(SVI)[EltNo];
12194 if (InEl < LHSWidth)
12195 return FindScalarElement(SVI->getOperand(0), InEl, Context);
12196 else if (InEl < LHSWidth*2)
12197 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12199 return UndefValue::get(PTy->getElementType());
12202 // Otherwise, we don't know.
12206 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12207 // If vector val is undef, replace extract with scalar undef.
12208 if (isa<UndefValue>(EI.getOperand(0)))
12209 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12211 // If vector val is constant 0, replace extract with scalar 0.
12212 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12213 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12215 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12216 // If vector val is constant with all elements the same, replace EI with
12217 // that element. When the elements are not identical, we cannot replace yet
12218 // (we do that below, but only when the index is constant).
12219 Constant *op0 = C->getOperand(0);
12220 for (unsigned i = 1; i != C->getNumOperands(); ++i)
12221 if (C->getOperand(i) != op0) {
12226 return ReplaceInstUsesWith(EI, op0);
12229 // If extracting a specified index from the vector, see if we can recursively
12230 // find a previously computed scalar that was inserted into the vector.
12231 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12232 unsigned IndexVal = IdxC->getZExtValue();
12233 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12235 // If this is extracting an invalid index, turn this into undef, to avoid
12236 // crashing the code below.
12237 if (IndexVal >= VectorWidth)
12238 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12240 // This instruction only demands the single element from the input vector.
12241 // If the input vector has a single use, simplify it based on this use
12243 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12244 APInt UndefElts(VectorWidth, 0);
12245 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12246 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12247 DemandedMask, UndefElts)) {
12248 EI.setOperand(0, V);
12253 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12254 return ReplaceInstUsesWith(EI, Elt);
12256 // If the this extractelement is directly using a bitcast from a vector of
12257 // the same number of elements, see if we can find the source element from
12258 // it. In this case, we will end up needing to bitcast the scalars.
12259 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12260 if (const VectorType *VT =
12261 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12262 if (VT->getNumElements() == VectorWidth)
12263 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12264 IndexVal, Context))
12265 return new BitCastInst(Elt, EI.getType());
12269 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12270 // Push extractelement into predecessor operation if legal and
12271 // profitable to do so
12272 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12273 if (I->hasOneUse() &&
12274 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12276 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12277 EI.getName()+".lhs");
12279 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12280 EI.getName()+".rhs");
12281 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12283 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12284 // Extracting the inserted element?
12285 if (IE->getOperand(2) == EI.getOperand(1))
12286 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12287 // If the inserted and extracted elements are constants, they must not
12288 // be the same value, extract from the pre-inserted value instead.
12289 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12290 Worklist.AddValue(EI.getOperand(0));
12291 EI.setOperand(0, IE->getOperand(0));
12294 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12295 // If this is extracting an element from a shufflevector, figure out where
12296 // it came from and extract from the appropriate input element instead.
12297 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12298 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12300 unsigned LHSWidth =
12301 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12303 if (SrcIdx < LHSWidth)
12304 Src = SVI->getOperand(0);
12305 else if (SrcIdx < LHSWidth*2) {
12306 SrcIdx -= LHSWidth;
12307 Src = SVI->getOperand(1);
12309 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12311 return ExtractElementInst::Create(Src,
12312 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12316 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12321 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12322 /// elements from either LHS or RHS, return the shuffle mask and true.
12323 /// Otherwise, return false.
12324 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12325 std::vector<Constant*> &Mask,
12326 LLVMContext *Context) {
12327 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12328 "Invalid CollectSingleShuffleElements");
12329 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12331 if (isa<UndefValue>(V)) {
12332 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12334 } else if (V == LHS) {
12335 for (unsigned i = 0; i != NumElts; ++i)
12336 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12338 } else if (V == RHS) {
12339 for (unsigned i = 0; i != NumElts; ++i)
12340 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12342 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12343 // If this is an insert of an extract from some other vector, include it.
12344 Value *VecOp = IEI->getOperand(0);
12345 Value *ScalarOp = IEI->getOperand(1);
12346 Value *IdxOp = IEI->getOperand(2);
12348 if (!isa<ConstantInt>(IdxOp))
12350 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12352 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12353 // Okay, we can handle this if the vector we are insertinting into is
12354 // transitively ok.
12355 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12356 // If so, update the mask to reflect the inserted undef.
12357 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12360 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12361 if (isa<ConstantInt>(EI->getOperand(1)) &&
12362 EI->getOperand(0)->getType() == V->getType()) {
12363 unsigned ExtractedIdx =
12364 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12366 // This must be extracting from either LHS or RHS.
12367 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12368 // Okay, we can handle this if the vector we are insertinting into is
12369 // transitively ok.
12370 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12371 // If so, update the mask to reflect the inserted value.
12372 if (EI->getOperand(0) == LHS) {
12373 Mask[InsertedIdx % NumElts] =
12374 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12376 assert(EI->getOperand(0) == RHS);
12377 Mask[InsertedIdx % NumElts] =
12378 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12387 // TODO: Handle shufflevector here!
12392 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12393 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12394 /// that computes V and the LHS value of the shuffle.
12395 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12396 Value *&RHS, LLVMContext *Context) {
12397 assert(isa<VectorType>(V->getType()) &&
12398 (RHS == 0 || V->getType() == RHS->getType()) &&
12399 "Invalid shuffle!");
12400 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12402 if (isa<UndefValue>(V)) {
12403 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12405 } else if (isa<ConstantAggregateZero>(V)) {
12406 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12408 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12409 // If this is an insert of an extract from some other vector, include it.
12410 Value *VecOp = IEI->getOperand(0);
12411 Value *ScalarOp = IEI->getOperand(1);
12412 Value *IdxOp = IEI->getOperand(2);
12414 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12415 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12416 EI->getOperand(0)->getType() == V->getType()) {
12417 unsigned ExtractedIdx =
12418 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12419 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12421 // Either the extracted from or inserted into vector must be RHSVec,
12422 // otherwise we'd end up with a shuffle of three inputs.
12423 if (EI->getOperand(0) == RHS || RHS == 0) {
12424 RHS = EI->getOperand(0);
12425 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12426 Mask[InsertedIdx % NumElts] =
12427 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12431 if (VecOp == RHS) {
12432 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12434 // Everything but the extracted element is replaced with the RHS.
12435 for (unsigned i = 0; i != NumElts; ++i) {
12436 if (i != InsertedIdx)
12437 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12442 // If this insertelement is a chain that comes from exactly these two
12443 // vectors, return the vector and the effective shuffle.
12444 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12446 return EI->getOperand(0);
12451 // TODO: Handle shufflevector here!
12453 // Otherwise, can't do anything fancy. Return an identity vector.
12454 for (unsigned i = 0; i != NumElts; ++i)
12455 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12459 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12460 Value *VecOp = IE.getOperand(0);
12461 Value *ScalarOp = IE.getOperand(1);
12462 Value *IdxOp = IE.getOperand(2);
12464 // Inserting an undef or into an undefined place, remove this.
12465 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12466 ReplaceInstUsesWith(IE, VecOp);
12468 // If the inserted element was extracted from some other vector, and if the
12469 // indexes are constant, try to turn this into a shufflevector operation.
12470 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12471 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12472 EI->getOperand(0)->getType() == IE.getType()) {
12473 unsigned NumVectorElts = IE.getType()->getNumElements();
12474 unsigned ExtractedIdx =
12475 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12476 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12478 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12479 return ReplaceInstUsesWith(IE, VecOp);
12481 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12482 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12484 // If we are extracting a value from a vector, then inserting it right
12485 // back into the same place, just use the input vector.
12486 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12487 return ReplaceInstUsesWith(IE, VecOp);
12489 // If this insertelement isn't used by some other insertelement, turn it
12490 // (and any insertelements it points to), into one big shuffle.
12491 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12492 std::vector<Constant*> Mask;
12494 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12495 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12496 // We now have a shuffle of LHS, RHS, Mask.
12497 return new ShuffleVectorInst(LHS, RHS,
12498 ConstantVector::get(Mask));
12503 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12504 APInt UndefElts(VWidth, 0);
12505 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12506 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12513 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12514 Value *LHS = SVI.getOperand(0);
12515 Value *RHS = SVI.getOperand(1);
12516 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12518 bool MadeChange = false;
12520 // Undefined shuffle mask -> undefined value.
12521 if (isa<UndefValue>(SVI.getOperand(2)))
12522 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12524 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12526 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12529 APInt UndefElts(VWidth, 0);
12530 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12531 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12532 LHS = SVI.getOperand(0);
12533 RHS = SVI.getOperand(1);
12537 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12538 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12539 if (LHS == RHS || isa<UndefValue>(LHS)) {
12540 if (isa<UndefValue>(LHS) && LHS == RHS) {
12541 // shuffle(undef,undef,mask) -> undef.
12542 return ReplaceInstUsesWith(SVI, LHS);
12545 // Remap any references to RHS to use LHS.
12546 std::vector<Constant*> Elts;
12547 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12548 if (Mask[i] >= 2*e)
12549 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12551 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12552 (Mask[i] < e && isa<UndefValue>(LHS))) {
12553 Mask[i] = 2*e; // Turn into undef.
12554 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12556 Mask[i] = Mask[i] % e; // Force to LHS.
12557 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12561 SVI.setOperand(0, SVI.getOperand(1));
12562 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12563 SVI.setOperand(2, ConstantVector::get(Elts));
12564 LHS = SVI.getOperand(0);
12565 RHS = SVI.getOperand(1);
12569 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12570 bool isLHSID = true, isRHSID = true;
12572 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12573 if (Mask[i] >= e*2) continue; // Ignore undef values.
12574 // Is this an identity shuffle of the LHS value?
12575 isLHSID &= (Mask[i] == i);
12577 // Is this an identity shuffle of the RHS value?
12578 isRHSID &= (Mask[i]-e == i);
12581 // Eliminate identity shuffles.
12582 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12583 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12585 // If the LHS is a shufflevector itself, see if we can combine it with this
12586 // one without producing an unusual shuffle. Here we are really conservative:
12587 // we are absolutely afraid of producing a shuffle mask not in the input
12588 // program, because the code gen may not be smart enough to turn a merged
12589 // shuffle into two specific shuffles: it may produce worse code. As such,
12590 // we only merge two shuffles if the result is one of the two input shuffle
12591 // masks. In this case, merging the shuffles just removes one instruction,
12592 // which we know is safe. This is good for things like turning:
12593 // (splat(splat)) -> splat.
12594 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12595 if (isa<UndefValue>(RHS)) {
12596 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12598 std::vector<unsigned> NewMask;
12599 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12600 if (Mask[i] >= 2*e)
12601 NewMask.push_back(2*e);
12603 NewMask.push_back(LHSMask[Mask[i]]);
12605 // If the result mask is equal to the src shuffle or this shuffle mask, do
12606 // the replacement.
12607 if (NewMask == LHSMask || NewMask == Mask) {
12608 unsigned LHSInNElts =
12609 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12610 std::vector<Constant*> Elts;
12611 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12612 if (NewMask[i] >= LHSInNElts*2) {
12613 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12615 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12618 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12619 LHSSVI->getOperand(1),
12620 ConstantVector::get(Elts));
12625 return MadeChange ? &SVI : 0;
12631 /// TryToSinkInstruction - Try to move the specified instruction from its
12632 /// current block into the beginning of DestBlock, which can only happen if it's
12633 /// safe to move the instruction past all of the instructions between it and the
12634 /// end of its block.
12635 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12636 assert(I->hasOneUse() && "Invariants didn't hold!");
12638 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12639 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12642 // Do not sink alloca instructions out of the entry block.
12643 if (isa<AllocaInst>(I) && I->getParent() ==
12644 &DestBlock->getParent()->getEntryBlock())
12647 // We can only sink load instructions if there is nothing between the load and
12648 // the end of block that could change the value.
12649 if (I->mayReadFromMemory()) {
12650 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12652 if (Scan->mayWriteToMemory())
12656 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12658 CopyPrecedingStopPoint(I, InsertPos);
12659 I->moveBefore(InsertPos);
12665 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12666 /// all reachable code to the worklist.
12668 /// This has a couple of tricks to make the code faster and more powerful. In
12669 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12670 /// them to the worklist (this significantly speeds up instcombine on code where
12671 /// many instructions are dead or constant). Additionally, if we find a branch
12672 /// whose condition is a known constant, we only visit the reachable successors.
12674 static void AddReachableCodeToWorklist(BasicBlock *BB,
12675 SmallPtrSet<BasicBlock*, 64> &Visited,
12677 const TargetData *TD) {
12678 SmallVector<BasicBlock*, 256> Worklist;
12679 Worklist.push_back(BB);
12681 std::vector<Instruction*> InstrsForInstCombineWorklist;
12682 InstrsForInstCombineWorklist.reserve(128);
12684 while (!Worklist.empty()) {
12685 BB = Worklist.back();
12686 Worklist.pop_back();
12688 // We have now visited this block! If we've already been here, ignore it.
12689 if (!Visited.insert(BB)) continue;
12691 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12692 Instruction *Inst = BBI++;
12694 // DCE instruction if trivially dead.
12695 if (isInstructionTriviallyDead(Inst)) {
12697 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12698 Inst->eraseFromParent();
12702 // ConstantProp instruction if trivially constant.
12703 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12704 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12706 Inst->replaceAllUsesWith(C);
12708 Inst->eraseFromParent();
12712 InstrsForInstCombineWorklist.push_back(Inst);
12715 // Recursively visit successors. If this is a branch or switch on a
12716 // constant, only visit the reachable successor.
12717 TerminatorInst *TI = BB->getTerminator();
12718 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12719 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12720 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12721 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12722 Worklist.push_back(ReachableBB);
12725 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12726 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12727 // See if this is an explicit destination.
12728 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12729 if (SI->getCaseValue(i) == Cond) {
12730 BasicBlock *ReachableBB = SI->getSuccessor(i);
12731 Worklist.push_back(ReachableBB);
12735 // Otherwise it is the default destination.
12736 Worklist.push_back(SI->getSuccessor(0));
12741 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12742 Worklist.push_back(TI->getSuccessor(i));
12745 // Once we've found all of the instructions to add to instcombine's worklist,
12746 // add them in reverse order. This way instcombine will visit from the top
12747 // of the function down. This jives well with the way that it adds all uses
12748 // of instructions to the worklist after doing a transformation, thus avoiding
12749 // some N^2 behavior in pathological cases.
12750 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12751 InstrsForInstCombineWorklist.size());
12754 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12755 MadeIRChange = false;
12756 TD = getAnalysisIfAvailable<TargetData>();
12758 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12759 << F.getNameStr() << "\n");
12762 // Do a depth-first traversal of the function, populate the worklist with
12763 // the reachable instructions. Ignore blocks that are not reachable. Keep
12764 // track of which blocks we visit.
12765 SmallPtrSet<BasicBlock*, 64> Visited;
12766 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12768 // Do a quick scan over the function. If we find any blocks that are
12769 // unreachable, remove any instructions inside of them. This prevents
12770 // the instcombine code from having to deal with some bad special cases.
12771 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12772 if (!Visited.count(BB)) {
12773 Instruction *Term = BB->getTerminator();
12774 while (Term != BB->begin()) { // Remove instrs bottom-up
12775 BasicBlock::iterator I = Term; --I;
12777 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12778 // A debug intrinsic shouldn't force another iteration if we weren't
12779 // going to do one without it.
12780 if (!isa<DbgInfoIntrinsic>(I)) {
12782 MadeIRChange = true;
12784 if (!I->use_empty())
12785 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12786 I->eraseFromParent();
12791 while (!Worklist.isEmpty()) {
12792 Instruction *I = Worklist.RemoveOne();
12793 if (I == 0) continue; // skip null values.
12795 // Check to see if we can DCE the instruction.
12796 if (isInstructionTriviallyDead(I)) {
12797 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12798 EraseInstFromFunction(*I);
12800 MadeIRChange = true;
12804 // Instruction isn't dead, see if we can constant propagate it.
12805 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12806 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12808 // Add operands to the worklist.
12809 ReplaceInstUsesWith(*I, C);
12811 EraseInstFromFunction(*I);
12812 MadeIRChange = true;
12817 // See if we can constant fold its operands.
12818 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12819 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12820 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12821 F.getContext(), TD))
12824 MadeIRChange = true;
12828 // See if we can trivially sink this instruction to a successor basic block.
12829 if (I->hasOneUse()) {
12830 BasicBlock *BB = I->getParent();
12831 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12832 if (UserParent != BB) {
12833 bool UserIsSuccessor = false;
12834 // See if the user is one of our successors.
12835 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12836 if (*SI == UserParent) {
12837 UserIsSuccessor = true;
12841 // If the user is one of our immediate successors, and if that successor
12842 // only has us as a predecessors (we'd have to split the critical edge
12843 // otherwise), we can keep going.
12844 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12845 next(pred_begin(UserParent)) == pred_end(UserParent))
12846 // Okay, the CFG is simple enough, try to sink this instruction.
12847 MadeIRChange |= TryToSinkInstruction(I, UserParent);
12851 // Now that we have an instruction, try combining it to simplify it.
12852 Builder->SetInsertPoint(I->getParent(), I);
12857 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12858 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12860 if (Instruction *Result = visit(*I)) {
12862 // Should we replace the old instruction with a new one?
12864 DEBUG(errs() << "IC: Old = " << *I << '\n'
12865 << " New = " << *Result << '\n');
12867 // Everything uses the new instruction now.
12868 I->replaceAllUsesWith(Result);
12870 // Push the new instruction and any users onto the worklist.
12871 Worklist.Add(Result);
12872 Worklist.AddUsersToWorkList(*Result);
12874 // Move the name to the new instruction first.
12875 Result->takeName(I);
12877 // Insert the new instruction into the basic block...
12878 BasicBlock *InstParent = I->getParent();
12879 BasicBlock::iterator InsertPos = I;
12881 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12882 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12885 InstParent->getInstList().insert(InsertPos, Result);
12887 EraseInstFromFunction(*I);
12890 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12891 << " New = " << *I << '\n');
12894 // If the instruction was modified, it's possible that it is now dead.
12895 // if so, remove it.
12896 if (isInstructionTriviallyDead(I)) {
12897 EraseInstFromFunction(*I);
12900 Worklist.AddUsersToWorkList(*I);
12903 MadeIRChange = true;
12908 return MadeIRChange;
12912 bool InstCombiner::runOnFunction(Function &F) {
12913 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12914 Context = &F.getContext();
12917 /// Builder - This is an IRBuilder that automatically inserts new
12918 /// instructions into the worklist when they are created.
12919 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12920 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12921 InstCombineIRInserter(Worklist));
12922 Builder = &TheBuilder;
12924 bool EverMadeChange = false;
12926 // Iterate while there is work to do.
12927 unsigned Iteration = 0;
12928 while (DoOneIteration(F, Iteration++))
12929 EverMadeChange = true;
12932 return EverMadeChange;
12935 FunctionPass *llvm::createInstructionCombiningPass() {
12936 return new InstCombiner();