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/InstructionSimplify.h"
46 #include "llvm/Analysis/MemoryBuiltins.h"
47 #include "llvm/Analysis/ValueTracking.h"
48 #include "llvm/Target/TargetData.h"
49 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50 #include "llvm/Transforms/Utils/Local.h"
51 #include "llvm/Support/CallSite.h"
52 #include "llvm/Support/ConstantRange.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/GetElementPtrTypeIterator.h"
56 #include "llvm/Support/InstVisitor.h"
57 #include "llvm/Support/IRBuilder.h"
58 #include "llvm/Support/MathExtras.h"
59 #include "llvm/Support/PatternMatch.h"
60 #include "llvm/Support/TargetFolder.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include "llvm/ADT/DenseMap.h"
63 #include "llvm/ADT/SmallVector.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/Statistic.h"
66 #include "llvm/ADT/STLExtras.h"
70 using namespace llvm::PatternMatch;
72 STATISTIC(NumCombined , "Number of insts combined");
73 STATISTIC(NumConstProp, "Number of constant folds");
74 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76 STATISTIC(NumSunkInst , "Number of instructions sunk");
79 /// InstCombineWorklist - This is the worklist management logic for
81 class InstCombineWorklist {
82 SmallVector<Instruction*, 256> Worklist;
83 DenseMap<Instruction*, unsigned> WorklistMap;
85 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
86 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
88 InstCombineWorklist() {}
90 bool isEmpty() const { return Worklist.empty(); }
92 /// Add - Add the specified instruction to the worklist if it isn't already
94 void Add(Instruction *I) {
95 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
96 DEBUG(errs() << "IC: ADD: " << *I << '\n');
97 Worklist.push_back(I);
101 void AddValue(Value *V) {
102 if (Instruction *I = dyn_cast<Instruction>(V))
106 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
107 /// which should only be done when the worklist is empty and when the group
108 /// has no duplicates.
109 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
110 assert(Worklist.empty() && "Worklist must be empty to add initial group");
111 Worklist.reserve(NumEntries+16);
112 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
113 for (; NumEntries; --NumEntries) {
114 Instruction *I = List[NumEntries-1];
115 WorklistMap.insert(std::make_pair(I, Worklist.size()));
116 Worklist.push_back(I);
120 // Remove - remove I from the worklist if it exists.
121 void Remove(Instruction *I) {
122 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
123 if (It == WorklistMap.end()) return; // Not in worklist.
125 // Don't bother moving everything down, just null out the slot.
126 Worklist[It->second] = 0;
128 WorklistMap.erase(It);
131 Instruction *RemoveOne() {
132 Instruction *I = Worklist.back();
134 WorklistMap.erase(I);
138 /// AddUsersToWorkList - When an instruction is simplified, add all users of
139 /// the instruction to the work lists because they might get more simplified
142 void AddUsersToWorkList(Instruction &I) {
143 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
145 Add(cast<Instruction>(*UI));
149 /// Zap - check that the worklist is empty and nuke the backing store for
150 /// the map if it is large.
152 assert(WorklistMap.empty() && "Worklist empty, but map not?");
154 // Do an explicit clear, this shrinks the map if needed.
158 } // end anonymous namespace.
162 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
163 /// just like the normal insertion helper, but also adds any new instructions
164 /// to the instcombine worklist.
165 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
166 InstCombineWorklist &Worklist;
168 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
170 void InsertHelper(Instruction *I, const Twine &Name,
171 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
172 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
176 } // end anonymous namespace
180 class InstCombiner : public FunctionPass,
181 public InstVisitor<InstCombiner, Instruction*> {
183 bool MustPreserveLCSSA;
186 /// Worklist - All of the instructions that need to be simplified.
187 InstCombineWorklist Worklist;
189 /// Builder - This is an IRBuilder that automatically inserts new
190 /// instructions into the worklist when they are created.
191 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
194 static char ID; // Pass identification, replacement for typeid
195 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
197 LLVMContext *Context;
198 LLVMContext *getContext() const { return Context; }
201 virtual bool runOnFunction(Function &F);
203 bool DoOneIteration(Function &F, unsigned ItNum);
205 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
206 AU.addPreservedID(LCSSAID);
207 AU.setPreservesCFG();
210 TargetData *getTargetData() const { return TD; }
212 // Visitation implementation - Implement instruction combining for different
213 // instruction types. The semantics are as follows:
215 // null - No change was made
216 // I - Change was made, I is still valid, I may be dead though
217 // otherwise - Change was made, replace I with returned instruction
219 Instruction *visitAdd(BinaryOperator &I);
220 Instruction *visitFAdd(BinaryOperator &I);
221 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
222 Instruction *visitSub(BinaryOperator &I);
223 Instruction *visitFSub(BinaryOperator &I);
224 Instruction *visitMul(BinaryOperator &I);
225 Instruction *visitFMul(BinaryOperator &I);
226 Instruction *visitURem(BinaryOperator &I);
227 Instruction *visitSRem(BinaryOperator &I);
228 Instruction *visitFRem(BinaryOperator &I);
229 bool SimplifyDivRemOfSelect(BinaryOperator &I);
230 Instruction *commonRemTransforms(BinaryOperator &I);
231 Instruction *commonIRemTransforms(BinaryOperator &I);
232 Instruction *commonDivTransforms(BinaryOperator &I);
233 Instruction *commonIDivTransforms(BinaryOperator &I);
234 Instruction *visitUDiv(BinaryOperator &I);
235 Instruction *visitSDiv(BinaryOperator &I);
236 Instruction *visitFDiv(BinaryOperator &I);
237 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
238 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
239 Instruction *visitAnd(BinaryOperator &I);
240 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
241 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
242 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
243 Value *A, Value *B, Value *C);
244 Instruction *visitOr (BinaryOperator &I);
245 Instruction *visitXor(BinaryOperator &I);
246 Instruction *visitShl(BinaryOperator &I);
247 Instruction *visitAShr(BinaryOperator &I);
248 Instruction *visitLShr(BinaryOperator &I);
249 Instruction *commonShiftTransforms(BinaryOperator &I);
250 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
252 Instruction *visitFCmpInst(FCmpInst &I);
253 Instruction *visitICmpInst(ICmpInst &I);
254 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
255 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
258 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
259 ConstantInt *DivRHS);
261 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
262 ICmpInst::Predicate Cond, Instruction &I);
263 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
265 Instruction *commonCastTransforms(CastInst &CI);
266 Instruction *commonIntCastTransforms(CastInst &CI);
267 Instruction *commonPointerCastTransforms(CastInst &CI);
268 Instruction *visitTrunc(TruncInst &CI);
269 Instruction *visitZExt(ZExtInst &CI);
270 Instruction *visitSExt(SExtInst &CI);
271 Instruction *visitFPTrunc(FPTruncInst &CI);
272 Instruction *visitFPExt(CastInst &CI);
273 Instruction *visitFPToUI(FPToUIInst &FI);
274 Instruction *visitFPToSI(FPToSIInst &FI);
275 Instruction *visitUIToFP(CastInst &CI);
276 Instruction *visitSIToFP(CastInst &CI);
277 Instruction *visitPtrToInt(PtrToIntInst &CI);
278 Instruction *visitIntToPtr(IntToPtrInst &CI);
279 Instruction *visitBitCast(BitCastInst &CI);
280 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
282 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
283 Instruction *visitSelectInst(SelectInst &SI);
284 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
285 Instruction *visitCallInst(CallInst &CI);
286 Instruction *visitInvokeInst(InvokeInst &II);
288 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
289 Instruction *visitPHINode(PHINode &PN);
290 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
291 Instruction *visitAllocaInst(AllocaInst &AI);
292 Instruction *visitFree(Instruction &FI);
293 Instruction *visitLoadInst(LoadInst &LI);
294 Instruction *visitStoreInst(StoreInst &SI);
295 Instruction *visitBranchInst(BranchInst &BI);
296 Instruction *visitSwitchInst(SwitchInst &SI);
297 Instruction *visitInsertElementInst(InsertElementInst &IE);
298 Instruction *visitExtractElementInst(ExtractElementInst &EI);
299 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
300 Instruction *visitExtractValueInst(ExtractValueInst &EV);
302 // visitInstruction - Specify what to return for unhandled instructions...
303 Instruction *visitInstruction(Instruction &I) { return 0; }
306 Instruction *visitCallSite(CallSite CS);
307 bool transformConstExprCastCall(CallSite CS);
308 Instruction *transformCallThroughTrampoline(CallSite CS);
309 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
310 bool DoXform = true);
311 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
312 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
316 // InsertNewInstBefore - insert an instruction New before instruction Old
317 // in the program. Add the new instruction to the worklist.
319 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
320 assert(New && New->getParent() == 0 &&
321 "New instruction already inserted into a basic block!");
322 BasicBlock *BB = Old.getParent();
323 BB->getInstList().insert(&Old, New); // Insert inst
328 // ReplaceInstUsesWith - This method is to be used when an instruction is
329 // found to be dead, replacable with another preexisting expression. Here
330 // we add all uses of I to the worklist, replace all uses of I with the new
331 // value, then return I, so that the inst combiner will know that I was
334 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
335 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
337 // If we are replacing the instruction with itself, this must be in a
338 // segment of unreachable code, so just clobber the instruction.
340 V = UndefValue::get(I.getType());
342 I.replaceAllUsesWith(V);
346 // EraseInstFromFunction - When dealing with an instruction that has side
347 // effects or produces a void value, we can't rely on DCE to delete the
348 // instruction. Instead, visit methods should return the value returned by
350 Instruction *EraseInstFromFunction(Instruction &I) {
351 DEBUG(errs() << "IC: ERASE " << I << '\n');
353 assert(I.use_empty() && "Cannot erase instruction that is used!");
354 // Make sure that we reprocess all operands now that we reduced their
356 if (I.getNumOperands() < 8) {
357 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
358 if (Instruction *Op = dyn_cast<Instruction>(*i))
364 return 0; // Don't do anything with FI
367 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
368 APInt &KnownOne, unsigned Depth = 0) const {
369 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
372 bool MaskedValueIsZero(Value *V, const APInt &Mask,
373 unsigned Depth = 0) const {
374 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
376 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
377 return llvm::ComputeNumSignBits(Op, TD, Depth);
382 /// SimplifyCommutative - This performs a few simplifications for
383 /// commutative operators.
384 bool SimplifyCommutative(BinaryOperator &I);
386 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
387 /// based on the demanded bits.
388 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
389 APInt& KnownZero, APInt& KnownOne,
391 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
392 APInt& KnownZero, APInt& KnownOne,
395 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
396 /// SimplifyDemandedBits knows about. See if the instruction has any
397 /// properties that allow us to simplify its operands.
398 bool SimplifyDemandedInstructionBits(Instruction &Inst);
400 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
401 APInt& UndefElts, unsigned Depth = 0);
403 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
404 // which has a PHI node as operand #0, see if we can fold the instruction
405 // into the PHI (which is only possible if all operands to the PHI are
408 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
409 // that would normally be unprofitable because they strongly encourage jump
411 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
413 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
414 // operator and they all are only used by the PHI, PHI together their
415 // inputs, and do the operation once, to the result of the PHI.
416 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
417 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
418 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
419 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
422 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
423 ConstantInt *AndRHS, BinaryOperator &TheAnd);
425 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
426 bool isSub, Instruction &I);
427 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
428 bool isSigned, bool Inside, Instruction &IB);
429 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
430 Instruction *MatchBSwap(BinaryOperator &I);
431 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
432 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
433 Instruction *SimplifyMemSet(MemSetInst *MI);
436 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
438 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
439 unsigned CastOpc, int &NumCastsRemoved);
440 unsigned GetOrEnforceKnownAlignment(Value *V,
441 unsigned PrefAlign = 0);
444 } // end anonymous namespace
446 char InstCombiner::ID = 0;
447 static RegisterPass<InstCombiner>
448 X("instcombine", "Combine redundant instructions");
450 // getComplexity: Assign a complexity or rank value to LLVM Values...
451 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
452 static unsigned getComplexity(Value *V) {
453 if (isa<Instruction>(V)) {
454 if (BinaryOperator::isNeg(V) ||
455 BinaryOperator::isFNeg(V) ||
456 BinaryOperator::isNot(V))
460 if (isa<Argument>(V)) return 3;
461 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
464 // isOnlyUse - Return true if this instruction will be deleted if we stop using
466 static bool isOnlyUse(Value *V) {
467 return V->hasOneUse() || isa<Constant>(V);
470 // getPromotedType - Return the specified type promoted as it would be to pass
471 // though a va_arg area...
472 static const Type *getPromotedType(const Type *Ty) {
473 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
474 if (ITy->getBitWidth() < 32)
475 return Type::getInt32Ty(Ty->getContext());
480 /// ShouldChangeType - Return true if it is desirable to convert a computation
481 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
482 /// type for example, or from a smaller to a larger illegal type.
483 static bool ShouldChangeType(const Type *From, const Type *To,
484 const TargetData *TD) {
485 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
487 // If we don't have TD, we don't know if the source/dest are legal.
488 if (!TD) return false;
490 unsigned FromWidth = From->getPrimitiveSizeInBits();
491 unsigned ToWidth = To->getPrimitiveSizeInBits();
492 bool FromLegal = TD->isLegalInteger(FromWidth);
493 bool ToLegal = TD->isLegalInteger(ToWidth);
495 // If this is a legal integer from type, and the result would be an illegal
496 // type, don't do the transformation.
497 if (FromLegal && !ToLegal)
500 // Otherwise, if both are illegal, do not increase the size of the result. We
501 // do allow things like i160 -> i64, but not i64 -> i160.
502 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
508 /// getBitCastOperand - If the specified operand is a CastInst, a constant
509 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
510 /// operand value, otherwise return null.
511 static Value *getBitCastOperand(Value *V) {
512 if (Operator *O = dyn_cast<Operator>(V)) {
513 if (O->getOpcode() == Instruction::BitCast)
514 return O->getOperand(0);
515 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
516 if (GEP->hasAllZeroIndices())
517 return GEP->getPointerOperand();
522 /// This function is a wrapper around CastInst::isEliminableCastPair. It
523 /// simply extracts arguments and returns what that function returns.
524 static Instruction::CastOps
525 isEliminableCastPair(
526 const CastInst *CI, ///< The first cast instruction
527 unsigned opcode, ///< The opcode of the second cast instruction
528 const Type *DstTy, ///< The target type for the second cast instruction
529 TargetData *TD ///< The target data for pointer size
532 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
533 const Type *MidTy = CI->getType(); // B from above
535 // Get the opcodes of the two Cast instructions
536 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
537 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
539 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
541 TD ? TD->getIntPtrType(CI->getContext()) : 0);
543 // We don't want to form an inttoptr or ptrtoint that converts to an integer
544 // type that differs from the pointer size.
545 if ((Res == Instruction::IntToPtr &&
546 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
547 (Res == Instruction::PtrToInt &&
548 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
551 return Instruction::CastOps(Res);
554 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
555 /// in any code being generated. It does not require codegen if V is simple
556 /// enough or if the cast can be folded into other casts.
557 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
558 const Type *Ty, TargetData *TD) {
559 if (V->getType() == Ty || isa<Constant>(V)) return false;
561 // If this is another cast that can be eliminated, it isn't codegen either.
562 if (const CastInst *CI = dyn_cast<CastInst>(V))
563 if (isEliminableCastPair(CI, opcode, Ty, TD))
568 // SimplifyCommutative - This performs a few simplifications for commutative
571 // 1. Order operands such that they are listed from right (least complex) to
572 // left (most complex). This puts constants before unary operators before
575 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
576 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
578 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
579 bool Changed = false;
580 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
581 Changed = !I.swapOperands();
583 if (!I.isAssociative()) return Changed;
584 Instruction::BinaryOps Opcode = I.getOpcode();
585 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
586 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
587 if (isa<Constant>(I.getOperand(1))) {
588 Constant *Folded = ConstantExpr::get(I.getOpcode(),
589 cast<Constant>(I.getOperand(1)),
590 cast<Constant>(Op->getOperand(1)));
591 I.setOperand(0, Op->getOperand(0));
592 I.setOperand(1, Folded);
594 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
595 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
596 isOnlyUse(Op) && isOnlyUse(Op1)) {
597 Constant *C1 = cast<Constant>(Op->getOperand(1));
598 Constant *C2 = cast<Constant>(Op1->getOperand(1));
600 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
601 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
602 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
606 I.setOperand(0, New);
607 I.setOperand(1, Folded);
614 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
615 // if the LHS is a constant zero (which is the 'negate' form).
617 static inline Value *dyn_castNegVal(Value *V) {
618 if (BinaryOperator::isNeg(V))
619 return BinaryOperator::getNegArgument(V);
621 // Constants can be considered to be negated values if they can be folded.
622 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
623 return ConstantExpr::getNeg(C);
625 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
626 if (C->getType()->getElementType()->isInteger())
627 return ConstantExpr::getNeg(C);
632 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
633 // instruction if the LHS is a constant negative zero (which is the 'negate'
636 static inline Value *dyn_castFNegVal(Value *V) {
637 if (BinaryOperator::isFNeg(V))
638 return BinaryOperator::getFNegArgument(V);
640 // Constants can be considered to be negated values if they can be folded.
641 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
642 return ConstantExpr::getFNeg(C);
644 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
645 if (C->getType()->getElementType()->isFloatingPoint())
646 return ConstantExpr::getFNeg(C);
651 /// isFreeToInvert - Return true if the specified value is free to invert (apply
652 /// ~ to). This happens in cases where the ~ can be eliminated.
653 static inline bool isFreeToInvert(Value *V) {
655 if (BinaryOperator::isNot(V))
658 // Constants can be considered to be not'ed values.
659 if (isa<ConstantInt>(V))
662 // Compares can be inverted if they have a single use.
663 if (CmpInst *CI = dyn_cast<CmpInst>(V))
664 return CI->hasOneUse();
669 static inline Value *dyn_castNotVal(Value *V) {
670 // If this is not(not(x)) don't return that this is a not: we want the two
671 // not's to be folded first.
672 if (BinaryOperator::isNot(V)) {
673 Value *Operand = BinaryOperator::getNotArgument(V);
674 if (!isFreeToInvert(Operand))
678 // Constants can be considered to be not'ed values...
679 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
680 return ConstantInt::get(C->getType(), ~C->getValue());
686 // dyn_castFoldableMul - If this value is a multiply that can be folded into
687 // other computations (because it has a constant operand), return the
688 // non-constant operand of the multiply, and set CST to point to the multiplier.
689 // Otherwise, return null.
691 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
692 if (V->hasOneUse() && V->getType()->isInteger())
693 if (Instruction *I = dyn_cast<Instruction>(V)) {
694 if (I->getOpcode() == Instruction::Mul)
695 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
696 return I->getOperand(0);
697 if (I->getOpcode() == Instruction::Shl)
698 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
699 // The multiplier is really 1 << CST.
700 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
701 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
702 CST = ConstantInt::get(V->getType()->getContext(),
703 APInt(BitWidth, 1).shl(CSTVal));
704 return I->getOperand(0);
710 /// AddOne - Add one to a ConstantInt
711 static Constant *AddOne(Constant *C) {
712 return ConstantExpr::getAdd(C,
713 ConstantInt::get(C->getType(), 1));
715 /// SubOne - Subtract one from a ConstantInt
716 static Constant *SubOne(ConstantInt *C) {
717 return ConstantExpr::getSub(C,
718 ConstantInt::get(C->getType(), 1));
720 /// MultiplyOverflows - True if the multiply can not be expressed in an int
722 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
723 uint32_t W = C1->getBitWidth();
724 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
733 APInt MulExt = LHSExt * RHSExt;
736 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
737 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
738 return MulExt.slt(Min) || MulExt.sgt(Max);
740 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
744 /// ShrinkDemandedConstant - Check to see if the specified operand of the
745 /// specified instruction is a constant integer. If so, check to see if there
746 /// are any bits set in the constant that are not demanded. If so, shrink the
747 /// constant and return true.
748 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
750 assert(I && "No instruction?");
751 assert(OpNo < I->getNumOperands() && "Operand index too large");
753 // If the operand is not a constant integer, nothing to do.
754 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
755 if (!OpC) return false;
757 // If there are no bits set that aren't demanded, nothing to do.
758 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
759 if ((~Demanded & OpC->getValue()) == 0)
762 // This instruction is producing bits that are not demanded. Shrink the RHS.
763 Demanded &= OpC->getValue();
764 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
768 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
769 // set of known zero and one bits, compute the maximum and minimum values that
770 // could have the specified known zero and known one bits, returning them in
772 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
773 const APInt& KnownOne,
774 APInt& Min, APInt& Max) {
775 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
776 KnownZero.getBitWidth() == Min.getBitWidth() &&
777 KnownZero.getBitWidth() == Max.getBitWidth() &&
778 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
779 APInt UnknownBits = ~(KnownZero|KnownOne);
781 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
782 // bit if it is unknown.
784 Max = KnownOne|UnknownBits;
786 if (UnknownBits.isNegative()) { // Sign bit is unknown
787 Min.set(Min.getBitWidth()-1);
788 Max.clear(Max.getBitWidth()-1);
792 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
793 // a set of known zero and one bits, compute the maximum and minimum values that
794 // could have the specified known zero and known one bits, returning them in
796 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
797 const APInt &KnownOne,
798 APInt &Min, APInt &Max) {
799 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
800 KnownZero.getBitWidth() == Min.getBitWidth() &&
801 KnownZero.getBitWidth() == Max.getBitWidth() &&
802 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
803 APInt UnknownBits = ~(KnownZero|KnownOne);
805 // The minimum value is when the unknown bits are all zeros.
807 // The maximum value is when the unknown bits are all ones.
808 Max = KnownOne|UnknownBits;
811 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
812 /// SimplifyDemandedBits knows about. See if the instruction has any
813 /// properties that allow us to simplify its operands.
814 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
815 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
816 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
817 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
819 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
820 KnownZero, KnownOne, 0);
821 if (V == 0) return false;
822 if (V == &Inst) return true;
823 ReplaceInstUsesWith(Inst, V);
827 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
828 /// specified instruction operand if possible, updating it in place. It returns
829 /// true if it made any change and false otherwise.
830 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
831 APInt &KnownZero, APInt &KnownOne,
833 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
834 KnownZero, KnownOne, Depth);
835 if (NewVal == 0) return false;
841 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
842 /// value based on the demanded bits. When this function is called, it is known
843 /// that only the bits set in DemandedMask of the result of V are ever used
844 /// downstream. Consequently, depending on the mask and V, it may be possible
845 /// to replace V with a constant or one of its operands. In such cases, this
846 /// function does the replacement and returns true. In all other cases, it
847 /// returns false after analyzing the expression and setting KnownOne and known
848 /// to be one in the expression. KnownZero contains all the bits that are known
849 /// to be zero in the expression. These are provided to potentially allow the
850 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
851 /// the expression. KnownOne and KnownZero always follow the invariant that
852 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
853 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
854 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
855 /// and KnownOne must all be the same.
857 /// This returns null if it did not change anything and it permits no
858 /// simplification. This returns V itself if it did some simplification of V's
859 /// operands based on the information about what bits are demanded. This returns
860 /// some other non-null value if it found out that V is equal to another value
861 /// in the context where the specified bits are demanded, but not for all users.
862 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
863 APInt &KnownZero, APInt &KnownOne,
865 assert(V != 0 && "Null pointer of Value???");
866 assert(Depth <= 6 && "Limit Search Depth");
867 uint32_t BitWidth = DemandedMask.getBitWidth();
868 const Type *VTy = V->getType();
869 assert((TD || !isa<PointerType>(VTy)) &&
870 "SimplifyDemandedBits needs to know bit widths!");
871 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
872 (!VTy->isIntOrIntVector() ||
873 VTy->getScalarSizeInBits() == BitWidth) &&
874 KnownZero.getBitWidth() == BitWidth &&
875 KnownOne.getBitWidth() == BitWidth &&
876 "Value *V, DemandedMask, KnownZero and KnownOne "
877 "must have same BitWidth");
878 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
879 // We know all of the bits for a constant!
880 KnownOne = CI->getValue() & DemandedMask;
881 KnownZero = ~KnownOne & DemandedMask;
884 if (isa<ConstantPointerNull>(V)) {
885 // We know all of the bits for a constant!
887 KnownZero = DemandedMask;
893 if (DemandedMask == 0) { // Not demanding any bits from V.
894 if (isa<UndefValue>(V))
896 return UndefValue::get(VTy);
899 if (Depth == 6) // Limit search depth.
902 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
903 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
905 Instruction *I = dyn_cast<Instruction>(V);
907 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
908 return 0; // Only analyze instructions.
911 // If there are multiple uses of this value and we aren't at the root, then
912 // we can't do any simplifications of the operands, because DemandedMask
913 // only reflects the bits demanded by *one* of the users.
914 if (Depth != 0 && !I->hasOneUse()) {
915 // Despite the fact that we can't simplify this instruction in all User's
916 // context, we can at least compute the knownzero/knownone bits, and we can
917 // do simplifications that apply to *just* the one user if we know that
918 // this instruction has a simpler value in that context.
919 if (I->getOpcode() == Instruction::And) {
920 // If either the LHS or the RHS are Zero, the result is zero.
921 ComputeMaskedBits(I->getOperand(1), DemandedMask,
922 RHSKnownZero, RHSKnownOne, Depth+1);
923 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
924 LHSKnownZero, LHSKnownOne, Depth+1);
926 // If all of the demanded bits are known 1 on one side, return the other.
927 // These bits cannot contribute to the result of the 'and' in this
929 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
930 (DemandedMask & ~LHSKnownZero))
931 return I->getOperand(0);
932 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
933 (DemandedMask & ~RHSKnownZero))
934 return I->getOperand(1);
936 // If all of the demanded bits in the inputs are known zeros, return zero.
937 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
938 return Constant::getNullValue(VTy);
940 } else if (I->getOpcode() == Instruction::Or) {
941 // We can simplify (X|Y) -> X or Y in the user's context if we know that
942 // only bits from X or Y are demanded.
944 // If either the LHS or the RHS are One, the result is One.
945 ComputeMaskedBits(I->getOperand(1), DemandedMask,
946 RHSKnownZero, RHSKnownOne, Depth+1);
947 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
948 LHSKnownZero, LHSKnownOne, Depth+1);
950 // If all of the demanded bits are known zero on one side, return the
951 // other. These bits cannot contribute to the result of the 'or' in this
953 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
954 (DemandedMask & ~LHSKnownOne))
955 return I->getOperand(0);
956 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
957 (DemandedMask & ~RHSKnownOne))
958 return I->getOperand(1);
960 // If all of the potentially set bits on one side are known to be set on
961 // the other side, just use the 'other' side.
962 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
963 (DemandedMask & (~RHSKnownZero)))
964 return I->getOperand(0);
965 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
966 (DemandedMask & (~LHSKnownZero)))
967 return I->getOperand(1);
970 // Compute the KnownZero/KnownOne bits to simplify things downstream.
971 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
975 // If this is the root being simplified, allow it to have multiple uses,
976 // just set the DemandedMask to all bits so that we can try to simplify the
977 // operands. This allows visitTruncInst (for example) to simplify the
978 // operand of a trunc without duplicating all the logic below.
979 if (Depth == 0 && !V->hasOneUse())
980 DemandedMask = APInt::getAllOnesValue(BitWidth);
982 switch (I->getOpcode()) {
984 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
986 case Instruction::And:
987 // If either the LHS or the RHS are Zero, the result is zero.
988 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1) ||
990 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
991 LHSKnownZero, LHSKnownOne, Depth+1))
993 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
994 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
996 // If all of the demanded bits are known 1 on one side, return the other.
997 // These bits cannot contribute to the result of the 'and'.
998 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
999 (DemandedMask & ~LHSKnownZero))
1000 return I->getOperand(0);
1001 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1002 (DemandedMask & ~RHSKnownZero))
1003 return I->getOperand(1);
1005 // If all of the demanded bits in the inputs are known zeros, return zero.
1006 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1007 return Constant::getNullValue(VTy);
1009 // If the RHS is a constant, see if we can simplify it.
1010 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1013 // Output known-1 bits are only known if set in both the LHS & RHS.
1014 RHSKnownOne &= LHSKnownOne;
1015 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1016 RHSKnownZero |= LHSKnownZero;
1018 case Instruction::Or:
1019 // If either the LHS or the RHS are One, the result is One.
1020 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1021 RHSKnownZero, RHSKnownOne, Depth+1) ||
1022 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
1023 LHSKnownZero, LHSKnownOne, Depth+1))
1025 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1026 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1028 // If all of the demanded bits are known zero on one side, return the other.
1029 // These bits cannot contribute to the result of the 'or'.
1030 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1031 (DemandedMask & ~LHSKnownOne))
1032 return I->getOperand(0);
1033 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1034 (DemandedMask & ~RHSKnownOne))
1035 return I->getOperand(1);
1037 // If all of the potentially set bits on one side are known to be set on
1038 // the other side, just use the 'other' side.
1039 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1040 (DemandedMask & (~RHSKnownZero)))
1041 return I->getOperand(0);
1042 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1043 (DemandedMask & (~LHSKnownZero)))
1044 return I->getOperand(1);
1046 // If the RHS is a constant, see if we can simplify it.
1047 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1050 // Output known-0 bits are only known if clear in both the LHS & RHS.
1051 RHSKnownZero &= LHSKnownZero;
1052 // Output known-1 are known to be set if set in either the LHS | RHS.
1053 RHSKnownOne |= LHSKnownOne;
1055 case Instruction::Xor: {
1056 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1057 RHSKnownZero, RHSKnownOne, Depth+1) ||
1058 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1059 LHSKnownZero, LHSKnownOne, Depth+1))
1061 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1062 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1064 // If all of the demanded bits are known zero on one side, return the other.
1065 // These bits cannot contribute to the result of the 'xor'.
1066 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1067 return I->getOperand(0);
1068 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1069 return I->getOperand(1);
1071 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1072 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1073 (RHSKnownOne & LHSKnownOne);
1074 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1075 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1076 (RHSKnownOne & LHSKnownZero);
1078 // If all of the demanded bits are known to be zero on one side or the
1079 // other, turn this into an *inclusive* or.
1080 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1081 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1083 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1085 return InsertNewInstBefore(Or, *I);
1088 // If all of the demanded bits on one side are known, and all of the set
1089 // bits on that side are also known to be set on the other side, turn this
1090 // into an AND, as we know the bits will be cleared.
1091 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1092 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1094 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1095 Constant *AndC = Constant::getIntegerValue(VTy,
1096 ~RHSKnownOne & DemandedMask);
1098 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1099 return InsertNewInstBefore(And, *I);
1103 // If the RHS is a constant, see if we can simplify it.
1104 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1105 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1108 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1109 // are flipping are known to be set, then the xor is just resetting those
1110 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1111 // simplifying both of them.
1112 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1113 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1114 isa<ConstantInt>(I->getOperand(1)) &&
1115 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1116 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1117 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1118 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1119 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1122 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1123 Instruction *NewAnd =
1124 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1125 InsertNewInstBefore(NewAnd, *I);
1128 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1129 Instruction *NewXor =
1130 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1131 return InsertNewInstBefore(NewXor, *I);
1135 RHSKnownZero = KnownZeroOut;
1136 RHSKnownOne = KnownOneOut;
1139 case Instruction::Select:
1140 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1141 RHSKnownZero, RHSKnownOne, Depth+1) ||
1142 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1143 LHSKnownZero, LHSKnownOne, Depth+1))
1145 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1146 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1148 // If the operands are constants, see if we can simplify them.
1149 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1150 ShrinkDemandedConstant(I, 2, DemandedMask))
1153 // Only known if known in both the LHS and RHS.
1154 RHSKnownOne &= LHSKnownOne;
1155 RHSKnownZero &= LHSKnownZero;
1157 case Instruction::Trunc: {
1158 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1159 DemandedMask.zext(truncBf);
1160 RHSKnownZero.zext(truncBf);
1161 RHSKnownOne.zext(truncBf);
1162 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1163 RHSKnownZero, RHSKnownOne, Depth+1))
1165 DemandedMask.trunc(BitWidth);
1166 RHSKnownZero.trunc(BitWidth);
1167 RHSKnownOne.trunc(BitWidth);
1168 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1171 case Instruction::BitCast:
1172 if (!I->getOperand(0)->getType()->isIntOrIntVector())
1173 return false; // vector->int or fp->int?
1175 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1176 if (const VectorType *SrcVTy =
1177 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1178 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1179 // Don't touch a bitcast between vectors of different element counts.
1182 // Don't touch a scalar-to-vector bitcast.
1184 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1185 // Don't touch a vector-to-scalar bitcast.
1188 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1189 RHSKnownZero, RHSKnownOne, Depth+1))
1191 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1193 case Instruction::ZExt: {
1194 // Compute the bits in the result that are not present in the input.
1195 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1197 DemandedMask.trunc(SrcBitWidth);
1198 RHSKnownZero.trunc(SrcBitWidth);
1199 RHSKnownOne.trunc(SrcBitWidth);
1200 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1201 RHSKnownZero, RHSKnownOne, Depth+1))
1203 DemandedMask.zext(BitWidth);
1204 RHSKnownZero.zext(BitWidth);
1205 RHSKnownOne.zext(BitWidth);
1206 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1207 // The top bits are known to be zero.
1208 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1211 case Instruction::SExt: {
1212 // Compute the bits in the result that are not present in the input.
1213 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1215 APInt InputDemandedBits = DemandedMask &
1216 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1218 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1219 // If any of the sign extended bits are demanded, we know that the sign
1221 if ((NewBits & DemandedMask) != 0)
1222 InputDemandedBits.set(SrcBitWidth-1);
1224 InputDemandedBits.trunc(SrcBitWidth);
1225 RHSKnownZero.trunc(SrcBitWidth);
1226 RHSKnownOne.trunc(SrcBitWidth);
1227 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1228 RHSKnownZero, RHSKnownOne, Depth+1))
1230 InputDemandedBits.zext(BitWidth);
1231 RHSKnownZero.zext(BitWidth);
1232 RHSKnownOne.zext(BitWidth);
1233 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1235 // If the sign bit of the input is known set or clear, then we know the
1236 // top bits of the result.
1238 // If the input sign bit is known zero, or if the NewBits are not demanded
1239 // convert this into a zero extension.
1240 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1241 // Convert to ZExt cast
1242 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1243 return InsertNewInstBefore(NewCast, *I);
1244 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1245 RHSKnownOne |= NewBits;
1249 case Instruction::Add: {
1250 // Figure out what the input bits are. If the top bits of the and result
1251 // are not demanded, then the add doesn't demand them from its input
1253 unsigned NLZ = DemandedMask.countLeadingZeros();
1255 // If there is a constant on the RHS, there are a variety of xformations
1257 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1258 // If null, this should be simplified elsewhere. Some of the xforms here
1259 // won't work if the RHS is zero.
1263 // If the top bit of the output is demanded, demand everything from the
1264 // input. Otherwise, we demand all the input bits except NLZ top bits.
1265 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1267 // Find information about known zero/one bits in the input.
1268 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1269 LHSKnownZero, LHSKnownOne, Depth+1))
1272 // If the RHS of the add has bits set that can't affect the input, reduce
1274 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1277 // Avoid excess work.
1278 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1281 // Turn it into OR if input bits are zero.
1282 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1284 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1286 return InsertNewInstBefore(Or, *I);
1289 // We can say something about the output known-zero and known-one bits,
1290 // depending on potential carries from the input constant and the
1291 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1292 // bits set and the RHS constant is 0x01001, then we know we have a known
1293 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1295 // To compute this, we first compute the potential carry bits. These are
1296 // the bits which may be modified. I'm not aware of a better way to do
1298 const APInt &RHSVal = RHS->getValue();
1299 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1301 // Now that we know which bits have carries, compute the known-1/0 sets.
1303 // Bits are known one if they are known zero in one operand and one in the
1304 // other, and there is no input carry.
1305 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1306 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1308 // Bits are known zero if they are known zero in both operands and there
1309 // is no input carry.
1310 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1312 // If the high-bits of this ADD are not demanded, then it does not demand
1313 // the high bits of its LHS or RHS.
1314 if (DemandedMask[BitWidth-1] == 0) {
1315 // Right fill the mask of bits for this ADD to demand the most
1316 // significant bit and all those below it.
1317 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1318 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1319 LHSKnownZero, LHSKnownOne, Depth+1) ||
1320 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1321 LHSKnownZero, LHSKnownOne, Depth+1))
1327 case Instruction::Sub:
1328 // If the high-bits of this SUB are not demanded, then it does not demand
1329 // the high bits of its LHS or RHS.
1330 if (DemandedMask[BitWidth-1] == 0) {
1331 // Right fill the mask of bits for this SUB to demand the most
1332 // significant bit and all those below it.
1333 uint32_t NLZ = DemandedMask.countLeadingZeros();
1334 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1335 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1336 LHSKnownZero, LHSKnownOne, Depth+1) ||
1337 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1338 LHSKnownZero, LHSKnownOne, Depth+1))
1341 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1342 // the known zeros and ones.
1343 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1345 case Instruction::Shl:
1346 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1347 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1348 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1349 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1350 RHSKnownZero, RHSKnownOne, Depth+1))
1352 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1353 RHSKnownZero <<= ShiftAmt;
1354 RHSKnownOne <<= ShiftAmt;
1355 // low bits known zero.
1357 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1360 case Instruction::LShr:
1361 // For a logical shift right
1362 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1363 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1365 // Unsigned shift right.
1366 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1367 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1368 RHSKnownZero, RHSKnownOne, Depth+1))
1370 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1371 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1372 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1374 // Compute the new bits that are at the top now.
1375 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1376 RHSKnownZero |= HighBits; // high bits known zero.
1380 case Instruction::AShr:
1381 // If this is an arithmetic shift right and only the low-bit is set, we can
1382 // always convert this into a logical shr, even if the shift amount is
1383 // variable. The low bit of the shift cannot be an input sign bit unless
1384 // the shift amount is >= the size of the datatype, which is undefined.
1385 if (DemandedMask == 1) {
1386 // Perform the logical shift right.
1387 Instruction *NewVal = BinaryOperator::CreateLShr(
1388 I->getOperand(0), I->getOperand(1), I->getName());
1389 return InsertNewInstBefore(NewVal, *I);
1392 // If the sign bit is the only bit demanded by this ashr, then there is no
1393 // need to do it, the shift doesn't change the high bit.
1394 if (DemandedMask.isSignBit())
1395 return I->getOperand(0);
1397 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1398 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1400 // Signed shift right.
1401 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1402 // If any of the "high bits" are demanded, we should set the sign bit as
1404 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1405 DemandedMaskIn.set(BitWidth-1);
1406 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1407 RHSKnownZero, RHSKnownOne, Depth+1))
1409 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1410 // Compute the new bits that are at the top now.
1411 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1412 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1413 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1415 // Handle the sign bits.
1416 APInt SignBit(APInt::getSignBit(BitWidth));
1417 // Adjust to where it is now in the mask.
1418 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1420 // If the input sign bit is known to be zero, or if none of the top bits
1421 // are demanded, turn this into an unsigned shift right.
1422 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1423 (HighBits & ~DemandedMask) == HighBits) {
1424 // Perform the logical shift right.
1425 Instruction *NewVal = BinaryOperator::CreateLShr(
1426 I->getOperand(0), SA, I->getName());
1427 return InsertNewInstBefore(NewVal, *I);
1428 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1429 RHSKnownOne |= HighBits;
1433 case Instruction::SRem:
1434 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1435 APInt RA = Rem->getValue().abs();
1436 if (RA.isPowerOf2()) {
1437 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
1438 return I->getOperand(0);
1440 APInt LowBits = RA - 1;
1441 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1442 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1443 LHSKnownZero, LHSKnownOne, Depth+1))
1446 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1447 LHSKnownZero |= ~LowBits;
1449 KnownZero |= LHSKnownZero & DemandedMask;
1451 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
1455 case Instruction::URem: {
1456 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1457 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1458 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1459 KnownZero2, KnownOne2, Depth+1) ||
1460 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1461 KnownZero2, KnownOne2, Depth+1))
1464 unsigned Leaders = KnownZero2.countLeadingOnes();
1465 Leaders = std::max(Leaders,
1466 KnownZero2.countLeadingOnes());
1467 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1470 case Instruction::Call:
1471 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1472 switch (II->getIntrinsicID()) {
1474 case Intrinsic::bswap: {
1475 // If the only bits demanded come from one byte of the bswap result,
1476 // just shift the input byte into position to eliminate the bswap.
1477 unsigned NLZ = DemandedMask.countLeadingZeros();
1478 unsigned NTZ = DemandedMask.countTrailingZeros();
1480 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1481 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1482 // have 14 leading zeros, round to 8.
1485 // If we need exactly one byte, we can do this transformation.
1486 if (BitWidth-NLZ-NTZ == 8) {
1487 unsigned ResultBit = NTZ;
1488 unsigned InputBit = BitWidth-NTZ-8;
1490 // Replace this with either a left or right shift to get the byte into
1492 Instruction *NewVal;
1493 if (InputBit > ResultBit)
1494 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1495 ConstantInt::get(I->getType(), InputBit-ResultBit));
1497 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1498 ConstantInt::get(I->getType(), ResultBit-InputBit));
1499 NewVal->takeName(I);
1500 return InsertNewInstBefore(NewVal, *I);
1503 // TODO: Could compute known zero/one bits based on the input.
1508 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1512 // If the client is only demanding bits that we know, return the known
1514 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1515 return Constant::getIntegerValue(VTy, RHSKnownOne);
1520 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1521 /// any number of elements. DemandedElts contains the set of elements that are
1522 /// actually used by the caller. This method analyzes which elements of the
1523 /// operand are undef and returns that information in UndefElts.
1525 /// If the information about demanded elements can be used to simplify the
1526 /// operation, the operation is simplified, then the resultant value is
1527 /// returned. This returns null if no change was made.
1528 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1531 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1532 APInt EltMask(APInt::getAllOnesValue(VWidth));
1533 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1535 if (isa<UndefValue>(V)) {
1536 // If the entire vector is undefined, just return this info.
1537 UndefElts = EltMask;
1539 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1540 UndefElts = EltMask;
1541 return UndefValue::get(V->getType());
1545 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1546 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1547 Constant *Undef = UndefValue::get(EltTy);
1549 std::vector<Constant*> Elts;
1550 for (unsigned i = 0; i != VWidth; ++i)
1551 if (!DemandedElts[i]) { // If not demanded, set to undef.
1552 Elts.push_back(Undef);
1554 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1555 Elts.push_back(Undef);
1557 } else { // Otherwise, defined.
1558 Elts.push_back(CP->getOperand(i));
1561 // If we changed the constant, return it.
1562 Constant *NewCP = ConstantVector::get(Elts);
1563 return NewCP != CP ? NewCP : 0;
1564 } else if (isa<ConstantAggregateZero>(V)) {
1565 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1568 // Check if this is identity. If so, return 0 since we are not simplifying
1570 if (DemandedElts == ((1ULL << VWidth) -1))
1573 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1574 Constant *Zero = Constant::getNullValue(EltTy);
1575 Constant *Undef = UndefValue::get(EltTy);
1576 std::vector<Constant*> Elts;
1577 for (unsigned i = 0; i != VWidth; ++i) {
1578 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1579 Elts.push_back(Elt);
1581 UndefElts = DemandedElts ^ EltMask;
1582 return ConstantVector::get(Elts);
1585 // Limit search depth.
1589 // If multiple users are using the root value, procede with
1590 // simplification conservatively assuming that all elements
1592 if (!V->hasOneUse()) {
1593 // Quit if we find multiple users of a non-root value though.
1594 // They'll be handled when it's their turn to be visited by
1595 // the main instcombine process.
1597 // TODO: Just compute the UndefElts information recursively.
1600 // Conservatively assume that all elements are needed.
1601 DemandedElts = EltMask;
1604 Instruction *I = dyn_cast<Instruction>(V);
1605 if (!I) return 0; // Only analyze instructions.
1607 bool MadeChange = false;
1608 APInt UndefElts2(VWidth, 0);
1610 switch (I->getOpcode()) {
1613 case Instruction::InsertElement: {
1614 // If this is a variable index, we don't know which element it overwrites.
1615 // demand exactly the same input as we produce.
1616 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1618 // Note that we can't propagate undef elt info, because we don't know
1619 // which elt is getting updated.
1620 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1621 UndefElts2, Depth+1);
1622 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1626 // If this is inserting an element that isn't demanded, remove this
1628 unsigned IdxNo = Idx->getZExtValue();
1629 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1631 return I->getOperand(0);
1634 // Otherwise, the element inserted overwrites whatever was there, so the
1635 // input demanded set is simpler than the output set.
1636 APInt DemandedElts2 = DemandedElts;
1637 DemandedElts2.clear(IdxNo);
1638 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1639 UndefElts, Depth+1);
1640 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1642 // The inserted element is defined.
1643 UndefElts.clear(IdxNo);
1646 case Instruction::ShuffleVector: {
1647 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1648 uint64_t LHSVWidth =
1649 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1650 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1651 for (unsigned i = 0; i < VWidth; i++) {
1652 if (DemandedElts[i]) {
1653 unsigned MaskVal = Shuffle->getMaskValue(i);
1654 if (MaskVal != -1u) {
1655 assert(MaskVal < LHSVWidth * 2 &&
1656 "shufflevector mask index out of range!");
1657 if (MaskVal < LHSVWidth)
1658 LeftDemanded.set(MaskVal);
1660 RightDemanded.set(MaskVal - LHSVWidth);
1665 APInt UndefElts4(LHSVWidth, 0);
1666 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1667 UndefElts4, Depth+1);
1668 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1670 APInt UndefElts3(LHSVWidth, 0);
1671 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1672 UndefElts3, Depth+1);
1673 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1675 bool NewUndefElts = false;
1676 for (unsigned i = 0; i < VWidth; i++) {
1677 unsigned MaskVal = Shuffle->getMaskValue(i);
1678 if (MaskVal == -1u) {
1680 } else if (MaskVal < LHSVWidth) {
1681 if (UndefElts4[MaskVal]) {
1682 NewUndefElts = true;
1686 if (UndefElts3[MaskVal - LHSVWidth]) {
1687 NewUndefElts = true;
1694 // Add additional discovered undefs.
1695 std::vector<Constant*> Elts;
1696 for (unsigned i = 0; i < VWidth; ++i) {
1698 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1700 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1701 Shuffle->getMaskValue(i)));
1703 I->setOperand(2, ConstantVector::get(Elts));
1708 case Instruction::BitCast: {
1709 // Vector->vector casts only.
1710 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1712 unsigned InVWidth = VTy->getNumElements();
1713 APInt InputDemandedElts(InVWidth, 0);
1716 if (VWidth == InVWidth) {
1717 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1718 // elements as are demanded of us.
1720 InputDemandedElts = DemandedElts;
1721 } else if (VWidth > InVWidth) {
1725 // If there are more elements in the result than there are in the source,
1726 // then an input element is live if any of the corresponding output
1727 // elements are live.
1728 Ratio = VWidth/InVWidth;
1729 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1730 if (DemandedElts[OutIdx])
1731 InputDemandedElts.set(OutIdx/Ratio);
1737 // If there are more elements in the source than there are in the result,
1738 // then an input element is live if the corresponding output element is
1740 Ratio = InVWidth/VWidth;
1741 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1742 if (DemandedElts[InIdx/Ratio])
1743 InputDemandedElts.set(InIdx);
1746 // div/rem demand all inputs, because they don't want divide by zero.
1747 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1748 UndefElts2, Depth+1);
1750 I->setOperand(0, TmpV);
1754 UndefElts = UndefElts2;
1755 if (VWidth > InVWidth) {
1756 llvm_unreachable("Unimp");
1757 // If there are more elements in the result than there are in the source,
1758 // then an output element is undef if the corresponding input element is
1760 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1761 if (UndefElts2[OutIdx/Ratio])
1762 UndefElts.set(OutIdx);
1763 } else if (VWidth < InVWidth) {
1764 llvm_unreachable("Unimp");
1765 // If there are more elements in the source than there are in the result,
1766 // then a result element is undef if all of the corresponding input
1767 // elements are undef.
1768 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1769 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1770 if (!UndefElts2[InIdx]) // Not undef?
1771 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
1775 case Instruction::And:
1776 case Instruction::Or:
1777 case Instruction::Xor:
1778 case Instruction::Add:
1779 case Instruction::Sub:
1780 case Instruction::Mul:
1781 // div/rem demand all inputs, because they don't want divide by zero.
1782 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1783 UndefElts, Depth+1);
1784 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1785 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1786 UndefElts2, Depth+1);
1787 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1789 // Output elements are undefined if both are undefined. Consider things
1790 // like undef&0. The result is known zero, not undef.
1791 UndefElts &= UndefElts2;
1794 case Instruction::Call: {
1795 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1797 switch (II->getIntrinsicID()) {
1800 // Binary vector operations that work column-wise. A dest element is a
1801 // function of the corresponding input elements from the two inputs.
1802 case Intrinsic::x86_sse_sub_ss:
1803 case Intrinsic::x86_sse_mul_ss:
1804 case Intrinsic::x86_sse_min_ss:
1805 case Intrinsic::x86_sse_max_ss:
1806 case Intrinsic::x86_sse2_sub_sd:
1807 case Intrinsic::x86_sse2_mul_sd:
1808 case Intrinsic::x86_sse2_min_sd:
1809 case Intrinsic::x86_sse2_max_sd:
1810 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1811 UndefElts, Depth+1);
1812 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1813 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1814 UndefElts2, Depth+1);
1815 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1817 // If only the low elt is demanded and this is a scalarizable intrinsic,
1818 // scalarize it now.
1819 if (DemandedElts == 1) {
1820 switch (II->getIntrinsicID()) {
1822 case Intrinsic::x86_sse_sub_ss:
1823 case Intrinsic::x86_sse_mul_ss:
1824 case Intrinsic::x86_sse2_sub_sd:
1825 case Intrinsic::x86_sse2_mul_sd:
1826 // TODO: Lower MIN/MAX/ABS/etc
1827 Value *LHS = II->getOperand(1);
1828 Value *RHS = II->getOperand(2);
1829 // Extract the element as scalars.
1830 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
1831 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1832 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1833 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1835 switch (II->getIntrinsicID()) {
1836 default: llvm_unreachable("Case stmts out of sync!");
1837 case Intrinsic::x86_sse_sub_ss:
1838 case Intrinsic::x86_sse2_sub_sd:
1839 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1840 II->getName()), *II);
1842 case Intrinsic::x86_sse_mul_ss:
1843 case Intrinsic::x86_sse2_mul_sd:
1844 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1845 II->getName()), *II);
1850 InsertElementInst::Create(
1851 UndefValue::get(II->getType()), TmpV,
1852 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1853 InsertNewInstBefore(New, *II);
1858 // Output elements are undefined if both are undefined. Consider things
1859 // like undef&0. The result is known zero, not undef.
1860 UndefElts &= UndefElts2;
1866 return MadeChange ? I : 0;
1870 /// AssociativeOpt - Perform an optimization on an associative operator. This
1871 /// function is designed to check a chain of associative operators for a
1872 /// potential to apply a certain optimization. Since the optimization may be
1873 /// applicable if the expression was reassociated, this checks the chain, then
1874 /// reassociates the expression as necessary to expose the optimization
1875 /// opportunity. This makes use of a special Functor, which must define
1876 /// 'shouldApply' and 'apply' methods.
1878 template<typename Functor>
1879 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1880 unsigned Opcode = Root.getOpcode();
1881 Value *LHS = Root.getOperand(0);
1883 // Quick check, see if the immediate LHS matches...
1884 if (F.shouldApply(LHS))
1885 return F.apply(Root);
1887 // Otherwise, if the LHS is not of the same opcode as the root, return.
1888 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1889 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1890 // Should we apply this transform to the RHS?
1891 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1893 // If not to the RHS, check to see if we should apply to the LHS...
1894 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1895 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1899 // If the functor wants to apply the optimization to the RHS of LHSI,
1900 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1902 // Now all of the instructions are in the current basic block, go ahead
1903 // and perform the reassociation.
1904 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1906 // First move the selected RHS to the LHS of the root...
1907 Root.setOperand(0, LHSI->getOperand(1));
1909 // Make what used to be the LHS of the root be the user of the root...
1910 Value *ExtraOperand = TmpLHSI->getOperand(1);
1911 if (&Root == TmpLHSI) {
1912 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1915 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1916 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1917 BasicBlock::iterator ARI = &Root; ++ARI;
1918 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1921 // Now propagate the ExtraOperand down the chain of instructions until we
1923 while (TmpLHSI != LHSI) {
1924 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1925 // Move the instruction to immediately before the chain we are
1926 // constructing to avoid breaking dominance properties.
1927 NextLHSI->moveBefore(ARI);
1930 Value *NextOp = NextLHSI->getOperand(1);
1931 NextLHSI->setOperand(1, ExtraOperand);
1933 ExtraOperand = NextOp;
1936 // Now that the instructions are reassociated, have the functor perform
1937 // the transformation...
1938 return F.apply(Root);
1941 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1948 // AddRHS - Implements: X + X --> X << 1
1951 explicit AddRHS(Value *rhs) : RHS(rhs) {}
1952 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1953 Instruction *apply(BinaryOperator &Add) const {
1954 return BinaryOperator::CreateShl(Add.getOperand(0),
1955 ConstantInt::get(Add.getType(), 1));
1959 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1961 struct AddMaskingAnd {
1963 explicit AddMaskingAnd(Constant *c) : C2(c) {}
1964 bool shouldApply(Value *LHS) const {
1966 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1967 ConstantExpr::getAnd(C1, C2)->isNullValue();
1969 Instruction *apply(BinaryOperator &Add) const {
1970 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1976 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1978 if (CastInst *CI = dyn_cast<CastInst>(&I))
1979 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1981 // Figure out if the constant is the left or the right argument.
1982 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1983 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1985 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1987 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1988 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1991 Value *Op0 = SO, *Op1 = ConstOperand;
1993 std::swap(Op0, Op1);
1995 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1996 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1997 SO->getName()+".op");
1998 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1999 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2000 SO->getName()+".cmp");
2001 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2002 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2003 SO->getName()+".cmp");
2004 llvm_unreachable("Unknown binary instruction type!");
2007 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2008 // constant as the other operand, try to fold the binary operator into the
2009 // select arguments. This also works for Cast instructions, which obviously do
2010 // not have a second operand.
2011 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2013 // Don't modify shared select instructions
2014 if (!SI->hasOneUse()) return 0;
2015 Value *TV = SI->getOperand(1);
2016 Value *FV = SI->getOperand(2);
2018 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2019 // Bool selects with constant operands can be folded to logical ops.
2020 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
2022 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2023 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2025 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2032 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2033 /// has a PHI node as operand #0, see if we can fold the instruction into the
2034 /// PHI (which is only possible if all operands to the PHI are constants).
2036 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2037 /// that would normally be unprofitable because they strongly encourage jump
2039 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2040 bool AllowAggressive) {
2041 AllowAggressive = false;
2042 PHINode *PN = cast<PHINode>(I.getOperand(0));
2043 unsigned NumPHIValues = PN->getNumIncomingValues();
2044 if (NumPHIValues == 0 ||
2045 // We normally only transform phis with a single use, unless we're trying
2046 // hard to make jump threading happen.
2047 (!PN->hasOneUse() && !AllowAggressive))
2051 // Check to see if all of the operands of the PHI are simple constants
2052 // (constantint/constantfp/undef). If there is one non-constant value,
2053 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2054 // bail out. We don't do arbitrary constant expressions here because moving
2055 // their computation can be expensive without a cost model.
2056 BasicBlock *NonConstBB = 0;
2057 for (unsigned i = 0; i != NumPHIValues; ++i)
2058 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2059 isa<ConstantExpr>(PN->getIncomingValue(i))) {
2060 if (NonConstBB) return 0; // More than one non-const value.
2061 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2062 NonConstBB = PN->getIncomingBlock(i);
2064 // If the incoming non-constant value is in I's block, we have an infinite
2066 if (NonConstBB == I.getParent())
2070 // If there is exactly one non-constant value, we can insert a copy of the
2071 // operation in that block. However, if this is a critical edge, we would be
2072 // inserting the computation one some other paths (e.g. inside a loop). Only
2073 // do this if the pred block is unconditionally branching into the phi block.
2074 if (NonConstBB != 0 && !AllowAggressive) {
2075 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2076 if (!BI || !BI->isUnconditional()) return 0;
2079 // Okay, we can do the transformation: create the new PHI node.
2080 PHINode *NewPN = PHINode::Create(I.getType(), "");
2081 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2082 InsertNewInstBefore(NewPN, *PN);
2083 NewPN->takeName(PN);
2085 // Next, add all of the operands to the PHI.
2086 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2087 // We only currently try to fold the condition of a select when it is a phi,
2088 // not the true/false values.
2089 Value *TrueV = SI->getTrueValue();
2090 Value *FalseV = SI->getFalseValue();
2091 BasicBlock *PhiTransBB = PN->getParent();
2092 for (unsigned i = 0; i != NumPHIValues; ++i) {
2093 BasicBlock *ThisBB = PN->getIncomingBlock(i);
2094 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2095 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2097 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2098 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2100 assert(PN->getIncomingBlock(i) == NonConstBB);
2101 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2103 "phitmp", NonConstBB->getTerminator());
2104 Worklist.Add(cast<Instruction>(InV));
2106 NewPN->addIncoming(InV, ThisBB);
2108 } else if (I.getNumOperands() == 2) {
2109 Constant *C = cast<Constant>(I.getOperand(1));
2110 for (unsigned i = 0; i != NumPHIValues; ++i) {
2112 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2113 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2114 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2116 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2118 assert(PN->getIncomingBlock(i) == NonConstBB);
2119 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2120 InV = BinaryOperator::Create(BO->getOpcode(),
2121 PN->getIncomingValue(i), C, "phitmp",
2122 NonConstBB->getTerminator());
2123 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2124 InV = CmpInst::Create(CI->getOpcode(),
2126 PN->getIncomingValue(i), C, "phitmp",
2127 NonConstBB->getTerminator());
2129 llvm_unreachable("Unknown binop!");
2131 Worklist.Add(cast<Instruction>(InV));
2133 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2136 CastInst *CI = cast<CastInst>(&I);
2137 const Type *RetTy = CI->getType();
2138 for (unsigned i = 0; i != NumPHIValues; ++i) {
2140 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2141 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2143 assert(PN->getIncomingBlock(i) == NonConstBB);
2144 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2145 I.getType(), "phitmp",
2146 NonConstBB->getTerminator());
2147 Worklist.Add(cast<Instruction>(InV));
2149 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2152 return ReplaceInstUsesWith(I, NewPN);
2156 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2157 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2158 /// This basically requires proving that the add in the original type would not
2159 /// overflow to change the sign bit or have a carry out.
2160 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2161 // There are different heuristics we can use for this. Here are some simple
2164 // Add has the property that adding any two 2's complement numbers can only
2165 // have one carry bit which can change a sign. As such, if LHS and RHS each
2166 // have at least two sign bits, we know that the addition of the two values
2167 // will sign extend fine.
2168 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2172 // If one of the operands only has one non-zero bit, and if the other operand
2173 // has a known-zero bit in a more significant place than it (not including the
2174 // sign bit) the ripple may go up to and fill the zero, but won't change the
2175 // sign. For example, (X & ~4) + 1.
2183 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2184 bool Changed = SimplifyCommutative(I);
2185 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2187 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2188 I.hasNoUnsignedWrap(), TD))
2189 return ReplaceInstUsesWith(I, V);
2192 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2193 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2194 // X + (signbit) --> X ^ signbit
2195 const APInt& Val = CI->getValue();
2196 uint32_t BitWidth = Val.getBitWidth();
2197 if (Val == APInt::getSignBit(BitWidth))
2198 return BinaryOperator::CreateXor(LHS, RHS);
2200 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2201 // (X & 254)+1 -> (X&254)|1
2202 if (SimplifyDemandedInstructionBits(I))
2205 // zext(bool) + C -> bool ? C + 1 : C
2206 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2207 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2208 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2211 if (isa<PHINode>(LHS))
2212 if (Instruction *NV = FoldOpIntoPhi(I))
2215 ConstantInt *XorRHS = 0;
2217 if (isa<ConstantInt>(RHSC) &&
2218 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2219 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2220 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2222 uint32_t Size = TySizeBits / 2;
2223 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2224 APInt CFF80Val(-C0080Val);
2226 if (TySizeBits > Size) {
2227 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2228 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2229 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2230 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2231 // This is a sign extend if the top bits are known zero.
2232 if (!MaskedValueIsZero(XorLHS,
2233 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2234 Size = 0; // Not a sign ext, but can't be any others either.
2239 C0080Val = APIntOps::lshr(C0080Val, Size);
2240 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2241 } while (Size >= 1);
2243 // FIXME: This shouldn't be necessary. When the backends can handle types
2244 // with funny bit widths then this switch statement should be removed. It
2245 // is just here to get the size of the "middle" type back up to something
2246 // that the back ends can handle.
2247 const Type *MiddleType = 0;
2250 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2251 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2252 case 8: MiddleType = Type::getInt8Ty(*Context); break;
2255 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2256 return new SExtInst(NewTrunc, I.getType(), I.getName());
2261 if (I.getType() == Type::getInt1Ty(*Context))
2262 return BinaryOperator::CreateXor(LHS, RHS);
2265 if (I.getType()->isInteger()) {
2266 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2269 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2270 if (RHSI->getOpcode() == Instruction::Sub)
2271 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2272 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2274 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2275 if (LHSI->getOpcode() == Instruction::Sub)
2276 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2277 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2282 // -A + -B --> -(A + B)
2283 if (Value *LHSV = dyn_castNegVal(LHS)) {
2284 if (LHS->getType()->isIntOrIntVector()) {
2285 if (Value *RHSV = dyn_castNegVal(RHS)) {
2286 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2287 return BinaryOperator::CreateNeg(NewAdd);
2291 return BinaryOperator::CreateSub(RHS, LHSV);
2295 if (!isa<Constant>(RHS))
2296 if (Value *V = dyn_castNegVal(RHS))
2297 return BinaryOperator::CreateSub(LHS, V);
2301 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2302 if (X == RHS) // X*C + X --> X * (C+1)
2303 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2305 // X*C1 + X*C2 --> X * (C1+C2)
2307 if (X == dyn_castFoldableMul(RHS, C1))
2308 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2311 // X + X*C --> X * (C+1)
2312 if (dyn_castFoldableMul(RHS, C2) == LHS)
2313 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2315 // X + ~X --> -1 since ~X = -X-1
2316 if (dyn_castNotVal(LHS) == RHS ||
2317 dyn_castNotVal(RHS) == LHS)
2318 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2321 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2322 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2323 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2326 // A+B --> A|B iff A and B have no bits set in common.
2327 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2328 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2329 APInt LHSKnownOne(IT->getBitWidth(), 0);
2330 APInt LHSKnownZero(IT->getBitWidth(), 0);
2331 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2332 if (LHSKnownZero != 0) {
2333 APInt RHSKnownOne(IT->getBitWidth(), 0);
2334 APInt RHSKnownZero(IT->getBitWidth(), 0);
2335 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2337 // No bits in common -> bitwise or.
2338 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2339 return BinaryOperator::CreateOr(LHS, RHS);
2343 // W*X + Y*Z --> W * (X+Z) iff W == Y
2344 if (I.getType()->isIntOrIntVector()) {
2345 Value *W, *X, *Y, *Z;
2346 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2347 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2351 } else if (Y == X) {
2353 } else if (X == Z) {
2360 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2361 return BinaryOperator::CreateMul(W, NewAdd);
2366 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2368 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2369 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2371 // (X & FF00) + xx00 -> (X+xx00) & FF00
2372 if (LHS->hasOneUse() &&
2373 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2374 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2375 if (Anded == CRHS) {
2376 // See if all bits from the first bit set in the Add RHS up are included
2377 // in the mask. First, get the rightmost bit.
2378 const APInt& AddRHSV = CRHS->getValue();
2380 // Form a mask of all bits from the lowest bit added through the top.
2381 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2383 // See if the and mask includes all of these bits.
2384 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2386 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2387 // Okay, the xform is safe. Insert the new add pronto.
2388 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2389 return BinaryOperator::CreateAnd(NewAdd, C2);
2394 // Try to fold constant add into select arguments.
2395 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2396 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2400 // add (select X 0 (sub n A)) A --> select X A n
2402 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2405 SI = dyn_cast<SelectInst>(RHS);
2408 if (SI && SI->hasOneUse()) {
2409 Value *TV = SI->getTrueValue();
2410 Value *FV = SI->getFalseValue();
2413 // Can we fold the add into the argument of the select?
2414 // We check both true and false select arguments for a matching subtract.
2415 if (match(FV, m_Zero()) &&
2416 match(TV, m_Sub(m_Value(N), m_Specific(A))))
2417 // Fold the add into the true select value.
2418 return SelectInst::Create(SI->getCondition(), N, A);
2419 if (match(TV, m_Zero()) &&
2420 match(FV, m_Sub(m_Value(N), m_Specific(A))))
2421 // Fold the add into the false select value.
2422 return SelectInst::Create(SI->getCondition(), A, N);
2426 // Check for (add (sext x), y), see if we can merge this into an
2427 // integer add followed by a sext.
2428 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2429 // (add (sext x), cst) --> (sext (add x, cst'))
2430 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2432 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2433 if (LHSConv->hasOneUse() &&
2434 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2435 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2436 // Insert the new, smaller add.
2437 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2439 return new SExtInst(NewAdd, I.getType());
2443 // (add (sext x), (sext y)) --> (sext (add int x, y))
2444 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2445 // Only do this if x/y have the same type, if at last one of them has a
2446 // single use (so we don't increase the number of sexts), and if the
2447 // integer add will not overflow.
2448 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2449 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2450 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2451 RHSConv->getOperand(0))) {
2452 // Insert the new integer add.
2453 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2454 RHSConv->getOperand(0), "addconv");
2455 return new SExtInst(NewAdd, I.getType());
2460 return Changed ? &I : 0;
2463 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2464 bool Changed = SimplifyCommutative(I);
2465 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2467 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2469 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2470 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2471 (I.getType())->getValueAPF()))
2472 return ReplaceInstUsesWith(I, LHS);
2475 if (isa<PHINode>(LHS))
2476 if (Instruction *NV = FoldOpIntoPhi(I))
2481 // -A + -B --> -(A + B)
2482 if (Value *LHSV = dyn_castFNegVal(LHS))
2483 return BinaryOperator::CreateFSub(RHS, LHSV);
2486 if (!isa<Constant>(RHS))
2487 if (Value *V = dyn_castFNegVal(RHS))
2488 return BinaryOperator::CreateFSub(LHS, V);
2490 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2491 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2492 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2493 return ReplaceInstUsesWith(I, LHS);
2495 // Check for (add double (sitofp x), y), see if we can merge this into an
2496 // integer add followed by a promotion.
2497 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2498 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2499 // ... if the constant fits in the integer value. This is useful for things
2500 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2501 // requires a constant pool load, and generally allows the add to be better
2503 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2505 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2506 if (LHSConv->hasOneUse() &&
2507 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2508 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2509 // Insert the new integer add.
2510 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2512 return new SIToFPInst(NewAdd, I.getType());
2516 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2517 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2518 // Only do this if x/y have the same type, if at last one of them has a
2519 // single use (so we don't increase the number of int->fp conversions),
2520 // and if the integer add will not overflow.
2521 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2522 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2523 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2524 RHSConv->getOperand(0))) {
2525 // Insert the new integer add.
2526 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2527 RHSConv->getOperand(0),"addconv");
2528 return new SIToFPInst(NewAdd, I.getType());
2533 return Changed ? &I : 0;
2537 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2538 /// code necessary to compute the offset from the base pointer (without adding
2539 /// in the base pointer). Return the result as a signed integer of intptr size.
2540 static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2541 TargetData &TD = *IC.getTargetData();
2542 gep_type_iterator GTI = gep_type_begin(GEP);
2543 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2544 Value *Result = Constant::getNullValue(IntPtrTy);
2546 // Build a mask for high order bits.
2547 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2548 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2550 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2553 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2554 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2555 if (OpC->isZero()) continue;
2557 // Handle a struct index, which adds its field offset to the pointer.
2558 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2559 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2561 Result = IC.Builder->CreateAdd(Result,
2562 ConstantInt::get(IntPtrTy, Size),
2563 GEP->getName()+".offs");
2567 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2569 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2570 Scale = ConstantExpr::getMul(OC, Scale);
2571 // Emit an add instruction.
2572 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2575 // Convert to correct type.
2576 if (Op->getType() != IntPtrTy)
2577 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2579 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2580 // We'll let instcombine(mul) convert this to a shl if possible.
2581 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2584 // Emit an add instruction.
2585 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2591 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2592 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2593 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2594 /// be complex, and scales are involved. The above expression would also be
2595 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2596 /// This later form is less amenable to optimization though, and we are allowed
2597 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
2599 /// If we can't emit an optimized form for this expression, this returns null.
2601 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2603 TargetData &TD = *IC.getTargetData();
2604 gep_type_iterator GTI = gep_type_begin(GEP);
2606 // Check to see if this gep only has a single variable index. If so, and if
2607 // any constant indices are a multiple of its scale, then we can compute this
2608 // in terms of the scale of the variable index. For example, if the GEP
2609 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2610 // because the expression will cross zero at the same point.
2611 unsigned i, e = GEP->getNumOperands();
2613 for (i = 1; i != e; ++i, ++GTI) {
2614 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2615 // Compute the aggregate offset of constant indices.
2616 if (CI->isZero()) continue;
2618 // Handle a struct index, which adds its field offset to the pointer.
2619 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2620 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2622 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2623 Offset += Size*CI->getSExtValue();
2626 // Found our variable index.
2631 // If there are no variable indices, we must have a constant offset, just
2632 // evaluate it the general way.
2633 if (i == e) return 0;
2635 Value *VariableIdx = GEP->getOperand(i);
2636 // Determine the scale factor of the variable element. For example, this is
2637 // 4 if the variable index is into an array of i32.
2638 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2640 // Verify that there are no other variable indices. If so, emit the hard way.
2641 for (++i, ++GTI; i != e; ++i, ++GTI) {
2642 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2645 // Compute the aggregate offset of constant indices.
2646 if (CI->isZero()) continue;
2648 // Handle a struct index, which adds its field offset to the pointer.
2649 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2650 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2652 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2653 Offset += Size*CI->getSExtValue();
2657 // Okay, we know we have a single variable index, which must be a
2658 // pointer/array/vector index. If there is no offset, life is simple, return
2660 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2662 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2663 // we don't need to bother extending: the extension won't affect where the
2664 // computation crosses zero.
2665 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2666 VariableIdx = new TruncInst(VariableIdx,
2667 TD.getIntPtrType(VariableIdx->getContext()),
2668 VariableIdx->getName(), &I);
2672 // Otherwise, there is an index. The computation we will do will be modulo
2673 // the pointer size, so get it.
2674 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2676 Offset &= PtrSizeMask;
2677 VariableScale &= PtrSizeMask;
2679 // To do this transformation, any constant index must be a multiple of the
2680 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2681 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2682 // multiple of the variable scale.
2683 int64_t NewOffs = Offset / (int64_t)VariableScale;
2684 if (Offset != NewOffs*(int64_t)VariableScale)
2687 // Okay, we can do this evaluation. Start by converting the index to intptr.
2688 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2689 if (VariableIdx->getType() != IntPtrTy)
2690 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2692 VariableIdx->getName(), &I);
2693 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2694 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2698 /// Optimize pointer differences into the same array into a size. Consider:
2699 /// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2700 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2702 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2704 assert(TD && "Must have target data info for this");
2706 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2709 GetElementPtrInst *GEP;
2711 if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2712 GEP->getOperand(0) == RHS)
2714 else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2715 GEP->getOperand(0) == LHS)
2720 // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2722 // Emit the offset of the GEP and an intptr_t.
2723 Value *Result = EmitGEPOffset(GEP, *this);
2725 // If we have p - gep(p, ...) then we have to negate the result.
2727 Result = Builder->CreateNeg(Result, "diff.neg");
2729 return Builder->CreateIntCast(Result, Ty, true);
2733 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2734 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2736 if (Op0 == Op1) // sub X, X -> 0
2737 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2739 // If this is a 'B = x-(-A)', change to B = x+A.
2740 if (Value *V = dyn_castNegVal(Op1))
2741 return BinaryOperator::CreateAdd(Op0, V);
2743 if (isa<UndefValue>(Op0))
2744 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2745 if (isa<UndefValue>(Op1))
2746 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2747 if (I.getType() == Type::getInt1Ty(*Context))
2748 return BinaryOperator::CreateXor(Op0, Op1);
2750 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2751 // Replace (-1 - A) with (~A).
2752 if (C->isAllOnesValue())
2753 return BinaryOperator::CreateNot(Op1);
2755 // C - ~X == X + (1+C)
2757 if (match(Op1, m_Not(m_Value(X))))
2758 return BinaryOperator::CreateAdd(X, AddOne(C));
2760 // -(X >>u 31) -> (X >>s 31)
2761 // -(X >>s 31) -> (X >>u 31)
2763 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2764 if (SI->getOpcode() == Instruction::LShr) {
2765 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2766 // Check to see if we are shifting out everything but the sign bit.
2767 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2768 SI->getType()->getPrimitiveSizeInBits()-1) {
2769 // Ok, the transformation is safe. Insert AShr.
2770 return BinaryOperator::Create(Instruction::AShr,
2771 SI->getOperand(0), CU, SI->getName());
2774 } else if (SI->getOpcode() == Instruction::AShr) {
2775 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2776 // Check to see if we are shifting out everything but the sign bit.
2777 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2778 SI->getType()->getPrimitiveSizeInBits()-1) {
2779 // Ok, the transformation is safe. Insert LShr.
2780 return BinaryOperator::CreateLShr(
2781 SI->getOperand(0), CU, SI->getName());
2788 // Try to fold constant sub into select arguments.
2789 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2790 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2793 // C - zext(bool) -> bool ? C - 1 : C
2794 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2795 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2796 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2799 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2800 if (Op1I->getOpcode() == Instruction::Add) {
2801 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2802 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2804 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2805 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2807 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2808 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2809 // C1-(X+C2) --> (C1-C2)-X
2810 return BinaryOperator::CreateSub(
2811 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2815 if (Op1I->hasOneUse()) {
2816 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2817 // is not used by anyone else...
2819 if (Op1I->getOpcode() == Instruction::Sub) {
2820 // Swap the two operands of the subexpr...
2821 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2822 Op1I->setOperand(0, IIOp1);
2823 Op1I->setOperand(1, IIOp0);
2825 // Create the new top level add instruction...
2826 return BinaryOperator::CreateAdd(Op0, Op1);
2829 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2831 if (Op1I->getOpcode() == Instruction::And &&
2832 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2833 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2835 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2836 return BinaryOperator::CreateAnd(Op0, NewNot);
2839 // 0 - (X sdiv C) -> (X sdiv -C)
2840 if (Op1I->getOpcode() == Instruction::SDiv)
2841 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2843 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2844 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2845 ConstantExpr::getNeg(DivRHS));
2847 // X - X*C --> X * (1-C)
2848 ConstantInt *C2 = 0;
2849 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2851 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2853 return BinaryOperator::CreateMul(Op0, CP1);
2858 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2859 if (Op0I->getOpcode() == Instruction::Add) {
2860 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2861 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2862 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2863 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2864 } else if (Op0I->getOpcode() == Instruction::Sub) {
2865 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2866 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2872 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2873 if (X == Op1) // X*C - X --> X * (C-1)
2874 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2876 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2877 if (X == dyn_castFoldableMul(Op1, C2))
2878 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2881 // Optimize pointer differences into the same array into a size. Consider:
2882 // &A[10] - &A[0]: we should compile this to "10".
2884 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2885 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2886 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2889 return ReplaceInstUsesWith(I, Res);
2891 // trunc(p)-trunc(q) -> trunc(p-q)
2892 if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2893 if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2894 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2895 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2896 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2899 return ReplaceInstUsesWith(I, Res);
2905 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2908 // If this is a 'B = x-(-A)', change to B = x+A...
2909 if (Value *V = dyn_castFNegVal(Op1))
2910 return BinaryOperator::CreateFAdd(Op0, V);
2912 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2913 if (Op1I->getOpcode() == Instruction::FAdd) {
2914 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2915 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2917 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2918 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2926 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2927 /// comparison only checks the sign bit. If it only checks the sign bit, set
2928 /// TrueIfSigned if the result of the comparison is true when the input value is
2930 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2931 bool &TrueIfSigned) {
2933 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2934 TrueIfSigned = true;
2935 return RHS->isZero();
2936 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2937 TrueIfSigned = true;
2938 return RHS->isAllOnesValue();
2939 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2940 TrueIfSigned = false;
2941 return RHS->isAllOnesValue();
2942 case ICmpInst::ICMP_UGT:
2943 // True if LHS u> RHS and RHS == high-bit-mask - 1
2944 TrueIfSigned = true;
2945 return RHS->getValue() ==
2946 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2947 case ICmpInst::ICMP_UGE:
2948 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2949 TrueIfSigned = true;
2950 return RHS->getValue().isSignBit();
2956 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2957 bool Changed = SimplifyCommutative(I);
2958 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2960 if (isa<UndefValue>(Op1)) // undef * X -> 0
2961 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2963 // Simplify mul instructions with a constant RHS.
2964 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2965 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
2967 // ((X << C1)*C2) == (X * (C2 << C1))
2968 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2969 if (SI->getOpcode() == Instruction::Shl)
2970 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2971 return BinaryOperator::CreateMul(SI->getOperand(0),
2972 ConstantExpr::getShl(CI, ShOp));
2975 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
2976 if (CI->equalsInt(1)) // X * 1 == X
2977 return ReplaceInstUsesWith(I, Op0);
2978 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2979 return BinaryOperator::CreateNeg(Op0, I.getName());
2981 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2982 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2983 return BinaryOperator::CreateShl(Op0,
2984 ConstantInt::get(Op0->getType(), Val.logBase2()));
2986 } else if (isa<VectorType>(Op1C->getType())) {
2987 if (Op1C->isNullValue())
2988 return ReplaceInstUsesWith(I, Op1C);
2990 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2991 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2992 return BinaryOperator::CreateNeg(Op0, I.getName());
2994 // As above, vector X*splat(1.0) -> X in all defined cases.
2995 if (Constant *Splat = Op1V->getSplatValue()) {
2996 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2997 if (CI->equalsInt(1))
2998 return ReplaceInstUsesWith(I, Op0);
3003 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3004 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
3005 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
3006 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
3007 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3008 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
3009 return BinaryOperator::CreateAdd(Add, C1C2);
3013 // Try to fold constant mul into select arguments.
3014 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3015 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3018 if (isa<PHINode>(Op0))
3019 if (Instruction *NV = FoldOpIntoPhi(I))
3023 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3024 if (Value *Op1v = dyn_castNegVal(Op1))
3025 return BinaryOperator::CreateMul(Op0v, Op1v);
3027 // (X / Y) * Y = X - (X % Y)
3028 // (X / Y) * -Y = (X % Y) - X
3031 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3033 (BO->getOpcode() != Instruction::UDiv &&
3034 BO->getOpcode() != Instruction::SDiv)) {
3036 BO = dyn_cast<BinaryOperator>(Op1);
3038 Value *Neg = dyn_castNegVal(Op1C);
3039 if (BO && BO->hasOneUse() &&
3040 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
3041 (BO->getOpcode() == Instruction::UDiv ||
3042 BO->getOpcode() == Instruction::SDiv)) {
3043 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3045 // If the division is exact, X % Y is zero.
3046 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3047 if (SDiv->isExact()) {
3049 return ReplaceInstUsesWith(I, Op0BO);
3050 return BinaryOperator::CreateNeg(Op0BO);
3054 if (BO->getOpcode() == Instruction::UDiv)
3055 Rem = Builder->CreateURem(Op0BO, Op1BO);
3057 Rem = Builder->CreateSRem(Op0BO, Op1BO);
3061 return BinaryOperator::CreateSub(Op0BO, Rem);
3062 return BinaryOperator::CreateSub(Rem, Op0BO);
3066 /// i1 mul -> i1 and.
3067 if (I.getType() == Type::getInt1Ty(*Context))
3068 return BinaryOperator::CreateAnd(Op0, Op1);
3070 // X*(1 << Y) --> X << Y
3071 // (1 << Y)*X --> X << Y
3074 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
3075 return BinaryOperator::CreateShl(Op1, Y);
3076 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
3077 return BinaryOperator::CreateShl(Op0, Y);
3080 // If one of the operands of the multiply is a cast from a boolean value, then
3081 // we know the bool is either zero or one, so this is a 'masking' multiply.
3082 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3083 if (!isa<VectorType>(I.getType())) {
3084 // -2 is "-1 << 1" so it is all bits set except the low one.
3085 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
3087 Value *BoolCast = 0, *OtherOp = 0;
3088 if (MaskedValueIsZero(Op0, Negative2))
3089 BoolCast = Op0, OtherOp = Op1;
3090 else if (MaskedValueIsZero(Op1, Negative2))
3091 BoolCast = Op1, OtherOp = Op0;
3094 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3096 return BinaryOperator::CreateAnd(V, OtherOp);
3100 return Changed ? &I : 0;
3103 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3104 bool Changed = SimplifyCommutative(I);
3105 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3107 // Simplify mul instructions with a constant RHS...
3108 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3109 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
3110 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3111 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3112 if (Op1F->isExactlyValue(1.0))
3113 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
3114 } else if (isa<VectorType>(Op1C->getType())) {
3115 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
3116 // As above, vector X*splat(1.0) -> X in all defined cases.
3117 if (Constant *Splat = Op1V->getSplatValue()) {
3118 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3119 if (F->isExactlyValue(1.0))
3120 return ReplaceInstUsesWith(I, Op0);
3125 // Try to fold constant mul into select arguments.
3126 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3127 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3130 if (isa<PHINode>(Op0))
3131 if (Instruction *NV = FoldOpIntoPhi(I))
3135 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
3136 if (Value *Op1v = dyn_castFNegVal(Op1))
3137 return BinaryOperator::CreateFMul(Op0v, Op1v);
3139 return Changed ? &I : 0;
3142 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3144 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3145 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3147 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3148 int NonNullOperand = -1;
3149 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3150 if (ST->isNullValue())
3152 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3153 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3154 if (ST->isNullValue())
3157 if (NonNullOperand == -1)
3160 Value *SelectCond = SI->getOperand(0);
3162 // Change the div/rem to use 'Y' instead of the select.
3163 I.setOperand(1, SI->getOperand(NonNullOperand));
3165 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3166 // problem. However, the select, or the condition of the select may have
3167 // multiple uses. Based on our knowledge that the operand must be non-zero,
3168 // propagate the known value for the select into other uses of it, and
3169 // propagate a known value of the condition into its other users.
3171 // If the select and condition only have a single use, don't bother with this,
3173 if (SI->use_empty() && SelectCond->hasOneUse())
3176 // Scan the current block backward, looking for other uses of SI.
3177 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3179 while (BBI != BBFront) {
3181 // If we found a call to a function, we can't assume it will return, so
3182 // information from below it cannot be propagated above it.
3183 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3186 // Replace uses of the select or its condition with the known values.
3187 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3190 *I = SI->getOperand(NonNullOperand);
3192 } else if (*I == SelectCond) {
3193 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3194 ConstantInt::getFalse(*Context);
3199 // If we past the instruction, quit looking for it.
3202 if (&*BBI == SelectCond)
3205 // If we ran out of things to eliminate, break out of the loop.
3206 if (SelectCond == 0 && SI == 0)
3214 /// This function implements the transforms on div instructions that work
3215 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3216 /// used by the visitors to those instructions.
3217 /// @brief Transforms common to all three div instructions
3218 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3219 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3221 // undef / X -> 0 for integer.
3222 // undef / X -> undef for FP (the undef could be a snan).
3223 if (isa<UndefValue>(Op0)) {
3224 if (Op0->getType()->isFPOrFPVector())
3225 return ReplaceInstUsesWith(I, Op0);
3226 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3229 // X / undef -> undef
3230 if (isa<UndefValue>(Op1))
3231 return ReplaceInstUsesWith(I, Op1);
3236 /// This function implements the transforms common to both integer division
3237 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3238 /// division instructions.
3239 /// @brief Common integer divide transforms
3240 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3241 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3243 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3245 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3246 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
3247 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3248 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3251 Constant *CI = ConstantInt::get(I.getType(), 1);
3252 return ReplaceInstUsesWith(I, CI);
3255 if (Instruction *Common = commonDivTransforms(I))
3258 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3259 // This does not apply for fdiv.
3260 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3263 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3265 if (RHS->equalsInt(1))
3266 return ReplaceInstUsesWith(I, Op0);
3268 // (X / C1) / C2 -> X / (C1*C2)
3269 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3270 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3271 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3272 if (MultiplyOverflows(RHS, LHSRHS,
3273 I.getOpcode()==Instruction::SDiv))
3274 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3276 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3277 ConstantExpr::getMul(RHS, LHSRHS));
3280 if (!RHS->isZero()) { // avoid X udiv 0
3281 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3282 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3284 if (isa<PHINode>(Op0))
3285 if (Instruction *NV = FoldOpIntoPhi(I))
3290 // 0 / X == 0, we don't need to preserve faults!
3291 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3292 if (LHS->equalsInt(0))
3293 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3295 // It can't be division by zero, hence it must be division by one.
3296 if (I.getType() == Type::getInt1Ty(*Context))
3297 return ReplaceInstUsesWith(I, Op0);
3299 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3300 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3303 return ReplaceInstUsesWith(I, Op0);
3309 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3310 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3312 // Handle the integer div common cases
3313 if (Instruction *Common = commonIDivTransforms(I))
3316 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3317 // X udiv C^2 -> X >> C
3318 // Check to see if this is an unsigned division with an exact power of 2,
3319 // if so, convert to a right shift.
3320 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3321 return BinaryOperator::CreateLShr(Op0,
3322 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3324 // X udiv C, where C >= signbit
3325 if (C->getValue().isNegative()) {
3326 Value *IC = Builder->CreateICmpULT( Op0, C);
3327 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3328 ConstantInt::get(I.getType(), 1));
3332 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3333 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3334 if (RHSI->getOpcode() == Instruction::Shl &&
3335 isa<ConstantInt>(RHSI->getOperand(0))) {
3336 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3337 if (C1.isPowerOf2()) {
3338 Value *N = RHSI->getOperand(1);
3339 const Type *NTy = N->getType();
3340 if (uint32_t C2 = C1.logBase2())
3341 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3342 return BinaryOperator::CreateLShr(Op0, N);
3347 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3348 // where C1&C2 are powers of two.
3349 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3350 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3351 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3352 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3353 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3354 // Compute the shift amounts
3355 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3356 // Construct the "on true" case of the select
3357 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3358 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3360 // Construct the "on false" case of the select
3361 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3362 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3364 // construct the select instruction and return it.
3365 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3371 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3372 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3374 // Handle the integer div common cases
3375 if (Instruction *Common = commonIDivTransforms(I))
3378 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3380 if (RHS->isAllOnesValue())
3381 return BinaryOperator::CreateNeg(Op0);
3383 // sdiv X, C --> ashr X, log2(C)
3384 if (cast<SDivOperator>(&I)->isExact() &&
3385 RHS->getValue().isNonNegative() &&
3386 RHS->getValue().isPowerOf2()) {
3387 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3388 RHS->getValue().exactLogBase2());
3389 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3392 // -X/C --> X/-C provided the negation doesn't overflow.
3393 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3394 if (isa<Constant>(Sub->getOperand(0)) &&
3395 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3396 Sub->hasNoSignedWrap())
3397 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3398 ConstantExpr::getNeg(RHS));
3401 // If the sign bits of both operands are zero (i.e. we can prove they are
3402 // unsigned inputs), turn this into a udiv.
3403 if (I.getType()->isInteger()) {
3404 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3405 if (MaskedValueIsZero(Op0, Mask)) {
3406 if (MaskedValueIsZero(Op1, Mask)) {
3407 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3408 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3410 ConstantInt *ShiftedInt;
3411 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3412 ShiftedInt->getValue().isPowerOf2()) {
3413 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3414 // Safe because the only negative value (1 << Y) can take on is
3415 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3416 // the sign bit set.
3417 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3425 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3426 return commonDivTransforms(I);
3429 /// This function implements the transforms on rem instructions that work
3430 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3431 /// is used by the visitors to those instructions.
3432 /// @brief Transforms common to all three rem instructions
3433 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3434 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3436 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3437 if (I.getType()->isFPOrFPVector())
3438 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3441 if (isa<UndefValue>(Op1))
3442 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3444 // Handle cases involving: rem X, (select Cond, Y, Z)
3445 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3451 /// This function implements the transforms common to both integer remainder
3452 /// instructions (urem and srem). It is called by the visitors to those integer
3453 /// remainder instructions.
3454 /// @brief Common integer remainder transforms
3455 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3456 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3458 if (Instruction *common = commonRemTransforms(I))
3461 // 0 % X == 0 for integer, we don't need to preserve faults!
3462 if (Constant *LHS = dyn_cast<Constant>(Op0))
3463 if (LHS->isNullValue())
3464 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3466 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3467 // X % 0 == undef, we don't need to preserve faults!
3468 if (RHS->equalsInt(0))
3469 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3471 if (RHS->equalsInt(1)) // X % 1 == 0
3472 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3474 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3475 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3476 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3478 } else if (isa<PHINode>(Op0I)) {
3479 if (Instruction *NV = FoldOpIntoPhi(I))
3483 // See if we can fold away this rem instruction.
3484 if (SimplifyDemandedInstructionBits(I))
3492 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3493 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3495 if (Instruction *common = commonIRemTransforms(I))
3498 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3499 // X urem C^2 -> X and C
3500 // Check to see if this is an unsigned remainder with an exact power of 2,
3501 // if so, convert to a bitwise and.
3502 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3503 if (C->getValue().isPowerOf2())
3504 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3507 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3508 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3509 if (RHSI->getOpcode() == Instruction::Shl &&
3510 isa<ConstantInt>(RHSI->getOperand(0))) {
3511 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3512 Constant *N1 = Constant::getAllOnesValue(I.getType());
3513 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3514 return BinaryOperator::CreateAnd(Op0, Add);
3519 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3520 // where C1&C2 are powers of two.
3521 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3522 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3523 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3524 // STO == 0 and SFO == 0 handled above.
3525 if ((STO->getValue().isPowerOf2()) &&
3526 (SFO->getValue().isPowerOf2())) {
3527 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3528 SI->getName()+".t");
3529 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3530 SI->getName()+".f");
3531 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3539 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3540 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3542 // Handle the integer rem common cases
3543 if (Instruction *Common = commonIRemTransforms(I))
3546 if (Value *RHSNeg = dyn_castNegVal(Op1))
3547 if (!isa<Constant>(RHSNeg) ||
3548 (isa<ConstantInt>(RHSNeg) &&
3549 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3551 Worklist.AddValue(I.getOperand(1));
3552 I.setOperand(1, RHSNeg);
3556 // If the sign bits of both operands are zero (i.e. we can prove they are
3557 // unsigned inputs), turn this into a urem.
3558 if (I.getType()->isInteger()) {
3559 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3560 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3561 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3562 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3566 // If it's a constant vector, flip any negative values positive.
3567 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3568 unsigned VWidth = RHSV->getNumOperands();
3570 bool hasNegative = false;
3571 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3572 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3573 if (RHS->getValue().isNegative())
3577 std::vector<Constant *> Elts(VWidth);
3578 for (unsigned i = 0; i != VWidth; ++i) {
3579 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3580 if (RHS->getValue().isNegative())
3581 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3587 Constant *NewRHSV = ConstantVector::get(Elts);
3588 if (NewRHSV != RHSV) {
3589 Worklist.AddValue(I.getOperand(1));
3590 I.setOperand(1, NewRHSV);
3599 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3600 return commonRemTransforms(I);
3603 // isOneBitSet - Return true if there is exactly one bit set in the specified
3605 static bool isOneBitSet(const ConstantInt *CI) {
3606 return CI->getValue().isPowerOf2();
3609 // isHighOnes - Return true if the constant is of the form 1+0+.
3610 // This is the same as lowones(~X).
3611 static bool isHighOnes(const ConstantInt *CI) {
3612 return (~CI->getValue() + 1).isPowerOf2();
3615 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3616 /// are carefully arranged to allow folding of expressions such as:
3618 /// (A < B) | (A > B) --> (A != B)
3620 /// Note that this is only valid if the first and second predicates have the
3621 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3623 /// Three bits are used to represent the condition, as follows:
3628 /// <=> Value Definition
3629 /// 000 0 Always false
3636 /// 111 7 Always true
3638 static unsigned getICmpCode(const ICmpInst *ICI) {
3639 switch (ICI->getPredicate()) {
3641 case ICmpInst::ICMP_UGT: return 1; // 001
3642 case ICmpInst::ICMP_SGT: return 1; // 001
3643 case ICmpInst::ICMP_EQ: return 2; // 010
3644 case ICmpInst::ICMP_UGE: return 3; // 011
3645 case ICmpInst::ICMP_SGE: return 3; // 011
3646 case ICmpInst::ICMP_ULT: return 4; // 100
3647 case ICmpInst::ICMP_SLT: return 4; // 100
3648 case ICmpInst::ICMP_NE: return 5; // 101
3649 case ICmpInst::ICMP_ULE: return 6; // 110
3650 case ICmpInst::ICMP_SLE: return 6; // 110
3653 llvm_unreachable("Invalid ICmp predicate!");
3658 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3659 /// predicate into a three bit mask. It also returns whether it is an ordered
3660 /// predicate by reference.
3661 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3664 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3665 case FCmpInst::FCMP_UNO: return 0; // 000
3666 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3667 case FCmpInst::FCMP_UGT: return 1; // 001
3668 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3669 case FCmpInst::FCMP_UEQ: return 2; // 010
3670 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3671 case FCmpInst::FCMP_UGE: return 3; // 011
3672 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3673 case FCmpInst::FCMP_ULT: return 4; // 100
3674 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3675 case FCmpInst::FCMP_UNE: return 5; // 101
3676 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3677 case FCmpInst::FCMP_ULE: return 6; // 110
3680 // Not expecting FCMP_FALSE and FCMP_TRUE;
3681 llvm_unreachable("Unexpected FCmp predicate!");
3686 /// getICmpValue - This is the complement of getICmpCode, which turns an
3687 /// opcode and two operands into either a constant true or false, or a brand
3688 /// new ICmp instruction. The sign is passed in to determine which kind
3689 /// of predicate to use in the new icmp instruction.
3690 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3691 LLVMContext *Context) {
3693 default: llvm_unreachable("Illegal ICmp code!");
3694 case 0: return ConstantInt::getFalse(*Context);
3697 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3699 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3700 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3703 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3705 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3708 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3710 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3711 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3714 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3716 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3717 case 7: return ConstantInt::getTrue(*Context);
3721 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3722 /// opcode and two operands into either a FCmp instruction. isordered is passed
3723 /// in to determine which kind of predicate to use in the new fcmp instruction.
3724 static Value *getFCmpValue(bool isordered, unsigned code,
3725 Value *LHS, Value *RHS, LLVMContext *Context) {
3727 default: llvm_unreachable("Illegal FCmp code!");
3730 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3732 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3735 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3737 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3740 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3742 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3745 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3747 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3750 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3752 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3755 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3757 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3760 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3762 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3763 case 7: return ConstantInt::getTrue(*Context);
3767 /// PredicatesFoldable - Return true if both predicates match sign or if at
3768 /// least one of them is an equality comparison (which is signless).
3769 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3770 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3771 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3772 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
3776 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3777 struct FoldICmpLogical {
3780 ICmpInst::Predicate pred;
3781 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3782 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3783 pred(ICI->getPredicate()) {}
3784 bool shouldApply(Value *V) const {
3785 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3786 if (PredicatesFoldable(pred, ICI->getPredicate()))
3787 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3788 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3791 Instruction *apply(Instruction &Log) const {
3792 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3793 if (ICI->getOperand(0) != LHS) {
3794 assert(ICI->getOperand(1) == LHS);
3795 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3798 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3799 unsigned LHSCode = getICmpCode(ICI);
3800 unsigned RHSCode = getICmpCode(RHSICI);
3802 switch (Log.getOpcode()) {
3803 case Instruction::And: Code = LHSCode & RHSCode; break;
3804 case Instruction::Or: Code = LHSCode | RHSCode; break;
3805 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3806 default: llvm_unreachable("Illegal logical opcode!"); return 0;
3809 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
3810 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3811 if (Instruction *I = dyn_cast<Instruction>(RV))
3813 // Otherwise, it's a constant boolean value...
3814 return IC.ReplaceInstUsesWith(Log, RV);
3817 } // end anonymous namespace
3819 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3820 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3821 // guaranteed to be a binary operator.
3822 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3824 ConstantInt *AndRHS,
3825 BinaryOperator &TheAnd) {
3826 Value *X = Op->getOperand(0);
3827 Constant *Together = 0;
3829 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3831 switch (Op->getOpcode()) {
3832 case Instruction::Xor:
3833 if (Op->hasOneUse()) {
3834 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3835 Value *And = Builder->CreateAnd(X, AndRHS);
3837 return BinaryOperator::CreateXor(And, Together);
3840 case Instruction::Or:
3841 if (Together == AndRHS) // (X | C) & C --> C
3842 return ReplaceInstUsesWith(TheAnd, AndRHS);
3844 if (Op->hasOneUse() && Together != OpRHS) {
3845 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3846 Value *Or = Builder->CreateOr(X, Together);
3848 return BinaryOperator::CreateAnd(Or, AndRHS);
3851 case Instruction::Add:
3852 if (Op->hasOneUse()) {
3853 // Adding a one to a single bit bit-field should be turned into an XOR
3854 // of the bit. First thing to check is to see if this AND is with a
3855 // single bit constant.
3856 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3858 // If there is only one bit set...
3859 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3860 // Ok, at this point, we know that we are masking the result of the
3861 // ADD down to exactly one bit. If the constant we are adding has
3862 // no bits set below this bit, then we can eliminate the ADD.
3863 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3865 // Check to see if any bits below the one bit set in AndRHSV are set.
3866 if ((AddRHS & (AndRHSV-1)) == 0) {
3867 // If not, the only thing that can effect the output of the AND is
3868 // the bit specified by AndRHSV. If that bit is set, the effect of
3869 // the XOR is to toggle the bit. If it is clear, then the ADD has
3871 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3872 TheAnd.setOperand(0, X);
3875 // Pull the XOR out of the AND.
3876 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3877 NewAnd->takeName(Op);
3878 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3885 case Instruction::Shl: {
3886 // We know that the AND will not produce any of the bits shifted in, so if
3887 // the anded constant includes them, clear them now!
3889 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3890 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3891 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3892 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3894 if (CI->getValue() == ShlMask) {
3895 // Masking out bits that the shift already masks
3896 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3897 } else if (CI != AndRHS) { // Reducing bits set in and.
3898 TheAnd.setOperand(1, CI);
3903 case Instruction::LShr:
3905 // We know that the AND will not produce any of the bits shifted in, so if
3906 // the anded constant includes them, clear them now! This only applies to
3907 // unsigned shifts, because a signed shr may bring in set bits!
3909 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3910 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3911 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3912 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3914 if (CI->getValue() == ShrMask) {
3915 // Masking out bits that the shift already masks.
3916 return ReplaceInstUsesWith(TheAnd, Op);
3917 } else if (CI != AndRHS) {
3918 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3923 case Instruction::AShr:
3925 // See if this is shifting in some sign extension, then masking it out
3927 if (Op->hasOneUse()) {
3928 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3929 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3930 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3931 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3932 if (C == AndRHS) { // Masking out bits shifted in.
3933 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3934 // Make the argument unsigned.
3935 Value *ShVal = Op->getOperand(0);
3936 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3937 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3946 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3947 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3948 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3949 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3950 /// insert new instructions.
3951 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3952 bool isSigned, bool Inside,
3954 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3955 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3956 "Lo is not <= Hi in range emission code!");
3959 if (Lo == Hi) // Trivially false.
3960 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3962 // V >= Min && V < Hi --> V < Hi
3963 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3964 ICmpInst::Predicate pred = (isSigned ?
3965 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3966 return new ICmpInst(pred, V, Hi);
3969 // Emit V-Lo <u Hi-Lo
3970 Constant *NegLo = ConstantExpr::getNeg(Lo);
3971 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3972 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3973 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3976 if (Lo == Hi) // Trivially true.
3977 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3979 // V < Min || V >= Hi -> V > Hi-1
3980 Hi = SubOne(cast<ConstantInt>(Hi));
3981 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3982 ICmpInst::Predicate pred = (isSigned ?
3983 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3984 return new ICmpInst(pred, V, Hi);
3987 // Emit V-Lo >u Hi-1-Lo
3988 // Note that Hi has already had one subtracted from it, above.
3989 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3990 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3991 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3992 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3995 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3996 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3997 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3998 // not, since all 1s are not contiguous.
3999 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
4000 const APInt& V = Val->getValue();
4001 uint32_t BitWidth = Val->getType()->getBitWidth();
4002 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
4004 // look for the first zero bit after the run of ones
4005 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
4006 // look for the first non-zero bit
4007 ME = V.getActiveBits();
4011 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4012 /// where isSub determines whether the operator is a sub. If we can fold one of
4013 /// the following xforms:
4015 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4016 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4017 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4019 /// return (A +/- B).
4021 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4022 ConstantInt *Mask, bool isSub,
4024 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4025 if (!LHSI || LHSI->getNumOperands() != 2 ||
4026 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4028 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4030 switch (LHSI->getOpcode()) {
4032 case Instruction::And:
4033 if (ConstantExpr::getAnd(N, Mask) == Mask) {
4034 // If the AndRHS is a power of two minus one (0+1+), this is simple.
4035 if ((Mask->getValue().countLeadingZeros() +
4036 Mask->getValue().countPopulation()) ==
4037 Mask->getValue().getBitWidth())
4040 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4041 // part, we don't need any explicit masks to take them out of A. If that
4042 // is all N is, ignore it.
4043 uint32_t MB = 0, ME = 0;
4044 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
4045 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4046 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4047 if (MaskedValueIsZero(RHS, Mask))
4052 case Instruction::Or:
4053 case Instruction::Xor:
4054 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4055 if ((Mask->getValue().countLeadingZeros() +
4056 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4057 && ConstantExpr::getAnd(N, Mask)->isNullValue())
4063 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4064 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
4067 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4068 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4069 ICmpInst *LHS, ICmpInst *RHS) {
4070 // (icmp eq A, null) & (icmp eq B, null) -->
4071 // (icmp eq (ptrtoint(A)|ptrtoint(B)), 0)
4073 LHS->getPredicate() == ICmpInst::ICMP_EQ &&
4074 RHS->getPredicate() == ICmpInst::ICMP_EQ &&
4075 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4076 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4077 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4078 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4079 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4080 Value *NewOr = Builder->CreateOr(A, B);
4081 return new ICmpInst(ICmpInst::ICMP_EQ, NewOr,
4082 Constant::getNullValue(IntPtrTy));
4086 ConstantInt *LHSCst, *RHSCst;
4087 ICmpInst::Predicate LHSCC, RHSCC;
4089 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
4090 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4091 m_ConstantInt(LHSCst))) ||
4092 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4093 m_ConstantInt(RHSCst))))
4096 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4097 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4098 // where C is a power of 2
4099 if (LHSCC == ICmpInst::ICMP_ULT &&
4100 LHSCst->getValue().isPowerOf2()) {
4101 Value *NewOr = Builder->CreateOr(Val, Val2);
4102 return new ICmpInst(LHSCC, NewOr, LHSCst);
4105 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4106 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4107 Value *NewOr = Builder->CreateOr(Val, Val2);
4108 return new ICmpInst(LHSCC, NewOr, LHSCst);
4112 // From here on, we only handle:
4113 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4114 if (Val != Val2) return 0;
4116 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4117 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4118 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4119 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4120 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4123 // We can't fold (ugt x, C) & (sgt x, C2).
4124 if (!PredicatesFoldable(LHSCC, RHSCC))
4127 // Ensure that the larger constant is on the RHS.
4129 if (CmpInst::isSigned(LHSCC) ||
4130 (ICmpInst::isEquality(LHSCC) &&
4131 CmpInst::isSigned(RHSCC)))
4132 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4134 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4137 std::swap(LHS, RHS);
4138 std::swap(LHSCst, RHSCst);
4139 std::swap(LHSCC, RHSCC);
4142 // At this point, we know we have have two icmp instructions
4143 // comparing a value against two constants and and'ing the result
4144 // together. Because of the above check, we know that we only have
4145 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4146 // (from the FoldICmpLogical check above), that the two constants
4147 // are not equal and that the larger constant is on the RHS
4148 assert(LHSCst != RHSCst && "Compares not folded above?");
4151 default: llvm_unreachable("Unknown integer condition code!");
4152 case ICmpInst::ICMP_EQ:
4154 default: llvm_unreachable("Unknown integer condition code!");
4155 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4156 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4157 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
4158 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4159 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4160 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4161 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4162 return ReplaceInstUsesWith(I, LHS);
4164 case ICmpInst::ICMP_NE:
4166 default: llvm_unreachable("Unknown integer condition code!");
4167 case ICmpInst::ICMP_ULT:
4168 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4169 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
4170 break; // (X != 13 & X u< 15) -> no change
4171 case ICmpInst::ICMP_SLT:
4172 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4173 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
4174 break; // (X != 13 & X s< 15) -> no change
4175 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4176 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4177 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4178 return ReplaceInstUsesWith(I, RHS);
4179 case ICmpInst::ICMP_NE:
4180 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4181 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4182 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4183 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4184 ConstantInt::get(Add->getType(), 1));
4186 break; // (X != 13 & X != 15) -> no change
4189 case ICmpInst::ICMP_ULT:
4191 default: llvm_unreachable("Unknown integer condition code!");
4192 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4193 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
4194 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4195 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4197 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4198 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4199 return ReplaceInstUsesWith(I, LHS);
4200 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4204 case ICmpInst::ICMP_SLT:
4206 default: llvm_unreachable("Unknown integer condition code!");
4207 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4208 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
4209 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4210 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4212 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4213 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4214 return ReplaceInstUsesWith(I, LHS);
4215 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4219 case ICmpInst::ICMP_UGT:
4221 default: llvm_unreachable("Unknown integer condition code!");
4222 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4223 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4224 return ReplaceInstUsesWith(I, RHS);
4225 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4227 case ICmpInst::ICMP_NE:
4228 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4229 return new ICmpInst(LHSCC, Val, RHSCst);
4230 break; // (X u> 13 & X != 15) -> no change
4231 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
4232 return InsertRangeTest(Val, AddOne(LHSCst),
4233 RHSCst, false, true, I);
4234 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4238 case ICmpInst::ICMP_SGT:
4240 default: llvm_unreachable("Unknown integer condition code!");
4241 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4242 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4243 return ReplaceInstUsesWith(I, RHS);
4244 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4246 case ICmpInst::ICMP_NE:
4247 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4248 return new ICmpInst(LHSCC, Val, RHSCst);
4249 break; // (X s> 13 & X != 15) -> no change
4250 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
4251 return InsertRangeTest(Val, AddOne(LHSCst),
4252 RHSCst, true, true, I);
4253 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4262 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4265 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4266 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4267 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4268 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4269 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4270 // If either of the constants are nans, then the whole thing returns
4272 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4273 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4274 return new FCmpInst(FCmpInst::FCMP_ORD,
4275 LHS->getOperand(0), RHS->getOperand(0));
4278 // Handle vector zeros. This occurs because the canonical form of
4279 // "fcmp ord x,x" is "fcmp ord x, 0".
4280 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4281 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4282 return new FCmpInst(FCmpInst::FCMP_ORD,
4283 LHS->getOperand(0), RHS->getOperand(0));
4287 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4288 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4289 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4292 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4293 // Swap RHS operands to match LHS.
4294 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4295 std::swap(Op1LHS, Op1RHS);
4298 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4299 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4301 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4303 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4304 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4305 if (Op0CC == FCmpInst::FCMP_TRUE)
4306 return ReplaceInstUsesWith(I, RHS);
4307 if (Op1CC == FCmpInst::FCMP_TRUE)
4308 return ReplaceInstUsesWith(I, LHS);
4312 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4313 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4315 std::swap(LHS, RHS);
4316 std::swap(Op0Pred, Op1Pred);
4317 std::swap(Op0Ordered, Op1Ordered);
4320 // uno && ueq -> uno && (uno || eq) -> ueq
4321 // ord && olt -> ord && (ord && lt) -> olt
4322 if (Op0Ordered == Op1Ordered)
4323 return ReplaceInstUsesWith(I, RHS);
4325 // uno && oeq -> uno && (ord && eq) -> false
4326 // uno && ord -> false
4328 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4329 // ord && ueq -> ord && (uno || eq) -> oeq
4330 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4331 Op0LHS, Op0RHS, Context));
4339 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4340 bool Changed = SimplifyCommutative(I);
4341 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4343 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4344 return ReplaceInstUsesWith(I, V);
4346 // See if we can simplify any instructions used by the instruction whose sole
4347 // purpose is to compute bits we don't care about.
4348 if (SimplifyDemandedInstructionBits(I))
4352 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4353 const APInt &AndRHSMask = AndRHS->getValue();
4354 APInt NotAndRHS(~AndRHSMask);
4356 // Optimize a variety of ((val OP C1) & C2) combinations...
4357 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4358 Value *Op0LHS = Op0I->getOperand(0);
4359 Value *Op0RHS = Op0I->getOperand(1);
4360 switch (Op0I->getOpcode()) {
4362 case Instruction::Xor:
4363 case Instruction::Or:
4364 // If the mask is only needed on one incoming arm, push it up.
4365 if (!Op0I->hasOneUse()) break;
4367 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4368 // Not masking anything out for the LHS, move to RHS.
4369 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4370 Op0RHS->getName()+".masked");
4371 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4373 if (!isa<Constant>(Op0RHS) &&
4374 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4375 // Not masking anything out for the RHS, move to LHS.
4376 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4377 Op0LHS->getName()+".masked");
4378 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4382 case Instruction::Add:
4383 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4384 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4385 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4386 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4387 return BinaryOperator::CreateAnd(V, AndRHS);
4388 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4389 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4392 case Instruction::Sub:
4393 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4394 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4395 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4396 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4397 return BinaryOperator::CreateAnd(V, AndRHS);
4399 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4400 // has 1's for all bits that the subtraction with A might affect.
4401 if (Op0I->hasOneUse()) {
4402 uint32_t BitWidth = AndRHSMask.getBitWidth();
4403 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4404 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4406 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4407 if (!(A && A->isZero()) && // avoid infinite recursion.
4408 MaskedValueIsZero(Op0LHS, Mask)) {
4409 Value *NewNeg = Builder->CreateNeg(Op0RHS);
4410 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4415 case Instruction::Shl:
4416 case Instruction::LShr:
4417 // (1 << x) & 1 --> zext(x == 0)
4418 // (1 >> x) & 1 --> zext(x == 0)
4419 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4421 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4422 return new ZExtInst(NewICmp, I.getType());
4427 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4428 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4430 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4431 // If this is an integer truncation or change from signed-to-unsigned, and
4432 // if the source is an and/or with immediate, transform it. This
4433 // frequently occurs for bitfield accesses.
4434 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4435 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4436 CastOp->getNumOperands() == 2)
4437 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
4438 if (CastOp->getOpcode() == Instruction::And) {
4439 // Change: and (cast (and X, C1) to T), C2
4440 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4441 // This will fold the two constants together, which may allow
4442 // other simplifications.
4443 Value *NewCast = Builder->CreateTruncOrBitCast(
4444 CastOp->getOperand(0), I.getType(),
4445 CastOp->getName()+".shrunk");
4446 // trunc_or_bitcast(C1)&C2
4447 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4448 C3 = ConstantExpr::getAnd(C3, AndRHS);
4449 return BinaryOperator::CreateAnd(NewCast, C3);
4450 } else if (CastOp->getOpcode() == Instruction::Or) {
4451 // Change: and (cast (or X, C1) to T), C2
4452 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4453 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4454 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4456 return ReplaceInstUsesWith(I, AndRHS);
4462 // Try to fold constant and into select arguments.
4463 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4464 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4466 if (isa<PHINode>(Op0))
4467 if (Instruction *NV = FoldOpIntoPhi(I))
4472 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4473 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4474 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4475 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4476 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4477 I.getName()+".demorgan");
4478 return BinaryOperator::CreateNot(Or);
4482 Value *A = 0, *B = 0, *C = 0, *D = 0;
4483 // (A|B) & ~(A&B) -> A^B
4484 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4485 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4486 ((A == C && B == D) || (A == D && B == C)))
4487 return BinaryOperator::CreateXor(A, B);
4489 // ~(A&B) & (A|B) -> A^B
4490 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4491 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4492 ((A == C && B == D) || (A == D && B == C)))
4493 return BinaryOperator::CreateXor(A, B);
4495 if (Op0->hasOneUse() &&
4496 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4497 if (A == Op1) { // (A^B)&A -> A&(A^B)
4498 I.swapOperands(); // Simplify below
4499 std::swap(Op0, Op1);
4500 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4501 cast<BinaryOperator>(Op0)->swapOperands();
4502 I.swapOperands(); // Simplify below
4503 std::swap(Op0, Op1);
4507 if (Op1->hasOneUse() &&
4508 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4509 if (B == Op0) { // B&(A^B) -> B&(B^A)
4510 cast<BinaryOperator>(Op1)->swapOperands();
4513 if (A == Op0) // A&(A^B) -> A & ~B
4514 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4517 // (A&((~A)|B)) -> A&B
4518 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4519 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4520 return BinaryOperator::CreateAnd(A, Op1);
4521 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4522 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4523 return BinaryOperator::CreateAnd(A, Op0);
4526 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4527 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4528 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4531 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4532 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4536 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4537 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4538 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4539 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4540 const Type *SrcTy = Op0C->getOperand(0)->getType();
4541 if (SrcTy == Op1C->getOperand(0)->getType() &&
4542 SrcTy->isIntOrIntVector() &&
4543 // Only do this if the casts both really cause code to be generated.
4544 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4546 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4548 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4549 Op1C->getOperand(0), I.getName());
4550 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4554 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4555 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4556 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4557 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4558 SI0->getOperand(1) == SI1->getOperand(1) &&
4559 (SI0->hasOneUse() || SI1->hasOneUse())) {
4561 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4563 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4564 SI1->getOperand(1));
4568 // If and'ing two fcmp, try combine them into one.
4569 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4570 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4571 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4575 return Changed ? &I : 0;
4578 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4579 /// capable of providing pieces of a bswap. The subexpression provides pieces
4580 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4581 /// the expression came from the corresponding "byte swapped" byte in some other
4582 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4583 /// we know that the expression deposits the low byte of %X into the high byte
4584 /// of the bswap result and that all other bytes are zero. This expression is
4585 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4588 /// This function returns true if the match was unsuccessful and false if so.
4589 /// On entry to the function the "OverallLeftShift" is a signed integer value
4590 /// indicating the number of bytes that the subexpression is later shifted. For
4591 /// example, if the expression is later right shifted by 16 bits, the
4592 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4593 /// byte of ByteValues is actually being set.
4595 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4596 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4597 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4598 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4599 /// always in the local (OverallLeftShift) coordinate space.
4601 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4602 SmallVector<Value*, 8> &ByteValues) {
4603 if (Instruction *I = dyn_cast<Instruction>(V)) {
4604 // If this is an or instruction, it may be an inner node of the bswap.
4605 if (I->getOpcode() == Instruction::Or) {
4606 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4608 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4612 // If this is a logical shift by a constant multiple of 8, recurse with
4613 // OverallLeftShift and ByteMask adjusted.
4614 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4616 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4617 // Ensure the shift amount is defined and of a byte value.
4618 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4621 unsigned ByteShift = ShAmt >> 3;
4622 if (I->getOpcode() == Instruction::Shl) {
4623 // X << 2 -> collect(X, +2)
4624 OverallLeftShift += ByteShift;
4625 ByteMask >>= ByteShift;
4627 // X >>u 2 -> collect(X, -2)
4628 OverallLeftShift -= ByteShift;
4629 ByteMask <<= ByteShift;
4630 ByteMask &= (~0U >> (32-ByteValues.size()));
4633 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4634 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4636 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4640 // If this is a logical 'and' with a mask that clears bytes, clear the
4641 // corresponding bytes in ByteMask.
4642 if (I->getOpcode() == Instruction::And &&
4643 isa<ConstantInt>(I->getOperand(1))) {
4644 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4645 unsigned NumBytes = ByteValues.size();
4646 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4647 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4649 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4650 // If this byte is masked out by a later operation, we don't care what
4652 if ((ByteMask & (1 << i)) == 0)
4655 // If the AndMask is all zeros for this byte, clear the bit.
4656 APInt MaskB = AndMask & Byte;
4658 ByteMask &= ~(1U << i);
4662 // If the AndMask is not all ones for this byte, it's not a bytezap.
4666 // Otherwise, this byte is kept.
4669 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4674 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4675 // the input value to the bswap. Some observations: 1) if more than one byte
4676 // is demanded from this input, then it could not be successfully assembled
4677 // into a byteswap. At least one of the two bytes would not be aligned with
4678 // their ultimate destination.
4679 if (!isPowerOf2_32(ByteMask)) return true;
4680 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4682 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4683 // is demanded, it needs to go into byte 0 of the result. This means that the
4684 // byte needs to be shifted until it lands in the right byte bucket. The
4685 // shift amount depends on the position: if the byte is coming from the high
4686 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4687 // low part, it must be shifted left.
4688 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4689 if (InputByteNo < ByteValues.size()/2) {
4690 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4693 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4697 // If the destination byte value is already defined, the values are or'd
4698 // together, which isn't a bswap (unless it's an or of the same bits).
4699 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4701 ByteValues[DestByteNo] = V;
4705 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4706 /// If so, insert the new bswap intrinsic and return it.
4707 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4708 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4709 if (!ITy || ITy->getBitWidth() % 16 ||
4710 // ByteMask only allows up to 32-byte values.
4711 ITy->getBitWidth() > 32*8)
4712 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4714 /// ByteValues - For each byte of the result, we keep track of which value
4715 /// defines each byte.
4716 SmallVector<Value*, 8> ByteValues;
4717 ByteValues.resize(ITy->getBitWidth()/8);
4719 // Try to find all the pieces corresponding to the bswap.
4720 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4721 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4724 // Check to see if all of the bytes come from the same value.
4725 Value *V = ByteValues[0];
4726 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4728 // Check to make sure that all of the bytes come from the same value.
4729 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4730 if (ByteValues[i] != V)
4732 const Type *Tys[] = { ITy };
4733 Module *M = I.getParent()->getParent()->getParent();
4734 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4735 return CallInst::Create(F, V);
4738 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4739 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4740 /// we can simplify this expression to "cond ? C : D or B".
4741 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4743 LLVMContext *Context) {
4744 // If A is not a select of -1/0, this cannot match.
4746 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4749 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4750 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4751 return SelectInst::Create(Cond, C, B);
4752 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4753 return SelectInst::Create(Cond, C, B);
4754 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4755 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4756 return SelectInst::Create(Cond, C, D);
4757 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4758 return SelectInst::Create(Cond, C, D);
4762 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4763 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4764 ICmpInst *LHS, ICmpInst *RHS) {
4765 // (icmp ne A, null) | (icmp ne B, null) -->
4766 // (icmp ne (ptrtoint(A)|ptrtoint(B)), 0)
4768 LHS->getPredicate() == ICmpInst::ICMP_NE &&
4769 RHS->getPredicate() == ICmpInst::ICMP_NE &&
4770 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4771 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4772 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4773 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4774 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4775 Value *NewOr = Builder->CreateOr(A, B);
4776 return new ICmpInst(ICmpInst::ICMP_NE, NewOr,
4777 Constant::getNullValue(IntPtrTy));
4781 ConstantInt *LHSCst, *RHSCst;
4782 ICmpInst::Predicate LHSCC, RHSCC;
4784 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4785 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4786 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4790 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4791 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4792 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4793 Value *NewOr = Builder->CreateOr(Val, Val2);
4794 return new ICmpInst(LHSCC, NewOr, LHSCst);
4797 // From here on, we only handle:
4798 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4799 if (Val != Val2) return 0;
4801 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4802 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4803 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4804 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4805 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4808 // We can't fold (ugt x, C) | (sgt x, C2).
4809 if (!PredicatesFoldable(LHSCC, RHSCC))
4812 // Ensure that the larger constant is on the RHS.
4814 if (CmpInst::isSigned(LHSCC) ||
4815 (ICmpInst::isEquality(LHSCC) &&
4816 CmpInst::isSigned(RHSCC)))
4817 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4819 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4822 std::swap(LHS, RHS);
4823 std::swap(LHSCst, RHSCst);
4824 std::swap(LHSCC, RHSCC);
4827 // At this point, we know we have have two icmp instructions
4828 // comparing a value against two constants and or'ing the result
4829 // together. Because of the above check, we know that we only have
4830 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4831 // FoldICmpLogical check above), that the two constants are not
4833 assert(LHSCst != RHSCst && "Compares not folded above?");
4836 default: llvm_unreachable("Unknown integer condition code!");
4837 case ICmpInst::ICMP_EQ:
4839 default: llvm_unreachable("Unknown integer condition code!");
4840 case ICmpInst::ICMP_EQ:
4841 if (LHSCst == SubOne(RHSCst)) {
4842 // (X == 13 | X == 14) -> X-13 <u 2
4843 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4844 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4845 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4846 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4848 break; // (X == 13 | X == 15) -> no change
4849 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4850 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4852 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4853 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4854 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4855 return ReplaceInstUsesWith(I, RHS);
4858 case ICmpInst::ICMP_NE:
4860 default: llvm_unreachable("Unknown integer condition code!");
4861 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4862 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4863 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4864 return ReplaceInstUsesWith(I, LHS);
4865 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4866 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4867 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4868 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4871 case ICmpInst::ICMP_ULT:
4873 default: llvm_unreachable("Unknown integer condition code!");
4874 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4876 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4877 // If RHSCst is [us]MAXINT, it is always false. Not handling
4878 // this can cause overflow.
4879 if (RHSCst->isMaxValue(false))
4880 return ReplaceInstUsesWith(I, LHS);
4881 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4883 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4885 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4886 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4887 return ReplaceInstUsesWith(I, RHS);
4888 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4892 case ICmpInst::ICMP_SLT:
4894 default: llvm_unreachable("Unknown integer condition code!");
4895 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4897 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4898 // If RHSCst is [us]MAXINT, it is always false. Not handling
4899 // this can cause overflow.
4900 if (RHSCst->isMaxValue(true))
4901 return ReplaceInstUsesWith(I, LHS);
4902 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4904 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4906 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4907 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4908 return ReplaceInstUsesWith(I, RHS);
4909 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4913 case ICmpInst::ICMP_UGT:
4915 default: llvm_unreachable("Unknown integer condition code!");
4916 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4917 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4918 return ReplaceInstUsesWith(I, LHS);
4919 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4921 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4922 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4923 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4924 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4928 case ICmpInst::ICMP_SGT:
4930 default: llvm_unreachable("Unknown integer condition code!");
4931 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4932 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4933 return ReplaceInstUsesWith(I, LHS);
4934 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4936 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4937 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4938 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4939 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4947 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4949 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4950 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4951 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4952 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4953 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4954 // If either of the constants are nans, then the whole thing returns
4956 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4957 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4959 // Otherwise, no need to compare the two constants, compare the
4961 return new FCmpInst(FCmpInst::FCMP_UNO,
4962 LHS->getOperand(0), RHS->getOperand(0));
4965 // Handle vector zeros. This occurs because the canonical form of
4966 // "fcmp uno x,x" is "fcmp uno x, 0".
4967 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4968 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4969 return new FCmpInst(FCmpInst::FCMP_UNO,
4970 LHS->getOperand(0), RHS->getOperand(0));
4975 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4976 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4977 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4979 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4980 // Swap RHS operands to match LHS.
4981 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4982 std::swap(Op1LHS, Op1RHS);
4984 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4985 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4987 return new FCmpInst((FCmpInst::Predicate)Op0CC,
4989 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4990 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4991 if (Op0CC == FCmpInst::FCMP_FALSE)
4992 return ReplaceInstUsesWith(I, RHS);
4993 if (Op1CC == FCmpInst::FCMP_FALSE)
4994 return ReplaceInstUsesWith(I, LHS);
4997 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4998 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4999 if (Op0Ordered == Op1Ordered) {
5000 // If both are ordered or unordered, return a new fcmp with
5001 // or'ed predicates.
5002 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5003 Op0LHS, Op0RHS, Context);
5004 if (Instruction *I = dyn_cast<Instruction>(RV))
5006 // Otherwise, it's a constant boolean value...
5007 return ReplaceInstUsesWith(I, RV);
5013 /// FoldOrWithConstants - This helper function folds:
5015 /// ((A | B) & C1) | (B & C2)
5021 /// when the XOR of the two constants is "all ones" (-1).
5022 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
5023 Value *A, Value *B, Value *C) {
5024 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5028 ConstantInt *CI2 = 0;
5029 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
5031 APInt Xor = CI1->getValue() ^ CI2->getValue();
5032 if (!Xor.isAllOnesValue()) return 0;
5034 if (V1 == A || V1 == B) {
5035 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
5036 return BinaryOperator::CreateOr(NewOp, V1);
5042 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
5043 bool Changed = SimplifyCommutative(I);
5044 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5046 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5047 return ReplaceInstUsesWith(I, V);
5050 // See if we can simplify any instructions used by the instruction whose sole
5051 // purpose is to compute bits we don't care about.
5052 if (SimplifyDemandedInstructionBits(I))
5055 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5056 ConstantInt *C1 = 0; Value *X = 0;
5057 // (X & C1) | C2 --> (X | C2) & (C1|C2)
5058 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
5060 Value *Or = Builder->CreateOr(X, RHS);
5062 return BinaryOperator::CreateAnd(Or,
5063 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
5066 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
5067 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
5069 Value *Or = Builder->CreateOr(X, RHS);
5071 return BinaryOperator::CreateXor(Or,
5072 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
5075 // Try to fold constant and into select arguments.
5076 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5077 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5079 if (isa<PHINode>(Op0))
5080 if (Instruction *NV = FoldOpIntoPhi(I))
5084 Value *A = 0, *B = 0;
5085 ConstantInt *C1 = 0, *C2 = 0;
5087 // (A | B) | C and A | (B | C) -> bswap if possible.
5088 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
5089 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5090 match(Op1, m_Or(m_Value(), m_Value())) ||
5091 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5092 match(Op1, m_Shift(m_Value(), m_Value())))) {
5093 if (Instruction *BSwap = MatchBSwap(I))
5097 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
5098 if (Op0->hasOneUse() &&
5099 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5100 MaskedValueIsZero(Op1, C1->getValue())) {
5101 Value *NOr = Builder->CreateOr(A, Op1);
5103 return BinaryOperator::CreateXor(NOr, C1);
5106 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
5107 if (Op1->hasOneUse() &&
5108 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5109 MaskedValueIsZero(Op0, C1->getValue())) {
5110 Value *NOr = Builder->CreateOr(A, Op0);
5112 return BinaryOperator::CreateXor(NOr, C1);
5116 Value *C = 0, *D = 0;
5117 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5118 match(Op1, m_And(m_Value(B), m_Value(D)))) {
5119 Value *V1 = 0, *V2 = 0, *V3 = 0;
5120 C1 = dyn_cast<ConstantInt>(C);
5121 C2 = dyn_cast<ConstantInt>(D);
5122 if (C1 && C2) { // (A & C1)|(B & C2)
5123 // If we have: ((V + N) & C1) | (V & C2)
5124 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5125 // replace with V+N.
5126 if (C1->getValue() == ~C2->getValue()) {
5127 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
5128 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
5129 // Add commutes, try both ways.
5130 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5131 return ReplaceInstUsesWith(I, A);
5132 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5133 return ReplaceInstUsesWith(I, A);
5135 // Or commutes, try both ways.
5136 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
5137 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
5138 // Add commutes, try both ways.
5139 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5140 return ReplaceInstUsesWith(I, B);
5141 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5142 return ReplaceInstUsesWith(I, B);
5145 V1 = 0; V2 = 0; V3 = 0;
5148 // Check to see if we have any common things being and'ed. If so, find the
5149 // terms for V1 & (V2|V3).
5150 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5151 if (A == B) // (A & C)|(A & D) == A & (C|D)
5152 V1 = A, V2 = C, V3 = D;
5153 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5154 V1 = A, V2 = B, V3 = C;
5155 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5156 V1 = C, V2 = A, V3 = D;
5157 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5158 V1 = C, V2 = A, V3 = B;
5161 Value *Or = Builder->CreateOr(V2, V3, "tmp");
5162 return BinaryOperator::CreateAnd(V1, Or);
5166 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
5167 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
5169 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
5171 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
5173 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
5176 // ((A&~B)|(~A&B)) -> A^B
5177 if ((match(C, m_Not(m_Specific(D))) &&
5178 match(B, m_Not(m_Specific(A)))))
5179 return BinaryOperator::CreateXor(A, D);
5180 // ((~B&A)|(~A&B)) -> A^B
5181 if ((match(A, m_Not(m_Specific(D))) &&
5182 match(B, m_Not(m_Specific(C)))))
5183 return BinaryOperator::CreateXor(C, D);
5184 // ((A&~B)|(B&~A)) -> A^B
5185 if ((match(C, m_Not(m_Specific(B))) &&
5186 match(D, m_Not(m_Specific(A)))))
5187 return BinaryOperator::CreateXor(A, B);
5188 // ((~B&A)|(B&~A)) -> A^B
5189 if ((match(A, m_Not(m_Specific(B))) &&
5190 match(D, m_Not(m_Specific(C)))))
5191 return BinaryOperator::CreateXor(C, B);
5194 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
5195 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5196 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5197 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
5198 SI0->getOperand(1) == SI1->getOperand(1) &&
5199 (SI0->hasOneUse() || SI1->hasOneUse())) {
5200 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5202 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
5203 SI1->getOperand(1));
5207 // ((A|B)&1)|(B&-2) -> (A&1) | B
5208 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5209 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5210 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
5211 if (Ret) return Ret;
5213 // (B&-2)|((A|B)&1) -> (A&1) | B
5214 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5215 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5216 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
5217 if (Ret) return Ret;
5220 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5221 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5222 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5223 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5224 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5225 I.getName()+".demorgan");
5226 return BinaryOperator::CreateNot(And);
5229 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5230 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
5231 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5234 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5235 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5239 // fold (or (cast A), (cast B)) -> (cast (or A, B))
5240 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5241 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5242 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
5243 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5244 !isa<ICmpInst>(Op1C->getOperand(0))) {
5245 const Type *SrcTy = Op0C->getOperand(0)->getType();
5246 if (SrcTy == Op1C->getOperand(0)->getType() &&
5247 SrcTy->isIntOrIntVector() &&
5248 // Only do this if the casts both really cause code to be
5250 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5252 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5254 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5255 Op1C->getOperand(0), I.getName());
5256 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5263 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5264 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5265 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5266 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5270 return Changed ? &I : 0;
5275 // XorSelf - Implements: X ^ X --> 0
5278 XorSelf(Value *rhs) : RHS(rhs) {}
5279 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5280 Instruction *apply(BinaryOperator &Xor) const {
5287 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5288 bool Changed = SimplifyCommutative(I);
5289 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5291 if (isa<UndefValue>(Op1)) {
5292 if (isa<UndefValue>(Op0))
5293 // Handle undef ^ undef -> 0 special case. This is a common
5295 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5296 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
5299 // xor X, X = 0, even if X is nested in a sequence of Xor's.
5300 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5301 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5302 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5305 // See if we can simplify any instructions used by the instruction whose sole
5306 // purpose is to compute bits we don't care about.
5307 if (SimplifyDemandedInstructionBits(I))
5309 if (isa<VectorType>(I.getType()))
5310 if (isa<ConstantAggregateZero>(Op1))
5311 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
5313 // Is this a ~ operation?
5314 if (Value *NotOp = dyn_castNotVal(&I)) {
5315 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5316 if (Op0I->getOpcode() == Instruction::And ||
5317 Op0I->getOpcode() == Instruction::Or) {
5318 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5319 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5320 if (dyn_castNotVal(Op0I->getOperand(1)))
5321 Op0I->swapOperands();
5322 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5324 Builder->CreateNot(Op0I->getOperand(1),
5325 Op0I->getOperand(1)->getName()+".not");
5326 if (Op0I->getOpcode() == Instruction::And)
5327 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5328 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5331 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5332 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5333 if (isFreeToInvert(Op0I->getOperand(0)) &&
5334 isFreeToInvert(Op0I->getOperand(1))) {
5336 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5338 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5339 if (Op0I->getOpcode() == Instruction::And)
5340 return BinaryOperator::CreateOr(NotX, NotY);
5341 return BinaryOperator::CreateAnd(NotX, NotY);
5348 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5349 if (RHS->isOne() && Op0->hasOneUse()) {
5350 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5351 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5352 return new ICmpInst(ICI->getInversePredicate(),
5353 ICI->getOperand(0), ICI->getOperand(1));
5355 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5356 return new FCmpInst(FCI->getInversePredicate(),
5357 FCI->getOperand(0), FCI->getOperand(1));
5360 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5361 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5362 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5363 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5364 Instruction::CastOps Opcode = Op0C->getOpcode();
5365 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5366 (RHS == ConstantExpr::getCast(Opcode,
5367 ConstantInt::getTrue(*Context),
5368 Op0C->getDestTy()))) {
5369 CI->setPredicate(CI->getInversePredicate());
5370 return CastInst::Create(Opcode, CI, Op0C->getType());
5376 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5377 // ~(c-X) == X-c-1 == X+(-c-1)
5378 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5379 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5380 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5381 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5382 ConstantInt::get(I.getType(), 1));
5383 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5386 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5387 if (Op0I->getOpcode() == Instruction::Add) {
5388 // ~(X-c) --> (-c-1)-X
5389 if (RHS->isAllOnesValue()) {
5390 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5391 return BinaryOperator::CreateSub(
5392 ConstantExpr::getSub(NegOp0CI,
5393 ConstantInt::get(I.getType(), 1)),
5394 Op0I->getOperand(0));
5395 } else if (RHS->getValue().isSignBit()) {
5396 // (X + C) ^ signbit -> (X + C + signbit)
5397 Constant *C = ConstantInt::get(*Context,
5398 RHS->getValue() + Op0CI->getValue());
5399 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5402 } else if (Op0I->getOpcode() == Instruction::Or) {
5403 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5404 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5405 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5406 // Anything in both C1 and C2 is known to be zero, remove it from
5408 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5409 NewRHS = ConstantExpr::getAnd(NewRHS,
5410 ConstantExpr::getNot(CommonBits));
5412 I.setOperand(0, Op0I->getOperand(0));
5413 I.setOperand(1, NewRHS);
5420 // Try to fold constant and into select arguments.
5421 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5422 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5424 if (isa<PHINode>(Op0))
5425 if (Instruction *NV = FoldOpIntoPhi(I))
5429 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5431 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5433 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5435 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5438 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5441 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5442 if (A == Op0) { // B^(B|A) == (A|B)^B
5443 Op1I->swapOperands();
5445 std::swap(Op0, Op1);
5446 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5447 I.swapOperands(); // Simplified below.
5448 std::swap(Op0, Op1);
5450 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5451 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5452 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5453 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5454 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
5456 if (A == Op0) { // A^(A&B) -> A^(B&A)
5457 Op1I->swapOperands();
5460 if (B == Op0) { // A^(B&A) -> (B&A)^A
5461 I.swapOperands(); // Simplified below.
5462 std::swap(Op0, Op1);
5467 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5470 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5471 Op0I->hasOneUse()) {
5472 if (A == Op1) // (B|A)^B == (A|B)^B
5474 if (B == Op1) // (A|B)^B == A & ~B
5475 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5476 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5477 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5478 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5479 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5480 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5482 if (A == Op1) // (A&B)^A -> (B&A)^A
5484 if (B == Op1 && // (B&A)^A == ~B & A
5485 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5486 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5491 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5492 if (Op0I && Op1I && Op0I->isShift() &&
5493 Op0I->getOpcode() == Op1I->getOpcode() &&
5494 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5495 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5497 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5499 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5500 Op1I->getOperand(1));
5504 Value *A, *B, *C, *D;
5505 // (A & B)^(A | B) -> A ^ B
5506 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5507 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5508 if ((A == C && B == D) || (A == D && B == C))
5509 return BinaryOperator::CreateXor(A, B);
5511 // (A | B)^(A & B) -> A ^ B
5512 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5513 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5514 if ((A == C && B == D) || (A == D && B == C))
5515 return BinaryOperator::CreateXor(A, B);
5519 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5520 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5521 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5522 // (X & Y)^(X & Y) -> (Y^Z) & X
5523 Value *X = 0, *Y = 0, *Z = 0;
5525 X = A, Y = B, Z = D;
5527 X = A, Y = B, Z = C;
5529 X = B, Y = A, Z = D;
5531 X = B, Y = A, Z = C;
5534 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5535 return BinaryOperator::CreateAnd(NewOp, X);
5540 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5541 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5542 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5545 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5546 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5547 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5548 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5549 const Type *SrcTy = Op0C->getOperand(0)->getType();
5550 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5551 // Only do this if the casts both really cause code to be generated.
5552 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5554 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5556 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5557 Op1C->getOperand(0), I.getName());
5558 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5563 return Changed ? &I : 0;
5566 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5567 LLVMContext *Context) {
5568 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5571 static bool HasAddOverflow(ConstantInt *Result,
5572 ConstantInt *In1, ConstantInt *In2,
5575 if (In2->getValue().isNegative())
5576 return Result->getValue().sgt(In1->getValue());
5578 return Result->getValue().slt(In1->getValue());
5580 return Result->getValue().ult(In1->getValue());
5583 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5584 /// overflowed for this type.
5585 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5586 Constant *In2, LLVMContext *Context,
5587 bool IsSigned = false) {
5588 Result = ConstantExpr::getAdd(In1, In2);
5590 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5591 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5592 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5593 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5594 ExtractElement(In1, Idx, Context),
5595 ExtractElement(In2, Idx, Context),
5602 return HasAddOverflow(cast<ConstantInt>(Result),
5603 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5607 static bool HasSubOverflow(ConstantInt *Result,
5608 ConstantInt *In1, ConstantInt *In2,
5611 if (In2->getValue().isNegative())
5612 return Result->getValue().slt(In1->getValue());
5614 return Result->getValue().sgt(In1->getValue());
5616 return Result->getValue().ugt(In1->getValue());
5619 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5620 /// overflowed for this type.
5621 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5622 Constant *In2, LLVMContext *Context,
5623 bool IsSigned = false) {
5624 Result = ConstantExpr::getSub(In1, In2);
5626 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5627 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5628 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5629 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5630 ExtractElement(In1, Idx, Context),
5631 ExtractElement(In2, Idx, Context),
5638 return HasSubOverflow(cast<ConstantInt>(Result),
5639 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5644 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5645 /// else. At this point we know that the GEP is on the LHS of the comparison.
5646 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5647 ICmpInst::Predicate Cond,
5649 // Look through bitcasts.
5650 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5651 RHS = BCI->getOperand(0);
5653 Value *PtrBase = GEPLHS->getOperand(0);
5654 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5655 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5656 // This transformation (ignoring the base and scales) is valid because we
5657 // know pointers can't overflow since the gep is inbounds. See if we can
5658 // output an optimized form.
5659 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5661 // If not, synthesize the offset the hard way.
5663 Offset = EmitGEPOffset(GEPLHS, *this);
5664 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5665 Constant::getNullValue(Offset->getType()));
5666 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5667 // If the base pointers are different, but the indices are the same, just
5668 // compare the base pointer.
5669 if (PtrBase != GEPRHS->getOperand(0)) {
5670 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5671 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5672 GEPRHS->getOperand(0)->getType();
5674 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5675 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5676 IndicesTheSame = false;
5680 // If all indices are the same, just compare the base pointers.
5682 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5683 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5685 // Otherwise, the base pointers are different and the indices are
5686 // different, bail out.
5690 // If one of the GEPs has all zero indices, recurse.
5691 bool AllZeros = true;
5692 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5693 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5694 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5699 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5700 ICmpInst::getSwappedPredicate(Cond), I);
5702 // If the other GEP has all zero indices, recurse.
5704 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5705 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5706 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5711 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5713 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5714 // If the GEPs only differ by one index, compare it.
5715 unsigned NumDifferences = 0; // Keep track of # differences.
5716 unsigned DiffOperand = 0; // The operand that differs.
5717 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5718 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5719 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5720 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5721 // Irreconcilable differences.
5725 if (NumDifferences++) break;
5730 if (NumDifferences == 0) // SAME GEP?
5731 return ReplaceInstUsesWith(I, // No comparison is needed here.
5732 ConstantInt::get(Type::getInt1Ty(*Context),
5733 ICmpInst::isTrueWhenEqual(Cond)));
5735 else if (NumDifferences == 1) {
5736 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5737 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5738 // Make sure we do a signed comparison here.
5739 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5743 // Only lower this if the icmp is the only user of the GEP or if we expect
5744 // the result to fold to a constant!
5746 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5747 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5748 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5749 Value *L = EmitGEPOffset(GEPLHS, *this);
5750 Value *R = EmitGEPOffset(GEPRHS, *this);
5751 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5757 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5759 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5762 if (!isa<ConstantFP>(RHSC)) return 0;
5763 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5765 // Get the width of the mantissa. We don't want to hack on conversions that
5766 // might lose information from the integer, e.g. "i64 -> float"
5767 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5768 if (MantissaWidth == -1) return 0; // Unknown.
5770 // Check to see that the input is converted from an integer type that is small
5771 // enough that preserves all bits. TODO: check here for "known" sign bits.
5772 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5773 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5775 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5776 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5780 // If the conversion would lose info, don't hack on this.
5781 if ((int)InputSize > MantissaWidth)
5784 // Otherwise, we can potentially simplify the comparison. We know that it
5785 // will always come through as an integer value and we know the constant is
5786 // not a NAN (it would have been previously simplified).
5787 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5789 ICmpInst::Predicate Pred;
5790 switch (I.getPredicate()) {
5791 default: llvm_unreachable("Unexpected predicate!");
5792 case FCmpInst::FCMP_UEQ:
5793 case FCmpInst::FCMP_OEQ:
5794 Pred = ICmpInst::ICMP_EQ;
5796 case FCmpInst::FCMP_UGT:
5797 case FCmpInst::FCMP_OGT:
5798 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5800 case FCmpInst::FCMP_UGE:
5801 case FCmpInst::FCMP_OGE:
5802 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5804 case FCmpInst::FCMP_ULT:
5805 case FCmpInst::FCMP_OLT:
5806 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5808 case FCmpInst::FCMP_ULE:
5809 case FCmpInst::FCMP_OLE:
5810 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5812 case FCmpInst::FCMP_UNE:
5813 case FCmpInst::FCMP_ONE:
5814 Pred = ICmpInst::ICMP_NE;
5816 case FCmpInst::FCMP_ORD:
5817 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5818 case FCmpInst::FCMP_UNO:
5819 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5822 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5824 // Now we know that the APFloat is a normal number, zero or inf.
5826 // See if the FP constant is too large for the integer. For example,
5827 // comparing an i8 to 300.0.
5828 unsigned IntWidth = IntTy->getScalarSizeInBits();
5831 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5832 // and large values.
5833 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5834 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5835 APFloat::rmNearestTiesToEven);
5836 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5837 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5838 Pred == ICmpInst::ICMP_SLE)
5839 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5840 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5843 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5844 // +INF and large values.
5845 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5846 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5847 APFloat::rmNearestTiesToEven);
5848 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5849 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5850 Pred == ICmpInst::ICMP_ULE)
5851 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5852 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5857 // See if the RHS value is < SignedMin.
5858 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5859 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5860 APFloat::rmNearestTiesToEven);
5861 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5862 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5863 Pred == ICmpInst::ICMP_SGE)
5864 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5865 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5869 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5870 // [0, UMAX], but it may still be fractional. See if it is fractional by
5871 // casting the FP value to the integer value and back, checking for equality.
5872 // Don't do this for zero, because -0.0 is not fractional.
5873 Constant *RHSInt = LHSUnsigned
5874 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5875 : ConstantExpr::getFPToSI(RHSC, IntTy);
5876 if (!RHS.isZero()) {
5877 bool Equal = LHSUnsigned
5878 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5879 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5881 // If we had a comparison against a fractional value, we have to adjust
5882 // the compare predicate and sometimes the value. RHSC is rounded towards
5883 // zero at this point.
5885 default: llvm_unreachable("Unexpected integer comparison!");
5886 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5887 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5888 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5889 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5890 case ICmpInst::ICMP_ULE:
5891 // (float)int <= 4.4 --> int <= 4
5892 // (float)int <= -4.4 --> false
5893 if (RHS.isNegative())
5894 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5896 case ICmpInst::ICMP_SLE:
5897 // (float)int <= 4.4 --> int <= 4
5898 // (float)int <= -4.4 --> int < -4
5899 if (RHS.isNegative())
5900 Pred = ICmpInst::ICMP_SLT;
5902 case ICmpInst::ICMP_ULT:
5903 // (float)int < -4.4 --> false
5904 // (float)int < 4.4 --> int <= 4
5905 if (RHS.isNegative())
5906 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5907 Pred = ICmpInst::ICMP_ULE;
5909 case ICmpInst::ICMP_SLT:
5910 // (float)int < -4.4 --> int < -4
5911 // (float)int < 4.4 --> int <= 4
5912 if (!RHS.isNegative())
5913 Pred = ICmpInst::ICMP_SLE;
5915 case ICmpInst::ICMP_UGT:
5916 // (float)int > 4.4 --> int > 4
5917 // (float)int > -4.4 --> true
5918 if (RHS.isNegative())
5919 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5921 case ICmpInst::ICMP_SGT:
5922 // (float)int > 4.4 --> int > 4
5923 // (float)int > -4.4 --> int >= -4
5924 if (RHS.isNegative())
5925 Pred = ICmpInst::ICMP_SGE;
5927 case ICmpInst::ICMP_UGE:
5928 // (float)int >= -4.4 --> true
5929 // (float)int >= 4.4 --> int > 4
5930 if (!RHS.isNegative())
5931 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5932 Pred = ICmpInst::ICMP_UGT;
5934 case ICmpInst::ICMP_SGE:
5935 // (float)int >= -4.4 --> int >= -4
5936 // (float)int >= 4.4 --> int > 4
5937 if (!RHS.isNegative())
5938 Pred = ICmpInst::ICMP_SGT;
5944 // Lower this FP comparison into an appropriate integer version of the
5946 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5949 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5950 bool Changed = false;
5952 /// Orders the operands of the compare so that they are listed from most
5953 /// complex to least complex. This puts constants before unary operators,
5954 /// before binary operators.
5955 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5960 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5962 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
5963 return ReplaceInstUsesWith(I, V);
5965 // Simplify 'fcmp pred X, X'
5967 switch (I.getPredicate()) {
5968 default: llvm_unreachable("Unknown predicate!");
5969 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5970 case FCmpInst::FCMP_ULT: // True if unordered or less than
5971 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5972 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5973 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5974 I.setPredicate(FCmpInst::FCMP_UNO);
5975 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5978 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5979 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5980 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5981 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5982 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5983 I.setPredicate(FCmpInst::FCMP_ORD);
5984 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5989 // Handle fcmp with constant RHS
5990 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5991 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5992 switch (LHSI->getOpcode()) {
5993 case Instruction::PHI:
5994 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5995 // block. If in the same block, we're encouraging jump threading. If
5996 // not, we are just pessimizing the code by making an i1 phi.
5997 if (LHSI->getParent() == I.getParent())
5998 if (Instruction *NV = FoldOpIntoPhi(I, true))
6001 case Instruction::SIToFP:
6002 case Instruction::UIToFP:
6003 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6006 case Instruction::Select:
6007 // If either operand of the select is a constant, we can fold the
6008 // comparison into the select arms, which will cause one to be
6009 // constant folded and the select turned into a bitwise or.
6010 Value *Op1 = 0, *Op2 = 0;
6011 if (LHSI->hasOneUse()) {
6012 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6013 // Fold the known value into the constant operand.
6014 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6015 // Insert a new FCmp of the other select operand.
6016 Op2 = Builder->CreateFCmp(I.getPredicate(),
6017 LHSI->getOperand(2), RHSC, I.getName());
6018 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6019 // Fold the known value into the constant operand.
6020 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6021 // Insert a new FCmp of the other select operand.
6022 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6028 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6033 return Changed ? &I : 0;
6036 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6037 bool Changed = false;
6039 /// Orders the operands of the compare so that they are listed from most
6040 /// complex to least complex. This puts constants before unary operators,
6041 /// before binary operators.
6042 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6047 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6049 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6050 return ReplaceInstUsesWith(I, V);
6052 const Type *Ty = Op0->getType();
6054 // icmp's with boolean values can always be turned into bitwise operations
6055 if (Ty == Type::getInt1Ty(*Context)) {
6056 switch (I.getPredicate()) {
6057 default: llvm_unreachable("Invalid icmp instruction!");
6058 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
6059 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
6060 return BinaryOperator::CreateNot(Xor);
6062 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
6063 return BinaryOperator::CreateXor(Op0, Op1);
6065 case ICmpInst::ICMP_UGT:
6066 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
6068 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
6069 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6070 return BinaryOperator::CreateAnd(Not, Op1);
6072 case ICmpInst::ICMP_SGT:
6073 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
6075 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
6076 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6077 return BinaryOperator::CreateAnd(Not, Op0);
6079 case ICmpInst::ICMP_UGE:
6080 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6082 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
6083 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6084 return BinaryOperator::CreateOr(Not, Op1);
6086 case ICmpInst::ICMP_SGE:
6087 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6089 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
6090 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6091 return BinaryOperator::CreateOr(Not, Op0);
6096 unsigned BitWidth = 0;
6098 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6099 else if (Ty->isIntOrIntVector())
6100 BitWidth = Ty->getScalarSizeInBits();
6102 bool isSignBit = false;
6104 // See if we are doing a comparison with a constant.
6105 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6106 Value *A = 0, *B = 0;
6108 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6109 if (I.isEquality() && CI->isNullValue() &&
6110 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6111 // (icmp cond A B) if cond is equality
6112 return new ICmpInst(I.getPredicate(), A, B);
6115 // If we have an icmp le or icmp ge instruction, turn it into the
6116 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6117 // them being folded in the code below. The SimplifyICmpInst code has
6118 // already handled the edge cases for us, so we just assert on them.
6119 switch (I.getPredicate()) {
6121 case ICmpInst::ICMP_ULE:
6122 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
6123 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6125 case ICmpInst::ICMP_SLE:
6126 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
6127 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6129 case ICmpInst::ICMP_UGE:
6130 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
6131 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6133 case ICmpInst::ICMP_SGE:
6134 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
6135 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6139 // If this comparison is a normal comparison, it demands all
6140 // bits, if it is a sign bit comparison, it only demands the sign bit.
6142 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6145 // See if we can fold the comparison based on range information we can get
6146 // by checking whether bits are known to be zero or one in the input.
6147 if (BitWidth != 0) {
6148 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6149 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6151 if (SimplifyDemandedBits(I.getOperandUse(0),
6152 isSignBit ? APInt::getSignBit(BitWidth)
6153 : APInt::getAllOnesValue(BitWidth),
6154 Op0KnownZero, Op0KnownOne, 0))
6156 if (SimplifyDemandedBits(I.getOperandUse(1),
6157 APInt::getAllOnesValue(BitWidth),
6158 Op1KnownZero, Op1KnownOne, 0))
6161 // Given the known and unknown bits, compute a range that the LHS could be
6162 // in. Compute the Min, Max and RHS values based on the known bits. For the
6163 // EQ and NE we use unsigned values.
6164 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6165 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6167 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6169 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6172 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6174 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6178 // If Min and Max are known to be the same, then SimplifyDemandedBits
6179 // figured out that the LHS is a constant. Just constant fold this now so
6180 // that code below can assume that Min != Max.
6181 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6182 return new ICmpInst(I.getPredicate(),
6183 ConstantInt::get(*Context, Op0Min), Op1);
6184 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6185 return new ICmpInst(I.getPredicate(), Op0,
6186 ConstantInt::get(*Context, Op1Min));
6188 // Based on the range information we know about the LHS, see if we can
6189 // simplify this comparison. For example, (x&4) < 8 is always true.
6190 switch (I.getPredicate()) {
6191 default: llvm_unreachable("Unknown icmp opcode!");
6192 case ICmpInst::ICMP_EQ:
6193 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6194 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6196 case ICmpInst::ICMP_NE:
6197 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6198 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6200 case ICmpInst::ICMP_ULT:
6201 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6202 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6203 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6204 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6205 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6206 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6207 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6208 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6209 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6212 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6213 if (CI->isMinValue(true))
6214 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6215 Constant::getAllOnesValue(Op0->getType()));
6218 case ICmpInst::ICMP_UGT:
6219 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6220 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6221 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6222 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6224 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6225 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6226 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6227 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6228 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6231 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6232 if (CI->isMaxValue(true))
6233 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6234 Constant::getNullValue(Op0->getType()));
6237 case ICmpInst::ICMP_SLT:
6238 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6239 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6240 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6241 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6242 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6243 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6244 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6245 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6246 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6250 case ICmpInst::ICMP_SGT:
6251 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6252 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6253 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6254 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6256 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6257 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6258 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6259 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6260 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6264 case ICmpInst::ICMP_SGE:
6265 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6266 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6267 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6268 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6269 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6271 case ICmpInst::ICMP_SLE:
6272 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6273 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6274 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6275 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6276 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6278 case ICmpInst::ICMP_UGE:
6279 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6280 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6281 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6282 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6283 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6285 case ICmpInst::ICMP_ULE:
6286 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6287 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6288 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6289 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6290 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6294 // Turn a signed comparison into an unsigned one if both operands
6295 // are known to have the same sign.
6297 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6298 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6299 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6302 // Test if the ICmpInst instruction is used exclusively by a select as
6303 // part of a minimum or maximum operation. If so, refrain from doing
6304 // any other folding. This helps out other analyses which understand
6305 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6306 // and CodeGen. And in this case, at least one of the comparison
6307 // operands has at least one user besides the compare (the select),
6308 // which would often largely negate the benefit of folding anyway.
6310 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6311 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6312 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6315 // See if we are doing a comparison between a constant and an instruction that
6316 // can be folded into the comparison.
6317 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6318 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6319 // instruction, see if that instruction also has constants so that the
6320 // instruction can be folded into the icmp
6321 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6322 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6326 // Handle icmp with constant (but not simple integer constant) RHS
6327 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6328 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6329 switch (LHSI->getOpcode()) {
6330 case Instruction::GetElementPtr:
6331 if (RHSC->isNullValue()) {
6332 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6333 bool isAllZeros = true;
6334 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6335 if (!isa<Constant>(LHSI->getOperand(i)) ||
6336 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6341 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6342 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6346 case Instruction::PHI:
6347 // Only fold icmp into the PHI if the phi and icmp are in the same
6348 // block. If in the same block, we're encouraging jump threading. If
6349 // not, we are just pessimizing the code by making an i1 phi.
6350 if (LHSI->getParent() == I.getParent())
6351 if (Instruction *NV = FoldOpIntoPhi(I, true))
6354 case Instruction::Select: {
6355 // If either operand of the select is a constant, we can fold the
6356 // comparison into the select arms, which will cause one to be
6357 // constant folded and the select turned into a bitwise or.
6358 Value *Op1 = 0, *Op2 = 0;
6359 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6360 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6361 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6362 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6364 // We only want to perform this transformation if it will not lead to
6365 // additional code. This is true if either both sides of the select
6366 // fold to a constant (in which case the icmp is replaced with a select
6367 // which will usually simplify) or this is the only user of the
6368 // select (in which case we are trading a select+icmp for a simpler
6370 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6372 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6375 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6377 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6381 case Instruction::Call:
6382 // If we have (malloc != null), and if the malloc has a single use, we
6383 // can assume it is successful and remove the malloc.
6384 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6385 isa<ConstantPointerNull>(RHSC)) {
6386 // Need to explicitly erase malloc call here, instead of adding it to
6387 // Worklist, because it won't get DCE'd from the Worklist since
6388 // isInstructionTriviallyDead() returns false for function calls.
6389 // It is OK to replace LHSI/MallocCall with Undef because the
6390 // instruction that uses it will be erased via Worklist.
6391 if (extractMallocCall(LHSI)) {
6392 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6393 EraseInstFromFunction(*LHSI);
6394 return ReplaceInstUsesWith(I,
6395 ConstantInt::get(Type::getInt1Ty(*Context),
6396 !I.isTrueWhenEqual()));
6398 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6399 if (MallocCall->hasOneUse()) {
6400 MallocCall->replaceAllUsesWith(
6401 UndefValue::get(MallocCall->getType()));
6402 EraseInstFromFunction(*MallocCall);
6403 Worklist.Add(LHSI); // The malloc's bitcast use.
6404 return ReplaceInstUsesWith(I,
6405 ConstantInt::get(Type::getInt1Ty(*Context),
6406 !I.isTrueWhenEqual()));
6413 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6414 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6415 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6417 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6418 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6419 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6422 // Test to see if the operands of the icmp are casted versions of other
6423 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6425 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6426 if (isa<PointerType>(Op0->getType()) &&
6427 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6428 // We keep moving the cast from the left operand over to the right
6429 // operand, where it can often be eliminated completely.
6430 Op0 = CI->getOperand(0);
6432 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6433 // so eliminate it as well.
6434 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6435 Op1 = CI2->getOperand(0);
6437 // If Op1 is a constant, we can fold the cast into the constant.
6438 if (Op0->getType() != Op1->getType()) {
6439 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6440 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6442 // Otherwise, cast the RHS right before the icmp
6443 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6446 return new ICmpInst(I.getPredicate(), Op0, Op1);
6450 if (isa<CastInst>(Op0)) {
6451 // Handle the special case of: icmp (cast bool to X), <cst>
6452 // This comes up when you have code like
6455 // For generality, we handle any zero-extension of any operand comparison
6456 // with a constant or another cast from the same type.
6457 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
6458 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6462 // See if it's the same type of instruction on the left and right.
6463 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6464 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6465 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6466 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6467 switch (Op0I->getOpcode()) {
6469 case Instruction::Add:
6470 case Instruction::Sub:
6471 case Instruction::Xor:
6472 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6473 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6474 Op1I->getOperand(0));
6475 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6476 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6477 if (CI->getValue().isSignBit()) {
6478 ICmpInst::Predicate Pred = I.isSigned()
6479 ? I.getUnsignedPredicate()
6480 : I.getSignedPredicate();
6481 return new ICmpInst(Pred, Op0I->getOperand(0),
6482 Op1I->getOperand(0));
6485 if (CI->getValue().isMaxSignedValue()) {
6486 ICmpInst::Predicate Pred = I.isSigned()
6487 ? I.getUnsignedPredicate()
6488 : I.getSignedPredicate();
6489 Pred = I.getSwappedPredicate(Pred);
6490 return new ICmpInst(Pred, Op0I->getOperand(0),
6491 Op1I->getOperand(0));
6495 case Instruction::Mul:
6496 if (!I.isEquality())
6499 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6500 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6501 // Mask = -1 >> count-trailing-zeros(Cst).
6502 if (!CI->isZero() && !CI->isOne()) {
6503 const APInt &AP = CI->getValue();
6504 ConstantInt *Mask = ConstantInt::get(*Context,
6505 APInt::getLowBitsSet(AP.getBitWidth(),
6507 AP.countTrailingZeros()));
6508 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6509 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6510 return new ICmpInst(I.getPredicate(), And1, And2);
6519 // ~x < ~y --> y < x
6521 if (match(Op0, m_Not(m_Value(A))) &&
6522 match(Op1, m_Not(m_Value(B))))
6523 return new ICmpInst(I.getPredicate(), B, A);
6526 if (I.isEquality()) {
6527 Value *A, *B, *C, *D;
6529 // -x == -y --> x == y
6530 if (match(Op0, m_Neg(m_Value(A))) &&
6531 match(Op1, m_Neg(m_Value(B))))
6532 return new ICmpInst(I.getPredicate(), A, B);
6534 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6535 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6536 Value *OtherVal = A == Op1 ? B : A;
6537 return new ICmpInst(I.getPredicate(), OtherVal,
6538 Constant::getNullValue(A->getType()));
6541 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6542 // A^c1 == C^c2 --> A == C^(c1^c2)
6543 ConstantInt *C1, *C2;
6544 if (match(B, m_ConstantInt(C1)) &&
6545 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6547 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6548 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6549 return new ICmpInst(I.getPredicate(), A, Xor);
6552 // A^B == A^D -> B == D
6553 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6554 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6555 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6556 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6560 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6561 (A == Op0 || B == Op0)) {
6562 // A == (A^B) -> B == 0
6563 Value *OtherVal = A == Op0 ? B : A;
6564 return new ICmpInst(I.getPredicate(), OtherVal,
6565 Constant::getNullValue(A->getType()));
6568 // (A-B) == A -> B == 0
6569 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6570 return new ICmpInst(I.getPredicate(), B,
6571 Constant::getNullValue(B->getType()));
6573 // A == (A-B) -> B == 0
6574 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6575 return new ICmpInst(I.getPredicate(), B,
6576 Constant::getNullValue(B->getType()));
6578 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6579 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6580 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6581 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6582 Value *X = 0, *Y = 0, *Z = 0;
6585 X = B; Y = D; Z = A;
6586 } else if (A == D) {
6587 X = B; Y = C; Z = A;
6588 } else if (B == C) {
6589 X = A; Y = D; Z = B;
6590 } else if (B == D) {
6591 X = A; Y = C; Z = B;
6594 if (X) { // Build (X^Y) & Z
6595 Op1 = Builder->CreateXor(X, Y, "tmp");
6596 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6597 I.setOperand(0, Op1);
6598 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6603 return Changed ? &I : 0;
6607 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6608 /// and CmpRHS are both known to be integer constants.
6609 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6610 ConstantInt *DivRHS) {
6611 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6612 const APInt &CmpRHSV = CmpRHS->getValue();
6614 // FIXME: If the operand types don't match the type of the divide
6615 // then don't attempt this transform. The code below doesn't have the
6616 // logic to deal with a signed divide and an unsigned compare (and
6617 // vice versa). This is because (x /s C1) <s C2 produces different
6618 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6619 // (x /u C1) <u C2. Simply casting the operands and result won't
6620 // work. :( The if statement below tests that condition and bails
6622 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6623 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
6625 if (DivRHS->isZero())
6626 return 0; // The ProdOV computation fails on divide by zero.
6627 if (DivIsSigned && DivRHS->isAllOnesValue())
6628 return 0; // The overflow computation also screws up here
6629 if (DivRHS->isOne())
6630 return 0; // Not worth bothering, and eliminates some funny cases
6633 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6634 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6635 // C2 (CI). By solving for X we can turn this into a range check
6636 // instead of computing a divide.
6637 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6639 // Determine if the product overflows by seeing if the product is
6640 // not equal to the divide. Make sure we do the same kind of divide
6641 // as in the LHS instruction that we're folding.
6642 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6643 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6645 // Get the ICmp opcode
6646 ICmpInst::Predicate Pred = ICI.getPredicate();
6648 // Figure out the interval that is being checked. For example, a comparison
6649 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6650 // Compute this interval based on the constants involved and the signedness of
6651 // the compare/divide. This computes a half-open interval, keeping track of
6652 // whether either value in the interval overflows. After analysis each
6653 // overflow variable is set to 0 if it's corresponding bound variable is valid
6654 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6655 int LoOverflow = 0, HiOverflow = 0;
6656 Constant *LoBound = 0, *HiBound = 0;
6658 if (!DivIsSigned) { // udiv
6659 // e.g. X/5 op 3 --> [15, 20)
6661 HiOverflow = LoOverflow = ProdOV;
6663 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6664 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6665 if (CmpRHSV == 0) { // (X / pos) op 0
6666 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6667 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6669 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6670 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6671 HiOverflow = LoOverflow = ProdOV;
6673 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6674 } else { // (X / pos) op neg
6675 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6676 HiBound = AddOne(Prod);
6677 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6679 ConstantInt* DivNeg =
6680 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6681 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6685 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6686 if (CmpRHSV == 0) { // (X / neg) op 0
6687 // e.g. X/-5 op 0 --> [-4, 5)
6688 LoBound = AddOne(DivRHS);
6689 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6690 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6691 HiOverflow = 1; // [INTMIN+1, overflow)
6692 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6694 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6695 // e.g. X/-5 op 3 --> [-19, -14)
6696 HiBound = AddOne(Prod);
6697 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6699 LoOverflow = AddWithOverflow(LoBound, HiBound,
6700 DivRHS, Context, true) ? -1 : 0;
6701 } else { // (X / neg) op neg
6702 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6703 LoOverflow = HiOverflow = ProdOV;
6705 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6708 // Dividing by a negative swaps the condition. LT <-> GT
6709 Pred = ICmpInst::getSwappedPredicate(Pred);
6712 Value *X = DivI->getOperand(0);
6714 default: llvm_unreachable("Unhandled icmp opcode!");
6715 case ICmpInst::ICMP_EQ:
6716 if (LoOverflow && HiOverflow)
6717 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6718 else if (HiOverflow)
6719 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6720 ICmpInst::ICMP_UGE, X, LoBound);
6721 else if (LoOverflow)
6722 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6723 ICmpInst::ICMP_ULT, X, HiBound);
6725 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6726 case ICmpInst::ICMP_NE:
6727 if (LoOverflow && HiOverflow)
6728 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6729 else if (HiOverflow)
6730 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6731 ICmpInst::ICMP_ULT, X, LoBound);
6732 else if (LoOverflow)
6733 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6734 ICmpInst::ICMP_UGE, X, HiBound);
6736 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6737 case ICmpInst::ICMP_ULT:
6738 case ICmpInst::ICMP_SLT:
6739 if (LoOverflow == +1) // Low bound is greater than input range.
6740 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6741 if (LoOverflow == -1) // Low bound is less than input range.
6742 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6743 return new ICmpInst(Pred, X, LoBound);
6744 case ICmpInst::ICMP_UGT:
6745 case ICmpInst::ICMP_SGT:
6746 if (HiOverflow == +1) // High bound greater than input range.
6747 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6748 else if (HiOverflow == -1) // High bound less than input range.
6749 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6750 if (Pred == ICmpInst::ICMP_UGT)
6751 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6753 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6758 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6760 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6763 const APInt &RHSV = RHS->getValue();
6765 switch (LHSI->getOpcode()) {
6766 case Instruction::Trunc:
6767 if (ICI.isEquality() && LHSI->hasOneUse()) {
6768 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6769 // of the high bits truncated out of x are known.
6770 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6771 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6772 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6773 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6774 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6776 // If all the high bits are known, we can do this xform.
6777 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6778 // Pull in the high bits from known-ones set.
6779 APInt NewRHS(RHS->getValue());
6780 NewRHS.zext(SrcBits);
6782 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6783 ConstantInt::get(*Context, NewRHS));
6788 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6789 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6790 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6792 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6793 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6794 Value *CompareVal = LHSI->getOperand(0);
6796 // If the sign bit of the XorCST is not set, there is no change to
6797 // the operation, just stop using the Xor.
6798 if (!XorCST->getValue().isNegative()) {
6799 ICI.setOperand(0, CompareVal);
6804 // Was the old condition true if the operand is positive?
6805 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6807 // If so, the new one isn't.
6808 isTrueIfPositive ^= true;
6810 if (isTrueIfPositive)
6811 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6814 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6818 if (LHSI->hasOneUse()) {
6819 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6820 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6821 const APInt &SignBit = XorCST->getValue();
6822 ICmpInst::Predicate Pred = ICI.isSigned()
6823 ? ICI.getUnsignedPredicate()
6824 : ICI.getSignedPredicate();
6825 return new ICmpInst(Pred, LHSI->getOperand(0),
6826 ConstantInt::get(*Context, RHSV ^ SignBit));
6829 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6830 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6831 const APInt &NotSignBit = XorCST->getValue();
6832 ICmpInst::Predicate Pred = ICI.isSigned()
6833 ? ICI.getUnsignedPredicate()
6834 : ICI.getSignedPredicate();
6835 Pred = ICI.getSwappedPredicate(Pred);
6836 return new ICmpInst(Pred, LHSI->getOperand(0),
6837 ConstantInt::get(*Context, RHSV ^ NotSignBit));
6842 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6843 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6844 LHSI->getOperand(0)->hasOneUse()) {
6845 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6847 // If the LHS is an AND of a truncating cast, we can widen the
6848 // and/compare to be the input width without changing the value
6849 // produced, eliminating a cast.
6850 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6851 // We can do this transformation if either the AND constant does not
6852 // have its sign bit set or if it is an equality comparison.
6853 // Extending a relational comparison when we're checking the sign
6854 // bit would not work.
6855 if (Cast->hasOneUse() &&
6856 (ICI.isEquality() ||
6857 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6859 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6860 APInt NewCST = AndCST->getValue();
6861 NewCST.zext(BitWidth);
6863 NewCI.zext(BitWidth);
6865 Builder->CreateAnd(Cast->getOperand(0),
6866 ConstantInt::get(*Context, NewCST), LHSI->getName());
6867 return new ICmpInst(ICI.getPredicate(), NewAnd,
6868 ConstantInt::get(*Context, NewCI));
6872 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6873 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6874 // happens a LOT in code produced by the C front-end, for bitfield
6876 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6877 if (Shift && !Shift->isShift())
6881 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6882 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6883 const Type *AndTy = AndCST->getType(); // Type of the and.
6885 // We can fold this as long as we can't shift unknown bits
6886 // into the mask. This can only happen with signed shift
6887 // rights, as they sign-extend.
6889 bool CanFold = Shift->isLogicalShift();
6891 // To test for the bad case of the signed shr, see if any
6892 // of the bits shifted in could be tested after the mask.
6893 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6894 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6896 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6897 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6898 AndCST->getValue()) == 0)
6904 if (Shift->getOpcode() == Instruction::Shl)
6905 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6907 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6909 // Check to see if we are shifting out any of the bits being
6911 if (ConstantExpr::get(Shift->getOpcode(),
6912 NewCst, ShAmt) != RHS) {
6913 // If we shifted bits out, the fold is not going to work out.
6914 // As a special case, check to see if this means that the
6915 // result is always true or false now.
6916 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6917 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6918 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6919 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6921 ICI.setOperand(1, NewCst);
6922 Constant *NewAndCST;
6923 if (Shift->getOpcode() == Instruction::Shl)
6924 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6926 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6927 LHSI->setOperand(1, NewAndCST);
6928 LHSI->setOperand(0, Shift->getOperand(0));
6929 Worklist.Add(Shift); // Shift is dead.
6935 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6936 // preferable because it allows the C<<Y expression to be hoisted out
6937 // of a loop if Y is invariant and X is not.
6938 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6939 ICI.isEquality() && !Shift->isArithmeticShift() &&
6940 !isa<Constant>(Shift->getOperand(0))) {
6943 if (Shift->getOpcode() == Instruction::LShr) {
6944 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6946 // Insert a logical shift.
6947 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6950 // Compute X & (C << Y).
6952 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6954 ICI.setOperand(0, NewAnd);
6960 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6961 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6964 uint32_t TypeBits = RHSV.getBitWidth();
6966 // Check that the shift amount is in range. If not, don't perform
6967 // undefined shifts. When the shift is visited it will be
6969 if (ShAmt->uge(TypeBits))
6972 if (ICI.isEquality()) {
6973 // If we are comparing against bits always shifted out, the
6974 // comparison cannot succeed.
6976 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6978 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6979 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6980 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6981 return ReplaceInstUsesWith(ICI, Cst);
6984 if (LHSI->hasOneUse()) {
6985 // Otherwise strength reduce the shift into an and.
6986 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6988 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
6989 TypeBits-ShAmtVal));
6992 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6993 return new ICmpInst(ICI.getPredicate(), And,
6994 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6998 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6999 bool TrueIfSigned = false;
7000 if (LHSI->hasOneUse() &&
7001 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7002 // (X << 31) <s 0 --> (X&1) != 0
7003 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
7004 (TypeBits-ShAmt->getZExtValue()-1));
7006 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
7007 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
7008 And, Constant::getNullValue(And->getType()));
7013 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
7014 case Instruction::AShr: {
7015 // Only handle equality comparisons of shift-by-constant.
7016 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7017 if (!ShAmt || !ICI.isEquality()) break;
7019 // Check that the shift amount is in range. If not, don't perform
7020 // undefined shifts. When the shift is visited it will be
7022 uint32_t TypeBits = RHSV.getBitWidth();
7023 if (ShAmt->uge(TypeBits))
7026 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7028 // If we are comparing against bits always shifted out, the
7029 // comparison cannot succeed.
7030 APInt Comp = RHSV << ShAmtVal;
7031 if (LHSI->getOpcode() == Instruction::LShr)
7032 Comp = Comp.lshr(ShAmtVal);
7034 Comp = Comp.ashr(ShAmtVal);
7036 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7037 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7038 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7039 return ReplaceInstUsesWith(ICI, Cst);
7042 // Otherwise, check to see if the bits shifted out are known to be zero.
7043 // If so, we can compare against the unshifted value:
7044 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
7045 if (LHSI->hasOneUse() &&
7046 MaskedValueIsZero(LHSI->getOperand(0),
7047 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7048 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7049 ConstantExpr::getShl(RHS, ShAmt));
7052 if (LHSI->hasOneUse()) {
7053 // Otherwise strength reduce the shift into an and.
7054 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7055 Constant *Mask = ConstantInt::get(*Context, Val);
7057 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7058 Mask, LHSI->getName()+".mask");
7059 return new ICmpInst(ICI.getPredicate(), And,
7060 ConstantExpr::getShl(RHS, ShAmt));
7065 case Instruction::SDiv:
7066 case Instruction::UDiv:
7067 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7068 // Fold this div into the comparison, producing a range check.
7069 // Determine, based on the divide type, what the range is being
7070 // checked. If there is an overflow on the low or high side, remember
7071 // it, otherwise compute the range [low, hi) bounding the new value.
7072 // See: InsertRangeTest above for the kinds of replacements possible.
7073 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7074 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7079 case Instruction::Add:
7080 // Fold: icmp pred (add, X, C1), C2
7082 if (!ICI.isEquality()) {
7083 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7085 const APInt &LHSV = LHSC->getValue();
7087 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7090 if (ICI.isSigned()) {
7091 if (CR.getLower().isSignBit()) {
7092 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7093 ConstantInt::get(*Context, CR.getUpper()));
7094 } else if (CR.getUpper().isSignBit()) {
7095 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7096 ConstantInt::get(*Context, CR.getLower()));
7099 if (CR.getLower().isMinValue()) {
7100 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7101 ConstantInt::get(*Context, CR.getUpper()));
7102 } else if (CR.getUpper().isMinValue()) {
7103 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7104 ConstantInt::get(*Context, CR.getLower()));
7111 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7112 if (ICI.isEquality()) {
7113 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7115 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7116 // the second operand is a constant, simplify a bit.
7117 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7118 switch (BO->getOpcode()) {
7119 case Instruction::SRem:
7120 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7121 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7122 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7123 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7125 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7127 return new ICmpInst(ICI.getPredicate(), NewRem,
7128 Constant::getNullValue(BO->getType()));
7132 case Instruction::Add:
7133 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7134 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7135 if (BO->hasOneUse())
7136 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7137 ConstantExpr::getSub(RHS, BOp1C));
7138 } else if (RHSV == 0) {
7139 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7140 // efficiently invertible, or if the add has just this one use.
7141 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7143 if (Value *NegVal = dyn_castNegVal(BOp1))
7144 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7145 else if (Value *NegVal = dyn_castNegVal(BOp0))
7146 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7147 else if (BO->hasOneUse()) {
7148 Value *Neg = Builder->CreateNeg(BOp1);
7150 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7154 case Instruction::Xor:
7155 // For the xor case, we can xor two constants together, eliminating
7156 // the explicit xor.
7157 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7158 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7159 ConstantExpr::getXor(RHS, BOC));
7162 case Instruction::Sub:
7163 // Replace (([sub|xor] A, B) != 0) with (A != B)
7165 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7169 case Instruction::Or:
7170 // If bits are being or'd in that are not present in the constant we
7171 // are comparing against, then the comparison could never succeed!
7172 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7173 Constant *NotCI = ConstantExpr::getNot(RHS);
7174 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7175 return ReplaceInstUsesWith(ICI,
7176 ConstantInt::get(Type::getInt1Ty(*Context),
7181 case Instruction::And:
7182 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7183 // If bits are being compared against that are and'd out, then the
7184 // comparison can never succeed!
7185 if ((RHSV & ~BOC->getValue()) != 0)
7186 return ReplaceInstUsesWith(ICI,
7187 ConstantInt::get(Type::getInt1Ty(*Context),
7190 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7191 if (RHS == BOC && RHSV.isPowerOf2())
7192 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7193 ICmpInst::ICMP_NE, LHSI,
7194 Constant::getNullValue(RHS->getType()));
7196 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7197 if (BOC->getValue().isSignBit()) {
7198 Value *X = BO->getOperand(0);
7199 Constant *Zero = Constant::getNullValue(X->getType());
7200 ICmpInst::Predicate pred = isICMP_NE ?
7201 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7202 return new ICmpInst(pred, X, Zero);
7205 // ((X & ~7) == 0) --> X < 8
7206 if (RHSV == 0 && isHighOnes(BOC)) {
7207 Value *X = BO->getOperand(0);
7208 Constant *NegX = ConstantExpr::getNeg(BOC);
7209 ICmpInst::Predicate pred = isICMP_NE ?
7210 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7211 return new ICmpInst(pred, X, NegX);
7216 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7217 // Handle icmp {eq|ne} <intrinsic>, intcst.
7218 if (II->getIntrinsicID() == Intrinsic::bswap) {
7220 ICI.setOperand(0, II->getOperand(1));
7221 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7229 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7230 /// We only handle extending casts so far.
7232 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7233 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7234 Value *LHSCIOp = LHSCI->getOperand(0);
7235 const Type *SrcTy = LHSCIOp->getType();
7236 const Type *DestTy = LHSCI->getType();
7239 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7240 // integer type is the same size as the pointer type.
7241 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7242 TD->getPointerSizeInBits() ==
7243 cast<IntegerType>(DestTy)->getBitWidth()) {
7245 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7246 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7247 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7248 RHSOp = RHSC->getOperand(0);
7249 // If the pointer types don't match, insert a bitcast.
7250 if (LHSCIOp->getType() != RHSOp->getType())
7251 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7255 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7258 // The code below only handles extension cast instructions, so far.
7260 if (LHSCI->getOpcode() != Instruction::ZExt &&
7261 LHSCI->getOpcode() != Instruction::SExt)
7264 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7265 bool isSignedCmp = ICI.isSigned();
7267 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7268 // Not an extension from the same type?
7269 RHSCIOp = CI->getOperand(0);
7270 if (RHSCIOp->getType() != LHSCIOp->getType())
7273 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7274 // and the other is a zext), then we can't handle this.
7275 if (CI->getOpcode() != LHSCI->getOpcode())
7278 // Deal with equality cases early.
7279 if (ICI.isEquality())
7280 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7282 // A signed comparison of sign extended values simplifies into a
7283 // signed comparison.
7284 if (isSignedCmp && isSignedExt)
7285 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7287 // The other three cases all fold into an unsigned comparison.
7288 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7291 // If we aren't dealing with a constant on the RHS, exit early
7292 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7296 // Compute the constant that would happen if we truncated to SrcTy then
7297 // reextended to DestTy.
7298 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7299 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7302 // If the re-extended constant didn't change...
7304 // Deal with equality cases early.
7305 if (ICI.isEquality())
7306 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7308 // A signed comparison of sign extended values simplifies into a
7309 // signed comparison.
7310 if (isSignedExt && isSignedCmp)
7311 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7313 // The other three cases all fold into an unsigned comparison.
7314 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
7317 // The re-extended constant changed so the constant cannot be represented
7318 // in the shorter type. Consequently, we cannot emit a simple comparison.
7320 // First, handle some easy cases. We know the result cannot be equal at this
7321 // point so handle the ICI.isEquality() cases
7322 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7323 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7324 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7325 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7327 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7328 // should have been folded away previously and not enter in here.
7331 // We're performing a signed comparison.
7332 if (cast<ConstantInt>(CI)->getValue().isNegative())
7333 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
7335 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
7337 // We're performing an unsigned comparison.
7339 // We're performing an unsigned comp with a sign extended value.
7340 // This is true if the input is >= 0. [aka >s -1]
7341 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7342 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7344 // Unsigned extend & unsigned compare -> always true.
7345 Result = ConstantInt::getTrue(*Context);
7349 // Finally, return the value computed.
7350 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7351 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7352 return ReplaceInstUsesWith(ICI, Result);
7354 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7355 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7356 "ICmp should be folded!");
7357 if (Constant *CI = dyn_cast<Constant>(Result))
7358 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7359 return BinaryOperator::CreateNot(Result);
7362 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7363 return commonShiftTransforms(I);
7366 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7367 return commonShiftTransforms(I);
7370 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7371 if (Instruction *R = commonShiftTransforms(I))
7374 Value *Op0 = I.getOperand(0);
7376 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7377 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7378 if (CSI->isAllOnesValue())
7379 return ReplaceInstUsesWith(I, CSI);
7381 // See if we can turn a signed shr into an unsigned shr.
7382 if (MaskedValueIsZero(Op0,
7383 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7384 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7386 // Arithmetic shifting an all-sign-bit value is a no-op.
7387 unsigned NumSignBits = ComputeNumSignBits(Op0);
7388 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7389 return ReplaceInstUsesWith(I, Op0);
7394 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7395 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7396 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7398 // shl X, 0 == X and shr X, 0 == X
7399 // shl 0, X == 0 and shr 0, X == 0
7400 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7401 Op0 == Constant::getNullValue(Op0->getType()))
7402 return ReplaceInstUsesWith(I, Op0);
7404 if (isa<UndefValue>(Op0)) {
7405 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7406 return ReplaceInstUsesWith(I, Op0);
7407 else // undef << X -> 0, undef >>u X -> 0
7408 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7410 if (isa<UndefValue>(Op1)) {
7411 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7412 return ReplaceInstUsesWith(I, Op0);
7413 else // X << undef, X >>u undef -> 0
7414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7417 // See if we can fold away this shift.
7418 if (SimplifyDemandedInstructionBits(I))
7421 // Try to fold constant and into select arguments.
7422 if (isa<Constant>(Op0))
7423 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7424 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7427 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7428 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7433 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7434 BinaryOperator &I) {
7435 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7437 // See if we can simplify any instructions used by the instruction whose sole
7438 // purpose is to compute bits we don't care about.
7439 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7441 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7444 if (Op1->uge(TypeBits)) {
7445 if (I.getOpcode() != Instruction::AShr)
7446 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7448 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7453 // ((X*C1) << C2) == (X * (C1 << C2))
7454 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7455 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7456 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7457 return BinaryOperator::CreateMul(BO->getOperand(0),
7458 ConstantExpr::getShl(BOOp, Op1));
7460 // Try to fold constant and into select arguments.
7461 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7462 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7464 if (isa<PHINode>(Op0))
7465 if (Instruction *NV = FoldOpIntoPhi(I))
7468 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7469 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7470 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7471 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7472 // place. Don't try to do this transformation in this case. Also, we
7473 // require that the input operand is a shift-by-constant so that we have
7474 // confidence that the shifts will get folded together. We could do this
7475 // xform in more cases, but it is unlikely to be profitable.
7476 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7477 isa<ConstantInt>(TrOp->getOperand(1))) {
7478 // Okay, we'll do this xform. Make the shift of shift.
7479 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7480 // (shift2 (shift1 & 0x00FF), c2)
7481 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7483 // For logical shifts, the truncation has the effect of making the high
7484 // part of the register be zeros. Emulate this by inserting an AND to
7485 // clear the top bits as needed. This 'and' will usually be zapped by
7486 // other xforms later if dead.
7487 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7488 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7489 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7491 // The mask we constructed says what the trunc would do if occurring
7492 // between the shifts. We want to know the effect *after* the second
7493 // shift. We know that it is a logical shift by a constant, so adjust the
7494 // mask as appropriate.
7495 if (I.getOpcode() == Instruction::Shl)
7496 MaskV <<= Op1->getZExtValue();
7498 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7499 MaskV = MaskV.lshr(Op1->getZExtValue());
7503 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7506 // Return the value truncated to the interesting size.
7507 return new TruncInst(And, I.getType());
7511 if (Op0->hasOneUse()) {
7512 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7513 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7516 switch (Op0BO->getOpcode()) {
7518 case Instruction::Add:
7519 case Instruction::And:
7520 case Instruction::Or:
7521 case Instruction::Xor: {
7522 // These operators commute.
7523 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7524 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7525 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7526 m_Specific(Op1)))) {
7527 Value *YS = // (Y << C)
7528 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7530 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7531 Op0BO->getOperand(1)->getName());
7532 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7533 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7534 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7537 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7538 Value *Op0BOOp1 = Op0BO->getOperand(1);
7539 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7541 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7542 m_ConstantInt(CC))) &&
7543 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7544 Value *YS = // (Y << C)
7545 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7548 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7549 V1->getName()+".mask");
7550 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7555 case Instruction::Sub: {
7556 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7557 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7558 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7559 m_Specific(Op1)))) {
7560 Value *YS = // (Y << C)
7561 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7563 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7564 Op0BO->getOperand(0)->getName());
7565 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7566 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7567 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7570 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7571 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7572 match(Op0BO->getOperand(0),
7573 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7574 m_ConstantInt(CC))) && V2 == Op1 &&
7575 cast<BinaryOperator>(Op0BO->getOperand(0))
7576 ->getOperand(0)->hasOneUse()) {
7577 Value *YS = // (Y << C)
7578 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7580 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7581 V1->getName()+".mask");
7583 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7591 // If the operand is an bitwise operator with a constant RHS, and the
7592 // shift is the only use, we can pull it out of the shift.
7593 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7594 bool isValid = true; // Valid only for And, Or, Xor
7595 bool highBitSet = false; // Transform if high bit of constant set?
7597 switch (Op0BO->getOpcode()) {
7598 default: isValid = false; break; // Do not perform transform!
7599 case Instruction::Add:
7600 isValid = isLeftShift;
7602 case Instruction::Or:
7603 case Instruction::Xor:
7606 case Instruction::And:
7611 // If this is a signed shift right, and the high bit is modified
7612 // by the logical operation, do not perform the transformation.
7613 // The highBitSet boolean indicates the value of the high bit of
7614 // the constant which would cause it to be modified for this
7617 if (isValid && I.getOpcode() == Instruction::AShr)
7618 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7621 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7624 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7625 NewShift->takeName(Op0BO);
7627 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7634 // Find out if this is a shift of a shift by a constant.
7635 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7636 if (ShiftOp && !ShiftOp->isShift())
7639 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7640 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7641 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7642 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7643 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7644 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7645 Value *X = ShiftOp->getOperand(0);
7647 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7649 const IntegerType *Ty = cast<IntegerType>(I.getType());
7651 // Check for (X << c1) << c2 and (X >> c1) >> c2
7652 if (I.getOpcode() == ShiftOp->getOpcode()) {
7653 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7655 if (AmtSum >= TypeBits) {
7656 if (I.getOpcode() != Instruction::AShr)
7657 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7658 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7661 return BinaryOperator::Create(I.getOpcode(), X,
7662 ConstantInt::get(Ty, AmtSum));
7665 if (ShiftOp->getOpcode() == Instruction::LShr &&
7666 I.getOpcode() == Instruction::AShr) {
7667 if (AmtSum >= TypeBits)
7668 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7670 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7671 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7674 if (ShiftOp->getOpcode() == Instruction::AShr &&
7675 I.getOpcode() == Instruction::LShr) {
7676 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7677 if (AmtSum >= TypeBits)
7678 AmtSum = TypeBits-1;
7680 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7682 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7683 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7686 // Okay, if we get here, one shift must be left, and the other shift must be
7687 // right. See if the amounts are equal.
7688 if (ShiftAmt1 == ShiftAmt2) {
7689 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7690 if (I.getOpcode() == Instruction::Shl) {
7691 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7692 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7694 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7695 if (I.getOpcode() == Instruction::LShr) {
7696 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7697 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7699 // We can simplify ((X << C) >>s C) into a trunc + sext.
7700 // NOTE: we could do this for any C, but that would make 'unusual' integer
7701 // types. For now, just stick to ones well-supported by the code
7703 const Type *SExtType = 0;
7704 switch (Ty->getBitWidth() - ShiftAmt1) {
7711 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7716 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7717 // Otherwise, we can't handle it yet.
7718 } else if (ShiftAmt1 < ShiftAmt2) {
7719 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7721 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7722 if (I.getOpcode() == Instruction::Shl) {
7723 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7724 ShiftOp->getOpcode() == Instruction::AShr);
7725 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7727 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7728 return BinaryOperator::CreateAnd(Shift,
7729 ConstantInt::get(*Context, Mask));
7732 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7733 if (I.getOpcode() == Instruction::LShr) {
7734 assert(ShiftOp->getOpcode() == Instruction::Shl);
7735 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7737 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7738 return BinaryOperator::CreateAnd(Shift,
7739 ConstantInt::get(*Context, Mask));
7742 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7744 assert(ShiftAmt2 < ShiftAmt1);
7745 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7747 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7748 if (I.getOpcode() == Instruction::Shl) {
7749 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7750 ShiftOp->getOpcode() == Instruction::AShr);
7751 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7752 ConstantInt::get(Ty, ShiftDiff));
7754 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7755 return BinaryOperator::CreateAnd(Shift,
7756 ConstantInt::get(*Context, Mask));
7759 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7760 if (I.getOpcode() == Instruction::LShr) {
7761 assert(ShiftOp->getOpcode() == Instruction::Shl);
7762 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7764 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7765 return BinaryOperator::CreateAnd(Shift,
7766 ConstantInt::get(*Context, Mask));
7769 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7776 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7777 /// expression. If so, decompose it, returning some value X, such that Val is
7780 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7781 int &Offset, LLVMContext *Context) {
7782 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7783 "Unexpected allocation size type!");
7784 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7785 Offset = CI->getZExtValue();
7787 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7788 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7789 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7790 if (I->getOpcode() == Instruction::Shl) {
7791 // This is a value scaled by '1 << the shift amt'.
7792 Scale = 1U << RHS->getZExtValue();
7794 return I->getOperand(0);
7795 } else if (I->getOpcode() == Instruction::Mul) {
7796 // This value is scaled by 'RHS'.
7797 Scale = RHS->getZExtValue();
7799 return I->getOperand(0);
7800 } else if (I->getOpcode() == Instruction::Add) {
7801 // We have X+C. Check to see if we really have (X*C2)+C1,
7802 // where C1 is divisible by C2.
7805 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7807 Offset += RHS->getZExtValue();
7814 // Otherwise, we can't look past this.
7821 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7822 /// try to eliminate the cast by moving the type information into the alloc.
7823 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7825 const PointerType *PTy = cast<PointerType>(CI.getType());
7827 BuilderTy AllocaBuilder(*Builder);
7828 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7830 // Remove any uses of AI that are dead.
7831 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7833 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7834 Instruction *User = cast<Instruction>(*UI++);
7835 if (isInstructionTriviallyDead(User)) {
7836 while (UI != E && *UI == User)
7837 ++UI; // If this instruction uses AI more than once, don't break UI.
7840 DEBUG(errs() << "IC: DCE: " << *User << '\n');
7841 EraseInstFromFunction(*User);
7845 // This requires TargetData to get the alloca alignment and size information.
7848 // Get the type really allocated and the type casted to.
7849 const Type *AllocElTy = AI.getAllocatedType();
7850 const Type *CastElTy = PTy->getElementType();
7851 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7853 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7854 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7855 if (CastElTyAlign < AllocElTyAlign) return 0;
7857 // If the allocation has multiple uses, only promote it if we are strictly
7858 // increasing the alignment of the resultant allocation. If we keep it the
7859 // same, we open the door to infinite loops of various kinds. (A reference
7860 // from a dbg.declare doesn't count as a use for this purpose.)
7861 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7862 CastElTyAlign == AllocElTyAlign) return 0;
7864 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7865 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7866 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7868 // See if we can satisfy the modulus by pulling a scale out of the array
7870 unsigned ArraySizeScale;
7872 Value *NumElements = // See if the array size is a decomposable linear expr.
7873 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7874 ArrayOffset, Context);
7876 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7878 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7879 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7881 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7886 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7887 // Insert before the alloca, not before the cast.
7888 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7891 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7892 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7893 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7896 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7897 New->setAlignment(AI.getAlignment());
7900 // If the allocation has one real use plus a dbg.declare, just remove the
7902 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7903 EraseInstFromFunction(*DI);
7905 // If the allocation has multiple real uses, insert a cast and change all
7906 // things that used it to use the new cast. This will also hack on CI, but it
7908 else if (!AI.hasOneUse()) {
7909 // New is the allocation instruction, pointer typed. AI is the original
7910 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7911 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7912 AI.replaceAllUsesWith(NewCast);
7914 return ReplaceInstUsesWith(CI, New);
7917 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7918 /// and return it as type Ty without inserting any new casts and without
7919 /// changing the computed value. This is used by code that tries to decide
7920 /// whether promoting or shrinking integer operations to wider or smaller types
7921 /// will allow us to eliminate a truncate or extend.
7923 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7924 /// extension operation if Ty is larger.
7926 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7927 /// should return true if trunc(V) can be computed by computing V in the smaller
7928 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7929 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7930 /// efficiently truncated.
7932 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7933 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7934 /// the final result.
7935 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7937 int &NumCastsRemoved){
7938 // We can always evaluate constants in another type.
7939 if (isa<Constant>(V))
7942 Instruction *I = dyn_cast<Instruction>(V);
7943 if (!I) return false;
7945 const Type *OrigTy = V->getType();
7947 // If this is an extension or truncate, we can often eliminate it.
7948 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7949 // If this is a cast from the destination type, we can trivially eliminate
7950 // it, and this will remove a cast overall.
7951 if (I->getOperand(0)->getType() == Ty) {
7952 // If the first operand is itself a cast, and is eliminable, do not count
7953 // this as an eliminable cast. We would prefer to eliminate those two
7955 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7961 // We can't extend or shrink something that has multiple uses: doing so would
7962 // require duplicating the instruction in general, which isn't profitable.
7963 if (!I->hasOneUse()) return false;
7965 unsigned Opc = I->getOpcode();
7967 case Instruction::Add:
7968 case Instruction::Sub:
7969 case Instruction::Mul:
7970 case Instruction::And:
7971 case Instruction::Or:
7972 case Instruction::Xor:
7973 // These operators can all arbitrarily be extended or truncated.
7974 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7976 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7979 case Instruction::UDiv:
7980 case Instruction::URem: {
7981 // UDiv and URem can be truncated if all the truncated bits are zero.
7982 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7983 uint32_t BitWidth = Ty->getScalarSizeInBits();
7984 if (BitWidth < OrigBitWidth) {
7985 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7986 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7987 MaskedValueIsZero(I->getOperand(1), Mask)) {
7988 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7990 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7996 case Instruction::Shl:
7997 // If we are truncating the result of this SHL, and if it's a shift of a
7998 // constant amount, we can always perform a SHL in a smaller type.
7999 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8000 uint32_t BitWidth = Ty->getScalarSizeInBits();
8001 if (BitWidth < OrigTy->getScalarSizeInBits() &&
8002 CI->getLimitedValue(BitWidth) < BitWidth)
8003 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8007 case Instruction::LShr:
8008 // If this is a truncate of a logical shr, we can truncate it to a smaller
8009 // lshr iff we know that the bits we would otherwise be shifting in are
8011 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8012 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8013 uint32_t BitWidth = Ty->getScalarSizeInBits();
8014 if (BitWidth < OrigBitWidth &&
8015 MaskedValueIsZero(I->getOperand(0),
8016 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8017 CI->getLimitedValue(BitWidth) < BitWidth) {
8018 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8023 case Instruction::ZExt:
8024 case Instruction::SExt:
8025 case Instruction::Trunc:
8026 // If this is the same kind of case as our original (e.g. zext+zext), we
8027 // can safely replace it. Note that replacing it does not reduce the number
8028 // of casts in the input.
8032 // sext (zext ty1), ty2 -> zext ty2
8033 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8036 case Instruction::Select: {
8037 SelectInst *SI = cast<SelectInst>(I);
8038 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8040 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8043 case Instruction::PHI: {
8044 // We can change a phi if we can change all operands.
8045 PHINode *PN = cast<PHINode>(I);
8046 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8047 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8053 // TODO: Can handle more cases here.
8060 /// EvaluateInDifferentType - Given an expression that
8061 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8062 /// evaluate the expression.
8063 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8065 if (Constant *C = dyn_cast<Constant>(V))
8066 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
8068 // Otherwise, it must be an instruction.
8069 Instruction *I = cast<Instruction>(V);
8070 Instruction *Res = 0;
8071 unsigned Opc = I->getOpcode();
8073 case Instruction::Add:
8074 case Instruction::Sub:
8075 case Instruction::Mul:
8076 case Instruction::And:
8077 case Instruction::Or:
8078 case Instruction::Xor:
8079 case Instruction::AShr:
8080 case Instruction::LShr:
8081 case Instruction::Shl:
8082 case Instruction::UDiv:
8083 case Instruction::URem: {
8084 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8085 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8086 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8089 case Instruction::Trunc:
8090 case Instruction::ZExt:
8091 case Instruction::SExt:
8092 // If the source type of the cast is the type we're trying for then we can
8093 // just return the source. There's no need to insert it because it is not
8095 if (I->getOperand(0)->getType() == Ty)
8096 return I->getOperand(0);
8098 // Otherwise, must be the same type of cast, so just reinsert a new one.
8099 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
8101 case Instruction::Select: {
8102 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8103 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8104 Res = SelectInst::Create(I->getOperand(0), True, False);
8107 case Instruction::PHI: {
8108 PHINode *OPN = cast<PHINode>(I);
8109 PHINode *NPN = PHINode::Create(Ty);
8110 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8111 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8112 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8118 // TODO: Can handle more cases here.
8119 llvm_unreachable("Unreachable!");
8124 return InsertNewInstBefore(Res, *I);
8127 /// @brief Implement the transforms common to all CastInst visitors.
8128 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8129 Value *Src = CI.getOperand(0);
8131 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8132 // eliminate it now.
8133 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8134 if (Instruction::CastOps opc =
8135 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8136 // The first cast (CSrc) is eliminable so we need to fix up or replace
8137 // the second cast (CI). CSrc will then have a good chance of being dead.
8138 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8142 // If we are casting a select then fold the cast into the select
8143 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8144 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8147 // If we are casting a PHI then fold the cast into the PHI
8148 if (isa<PHINode>(Src)) {
8149 // We don't do this if this would create a PHI node with an illegal type if
8150 // it is currently legal.
8151 if (!isa<IntegerType>(Src->getType()) ||
8152 !isa<IntegerType>(CI.getType()) ||
8153 ShouldChangeType(CI.getType(), Src->getType(), TD))
8154 if (Instruction *NV = FoldOpIntoPhi(CI))
8161 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8162 /// or not there is a sequence of GEP indices into the type that will land us at
8163 /// the specified offset. If so, fill them into NewIndices and return the
8164 /// resultant element type, otherwise return null.
8165 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8166 SmallVectorImpl<Value*> &NewIndices,
8167 const TargetData *TD,
8168 LLVMContext *Context) {
8170 if (!Ty->isSized()) return 0;
8172 // Start with the index over the outer type. Note that the type size
8173 // might be zero (even if the offset isn't zero) if the indexed type
8174 // is something like [0 x {int, int}]
8175 const Type *IntPtrTy = TD->getIntPtrType(*Context);
8176 int64_t FirstIdx = 0;
8177 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8178 FirstIdx = Offset/TySize;
8179 Offset -= FirstIdx*TySize;
8181 // Handle hosts where % returns negative instead of values [0..TySize).
8185 assert(Offset >= 0);
8187 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8190 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8192 // Index into the types. If we fail, set OrigBase to null.
8194 // Indexing into tail padding between struct/array elements.
8195 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8198 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8199 const StructLayout *SL = TD->getStructLayout(STy);
8200 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8201 "Offset must stay within the indexed type");
8203 unsigned Elt = SL->getElementContainingOffset(Offset);
8204 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8206 Offset -= SL->getElementOffset(Elt);
8207 Ty = STy->getElementType(Elt);
8208 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8209 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8210 assert(EltSize && "Cannot index into a zero-sized array");
8211 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8213 Ty = AT->getElementType();
8215 // Otherwise, we can't index into the middle of this atomic type, bail.
8223 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8224 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8225 Value *Src = CI.getOperand(0);
8227 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8228 // If casting the result of a getelementptr instruction with no offset, turn
8229 // this into a cast of the original pointer!
8230 if (GEP->hasAllZeroIndices()) {
8231 // Changing the cast operand is usually not a good idea but it is safe
8232 // here because the pointer operand is being replaced with another
8233 // pointer operand so the opcode doesn't need to change.
8235 CI.setOperand(0, GEP->getOperand(0));
8239 // If the GEP has a single use, and the base pointer is a bitcast, and the
8240 // GEP computes a constant offset, see if we can convert these three
8241 // instructions into fewer. This typically happens with unions and other
8242 // non-type-safe code.
8243 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8244 if (GEP->hasAllConstantIndices()) {
8245 // We are guaranteed to get a constant from EmitGEPOffset.
8246 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
8247 int64_t Offset = OffsetV->getSExtValue();
8249 // Get the base pointer input of the bitcast, and the type it points to.
8250 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8251 const Type *GEPIdxTy =
8252 cast<PointerType>(OrigBase->getType())->getElementType();
8253 SmallVector<Value*, 8> NewIndices;
8254 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8255 // If we were able to index down into an element, create the GEP
8256 // and bitcast the result. This eliminates one bitcast, potentially
8258 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8259 Builder->CreateInBoundsGEP(OrigBase,
8260 NewIndices.begin(), NewIndices.end()) :
8261 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8262 NGEP->takeName(GEP);
8264 if (isa<BitCastInst>(CI))
8265 return new BitCastInst(NGEP, CI.getType());
8266 assert(isa<PtrToIntInst>(CI));
8267 return new PtrToIntInst(NGEP, CI.getType());
8273 return commonCastTransforms(CI);
8276 /// commonIntCastTransforms - This function implements the common transforms
8277 /// for trunc, zext, and sext.
8278 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8279 if (Instruction *Result = commonCastTransforms(CI))
8282 Value *Src = CI.getOperand(0);
8283 const Type *SrcTy = Src->getType();
8284 const Type *DestTy = CI.getType();
8285 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8286 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8288 // See if we can simplify any instructions used by the LHS whose sole
8289 // purpose is to compute bits we don't care about.
8290 if (SimplifyDemandedInstructionBits(CI))
8293 // If the source isn't an instruction or has more than one use then we
8294 // can't do anything more.
8295 Instruction *SrcI = dyn_cast<Instruction>(Src);
8296 if (!SrcI || !Src->hasOneUse())
8299 // Attempt to propagate the cast into the instruction for int->int casts.
8300 int NumCastsRemoved = 0;
8301 // Only do this if the dest type is a simple type, don't convert the
8302 // expression tree to something weird like i93 unless the source is also
8304 if ((isa<VectorType>(DestTy) ||
8305 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8306 CanEvaluateInDifferentType(SrcI, DestTy,
8307 CI.getOpcode(), NumCastsRemoved)) {
8308 // If this cast is a truncate, evaluting in a different type always
8309 // eliminates the cast, so it is always a win. If this is a zero-extension,
8310 // we need to do an AND to maintain the clear top-part of the computation,
8311 // so we require that the input have eliminated at least one cast. If this
8312 // is a sign extension, we insert two new casts (to do the extension) so we
8313 // require that two casts have been eliminated.
8314 bool DoXForm = false;
8315 bool JustReplace = false;
8316 switch (CI.getOpcode()) {
8318 // All the others use floating point so we shouldn't actually
8319 // get here because of the check above.
8320 llvm_unreachable("Unknown cast type");
8321 case Instruction::Trunc:
8324 case Instruction::ZExt: {
8325 DoXForm = NumCastsRemoved >= 1;
8327 if (!DoXForm && 0) {
8328 // If it's unnecessary to issue an AND to clear the high bits, it's
8329 // always profitable to do this xform.
8330 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8331 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8332 if (MaskedValueIsZero(TryRes, Mask))
8333 return ReplaceInstUsesWith(CI, TryRes);
8335 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8336 if (TryI->use_empty())
8337 EraseInstFromFunction(*TryI);
8341 case Instruction::SExt: {
8342 DoXForm = NumCastsRemoved >= 2;
8343 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8344 // If we do not have to emit the truncate + sext pair, then it's always
8345 // profitable to do this xform.
8347 // It's not safe to eliminate the trunc + sext pair if one of the
8348 // eliminated cast is a truncate. e.g.
8349 // t2 = trunc i32 t1 to i16
8350 // t3 = sext i16 t2 to i32
8353 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8354 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8355 if (NumSignBits > (DestBitSize - SrcBitSize))
8356 return ReplaceInstUsesWith(CI, TryRes);
8358 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8359 if (TryI->use_empty())
8360 EraseInstFromFunction(*TryI);
8367 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8368 " to avoid cast: " << CI);
8369 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8370 CI.getOpcode() == Instruction::SExt);
8372 // Just replace this cast with the result.
8373 return ReplaceInstUsesWith(CI, Res);
8375 assert(Res->getType() == DestTy);
8376 switch (CI.getOpcode()) {
8377 default: llvm_unreachable("Unknown cast type!");
8378 case Instruction::Trunc:
8379 // Just replace this cast with the result.
8380 return ReplaceInstUsesWith(CI, Res);
8381 case Instruction::ZExt: {
8382 assert(SrcBitSize < DestBitSize && "Not a zext?");
8384 // If the high bits are already zero, just replace this cast with the
8386 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8387 if (MaskedValueIsZero(Res, Mask))
8388 return ReplaceInstUsesWith(CI, Res);
8390 // We need to emit an AND to clear the high bits.
8391 Constant *C = ConstantInt::get(*Context,
8392 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8393 return BinaryOperator::CreateAnd(Res, C);
8395 case Instruction::SExt: {
8396 // If the high bits are already filled with sign bit, just replace this
8397 // cast with the result.
8398 unsigned NumSignBits = ComputeNumSignBits(Res);
8399 if (NumSignBits > (DestBitSize - SrcBitSize))
8400 return ReplaceInstUsesWith(CI, Res);
8402 // We need to emit a cast to truncate, then a cast to sext.
8403 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8409 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8410 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8412 switch (SrcI->getOpcode()) {
8413 case Instruction::Add:
8414 case Instruction::Mul:
8415 case Instruction::And:
8416 case Instruction::Or:
8417 case Instruction::Xor:
8418 // If we are discarding information, rewrite.
8419 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8420 // Don't insert two casts unless at least one can be eliminated.
8421 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8422 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8423 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8424 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8425 return BinaryOperator::Create(
8426 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8430 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8431 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8432 SrcI->getOpcode() == Instruction::Xor &&
8433 Op1 == ConstantInt::getTrue(*Context) &&
8434 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8435 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8436 return BinaryOperator::CreateXor(New,
8437 ConstantInt::get(CI.getType(), 1));
8441 case Instruction::Shl: {
8442 // Canonicalize trunc inside shl, if we can.
8443 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8444 if (CI && DestBitSize < SrcBitSize &&
8445 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8446 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8447 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8448 return BinaryOperator::CreateShl(Op0c, Op1c);
8456 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8457 if (Instruction *Result = commonIntCastTransforms(CI))
8460 Value *Src = CI.getOperand(0);
8461 const Type *Ty = CI.getType();
8462 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8463 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8465 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8466 if (DestBitWidth == 1) {
8467 Constant *One = ConstantInt::get(Src->getType(), 1);
8468 Src = Builder->CreateAnd(Src, One, "tmp");
8469 Value *Zero = Constant::getNullValue(Src->getType());
8470 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8473 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8474 ConstantInt *ShAmtV = 0;
8476 if (Src->hasOneUse() &&
8477 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8478 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8480 // Get a mask for the bits shifting in.
8481 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8482 if (MaskedValueIsZero(ShiftOp, Mask)) {
8483 if (ShAmt >= DestBitWidth) // All zeros.
8484 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8486 // Okay, we can shrink this. Truncate the input, then return a new
8488 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8489 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8490 return BinaryOperator::CreateLShr(V1, V2);
8497 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8498 /// in order to eliminate the icmp.
8499 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8501 // If we are just checking for a icmp eq of a single bit and zext'ing it
8502 // to an integer, then shift the bit to the appropriate place and then
8503 // cast to integer to avoid the comparison.
8504 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8505 const APInt &Op1CV = Op1C->getValue();
8507 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8508 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8509 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8510 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8511 if (!DoXform) return ICI;
8513 Value *In = ICI->getOperand(0);
8514 Value *Sh = ConstantInt::get(In->getType(),
8515 In->getType()->getScalarSizeInBits()-1);
8516 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8517 if (In->getType() != CI.getType())
8518 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8520 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8521 Constant *One = ConstantInt::get(In->getType(), 1);
8522 In = Builder->CreateXor(In, One, In->getName()+".not");
8525 return ReplaceInstUsesWith(CI, In);
8530 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8531 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8532 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8533 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8534 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8535 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8536 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8537 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8538 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8539 // This only works for EQ and NE
8540 ICI->isEquality()) {
8541 // If Op1C some other power of two, convert:
8542 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8543 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8544 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8545 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8547 APInt KnownZeroMask(~KnownZero);
8548 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8549 if (!DoXform) return ICI;
8551 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8552 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8553 // (X&4) == 2 --> false
8554 // (X&4) != 2 --> true
8555 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8556 Res = ConstantExpr::getZExt(Res, CI.getType());
8557 return ReplaceInstUsesWith(CI, Res);
8560 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8561 Value *In = ICI->getOperand(0);
8563 // Perform a logical shr by shiftamt.
8564 // Insert the shift to put the result in the low bit.
8565 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8566 In->getName()+".lobit");
8569 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8570 Constant *One = ConstantInt::get(In->getType(), 1);
8571 In = Builder->CreateXor(In, One, "tmp");
8574 if (CI.getType() == In->getType())
8575 return ReplaceInstUsesWith(CI, In);
8577 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8582 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8583 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8584 // may lead to additional simplifications.
8585 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8586 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8587 uint32_t BitWidth = ITy->getBitWidth();
8588 Value *LHS = ICI->getOperand(0);
8589 Value *RHS = ICI->getOperand(1);
8591 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8592 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8593 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8594 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8595 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
8597 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8598 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8599 APInt UnknownBit = ~KnownBits;
8600 if (UnknownBit.countPopulation() == 1) {
8601 if (!DoXform) return ICI;
8603 Value *Result = Builder->CreateXor(LHS, RHS);
8605 // Mask off any bits that are set and won't be shifted away.
8606 if (KnownOneLHS.uge(UnknownBit))
8607 Result = Builder->CreateAnd(Result,
8608 ConstantInt::get(ITy, UnknownBit));
8610 // Shift the bit we're testing down to the lsb.
8611 Result = Builder->CreateLShr(
8612 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8614 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8615 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8616 Result->takeName(ICI);
8617 return ReplaceInstUsesWith(CI, Result);
8626 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8627 // If one of the common conversion will work ..
8628 if (Instruction *Result = commonIntCastTransforms(CI))
8631 Value *Src = CI.getOperand(0);
8633 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8634 // types and if the sizes are just right we can convert this into a logical
8635 // 'and' which will be much cheaper than the pair of casts.
8636 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8637 // Get the sizes of the types involved. We know that the intermediate type
8638 // will be smaller than A or C, but don't know the relation between A and C.
8639 Value *A = CSrc->getOperand(0);
8640 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8641 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8642 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8643 // If we're actually extending zero bits, then if
8644 // SrcSize < DstSize: zext(a & mask)
8645 // SrcSize == DstSize: a & mask
8646 // SrcSize > DstSize: trunc(a) & mask
8647 if (SrcSize < DstSize) {
8648 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8649 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8650 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8651 return new ZExtInst(And, CI.getType());
8654 if (SrcSize == DstSize) {
8655 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8656 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8659 if (SrcSize > DstSize) {
8660 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8661 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8662 return BinaryOperator::CreateAnd(Trunc,
8663 ConstantInt::get(Trunc->getType(),
8668 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8669 return transformZExtICmp(ICI, CI);
8671 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8672 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8673 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8674 // of the (zext icmp) will be transformed.
8675 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8676 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8677 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8678 (transformZExtICmp(LHS, CI, false) ||
8679 transformZExtICmp(RHS, CI, false))) {
8680 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8681 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8682 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8686 // zext(trunc(t) & C) -> (t & zext(C)).
8687 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8688 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8689 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8690 Value *TI0 = TI->getOperand(0);
8691 if (TI0->getType() == CI.getType())
8693 BinaryOperator::CreateAnd(TI0,
8694 ConstantExpr::getZExt(C, CI.getType()));
8697 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8698 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8699 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8700 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8701 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8702 And->getOperand(1) == C)
8703 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8704 Value *TI0 = TI->getOperand(0);
8705 if (TI0->getType() == CI.getType()) {
8706 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8707 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8708 return BinaryOperator::CreateXor(NewAnd, ZC);
8715 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8716 if (Instruction *I = commonIntCastTransforms(CI))
8719 Value *Src = CI.getOperand(0);
8721 // Canonicalize sign-extend from i1 to a select.
8722 if (Src->getType() == Type::getInt1Ty(*Context))
8723 return SelectInst::Create(Src,
8724 Constant::getAllOnesValue(CI.getType()),
8725 Constant::getNullValue(CI.getType()));
8727 // See if the value being truncated is already sign extended. If so, just
8728 // eliminate the trunc/sext pair.
8729 if (Operator::getOpcode(Src) == Instruction::Trunc) {
8730 Value *Op = cast<User>(Src)->getOperand(0);
8731 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8732 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8733 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8734 unsigned NumSignBits = ComputeNumSignBits(Op);
8736 if (OpBits == DestBits) {
8737 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8738 // bits, it is already ready.
8739 if (NumSignBits > DestBits-MidBits)
8740 return ReplaceInstUsesWith(CI, Op);
8741 } else if (OpBits < DestBits) {
8742 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8743 // bits, just sext from i32.
8744 if (NumSignBits > OpBits-MidBits)
8745 return new SExtInst(Op, CI.getType(), "tmp");
8747 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8748 // bits, just truncate to i32.
8749 if (NumSignBits > OpBits-MidBits)
8750 return new TruncInst(Op, CI.getType(), "tmp");
8754 // If the input is a shl/ashr pair of a same constant, then this is a sign
8755 // extension from a smaller value. If we could trust arbitrary bitwidth
8756 // integers, we could turn this into a truncate to the smaller bit and then
8757 // use a sext for the whole extension. Since we don't, look deeper and check
8758 // for a truncate. If the source and dest are the same type, eliminate the
8759 // trunc and extend and just do shifts. For example, turn:
8760 // %a = trunc i32 %i to i8
8761 // %b = shl i8 %a, 6
8762 // %c = ashr i8 %b, 6
8763 // %d = sext i8 %c to i32
8765 // %a = shl i32 %i, 30
8766 // %d = ashr i32 %a, 30
8768 ConstantInt *BA = 0, *CA = 0;
8769 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8770 m_ConstantInt(CA))) &&
8771 BA == CA && isa<TruncInst>(A)) {
8772 Value *I = cast<TruncInst>(A)->getOperand(0);
8773 if (I->getType() == CI.getType()) {
8774 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8775 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8776 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8777 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8778 I = Builder->CreateShl(I, ShAmtV, CI.getName());
8779 return BinaryOperator::CreateAShr(I, ShAmtV);
8786 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8787 /// in the specified FP type without changing its value.
8788 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8789 LLVMContext *Context) {
8791 APFloat F = CFP->getValueAPF();
8792 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8794 return ConstantFP::get(*Context, F);
8798 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8799 /// through it until we get the source value.
8800 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8801 if (Instruction *I = dyn_cast<Instruction>(V))
8802 if (I->getOpcode() == Instruction::FPExt)
8803 return LookThroughFPExtensions(I->getOperand(0), Context);
8805 // If this value is a constant, return the constant in the smallest FP type
8806 // that can accurately represent it. This allows us to turn
8807 // (float)((double)X+2.0) into x+2.0f.
8808 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8809 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8810 return V; // No constant folding of this.
8811 // See if the value can be truncated to float and then reextended.
8812 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8814 if (CFP->getType() == Type::getDoubleTy(*Context))
8815 return V; // Won't shrink.
8816 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8818 // Don't try to shrink to various long double types.
8824 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8825 if (Instruction *I = commonCastTransforms(CI))
8828 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8829 // smaller than the destination type, we can eliminate the truncate by doing
8830 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8831 // many builtins (sqrt, etc).
8832 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8833 if (OpI && OpI->hasOneUse()) {
8834 switch (OpI->getOpcode()) {
8836 case Instruction::FAdd:
8837 case Instruction::FSub:
8838 case Instruction::FMul:
8839 case Instruction::FDiv:
8840 case Instruction::FRem:
8841 const Type *SrcTy = OpI->getType();
8842 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8843 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8844 if (LHSTrunc->getType() != SrcTy &&
8845 RHSTrunc->getType() != SrcTy) {
8846 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8847 // If the source types were both smaller than the destination type of
8848 // the cast, do this xform.
8849 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8850 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8851 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8852 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8853 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8862 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8863 return commonCastTransforms(CI);
8866 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8867 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8869 return commonCastTransforms(FI);
8871 // fptoui(uitofp(X)) --> X
8872 // fptoui(sitofp(X)) --> X
8873 // This is safe if the intermediate type has enough bits in its mantissa to
8874 // accurately represent all values of X. For example, do not do this with
8875 // i64->float->i64. This is also safe for sitofp case, because any negative
8876 // 'X' value would cause an undefined result for the fptoui.
8877 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8878 OpI->getOperand(0)->getType() == FI.getType() &&
8879 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8880 OpI->getType()->getFPMantissaWidth())
8881 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8883 return commonCastTransforms(FI);
8886 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8887 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8889 return commonCastTransforms(FI);
8891 // fptosi(sitofp(X)) --> X
8892 // fptosi(uitofp(X)) --> X
8893 // This is safe if the intermediate type has enough bits in its mantissa to
8894 // accurately represent all values of X. For example, do not do this with
8895 // i64->float->i64. This is also safe for sitofp case, because any negative
8896 // 'X' value would cause an undefined result for the fptoui.
8897 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8898 OpI->getOperand(0)->getType() == FI.getType() &&
8899 (int)FI.getType()->getScalarSizeInBits() <=
8900 OpI->getType()->getFPMantissaWidth())
8901 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8903 return commonCastTransforms(FI);
8906 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8907 return commonCastTransforms(CI);
8910 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8911 return commonCastTransforms(CI);
8914 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8915 // If the destination integer type is smaller than the intptr_t type for
8916 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8917 // trunc to be exposed to other transforms. Don't do this for extending
8918 // ptrtoint's, because we don't know if the target sign or zero extends its
8921 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8922 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8923 TD->getIntPtrType(CI.getContext()),
8925 return new TruncInst(P, CI.getType());
8928 return commonPointerCastTransforms(CI);
8931 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8932 // If the source integer type is larger than the intptr_t type for
8933 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8934 // allows the trunc to be exposed to other transforms. Don't do this for
8935 // extending inttoptr's, because we don't know if the target sign or zero
8936 // extends to pointers.
8937 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8938 TD->getPointerSizeInBits()) {
8939 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8940 TD->getIntPtrType(CI.getContext()), "tmp");
8941 return new IntToPtrInst(P, CI.getType());
8944 if (Instruction *I = commonCastTransforms(CI))
8950 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8951 // If the operands are integer typed then apply the integer transforms,
8952 // otherwise just apply the common ones.
8953 Value *Src = CI.getOperand(0);
8954 const Type *SrcTy = Src->getType();
8955 const Type *DestTy = CI.getType();
8957 if (isa<PointerType>(SrcTy)) {
8958 if (Instruction *I = commonPointerCastTransforms(CI))
8961 if (Instruction *Result = commonCastTransforms(CI))
8966 // Get rid of casts from one type to the same type. These are useless and can
8967 // be replaced by the operand.
8968 if (DestTy == Src->getType())
8969 return ReplaceInstUsesWith(CI, Src);
8971 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8972 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8973 const Type *DstElTy = DstPTy->getElementType();
8974 const Type *SrcElTy = SrcPTy->getElementType();
8976 // If the address spaces don't match, don't eliminate the bitcast, which is
8977 // required for changing types.
8978 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8981 // If we are casting a alloca to a pointer to a type of the same
8982 // size, rewrite the allocation instruction to allocate the "right" type.
8983 // There is no need to modify malloc calls because it is their bitcast that
8984 // needs to be cleaned up.
8985 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
8986 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8989 // If the source and destination are pointers, and this cast is equivalent
8990 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8991 // This can enhance SROA and other transforms that want type-safe pointers.
8992 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8993 unsigned NumZeros = 0;
8994 while (SrcElTy != DstElTy &&
8995 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8996 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8997 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9001 // If we found a path from the src to dest, create the getelementptr now.
9002 if (SrcElTy == DstElTy) {
9003 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9004 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9005 ((Instruction*) NULL));
9009 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9010 if (DestVTy->getNumElements() == 1) {
9011 if (!isa<VectorType>(SrcTy)) {
9012 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
9013 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9014 Constant::getNullValue(Type::getInt32Ty(*Context)));
9016 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9020 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9021 if (SrcVTy->getNumElements() == 1) {
9022 if (!isa<VectorType>(DestTy)) {
9024 Builder->CreateExtractElement(Src,
9025 Constant::getNullValue(Type::getInt32Ty(*Context)));
9026 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9031 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9032 if (SVI->hasOneUse()) {
9033 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9034 // a bitconvert to a vector with the same # elts.
9035 if (isa<VectorType>(DestTy) &&
9036 cast<VectorType>(DestTy)->getNumElements() ==
9037 SVI->getType()->getNumElements() &&
9038 SVI->getType()->getNumElements() ==
9039 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9041 // If either of the operands is a cast from CI.getType(), then
9042 // evaluating the shuffle in the casted destination's type will allow
9043 // us to eliminate at least one cast.
9044 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9045 Tmp->getOperand(0)->getType() == DestTy) ||
9046 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9047 Tmp->getOperand(0)->getType() == DestTy)) {
9048 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9049 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
9050 // Return a new shuffle vector. Use the same element ID's, as we
9051 // know the vector types match #elts.
9052 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9060 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9062 /// %D = select %cond, %C, %A
9064 /// %C = select %cond, %B, 0
9067 /// Assuming that the specified instruction is an operand to the select, return
9068 /// a bitmask indicating which operands of this instruction are foldable if they
9069 /// equal the other incoming value of the select.
9071 static unsigned GetSelectFoldableOperands(Instruction *I) {
9072 switch (I->getOpcode()) {
9073 case Instruction::Add:
9074 case Instruction::Mul:
9075 case Instruction::And:
9076 case Instruction::Or:
9077 case Instruction::Xor:
9078 return 3; // Can fold through either operand.
9079 case Instruction::Sub: // Can only fold on the amount subtracted.
9080 case Instruction::Shl: // Can only fold on the shift amount.
9081 case Instruction::LShr:
9082 case Instruction::AShr:
9085 return 0; // Cannot fold
9089 /// GetSelectFoldableConstant - For the same transformation as the previous
9090 /// function, return the identity constant that goes into the select.
9091 static Constant *GetSelectFoldableConstant(Instruction *I,
9092 LLVMContext *Context) {
9093 switch (I->getOpcode()) {
9094 default: llvm_unreachable("This cannot happen!");
9095 case Instruction::Add:
9096 case Instruction::Sub:
9097 case Instruction::Or:
9098 case Instruction::Xor:
9099 case Instruction::Shl:
9100 case Instruction::LShr:
9101 case Instruction::AShr:
9102 return Constant::getNullValue(I->getType());
9103 case Instruction::And:
9104 return Constant::getAllOnesValue(I->getType());
9105 case Instruction::Mul:
9106 return ConstantInt::get(I->getType(), 1);
9110 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9111 /// have the same opcode and only one use each. Try to simplify this.
9112 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9114 if (TI->getNumOperands() == 1) {
9115 // If this is a non-volatile load or a cast from the same type,
9118 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9121 return 0; // unknown unary op.
9124 // Fold this by inserting a select from the input values.
9125 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9126 FI->getOperand(0), SI.getName()+".v");
9127 InsertNewInstBefore(NewSI, SI);
9128 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
9132 // Only handle binary operators here.
9133 if (!isa<BinaryOperator>(TI))
9136 // Figure out if the operations have any operands in common.
9137 Value *MatchOp, *OtherOpT, *OtherOpF;
9139 if (TI->getOperand(0) == FI->getOperand(0)) {
9140 MatchOp = TI->getOperand(0);
9141 OtherOpT = TI->getOperand(1);
9142 OtherOpF = FI->getOperand(1);
9143 MatchIsOpZero = true;
9144 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9145 MatchOp = TI->getOperand(1);
9146 OtherOpT = TI->getOperand(0);
9147 OtherOpF = FI->getOperand(0);
9148 MatchIsOpZero = false;
9149 } else if (!TI->isCommutative()) {
9151 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9152 MatchOp = TI->getOperand(0);
9153 OtherOpT = TI->getOperand(1);
9154 OtherOpF = FI->getOperand(0);
9155 MatchIsOpZero = true;
9156 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9157 MatchOp = TI->getOperand(1);
9158 OtherOpT = TI->getOperand(0);
9159 OtherOpF = FI->getOperand(1);
9160 MatchIsOpZero = true;
9165 // If we reach here, they do have operations in common.
9166 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9167 OtherOpF, SI.getName()+".v");
9168 InsertNewInstBefore(NewSI, SI);
9170 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9172 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9174 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9176 llvm_unreachable("Shouldn't get here");
9180 static bool isSelect01(Constant *C1, Constant *C2) {
9181 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9184 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9187 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9190 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9191 /// facilitate further optimization.
9192 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9194 // See the comment above GetSelectFoldableOperands for a description of the
9195 // transformation we are doing here.
9196 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9197 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9198 !isa<Constant>(FalseVal)) {
9199 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9200 unsigned OpToFold = 0;
9201 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9203 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9208 Constant *C = GetSelectFoldableConstant(TVI, Context);
9209 Value *OOp = TVI->getOperand(2-OpToFold);
9210 // Avoid creating select between 2 constants unless it's selecting
9212 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9213 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9214 InsertNewInstBefore(NewSel, SI);
9215 NewSel->takeName(TVI);
9216 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9217 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9218 llvm_unreachable("Unknown instruction!!");
9225 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9226 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9227 !isa<Constant>(TrueVal)) {
9228 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9229 unsigned OpToFold = 0;
9230 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9232 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9237 Constant *C = GetSelectFoldableConstant(FVI, Context);
9238 Value *OOp = FVI->getOperand(2-OpToFold);
9239 // Avoid creating select between 2 constants unless it's selecting
9241 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9242 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9243 InsertNewInstBefore(NewSel, SI);
9244 NewSel->takeName(FVI);
9245 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9246 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9247 llvm_unreachable("Unknown instruction!!");
9257 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9258 /// ICmpInst as its first operand.
9260 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9262 bool Changed = false;
9263 ICmpInst::Predicate Pred = ICI->getPredicate();
9264 Value *CmpLHS = ICI->getOperand(0);
9265 Value *CmpRHS = ICI->getOperand(1);
9266 Value *TrueVal = SI.getTrueValue();
9267 Value *FalseVal = SI.getFalseValue();
9269 // Check cases where the comparison is with a constant that
9270 // can be adjusted to fit the min/max idiom. We may edit ICI in
9271 // place here, so make sure the select is the only user.
9272 if (ICI->hasOneUse())
9273 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9276 case ICmpInst::ICMP_ULT:
9277 case ICmpInst::ICMP_SLT: {
9278 // X < MIN ? T : F --> F
9279 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9280 return ReplaceInstUsesWith(SI, FalseVal);
9281 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9282 Constant *AdjustedRHS = SubOne(CI);
9283 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9284 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9285 Pred = ICmpInst::getSwappedPredicate(Pred);
9286 CmpRHS = AdjustedRHS;
9287 std::swap(FalseVal, TrueVal);
9288 ICI->setPredicate(Pred);
9289 ICI->setOperand(1, CmpRHS);
9290 SI.setOperand(1, TrueVal);
9291 SI.setOperand(2, FalseVal);
9296 case ICmpInst::ICMP_UGT:
9297 case ICmpInst::ICMP_SGT: {
9298 // X > MAX ? T : F --> F
9299 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9300 return ReplaceInstUsesWith(SI, FalseVal);
9301 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9302 Constant *AdjustedRHS = AddOne(CI);
9303 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9304 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9305 Pred = ICmpInst::getSwappedPredicate(Pred);
9306 CmpRHS = AdjustedRHS;
9307 std::swap(FalseVal, TrueVal);
9308 ICI->setPredicate(Pred);
9309 ICI->setOperand(1, CmpRHS);
9310 SI.setOperand(1, TrueVal);
9311 SI.setOperand(2, FalseVal);
9318 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9319 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9320 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9321 if (match(TrueVal, m_ConstantInt<-1>()) &&
9322 match(FalseVal, m_ConstantInt<0>()))
9323 Pred = ICI->getPredicate();
9324 else if (match(TrueVal, m_ConstantInt<0>()) &&
9325 match(FalseVal, m_ConstantInt<-1>()))
9326 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9328 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9329 // If we are just checking for a icmp eq of a single bit and zext'ing it
9330 // to an integer, then shift the bit to the appropriate place and then
9331 // cast to integer to avoid the comparison.
9332 const APInt &Op1CV = CI->getValue();
9334 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9335 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9336 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9337 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9338 Value *In = ICI->getOperand(0);
9339 Value *Sh = ConstantInt::get(In->getType(),
9340 In->getType()->getScalarSizeInBits()-1);
9341 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9342 In->getName()+".lobit"),
9344 if (In->getType() != SI.getType())
9345 In = CastInst::CreateIntegerCast(In, SI.getType(),
9346 true/*SExt*/, "tmp", ICI);
9348 if (Pred == ICmpInst::ICMP_SGT)
9349 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9350 In->getName()+".not"), *ICI);
9352 return ReplaceInstUsesWith(SI, In);
9357 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9358 // Transform (X == Y) ? X : Y -> Y
9359 if (Pred == ICmpInst::ICMP_EQ)
9360 return ReplaceInstUsesWith(SI, FalseVal);
9361 // Transform (X != Y) ? X : Y -> X
9362 if (Pred == ICmpInst::ICMP_NE)
9363 return ReplaceInstUsesWith(SI, TrueVal);
9364 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9366 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9367 // Transform (X == Y) ? Y : X -> X
9368 if (Pred == ICmpInst::ICMP_EQ)
9369 return ReplaceInstUsesWith(SI, FalseVal);
9370 // Transform (X != Y) ? Y : X -> Y
9371 if (Pred == ICmpInst::ICMP_NE)
9372 return ReplaceInstUsesWith(SI, TrueVal);
9373 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9376 /// NOTE: if we wanted to, this is where to detect integer ABS
9378 return Changed ? &SI : 0;
9382 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9383 /// PHI node (but the two may be in different blocks). See if the true/false
9384 /// values (V) are live in all of the predecessor blocks of the PHI. For
9385 /// example, cases like this cannot be mapped:
9387 /// X = phi [ C1, BB1], [C2, BB2]
9389 /// Z = select X, Y, 0
9391 /// because Y is not live in BB1/BB2.
9393 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9394 const SelectInst &SI) {
9395 // If the value is a non-instruction value like a constant or argument, it
9396 // can always be mapped.
9397 const Instruction *I = dyn_cast<Instruction>(V);
9398 if (I == 0) return true;
9400 // If V is a PHI node defined in the same block as the condition PHI, we can
9401 // map the arguments.
9402 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9404 if (const PHINode *VP = dyn_cast<PHINode>(I))
9405 if (VP->getParent() == CondPHI->getParent())
9408 // Otherwise, if the PHI and select are defined in the same block and if V is
9409 // defined in a different block, then we can transform it.
9410 if (SI.getParent() == CondPHI->getParent() &&
9411 I->getParent() != CondPHI->getParent())
9414 // Otherwise we have a 'hard' case and we can't tell without doing more
9415 // detailed dominator based analysis, punt.
9419 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9420 Value *CondVal = SI.getCondition();
9421 Value *TrueVal = SI.getTrueValue();
9422 Value *FalseVal = SI.getFalseValue();
9424 // select true, X, Y -> X
9425 // select false, X, Y -> Y
9426 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9427 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9429 // select C, X, X -> X
9430 if (TrueVal == FalseVal)
9431 return ReplaceInstUsesWith(SI, TrueVal);
9433 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9434 return ReplaceInstUsesWith(SI, FalseVal);
9435 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9436 return ReplaceInstUsesWith(SI, TrueVal);
9437 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9438 if (isa<Constant>(TrueVal))
9439 return ReplaceInstUsesWith(SI, TrueVal);
9441 return ReplaceInstUsesWith(SI, FalseVal);
9444 if (SI.getType() == Type::getInt1Ty(*Context)) {
9445 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9446 if (C->getZExtValue()) {
9447 // Change: A = select B, true, C --> A = or B, C
9448 return BinaryOperator::CreateOr(CondVal, FalseVal);
9450 // Change: A = select B, false, C --> A = and !B, C
9452 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9453 "not."+CondVal->getName()), SI);
9454 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9456 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9457 if (C->getZExtValue() == false) {
9458 // Change: A = select B, C, false --> A = and B, C
9459 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9461 // Change: A = select B, C, true --> A = or !B, C
9463 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9464 "not."+CondVal->getName()), SI);
9465 return BinaryOperator::CreateOr(NotCond, TrueVal);
9469 // select a, b, a -> a&b
9470 // select a, a, b -> a|b
9471 if (CondVal == TrueVal)
9472 return BinaryOperator::CreateOr(CondVal, FalseVal);
9473 else if (CondVal == FalseVal)
9474 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9477 // Selecting between two integer constants?
9478 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9479 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9480 // select C, 1, 0 -> zext C to int
9481 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9482 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9483 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9484 // select C, 0, 1 -> zext !C to int
9486 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9487 "not."+CondVal->getName()), SI);
9488 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9491 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9492 // If one of the constants is zero (we know they can't both be) and we
9493 // have an icmp instruction with zero, and we have an 'and' with the
9494 // non-constant value, eliminate this whole mess. This corresponds to
9495 // cases like this: ((X & 27) ? 27 : 0)
9496 if (TrueValC->isZero() || FalseValC->isZero())
9497 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9498 cast<Constant>(IC->getOperand(1))->isNullValue())
9499 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9500 if (ICA->getOpcode() == Instruction::And &&
9501 isa<ConstantInt>(ICA->getOperand(1)) &&
9502 (ICA->getOperand(1) == TrueValC ||
9503 ICA->getOperand(1) == FalseValC) &&
9504 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9505 // Okay, now we know that everything is set up, we just don't
9506 // know whether we have a icmp_ne or icmp_eq and whether the
9507 // true or false val is the zero.
9508 bool ShouldNotVal = !TrueValC->isZero();
9509 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9512 V = InsertNewInstBefore(BinaryOperator::Create(
9513 Instruction::Xor, V, ICA->getOperand(1)), SI);
9514 return ReplaceInstUsesWith(SI, V);
9519 // See if we are selecting two values based on a comparison of the two values.
9520 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9521 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9522 // Transform (X == Y) ? X : Y -> Y
9523 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9524 // This is not safe in general for floating point:
9525 // consider X== -0, Y== +0.
9526 // It becomes safe if either operand is a nonzero constant.
9527 ConstantFP *CFPt, *CFPf;
9528 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9529 !CFPt->getValueAPF().isZero()) ||
9530 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9531 !CFPf->getValueAPF().isZero()))
9532 return ReplaceInstUsesWith(SI, FalseVal);
9534 // Transform (X != Y) ? X : Y -> X
9535 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9536 return ReplaceInstUsesWith(SI, TrueVal);
9537 // NOTE: if we wanted to, this is where to detect MIN/MAX
9539 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9540 // Transform (X == Y) ? Y : X -> X
9541 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9542 // This is not safe in general for floating point:
9543 // consider X== -0, Y== +0.
9544 // It becomes safe if either operand is a nonzero constant.
9545 ConstantFP *CFPt, *CFPf;
9546 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9547 !CFPt->getValueAPF().isZero()) ||
9548 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9549 !CFPf->getValueAPF().isZero()))
9550 return ReplaceInstUsesWith(SI, FalseVal);
9552 // Transform (X != Y) ? Y : X -> Y
9553 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9554 return ReplaceInstUsesWith(SI, TrueVal);
9555 // NOTE: if we wanted to, this is where to detect MIN/MAX
9557 // NOTE: if we wanted to, this is where to detect ABS
9560 // See if we are selecting two values based on a comparison of the two values.
9561 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9562 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9565 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9566 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9567 if (TI->hasOneUse() && FI->hasOneUse()) {
9568 Instruction *AddOp = 0, *SubOp = 0;
9570 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9571 if (TI->getOpcode() == FI->getOpcode())
9572 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9575 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9576 // even legal for FP.
9577 if ((TI->getOpcode() == Instruction::Sub &&
9578 FI->getOpcode() == Instruction::Add) ||
9579 (TI->getOpcode() == Instruction::FSub &&
9580 FI->getOpcode() == Instruction::FAdd)) {
9581 AddOp = FI; SubOp = TI;
9582 } else if ((FI->getOpcode() == Instruction::Sub &&
9583 TI->getOpcode() == Instruction::Add) ||
9584 (FI->getOpcode() == Instruction::FSub &&
9585 TI->getOpcode() == Instruction::FAdd)) {
9586 AddOp = TI; SubOp = FI;
9590 Value *OtherAddOp = 0;
9591 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9592 OtherAddOp = AddOp->getOperand(1);
9593 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9594 OtherAddOp = AddOp->getOperand(0);
9598 // So at this point we know we have (Y -> OtherAddOp):
9599 // select C, (add X, Y), (sub X, Z)
9600 Value *NegVal; // Compute -Z
9601 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9602 NegVal = ConstantExpr::getNeg(C);
9604 NegVal = InsertNewInstBefore(
9605 BinaryOperator::CreateNeg(SubOp->getOperand(1),
9609 Value *NewTrueOp = OtherAddOp;
9610 Value *NewFalseOp = NegVal;
9612 std::swap(NewTrueOp, NewFalseOp);
9613 Instruction *NewSel =
9614 SelectInst::Create(CondVal, NewTrueOp,
9615 NewFalseOp, SI.getName() + ".p");
9617 NewSel = InsertNewInstBefore(NewSel, SI);
9618 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9623 // See if we can fold the select into one of our operands.
9624 if (SI.getType()->isInteger()) {
9625 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9630 // See if we can fold the select into a phi node if the condition is a select.
9631 if (isa<PHINode>(SI.getCondition()))
9632 // The true/false values have to be live in the PHI predecessor's blocks.
9633 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9634 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9635 if (Instruction *NV = FoldOpIntoPhi(SI))
9638 if (BinaryOperator::isNot(CondVal)) {
9639 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9640 SI.setOperand(1, FalseVal);
9641 SI.setOperand(2, TrueVal);
9648 /// EnforceKnownAlignment - If the specified pointer points to an object that
9649 /// we control, modify the object's alignment to PrefAlign. This isn't
9650 /// often possible though. If alignment is important, a more reliable approach
9651 /// is to simply align all global variables and allocation instructions to
9652 /// their preferred alignment from the beginning.
9654 static unsigned EnforceKnownAlignment(Value *V,
9655 unsigned Align, unsigned PrefAlign) {
9657 User *U = dyn_cast<User>(V);
9658 if (!U) return Align;
9660 switch (Operator::getOpcode(U)) {
9662 case Instruction::BitCast:
9663 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9664 case Instruction::GetElementPtr: {
9665 // If all indexes are zero, it is just the alignment of the base pointer.
9666 bool AllZeroOperands = true;
9667 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9668 if (!isa<Constant>(*i) ||
9669 !cast<Constant>(*i)->isNullValue()) {
9670 AllZeroOperands = false;
9674 if (AllZeroOperands) {
9675 // Treat this like a bitcast.
9676 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9682 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9683 // If there is a large requested alignment and we can, bump up the alignment
9685 if (!GV->isDeclaration()) {
9686 if (GV->getAlignment() >= PrefAlign)
9687 Align = GV->getAlignment();
9689 GV->setAlignment(PrefAlign);
9693 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9694 // If there is a requested alignment and if this is an alloca, round up.
9695 if (AI->getAlignment() >= PrefAlign)
9696 Align = AI->getAlignment();
9698 AI->setAlignment(PrefAlign);
9706 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9707 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9708 /// and it is more than the alignment of the ultimate object, see if we can
9709 /// increase the alignment of the ultimate object, making this check succeed.
9710 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9711 unsigned PrefAlign) {
9712 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9713 sizeof(PrefAlign) * CHAR_BIT;
9714 APInt Mask = APInt::getAllOnesValue(BitWidth);
9715 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9716 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9717 unsigned TrailZ = KnownZero.countTrailingOnes();
9718 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9720 if (PrefAlign > Align)
9721 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9723 // We don't need to make any adjustment.
9727 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9728 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9729 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9730 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9731 unsigned CopyAlign = MI->getAlignment();
9733 if (CopyAlign < MinAlign) {
9734 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9739 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9741 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9742 if (MemOpLength == 0) return 0;
9744 // Source and destination pointer types are always "i8*" for intrinsic. See
9745 // if the size is something we can handle with a single primitive load/store.
9746 // A single load+store correctly handles overlapping memory in the memmove
9748 unsigned Size = MemOpLength->getZExtValue();
9749 if (Size == 0) return MI; // Delete this mem transfer.
9751 if (Size > 8 || (Size&(Size-1)))
9752 return 0; // If not 1/2/4/8 bytes, exit.
9754 // Use an integer load+store unless we can find something better.
9756 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9758 // Memcpy forces the use of i8* for the source and destination. That means
9759 // that if you're using memcpy to move one double around, you'll get a cast
9760 // from double* to i8*. We'd much rather use a double load+store rather than
9761 // an i64 load+store, here because this improves the odds that the source or
9762 // dest address will be promotable. See if we can find a better type than the
9763 // integer datatype.
9764 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9765 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9766 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9767 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9768 // down through these levels if so.
9769 while (!SrcETy->isSingleValueType()) {
9770 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9771 if (STy->getNumElements() == 1)
9772 SrcETy = STy->getElementType(0);
9775 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9776 if (ATy->getNumElements() == 1)
9777 SrcETy = ATy->getElementType();
9784 if (SrcETy->isSingleValueType())
9785 NewPtrTy = PointerType::getUnqual(SrcETy);
9790 // If the memcpy/memmove provides better alignment info than we can
9792 SrcAlign = std::max(SrcAlign, CopyAlign);
9793 DstAlign = std::max(DstAlign, CopyAlign);
9795 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9796 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9797 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9798 InsertNewInstBefore(L, *MI);
9799 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9801 // Set the size of the copy to 0, it will be deleted on the next iteration.
9802 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9806 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9807 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9808 if (MI->getAlignment() < Alignment) {
9809 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9814 // Extract the length and alignment and fill if they are constant.
9815 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9816 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9817 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9819 uint64_t Len = LenC->getZExtValue();
9820 Alignment = MI->getAlignment();
9822 // If the length is zero, this is a no-op
9823 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9825 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9826 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9827 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
9829 Value *Dest = MI->getDest();
9830 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9832 // Alignment 0 is identity for alignment 1 for memset, but not store.
9833 if (Alignment == 0) Alignment = 1;
9835 // Extract the fill value and store.
9836 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9837 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9838 Dest, false, Alignment), *MI);
9840 // Set the size of the copy to 0, it will be deleted on the next iteration.
9841 MI->setLength(Constant::getNullValue(LenC->getType()));
9849 /// visitCallInst - CallInst simplification. This mostly only handles folding
9850 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9851 /// the heavy lifting.
9853 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9854 if (isFreeCall(&CI))
9855 return visitFree(CI);
9857 // If the caller function is nounwind, mark the call as nounwind, even if the
9859 if (CI.getParent()->getParent()->doesNotThrow() &&
9860 !CI.doesNotThrow()) {
9861 CI.setDoesNotThrow();
9865 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9866 if (!II) return visitCallSite(&CI);
9868 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9870 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9871 bool Changed = false;
9873 // memmove/cpy/set of zero bytes is a noop.
9874 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9875 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9877 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9878 if (CI->getZExtValue() == 1) {
9879 // Replace the instruction with just byte operations. We would
9880 // transform other cases to loads/stores, but we don't know if
9881 // alignment is sufficient.
9885 // If we have a memmove and the source operation is a constant global,
9886 // then the source and dest pointers can't alias, so we can change this
9887 // into a call to memcpy.
9888 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9889 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9890 if (GVSrc->isConstant()) {
9891 Module *M = CI.getParent()->getParent()->getParent();
9892 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9894 Tys[0] = CI.getOperand(3)->getType();
9896 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9901 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
9902 // memmove(x,x,size) -> noop.
9903 if (MTI->getSource() == MTI->getDest())
9904 return EraseInstFromFunction(CI);
9907 // If we can determine a pointer alignment that is bigger than currently
9908 // set, update the alignment.
9909 if (isa<MemTransferInst>(MI)) {
9910 if (Instruction *I = SimplifyMemTransfer(MI))
9912 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9913 if (Instruction *I = SimplifyMemSet(MSI))
9917 if (Changed) return II;
9920 switch (II->getIntrinsicID()) {
9922 case Intrinsic::bswap:
9923 // bswap(bswap(x)) -> x
9924 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9925 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9926 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9928 case Intrinsic::uadd_with_overflow: {
9929 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
9930 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
9931 uint32_t BitWidth = IT->getBitWidth();
9932 APInt Mask = APInt::getSignBit(BitWidth);
9933 APInt LHSKnownZero(BitWidth, 0);
9934 APInt LHSKnownOne(BitWidth, 0);
9935 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
9936 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
9937 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
9939 if (LHSKnownNegative || LHSKnownPositive) {
9940 APInt RHSKnownZero(BitWidth, 0);
9941 APInt RHSKnownOne(BitWidth, 0);
9942 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
9943 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
9944 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
9945 if (LHSKnownNegative && RHSKnownNegative) {
9946 // The sign bit is set in both cases: this MUST overflow.
9947 // Create a simple add instruction, and insert it into the struct.
9948 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
9951 UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
9953 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9954 return InsertValueInst::Create(Struct, Add, 0);
9957 if (LHSKnownPositive && RHSKnownPositive) {
9958 // The sign bit is clear in both cases: this CANNOT overflow.
9959 // Create a simple add instruction, and insert it into the struct.
9960 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
9963 UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
9965 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9966 return InsertValueInst::Create(Struct, Add, 0);
9970 // FALL THROUGH uadd into sadd
9971 case Intrinsic::sadd_with_overflow:
9972 // Canonicalize constants into the RHS.
9973 if (isa<Constant>(II->getOperand(1)) &&
9974 !isa<Constant>(II->getOperand(2))) {
9975 Value *LHS = II->getOperand(1);
9976 II->setOperand(1, II->getOperand(2));
9977 II->setOperand(2, LHS);
9981 // X + undef -> undef
9982 if (isa<UndefValue>(II->getOperand(2)))
9983 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
9985 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
9986 // X + 0 -> {X, false}
9987 if (RHS->isZero()) {
9989 UndefValue::get(II->getOperand(0)->getType()),
9990 ConstantInt::getFalse(*Context)
9992 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9993 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
9997 case Intrinsic::usub_with_overflow:
9998 case Intrinsic::ssub_with_overflow:
9999 // undef - X -> undef
10000 // X - undef -> undef
10001 if (isa<UndefValue>(II->getOperand(1)) ||
10002 isa<UndefValue>(II->getOperand(2)))
10003 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10005 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10006 // X - 0 -> {X, false}
10007 if (RHS->isZero()) {
10009 UndefValue::get(II->getOperand(1)->getType()),
10010 ConstantInt::getFalse(*Context)
10012 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10013 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10017 case Intrinsic::umul_with_overflow:
10018 case Intrinsic::smul_with_overflow:
10019 // Canonicalize constants into the RHS.
10020 if (isa<Constant>(II->getOperand(1)) &&
10021 !isa<Constant>(II->getOperand(2))) {
10022 Value *LHS = II->getOperand(1);
10023 II->setOperand(1, II->getOperand(2));
10024 II->setOperand(2, LHS);
10028 // X * undef -> undef
10029 if (isa<UndefValue>(II->getOperand(2)))
10030 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10032 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10033 // X*0 -> {0, false}
10034 if (RHSI->isZero())
10035 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10037 // X * 1 -> {X, false}
10038 if (RHSI->equalsInt(1)) {
10040 UndefValue::get(II->getOperand(1)->getType()),
10041 ConstantInt::getFalse(*Context)
10043 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10044 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10048 case Intrinsic::ppc_altivec_lvx:
10049 case Intrinsic::ppc_altivec_lvxl:
10050 case Intrinsic::x86_sse_loadu_ps:
10051 case Intrinsic::x86_sse2_loadu_pd:
10052 case Intrinsic::x86_sse2_loadu_dq:
10053 // Turn PPC lvx -> load if the pointer is known aligned.
10054 // Turn X86 loadups -> load if the pointer is known aligned.
10055 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10056 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10057 PointerType::getUnqual(II->getType()));
10058 return new LoadInst(Ptr);
10061 case Intrinsic::ppc_altivec_stvx:
10062 case Intrinsic::ppc_altivec_stvxl:
10063 // Turn stvx -> store if the pointer is known aligned.
10064 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10065 const Type *OpPtrTy =
10066 PointerType::getUnqual(II->getOperand(1)->getType());
10067 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
10068 return new StoreInst(II->getOperand(1), Ptr);
10071 case Intrinsic::x86_sse_storeu_ps:
10072 case Intrinsic::x86_sse2_storeu_pd:
10073 case Intrinsic::x86_sse2_storeu_dq:
10074 // Turn X86 storeu -> store if the pointer is known aligned.
10075 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10076 const Type *OpPtrTy =
10077 PointerType::getUnqual(II->getOperand(2)->getType());
10078 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
10079 return new StoreInst(II->getOperand(2), Ptr);
10083 case Intrinsic::x86_sse_cvttss2si: {
10084 // These intrinsics only demands the 0th element of its input vector. If
10085 // we can simplify the input based on that, do so now.
10087 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10088 APInt DemandedElts(VWidth, 1);
10089 APInt UndefElts(VWidth, 0);
10090 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
10092 II->setOperand(1, V);
10098 case Intrinsic::ppc_altivec_vperm:
10099 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10100 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10101 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
10103 // Check that all of the elements are integer constants or undefs.
10104 bool AllEltsOk = true;
10105 for (unsigned i = 0; i != 16; ++i) {
10106 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10107 !isa<UndefValue>(Mask->getOperand(i))) {
10114 // Cast the input vectors to byte vectors.
10115 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10116 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
10117 Value *Result = UndefValue::get(Op0->getType());
10119 // Only extract each element once.
10120 Value *ExtractedElts[32];
10121 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10123 for (unsigned i = 0; i != 16; ++i) {
10124 if (isa<UndefValue>(Mask->getOperand(i)))
10126 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10127 Idx &= 31; // Match the hardware behavior.
10129 if (ExtractedElts[Idx] == 0) {
10130 ExtractedElts[Idx] =
10131 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10132 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10136 // Insert this value into the result vector.
10137 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10138 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10141 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
10146 case Intrinsic::stackrestore: {
10147 // If the save is right next to the restore, remove the restore. This can
10148 // happen when variable allocas are DCE'd.
10149 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10150 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10151 BasicBlock::iterator BI = SS;
10153 return EraseInstFromFunction(CI);
10157 // Scan down this block to see if there is another stack restore in the
10158 // same block without an intervening call/alloca.
10159 BasicBlock::iterator BI = II;
10160 TerminatorInst *TI = II->getParent()->getTerminator();
10161 bool CannotRemove = false;
10162 for (++BI; &*BI != TI; ++BI) {
10163 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
10164 CannotRemove = true;
10167 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10168 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10169 // If there is a stackrestore below this one, remove this one.
10170 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10171 return EraseInstFromFunction(CI);
10172 // Otherwise, ignore the intrinsic.
10174 // If we found a non-intrinsic call, we can't remove the stack
10176 CannotRemove = true;
10182 // If the stack restore is in a return/unwind block and if there are no
10183 // allocas or calls between the restore and the return, nuke the restore.
10184 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10185 return EraseInstFromFunction(CI);
10190 return visitCallSite(II);
10193 // InvokeInst simplification
10195 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10196 return visitCallSite(&II);
10199 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
10200 /// passed through the varargs area, we can eliminate the use of the cast.
10201 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10202 const CastInst * const CI,
10203 const TargetData * const TD,
10205 if (!CI->isLosslessCast())
10208 // The size of ByVal arguments is derived from the type, so we
10209 // can't change to a type with a different size. If the size were
10210 // passed explicitly we could avoid this check.
10211 if (!CS.paramHasAttr(ix, Attribute::ByVal))
10214 const Type* SrcTy =
10215 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10216 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10217 if (!SrcTy->isSized() || !DstTy->isSized())
10219 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10224 // visitCallSite - Improvements for call and invoke instructions.
10226 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10227 bool Changed = false;
10229 // If the callee is a constexpr cast of a function, attempt to move the cast
10230 // to the arguments of the call/invoke.
10231 if (transformConstExprCastCall(CS)) return 0;
10233 Value *Callee = CS.getCalledValue();
10235 if (Function *CalleeF = dyn_cast<Function>(Callee))
10236 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10237 Instruction *OldCall = CS.getInstruction();
10238 // If the call and callee calling conventions don't match, this call must
10239 // be unreachable, as the call is undefined.
10240 new StoreInst(ConstantInt::getTrue(*Context),
10241 UndefValue::get(Type::getInt1PtrTy(*Context)),
10243 // If OldCall dues not return void then replaceAllUsesWith undef.
10244 // This allows ValueHandlers and custom metadata to adjust itself.
10245 if (!OldCall->getType()->isVoidTy())
10246 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10247 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10248 return EraseInstFromFunction(*OldCall);
10252 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10253 // This instruction is not reachable, just remove it. We insert a store to
10254 // undef so that we know that this code is not reachable, despite the fact
10255 // that we can't modify the CFG here.
10256 new StoreInst(ConstantInt::getTrue(*Context),
10257 UndefValue::get(Type::getInt1PtrTy(*Context)),
10258 CS.getInstruction());
10260 // If CS dues not return void then replaceAllUsesWith undef.
10261 // This allows ValueHandlers and custom metadata to adjust itself.
10262 if (!CS.getInstruction()->getType()->isVoidTy())
10263 CS.getInstruction()->
10264 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10266 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10267 // Don't break the CFG, insert a dummy cond branch.
10268 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10269 ConstantInt::getTrue(*Context), II);
10271 return EraseInstFromFunction(*CS.getInstruction());
10274 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10275 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10276 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10277 return transformCallThroughTrampoline(CS);
10279 const PointerType *PTy = cast<PointerType>(Callee->getType());
10280 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10281 if (FTy->isVarArg()) {
10282 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10283 // See if we can optimize any arguments passed through the varargs area of
10285 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10286 E = CS.arg_end(); I != E; ++I, ++ix) {
10287 CastInst *CI = dyn_cast<CastInst>(*I);
10288 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10289 *I = CI->getOperand(0);
10295 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10296 // Inline asm calls cannot throw - mark them 'nounwind'.
10297 CS.setDoesNotThrow();
10301 return Changed ? CS.getInstruction() : 0;
10304 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10305 // attempt to move the cast to the arguments of the call/invoke.
10307 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10308 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10309 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10310 if (CE->getOpcode() != Instruction::BitCast ||
10311 !isa<Function>(CE->getOperand(0)))
10313 Function *Callee = cast<Function>(CE->getOperand(0));
10314 Instruction *Caller = CS.getInstruction();
10315 const AttrListPtr &CallerPAL = CS.getAttributes();
10317 // Okay, this is a cast from a function to a different type. Unless doing so
10318 // would cause a type conversion of one of our arguments, change this call to
10319 // be a direct call with arguments casted to the appropriate types.
10321 const FunctionType *FT = Callee->getFunctionType();
10322 const Type *OldRetTy = Caller->getType();
10323 const Type *NewRetTy = FT->getReturnType();
10325 if (isa<StructType>(NewRetTy))
10326 return false; // TODO: Handle multiple return values.
10328 // Check to see if we are changing the return type...
10329 if (OldRetTy != NewRetTy) {
10330 if (Callee->isDeclaration() &&
10331 // Conversion is ok if changing from one pointer type to another or from
10332 // a pointer to an integer of the same size.
10333 !((isa<PointerType>(OldRetTy) || !TD ||
10334 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10335 (isa<PointerType>(NewRetTy) || !TD ||
10336 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10337 return false; // Cannot transform this return value.
10339 if (!Caller->use_empty() &&
10340 // void -> non-void is handled specially
10341 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10342 return false; // Cannot transform this return value.
10344 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10345 Attributes RAttrs = CallerPAL.getRetAttributes();
10346 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10347 return false; // Attribute not compatible with transformed value.
10350 // If the callsite is an invoke instruction, and the return value is used by
10351 // a PHI node in a successor, we cannot change the return type of the call
10352 // because there is no place to put the cast instruction (without breaking
10353 // the critical edge). Bail out in this case.
10354 if (!Caller->use_empty())
10355 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10356 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10358 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10359 if (PN->getParent() == II->getNormalDest() ||
10360 PN->getParent() == II->getUnwindDest())
10364 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10365 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10367 CallSite::arg_iterator AI = CS.arg_begin();
10368 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10369 const Type *ParamTy = FT->getParamType(i);
10370 const Type *ActTy = (*AI)->getType();
10372 if (!CastInst::isCastable(ActTy, ParamTy))
10373 return false; // Cannot transform this parameter value.
10375 if (CallerPAL.getParamAttributes(i + 1)
10376 & Attribute::typeIncompatible(ParamTy))
10377 return false; // Attribute not compatible with transformed value.
10379 // Converting from one pointer type to another or between a pointer and an
10380 // integer of the same size is safe even if we do not have a body.
10381 bool isConvertible = ActTy == ParamTy ||
10382 (TD && ((isa<PointerType>(ParamTy) ||
10383 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10384 (isa<PointerType>(ActTy) ||
10385 ActTy == TD->getIntPtrType(Caller->getContext()))));
10386 if (Callee->isDeclaration() && !isConvertible) return false;
10389 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10390 Callee->isDeclaration())
10391 return false; // Do not delete arguments unless we have a function body.
10393 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10394 !CallerPAL.isEmpty())
10395 // In this case we have more arguments than the new function type, but we
10396 // won't be dropping them. Check that these extra arguments have attributes
10397 // that are compatible with being a vararg call argument.
10398 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10399 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10401 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10402 if (PAttrs & Attribute::VarArgsIncompatible)
10406 // Okay, we decided that this is a safe thing to do: go ahead and start
10407 // inserting cast instructions as necessary...
10408 std::vector<Value*> Args;
10409 Args.reserve(NumActualArgs);
10410 SmallVector<AttributeWithIndex, 8> attrVec;
10411 attrVec.reserve(NumCommonArgs);
10413 // Get any return attributes.
10414 Attributes RAttrs = CallerPAL.getRetAttributes();
10416 // If the return value is not being used, the type may not be compatible
10417 // with the existing attributes. Wipe out any problematic attributes.
10418 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10420 // Add the new return attributes.
10422 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10424 AI = CS.arg_begin();
10425 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10426 const Type *ParamTy = FT->getParamType(i);
10427 if ((*AI)->getType() == ParamTy) {
10428 Args.push_back(*AI);
10430 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10431 false, ParamTy, false);
10432 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10435 // Add any parameter attributes.
10436 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10437 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10440 // If the function takes more arguments than the call was taking, add them
10442 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10443 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10445 // If we are removing arguments to the function, emit an obnoxious warning.
10446 if (FT->getNumParams() < NumActualArgs) {
10447 if (!FT->isVarArg()) {
10448 errs() << "WARNING: While resolving call to function '"
10449 << Callee->getName() << "' arguments were dropped!\n";
10451 // Add all of the arguments in their promoted form to the arg list.
10452 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10453 const Type *PTy = getPromotedType((*AI)->getType());
10454 if (PTy != (*AI)->getType()) {
10455 // Must promote to pass through va_arg area!
10456 Instruction::CastOps opcode =
10457 CastInst::getCastOpcode(*AI, false, PTy, false);
10458 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10460 Args.push_back(*AI);
10463 // Add any parameter attributes.
10464 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10465 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10470 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10471 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10473 if (NewRetTy->isVoidTy())
10474 Caller->setName(""); // Void type should not have a name.
10476 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10480 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10481 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10482 Args.begin(), Args.end(),
10483 Caller->getName(), Caller);
10484 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10485 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10487 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10488 Caller->getName(), Caller);
10489 CallInst *CI = cast<CallInst>(Caller);
10490 if (CI->isTailCall())
10491 cast<CallInst>(NC)->setTailCall();
10492 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10493 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10496 // Insert a cast of the return type as necessary.
10498 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10499 if (!NV->getType()->isVoidTy()) {
10500 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10502 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10504 // If this is an invoke instruction, we should insert it after the first
10505 // non-phi, instruction in the normal successor block.
10506 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10507 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10508 InsertNewInstBefore(NC, *I);
10510 // Otherwise, it's a call, just insert cast right after the call instr
10511 InsertNewInstBefore(NC, *Caller);
10513 Worklist.AddUsersToWorkList(*Caller);
10515 NV = UndefValue::get(Caller->getType());
10520 if (!Caller->use_empty())
10521 Caller->replaceAllUsesWith(NV);
10523 EraseInstFromFunction(*Caller);
10527 // transformCallThroughTrampoline - Turn a call to a function created by the
10528 // init_trampoline intrinsic into a direct call to the underlying function.
10530 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10531 Value *Callee = CS.getCalledValue();
10532 const PointerType *PTy = cast<PointerType>(Callee->getType());
10533 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10534 const AttrListPtr &Attrs = CS.getAttributes();
10536 // If the call already has the 'nest' attribute somewhere then give up -
10537 // otherwise 'nest' would occur twice after splicing in the chain.
10538 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10541 IntrinsicInst *Tramp =
10542 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10544 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10545 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10546 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10548 const AttrListPtr &NestAttrs = NestF->getAttributes();
10549 if (!NestAttrs.isEmpty()) {
10550 unsigned NestIdx = 1;
10551 const Type *NestTy = 0;
10552 Attributes NestAttr = Attribute::None;
10554 // Look for a parameter marked with the 'nest' attribute.
10555 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10556 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10557 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10558 // Record the parameter type and any other attributes.
10560 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10565 Instruction *Caller = CS.getInstruction();
10566 std::vector<Value*> NewArgs;
10567 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10569 SmallVector<AttributeWithIndex, 8> NewAttrs;
10570 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10572 // Insert the nest argument into the call argument list, which may
10573 // mean appending it. Likewise for attributes.
10575 // Add any result attributes.
10576 if (Attributes Attr = Attrs.getRetAttributes())
10577 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10581 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10583 if (Idx == NestIdx) {
10584 // Add the chain argument and attributes.
10585 Value *NestVal = Tramp->getOperand(3);
10586 if (NestVal->getType() != NestTy)
10587 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10588 NewArgs.push_back(NestVal);
10589 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10595 // Add the original argument and attributes.
10596 NewArgs.push_back(*I);
10597 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10599 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10605 // Add any function attributes.
10606 if (Attributes Attr = Attrs.getFnAttributes())
10607 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10609 // The trampoline may have been bitcast to a bogus type (FTy).
10610 // Handle this by synthesizing a new function type, equal to FTy
10611 // with the chain parameter inserted.
10613 std::vector<const Type*> NewTypes;
10614 NewTypes.reserve(FTy->getNumParams()+1);
10616 // Insert the chain's type into the list of parameter types, which may
10617 // mean appending it.
10620 FunctionType::param_iterator I = FTy->param_begin(),
10621 E = FTy->param_end();
10624 if (Idx == NestIdx)
10625 // Add the chain's type.
10626 NewTypes.push_back(NestTy);
10631 // Add the original type.
10632 NewTypes.push_back(*I);
10638 // Replace the trampoline call with a direct call. Let the generic
10639 // code sort out any function type mismatches.
10640 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
10642 Constant *NewCallee =
10643 NestF->getType() == PointerType::getUnqual(NewFTy) ?
10644 NestF : ConstantExpr::getBitCast(NestF,
10645 PointerType::getUnqual(NewFTy));
10646 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10649 Instruction *NewCaller;
10650 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10651 NewCaller = InvokeInst::Create(NewCallee,
10652 II->getNormalDest(), II->getUnwindDest(),
10653 NewArgs.begin(), NewArgs.end(),
10654 Caller->getName(), Caller);
10655 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10656 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10658 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10659 Caller->getName(), Caller);
10660 if (cast<CallInst>(Caller)->isTailCall())
10661 cast<CallInst>(NewCaller)->setTailCall();
10662 cast<CallInst>(NewCaller)->
10663 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10664 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10666 if (!Caller->getType()->isVoidTy())
10667 Caller->replaceAllUsesWith(NewCaller);
10668 Caller->eraseFromParent();
10669 Worklist.Remove(Caller);
10674 // Replace the trampoline call with a direct call. Since there is no 'nest'
10675 // parameter, there is no need to adjust the argument list. Let the generic
10676 // code sort out any function type mismatches.
10677 Constant *NewCallee =
10678 NestF->getType() == PTy ? NestF :
10679 ConstantExpr::getBitCast(NestF, PTy);
10680 CS.setCalledFunction(NewCallee);
10681 return CS.getInstruction();
10684 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10685 /// and if a/b/c and the add's all have a single use, turn this into a phi
10686 /// and a single binop.
10687 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10688 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10689 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10690 unsigned Opc = FirstInst->getOpcode();
10691 Value *LHSVal = FirstInst->getOperand(0);
10692 Value *RHSVal = FirstInst->getOperand(1);
10694 const Type *LHSType = LHSVal->getType();
10695 const Type *RHSType = RHSVal->getType();
10697 // Scan to see if all operands are the same opcode, and all have one use.
10698 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10699 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10700 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10701 // Verify type of the LHS matches so we don't fold cmp's of different
10702 // types or GEP's with different index types.
10703 I->getOperand(0)->getType() != LHSType ||
10704 I->getOperand(1)->getType() != RHSType)
10707 // If they are CmpInst instructions, check their predicates
10708 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10709 if (cast<CmpInst>(I)->getPredicate() !=
10710 cast<CmpInst>(FirstInst)->getPredicate())
10713 // Keep track of which operand needs a phi node.
10714 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10715 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10718 // If both LHS and RHS would need a PHI, don't do this transformation,
10719 // because it would increase the number of PHIs entering the block,
10720 // which leads to higher register pressure. This is especially
10721 // bad when the PHIs are in the header of a loop.
10722 if (!LHSVal && !RHSVal)
10725 // Otherwise, this is safe to transform!
10727 Value *InLHS = FirstInst->getOperand(0);
10728 Value *InRHS = FirstInst->getOperand(1);
10729 PHINode *NewLHS = 0, *NewRHS = 0;
10731 NewLHS = PHINode::Create(LHSType,
10732 FirstInst->getOperand(0)->getName() + ".pn");
10733 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10734 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10735 InsertNewInstBefore(NewLHS, PN);
10740 NewRHS = PHINode::Create(RHSType,
10741 FirstInst->getOperand(1)->getName() + ".pn");
10742 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10743 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10744 InsertNewInstBefore(NewRHS, PN);
10748 // Add all operands to the new PHIs.
10749 if (NewLHS || NewRHS) {
10750 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10751 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10753 Value *NewInLHS = InInst->getOperand(0);
10754 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10757 Value *NewInRHS = InInst->getOperand(1);
10758 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10763 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10764 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10765 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10766 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10770 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10771 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10773 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10774 FirstInst->op_end());
10775 // This is true if all GEP bases are allocas and if all indices into them are
10777 bool AllBasePointersAreAllocas = true;
10779 // We don't want to replace this phi if the replacement would require
10780 // more than one phi, which leads to higher register pressure. This is
10781 // especially bad when the PHIs are in the header of a loop.
10782 bool NeededPhi = false;
10784 // Scan to see if all operands are the same opcode, and all have one use.
10785 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10786 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10787 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10788 GEP->getNumOperands() != FirstInst->getNumOperands())
10791 // Keep track of whether or not all GEPs are of alloca pointers.
10792 if (AllBasePointersAreAllocas &&
10793 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10794 !GEP->hasAllConstantIndices()))
10795 AllBasePointersAreAllocas = false;
10797 // Compare the operand lists.
10798 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10799 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10802 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10803 // if one of the PHIs has a constant for the index. The index may be
10804 // substantially cheaper to compute for the constants, so making it a
10805 // variable index could pessimize the path. This also handles the case
10806 // for struct indices, which must always be constant.
10807 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10808 isa<ConstantInt>(GEP->getOperand(op)))
10811 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10814 // If we already needed a PHI for an earlier operand, and another operand
10815 // also requires a PHI, we'd be introducing more PHIs than we're
10816 // eliminating, which increases register pressure on entry to the PHI's
10821 FixedOperands[op] = 0; // Needs a PHI.
10826 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10827 // bother doing this transformation. At best, this will just save a bit of
10828 // offset calculation, but all the predecessors will have to materialize the
10829 // stack address into a register anyway. We'd actually rather *clone* the
10830 // load up into the predecessors so that we have a load of a gep of an alloca,
10831 // which can usually all be folded into the load.
10832 if (AllBasePointersAreAllocas)
10835 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10836 // that is variable.
10837 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10839 bool HasAnyPHIs = false;
10840 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10841 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10842 Value *FirstOp = FirstInst->getOperand(i);
10843 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10844 FirstOp->getName()+".pn");
10845 InsertNewInstBefore(NewPN, PN);
10847 NewPN->reserveOperandSpace(e);
10848 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10849 OperandPhis[i] = NewPN;
10850 FixedOperands[i] = NewPN;
10855 // Add all operands to the new PHIs.
10857 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10858 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10859 BasicBlock *InBB = PN.getIncomingBlock(i);
10861 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10862 if (PHINode *OpPhi = OperandPhis[op])
10863 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10867 Value *Base = FixedOperands[0];
10868 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10869 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10870 FixedOperands.end()) :
10871 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10872 FixedOperands.end());
10876 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10877 /// sink the load out of the block that defines it. This means that it must be
10878 /// obvious the value of the load is not changed from the point of the load to
10879 /// the end of the block it is in.
10881 /// Finally, it is safe, but not profitable, to sink a load targetting a
10882 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10884 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10885 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10887 for (++BBI; BBI != E; ++BBI)
10888 if (BBI->mayWriteToMemory())
10891 // Check for non-address taken alloca. If not address-taken already, it isn't
10892 // profitable to do this xform.
10893 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10894 bool isAddressTaken = false;
10895 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10897 if (isa<LoadInst>(UI)) continue;
10898 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10899 // If storing TO the alloca, then the address isn't taken.
10900 if (SI->getOperand(1) == AI) continue;
10902 isAddressTaken = true;
10906 if (!isAddressTaken && AI->isStaticAlloca())
10910 // If this load is a load from a GEP with a constant offset from an alloca,
10911 // then we don't want to sink it. In its present form, it will be
10912 // load [constant stack offset]. Sinking it will cause us to have to
10913 // materialize the stack addresses in each predecessor in a register only to
10914 // do a shared load from register in the successor.
10915 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10916 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10917 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10923 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10924 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10926 // When processing loads, we need to propagate two bits of information to the
10927 // sunk load: whether it is volatile, and what its alignment is. We currently
10928 // don't sink loads when some have their alignment specified and some don't.
10929 // visitLoadInst will propagate an alignment onto the load when TD is around,
10930 // and if TD isn't around, we can't handle the mixed case.
10931 bool isVolatile = FirstLI->isVolatile();
10932 unsigned LoadAlignment = FirstLI->getAlignment();
10934 // We can't sink the load if the loaded value could be modified between the
10935 // load and the PHI.
10936 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10937 !isSafeAndProfitableToSinkLoad(FirstLI))
10940 // If the PHI is of volatile loads and the load block has multiple
10941 // successors, sinking it would remove a load of the volatile value from
10942 // the path through the other successor.
10944 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10947 // Check to see if all arguments are the same operation.
10948 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10949 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10950 if (!LI || !LI->hasOneUse())
10953 // We can't sink the load if the loaded value could be modified between
10954 // the load and the PHI.
10955 if (LI->isVolatile() != isVolatile ||
10956 LI->getParent() != PN.getIncomingBlock(i) ||
10957 !isSafeAndProfitableToSinkLoad(LI))
10960 // If some of the loads have an alignment specified but not all of them,
10961 // we can't do the transformation.
10962 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10965 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
10967 // If the PHI is of volatile loads and the load block has multiple
10968 // successors, sinking it would remove a load of the volatile value from
10969 // the path through the other successor.
10971 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10975 // Okay, they are all the same operation. Create a new PHI node of the
10976 // correct type, and PHI together all of the LHS's of the instructions.
10977 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10978 PN.getName()+".in");
10979 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10981 Value *InVal = FirstLI->getOperand(0);
10982 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10984 // Add all operands to the new PHI.
10985 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10986 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10987 if (NewInVal != InVal)
10989 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10994 // The new PHI unions all of the same values together. This is really
10995 // common, so we handle it intelligently here for compile-time speed.
10999 InsertNewInstBefore(NewPN, PN);
11003 // If this was a volatile load that we are merging, make sure to loop through
11004 // and mark all the input loads as non-volatile. If we don't do this, we will
11005 // insert a new volatile load and the old ones will not be deletable.
11007 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11008 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11010 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11015 /// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11016 /// operator and they all are only used by the PHI, PHI together their
11017 /// inputs, and do the operation once, to the result of the PHI.
11018 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11019 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11021 if (isa<GetElementPtrInst>(FirstInst))
11022 return FoldPHIArgGEPIntoPHI(PN);
11023 if (isa<LoadInst>(FirstInst))
11024 return FoldPHIArgLoadIntoPHI(PN);
11026 // Scan the instruction, looking for input operations that can be folded away.
11027 // If all input operands to the phi are the same instruction (e.g. a cast from
11028 // the same type or "+42") we can pull the operation through the PHI, reducing
11029 // code size and simplifying code.
11030 Constant *ConstantOp = 0;
11031 const Type *CastSrcTy = 0;
11033 if (isa<CastInst>(FirstInst)) {
11034 CastSrcTy = FirstInst->getOperand(0)->getType();
11036 // Be careful about transforming integer PHIs. We don't want to pessimize
11037 // the code by turning an i32 into an i1293.
11038 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
11039 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
11042 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
11043 // Can fold binop, compare or shift here if the RHS is a constant,
11044 // otherwise call FoldPHIArgBinOpIntoPHI.
11045 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
11046 if (ConstantOp == 0)
11047 return FoldPHIArgBinOpIntoPHI(PN);
11049 return 0; // Cannot fold this operation.
11052 // Check to see if all arguments are the same operation.
11053 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11054 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11055 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
11058 if (I->getOperand(0)->getType() != CastSrcTy)
11059 return 0; // Cast operation must match.
11060 } else if (I->getOperand(1) != ConstantOp) {
11065 // Okay, they are all the same operation. Create a new PHI node of the
11066 // correct type, and PHI together all of the LHS's of the instructions.
11067 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11068 PN.getName()+".in");
11069 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11071 Value *InVal = FirstInst->getOperand(0);
11072 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11074 // Add all operands to the new PHI.
11075 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11076 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11077 if (NewInVal != InVal)
11079 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11084 // The new PHI unions all of the same values together. This is really
11085 // common, so we handle it intelligently here for compile-time speed.
11089 InsertNewInstBefore(NewPN, PN);
11093 // Insert and return the new operation.
11094 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
11095 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
11097 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
11098 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
11100 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11101 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11102 PhiVal, ConstantOp);
11105 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11107 static bool DeadPHICycle(PHINode *PN,
11108 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
11109 if (PN->use_empty()) return true;
11110 if (!PN->hasOneUse()) return false;
11112 // Remember this node, and if we find the cycle, return.
11113 if (!PotentiallyDeadPHIs.insert(PN))
11116 // Don't scan crazily complex things.
11117 if (PotentiallyDeadPHIs.size() == 16)
11120 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11121 return DeadPHICycle(PU, PotentiallyDeadPHIs);
11126 /// PHIsEqualValue - Return true if this phi node is always equal to
11127 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11128 /// z = some value; x = phi (y, z); y = phi (x, z)
11129 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11130 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11131 // See if we already saw this PHI node.
11132 if (!ValueEqualPHIs.insert(PN))
11135 // Don't scan crazily complex things.
11136 if (ValueEqualPHIs.size() == 16)
11139 // Scan the operands to see if they are either phi nodes or are equal to
11141 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11142 Value *Op = PN->getIncomingValue(i);
11143 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11144 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11146 } else if (Op != NonPhiInVal)
11155 struct PHIUsageRecord {
11156 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
11157 unsigned Shift; // The amount shifted.
11158 Instruction *Inst; // The trunc instruction.
11160 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11161 : PHIId(pn), Shift(Sh), Inst(User) {}
11163 bool operator<(const PHIUsageRecord &RHS) const {
11164 if (PHIId < RHS.PHIId) return true;
11165 if (PHIId > RHS.PHIId) return false;
11166 if (Shift < RHS.Shift) return true;
11167 if (Shift > RHS.Shift) return false;
11168 return Inst->getType()->getPrimitiveSizeInBits() <
11169 RHS.Inst->getType()->getPrimitiveSizeInBits();
11173 struct LoweredPHIRecord {
11174 PHINode *PN; // The PHI that was lowered.
11175 unsigned Shift; // The amount shifted.
11176 unsigned Width; // The width extracted.
11178 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11179 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11181 // Ctor form used by DenseMap.
11182 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11183 : PN(pn), Shift(Sh), Width(0) {}
11189 struct DenseMapInfo<LoweredPHIRecord> {
11190 static inline LoweredPHIRecord getEmptyKey() {
11191 return LoweredPHIRecord(0, 0);
11193 static inline LoweredPHIRecord getTombstoneKey() {
11194 return LoweredPHIRecord(0, 1);
11196 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11197 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11200 static bool isEqual(const LoweredPHIRecord &LHS,
11201 const LoweredPHIRecord &RHS) {
11202 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11203 LHS.Width == RHS.Width;
11207 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
11211 /// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11212 /// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11213 /// so, we split the PHI into the various pieces being extracted. This sort of
11214 /// thing is introduced when SROA promotes an aggregate to large integer values.
11216 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11217 /// inttoptr. We should produce new PHIs in the right type.
11219 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11220 // PHIUsers - Keep track of all of the truncated values extracted from a set
11221 // of PHIs, along with their offset. These are the things we want to rewrite.
11222 SmallVector<PHIUsageRecord, 16> PHIUsers;
11224 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11225 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11226 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11227 // check the uses of (to ensure they are all extracts).
11228 SmallVector<PHINode*, 8> PHIsToSlice;
11229 SmallPtrSet<PHINode*, 8> PHIsInspected;
11231 PHIsToSlice.push_back(&FirstPhi);
11232 PHIsInspected.insert(&FirstPhi);
11234 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11235 PHINode *PN = PHIsToSlice[PHIId];
11237 // Scan the input list of the PHI. If any input is an invoke, and if the
11238 // input is defined in the predecessor, then we won't be split the critical
11239 // edge which is required to insert a truncate. Because of this, we have to
11241 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11242 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11243 if (II == 0) continue;
11244 if (II->getParent() != PN->getIncomingBlock(i))
11247 // If we have a phi, and if it's directly in the predecessor, then we have
11248 // a critical edge where we need to put the truncate. Since we can't
11249 // split the edge in instcombine, we have to bail out.
11254 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11256 Instruction *User = cast<Instruction>(*UI);
11258 // If the user is a PHI, inspect its uses recursively.
11259 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11260 if (PHIsInspected.insert(UserPN))
11261 PHIsToSlice.push_back(UserPN);
11265 // Truncates are always ok.
11266 if (isa<TruncInst>(User)) {
11267 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11271 // Otherwise it must be a lshr which can only be used by one trunc.
11272 if (User->getOpcode() != Instruction::LShr ||
11273 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11274 !isa<ConstantInt>(User->getOperand(1)))
11277 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11278 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
11282 // If we have no users, they must be all self uses, just nuke the PHI.
11283 if (PHIUsers.empty())
11284 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
11286 // If this phi node is transformable, create new PHIs for all the pieces
11287 // extracted out of it. First, sort the users by their offset and size.
11288 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11290 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11291 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11292 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11295 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11296 // hoisted out here to avoid construction/destruction thrashing.
11297 DenseMap<BasicBlock*, Value*> PredValues;
11299 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11300 // introduce redundant PHIs.
11301 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11303 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11304 unsigned PHIId = PHIUsers[UserI].PHIId;
11305 PHINode *PN = PHIsToSlice[PHIId];
11306 unsigned Offset = PHIUsers[UserI].Shift;
11307 const Type *Ty = PHIUsers[UserI].Inst->getType();
11311 // If we've already lowered a user like this, reuse the previously lowered
11313 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
11315 // Otherwise, Create the new PHI node for this user.
11316 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11317 assert(EltPHI->getType() != PN->getType() &&
11318 "Truncate didn't shrink phi?");
11320 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11321 BasicBlock *Pred = PN->getIncomingBlock(i);
11322 Value *&PredVal = PredValues[Pred];
11324 // If we already have a value for this predecessor, reuse it.
11326 EltPHI->addIncoming(PredVal, Pred);
11330 // Handle the PHI self-reuse case.
11331 Value *InVal = PN->getIncomingValue(i);
11334 EltPHI->addIncoming(PredVal, Pred);
11338 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
11339 // If the incoming value was a PHI, and if it was one of the PHIs we
11340 // already rewrote it, just use the lowered value.
11341 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11343 EltPHI->addIncoming(PredVal, Pred);
11348 // Otherwise, do an extract in the predecessor.
11349 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11350 Value *Res = InVal;
11352 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11353 Offset), "extract");
11354 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11356 EltPHI->addIncoming(Res, Pred);
11358 // If the incoming value was a PHI, and if it was one of the PHIs we are
11359 // rewriting, we will ultimately delete the code we inserted. This
11360 // means we need to revisit that PHI to make sure we extract out the
11362 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11363 if (PHIsInspected.count(OldInVal)) {
11364 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11365 OldInVal)-PHIsToSlice.begin();
11366 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11367 cast<Instruction>(Res)));
11371 PredValues.clear();
11373 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11374 << *EltPHI << '\n');
11375 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
11378 // Replace the use of this piece with the PHI node.
11379 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
11382 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11384 Value *Undef = UndefValue::get(FirstPhi.getType());
11385 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11386 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11387 return ReplaceInstUsesWith(FirstPhi, Undef);
11390 // PHINode simplification
11392 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11393 // If LCSSA is around, don't mess with Phi nodes
11394 if (MustPreserveLCSSA) return 0;
11396 if (Value *V = PN.hasConstantValue())
11397 return ReplaceInstUsesWith(PN, V);
11399 // If all PHI operands are the same operation, pull them through the PHI,
11400 // reducing code size.
11401 if (isa<Instruction>(PN.getIncomingValue(0)) &&
11402 isa<Instruction>(PN.getIncomingValue(1)) &&
11403 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11404 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11405 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11406 // than themselves more than once.
11407 PN.getIncomingValue(0)->hasOneUse())
11408 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11411 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11412 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11413 // PHI)... break the cycle.
11414 if (PN.hasOneUse()) {
11415 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11416 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11417 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11418 PotentiallyDeadPHIs.insert(&PN);
11419 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
11420 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11423 // If this phi has a single use, and if that use just computes a value for
11424 // the next iteration of a loop, delete the phi. This occurs with unused
11425 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11426 // common case here is good because the only other things that catch this
11427 // are induction variable analysis (sometimes) and ADCE, which is only run
11429 if (PHIUser->hasOneUse() &&
11430 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11431 PHIUser->use_back() == &PN) {
11432 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11436 // We sometimes end up with phi cycles that non-obviously end up being the
11437 // same value, for example:
11438 // z = some value; x = phi (y, z); y = phi (x, z)
11439 // where the phi nodes don't necessarily need to be in the same block. Do a
11440 // quick check to see if the PHI node only contains a single non-phi value, if
11441 // so, scan to see if the phi cycle is actually equal to that value.
11443 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11444 // Scan for the first non-phi operand.
11445 while (InValNo != NumOperandVals &&
11446 isa<PHINode>(PN.getIncomingValue(InValNo)))
11449 if (InValNo != NumOperandVals) {
11450 Value *NonPhiInVal = PN.getOperand(InValNo);
11452 // Scan the rest of the operands to see if there are any conflicts, if so
11453 // there is no need to recursively scan other phis.
11454 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11455 Value *OpVal = PN.getIncomingValue(InValNo);
11456 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11460 // If we scanned over all operands, then we have one unique value plus
11461 // phi values. Scan PHI nodes to see if they all merge in each other or
11463 if (InValNo == NumOperandVals) {
11464 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11465 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11466 return ReplaceInstUsesWith(PN, NonPhiInVal);
11471 // If there are multiple PHIs, sort their operands so that they all list
11472 // the blocks in the same order. This will help identical PHIs be eliminated
11473 // by other passes. Other passes shouldn't depend on this for correctness
11475 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11476 if (&PN != FirstPN)
11477 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
11478 BasicBlock *BBA = PN.getIncomingBlock(i);
11479 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11481 Value *VA = PN.getIncomingValue(i);
11482 unsigned j = PN.getBasicBlockIndex(BBB);
11483 Value *VB = PN.getIncomingValue(j);
11484 PN.setIncomingBlock(i, BBB);
11485 PN.setIncomingValue(i, VB);
11486 PN.setIncomingBlock(j, BBA);
11487 PN.setIncomingValue(j, VA);
11488 // NOTE: Instcombine normally would want us to "return &PN" if we
11489 // modified any of the operands of an instruction. However, since we
11490 // aren't adding or removing uses (just rearranging them) we don't do
11491 // this in this case.
11495 // If this is an integer PHI and we know that it has an illegal type, see if
11496 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11497 // PHI into the various pieces being extracted. This sort of thing is
11498 // introduced when SROA promotes an aggregate to a single large integer type.
11499 if (isa<IntegerType>(PN.getType()) && TD &&
11500 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11501 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11507 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11508 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11510 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11511 return ReplaceInstUsesWith(GEP, V);
11513 Value *PtrOp = GEP.getOperand(0);
11515 if (isa<UndefValue>(GEP.getOperand(0)))
11516 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11518 // Eliminate unneeded casts for indices.
11520 bool MadeChange = false;
11521 unsigned PtrSize = TD->getPointerSizeInBits();
11523 gep_type_iterator GTI = gep_type_begin(GEP);
11524 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11525 I != E; ++I, ++GTI) {
11526 if (!isa<SequentialType>(*GTI)) continue;
11528 // If we are using a wider index than needed for this platform, shrink it
11529 // to what we need. If narrower, sign-extend it to what we need. This
11530 // explicit cast can make subsequent optimizations more obvious.
11531 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11532 if (OpBits == PtrSize)
11535 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
11538 if (MadeChange) return &GEP;
11541 // Combine Indices - If the source pointer to this getelementptr instruction
11542 // is a getelementptr instruction, combine the indices of the two
11543 // getelementptr instructions into a single instruction.
11545 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11546 // Note that if our source is a gep chain itself that we wait for that
11547 // chain to be resolved before we perform this transformation. This
11548 // avoids us creating a TON of code in some cases.
11550 if (GetElementPtrInst *SrcGEP =
11551 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11552 if (SrcGEP->getNumOperands() == 2)
11553 return 0; // Wait until our source is folded to completion.
11555 SmallVector<Value*, 8> Indices;
11557 // Find out whether the last index in the source GEP is a sequential idx.
11558 bool EndsWithSequential = false;
11559 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11561 EndsWithSequential = !isa<StructType>(*I);
11563 // Can we combine the two pointer arithmetics offsets?
11564 if (EndsWithSequential) {
11565 // Replace: gep (gep %P, long B), long A, ...
11566 // With: T = long A+B; gep %P, T, ...
11569 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11570 Value *GO1 = GEP.getOperand(1);
11571 if (SO1 == Constant::getNullValue(SO1->getType())) {
11573 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11576 // If they aren't the same type, then the input hasn't been processed
11577 // by the loop above yet (which canonicalizes sequential index types to
11578 // intptr_t). Just avoid transforming this until the input has been
11580 if (SO1->getType() != GO1->getType())
11582 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11585 // Update the GEP in place if possible.
11586 if (Src->getNumOperands() == 2) {
11587 GEP.setOperand(0, Src->getOperand(0));
11588 GEP.setOperand(1, Sum);
11591 Indices.append(Src->op_begin()+1, Src->op_end()-1);
11592 Indices.push_back(Sum);
11593 Indices.append(GEP.op_begin()+2, GEP.op_end());
11594 } else if (isa<Constant>(*GEP.idx_begin()) &&
11595 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11596 Src->getNumOperands() != 1) {
11597 // Otherwise we can do the fold if the first index of the GEP is a zero
11598 Indices.append(Src->op_begin()+1, Src->op_end());
11599 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11602 if (!Indices.empty())
11603 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11604 Src->isInBounds()) ?
11605 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11606 Indices.end(), GEP.getName()) :
11607 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11608 Indices.end(), GEP.getName());
11611 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11612 if (Value *X = getBitCastOperand(PtrOp)) {
11613 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11615 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11616 // want to change the gep until the bitcasts are eliminated.
11617 if (getBitCastOperand(X)) {
11618 Worklist.AddValue(PtrOp);
11622 bool HasZeroPointerIndex = false;
11623 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
11624 HasZeroPointerIndex = C->isZero();
11626 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11627 // into : GEP [10 x i8]* X, i32 0, ...
11629 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11630 // into : GEP i8* X, ...
11632 // This occurs when the program declares an array extern like "int X[];"
11633 if (HasZeroPointerIndex) {
11634 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11635 const PointerType *XTy = cast<PointerType>(X->getType());
11636 if (const ArrayType *CATy =
11637 dyn_cast<ArrayType>(CPTy->getElementType())) {
11638 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11639 if (CATy->getElementType() == XTy->getElementType()) {
11640 // -> GEP i8* X, ...
11641 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11642 return cast<GEPOperator>(&GEP)->isInBounds() ?
11643 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11645 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11649 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11650 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11651 if (CATy->getElementType() == XATy->getElementType()) {
11652 // -> GEP [10 x i8]* X, i32 0, ...
11653 // At this point, we know that the cast source type is a pointer
11654 // to an array of the same type as the destination pointer
11655 // array. Because the array type is never stepped over (there
11656 // is a leading zero) we can fold the cast into this GEP.
11657 GEP.setOperand(0, X);
11662 } else if (GEP.getNumOperands() == 2) {
11663 // Transform things like:
11664 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11665 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11666 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11667 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11668 if (TD && isa<ArrayType>(SrcElTy) &&
11669 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11670 TD->getTypeAllocSize(ResElTy)) {
11672 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11673 Idx[1] = GEP.getOperand(1);
11674 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11675 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11676 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11677 // V and GEP are both pointer types --> BitCast
11678 return new BitCastInst(NewGEP, GEP.getType());
11681 // Transform things like:
11682 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11683 // (where tmp = 8*tmp2) into:
11684 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11686 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11687 uint64_t ArrayEltSize =
11688 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11690 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11691 // allow either a mul, shift, or constant here.
11693 ConstantInt *Scale = 0;
11694 if (ArrayEltSize == 1) {
11695 NewIdx = GEP.getOperand(1);
11696 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11697 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11698 NewIdx = ConstantInt::get(CI->getType(), 1);
11700 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11701 if (Inst->getOpcode() == Instruction::Shl &&
11702 isa<ConstantInt>(Inst->getOperand(1))) {
11703 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11704 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11705 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11707 NewIdx = Inst->getOperand(0);
11708 } else if (Inst->getOpcode() == Instruction::Mul &&
11709 isa<ConstantInt>(Inst->getOperand(1))) {
11710 Scale = cast<ConstantInt>(Inst->getOperand(1));
11711 NewIdx = Inst->getOperand(0);
11715 // If the index will be to exactly the right offset with the scale taken
11716 // out, perform the transformation. Note, we don't know whether Scale is
11717 // signed or not. We'll use unsigned version of division/modulo
11718 // operation after making sure Scale doesn't have the sign bit set.
11719 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11720 Scale->getZExtValue() % ArrayEltSize == 0) {
11721 Scale = ConstantInt::get(Scale->getType(),
11722 Scale->getZExtValue() / ArrayEltSize);
11723 if (Scale->getZExtValue() != 1) {
11724 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11726 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11729 // Insert the new GEP instruction.
11731 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11733 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11734 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11735 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11736 // The NewGEP must be pointer typed, so must the old one -> BitCast
11737 return new BitCastInst(NewGEP, GEP.getType());
11743 /// See if we can simplify:
11744 /// X = bitcast A* to B*
11745 /// Y = gep X, <...constant indices...>
11746 /// into a gep of the original struct. This is important for SROA and alias
11747 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11748 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11750 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11751 // Determine how much the GEP moves the pointer. We are guaranteed to get
11752 // a constant back from EmitGEPOffset.
11753 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
11754 int64_t Offset = OffsetV->getSExtValue();
11756 // If this GEP instruction doesn't move the pointer, just replace the GEP
11757 // with a bitcast of the real input to the dest type.
11759 // If the bitcast is of an allocation, and the allocation will be
11760 // converted to match the type of the cast, don't touch this.
11761 if (isa<AllocaInst>(BCI->getOperand(0)) ||
11762 isMalloc(BCI->getOperand(0))) {
11763 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11764 if (Instruction *I = visitBitCast(*BCI)) {
11767 BCI->getParent()->getInstList().insert(BCI, I);
11768 ReplaceInstUsesWith(*BCI, I);
11773 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11776 // Otherwise, if the offset is non-zero, we need to find out if there is a
11777 // field at Offset in 'A's type. If so, we can pull the cast through the
11779 SmallVector<Value*, 8> NewIndices;
11781 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11782 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11783 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11784 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11785 NewIndices.end()) :
11786 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11789 if (NGEP->getType() == GEP.getType())
11790 return ReplaceInstUsesWith(GEP, NGEP);
11791 NGEP->takeName(&GEP);
11792 return new BitCastInst(NGEP, GEP.getType());
11800 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
11801 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
11802 if (AI.isArrayAllocation()) { // Check C != 1
11803 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11804 const Type *NewTy =
11805 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11806 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11807 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11808 New->setAlignment(AI.getAlignment());
11810 // Scan to the end of the allocation instructions, to skip over a block of
11811 // allocas if possible...also skip interleaved debug info
11813 BasicBlock::iterator It = New;
11814 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11816 // Now that I is pointing to the first non-allocation-inst in the block,
11817 // insert our getelementptr instruction...
11819 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11823 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11824 New->getName()+".sub", It);
11826 // Now make everything use the getelementptr instead of the original
11828 return ReplaceInstUsesWith(AI, V);
11829 } else if (isa<UndefValue>(AI.getArraySize())) {
11830 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11834 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11835 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11836 // Note that we only do this for alloca's, because malloc should allocate
11837 // and return a unique pointer, even for a zero byte allocation.
11838 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11839 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11841 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11842 if (AI.getAlignment() == 0)
11843 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11849 Instruction *InstCombiner::visitFree(Instruction &FI) {
11850 Value *Op = FI.getOperand(1);
11852 // free undef -> unreachable.
11853 if (isa<UndefValue>(Op)) {
11854 // Insert a new store to null because we cannot modify the CFG here.
11855 new StoreInst(ConstantInt::getTrue(*Context),
11856 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11857 return EraseInstFromFunction(FI);
11860 // If we have 'free null' delete the instruction. This can happen in stl code
11861 // when lots of inlining happens.
11862 if (isa<ConstantPointerNull>(Op))
11863 return EraseInstFromFunction(FI);
11865 // If we have a malloc call whose only use is a free call, delete both.
11866 if (isMalloc(Op)) {
11867 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11868 if (Op->hasOneUse() && CI->hasOneUse()) {
11869 EraseInstFromFunction(FI);
11870 EraseInstFromFunction(*CI);
11871 return EraseInstFromFunction(*cast<Instruction>(Op));
11874 // Op is a call to malloc
11875 if (Op->hasOneUse()) {
11876 EraseInstFromFunction(FI);
11877 return EraseInstFromFunction(*cast<Instruction>(Op));
11885 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11886 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11887 const TargetData *TD) {
11888 User *CI = cast<User>(LI.getOperand(0));
11889 Value *CastOp = CI->getOperand(0);
11890 LLVMContext *Context = IC.getContext();
11892 const PointerType *DestTy = cast<PointerType>(CI->getType());
11893 const Type *DestPTy = DestTy->getElementType();
11894 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11896 // If the address spaces don't match, don't eliminate the cast.
11897 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11900 const Type *SrcPTy = SrcTy->getElementType();
11902 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11903 isa<VectorType>(DestPTy)) {
11904 // If the source is an array, the code below will not succeed. Check to
11905 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11907 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11908 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11909 if (ASrcTy->getNumElements() != 0) {
11911 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11913 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11914 SrcTy = cast<PointerType>(CastOp->getType());
11915 SrcPTy = SrcTy->getElementType();
11918 if (IC.getTargetData() &&
11919 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11920 isa<VectorType>(SrcPTy)) &&
11921 // Do not allow turning this into a load of an integer, which is then
11922 // casted to a pointer, this pessimizes pointer analysis a lot.
11923 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11924 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11925 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11927 // Okay, we are casting from one integer or pointer type to another of
11928 // the same size. Instead of casting the pointer before the load, cast
11929 // the result of the loaded value.
11931 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11932 // Now cast the result of the load.
11933 return new BitCastInst(NewLoad, LI.getType());
11940 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11941 Value *Op = LI.getOperand(0);
11943 // Attempt to improve the alignment.
11945 unsigned KnownAlign =
11946 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11948 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11949 LI.getAlignment()))
11950 LI.setAlignment(KnownAlign);
11953 // load (cast X) --> cast (load X) iff safe.
11954 if (isa<CastInst>(Op))
11955 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11958 // None of the following transforms are legal for volatile loads.
11959 if (LI.isVolatile()) return 0;
11961 // Do really simple store-to-load forwarding and load CSE, to catch cases
11962 // where there are several consequtive memory accesses to the same location,
11963 // separated by a few arithmetic operations.
11964 BasicBlock::iterator BBI = &LI;
11965 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11966 return ReplaceInstUsesWith(LI, AvailableVal);
11968 // load(gep null, ...) -> unreachable
11969 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11970 const Value *GEPI0 = GEPI->getOperand(0);
11971 // TODO: Consider a target hook for valid address spaces for this xform.
11972 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11973 // Insert a new store to null instruction before the load to indicate
11974 // that this code is not reachable. We do this instead of inserting
11975 // an unreachable instruction directly because we cannot modify the
11977 new StoreInst(UndefValue::get(LI.getType()),
11978 Constant::getNullValue(Op->getType()), &LI);
11979 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11983 // load null/undef -> unreachable
11984 // TODO: Consider a target hook for valid address spaces for this xform.
11985 if (isa<UndefValue>(Op) ||
11986 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11987 // Insert a new store to null instruction before the load to indicate that
11988 // this code is not reachable. We do this instead of inserting an
11989 // unreachable instruction directly because we cannot modify the CFG.
11990 new StoreInst(UndefValue::get(LI.getType()),
11991 Constant::getNullValue(Op->getType()), &LI);
11992 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11995 // Instcombine load (constantexpr_cast global) -> cast (load global)
11996 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11998 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12001 if (Op->hasOneUse()) {
12002 // Change select and PHI nodes to select values instead of addresses: this
12003 // helps alias analysis out a lot, allows many others simplifications, and
12004 // exposes redundancy in the code.
12006 // Note that we cannot do the transformation unless we know that the
12007 // introduced loads cannot trap! Something like this is valid as long as
12008 // the condition is always false: load (select bool %C, int* null, int* %G),
12009 // but it would not be valid if we transformed it to load from null
12010 // unconditionally.
12012 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12013 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
12014 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12015 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
12016 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12017 SI->getOperand(1)->getName()+".val");
12018 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12019 SI->getOperand(2)->getName()+".val");
12020 return SelectInst::Create(SI->getCondition(), V1, V2);
12023 // load (select (cond, null, P)) -> load P
12024 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12025 if (C->isNullValue()) {
12026 LI.setOperand(0, SI->getOperand(2));
12030 // load (select (cond, P, null)) -> load P
12031 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12032 if (C->isNullValue()) {
12033 LI.setOperand(0, SI->getOperand(1));
12041 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
12042 /// when possible. This makes it generally easy to do alias analysis and/or
12043 /// SROA/mem2reg of the memory object.
12044 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12045 User *CI = cast<User>(SI.getOperand(1));
12046 Value *CastOp = CI->getOperand(0);
12048 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
12049 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12050 if (SrcTy == 0) return 0;
12052 const Type *SrcPTy = SrcTy->getElementType();
12054 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12057 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12058 /// to its first element. This allows us to handle things like:
12059 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12060 /// on 32-bit hosts.
12061 SmallVector<Value*, 4> NewGEPIndices;
12063 // If the source is an array, the code below will not succeed. Check to
12064 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12066 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12067 // Index through pointer.
12068 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
12069 NewGEPIndices.push_back(Zero);
12072 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
12073 if (!STy->getNumElements()) /* Struct can be empty {} */
12075 NewGEPIndices.push_back(Zero);
12076 SrcPTy = STy->getElementType(0);
12077 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12078 NewGEPIndices.push_back(Zero);
12079 SrcPTy = ATy->getElementType();
12085 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
12088 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12091 // If the pointers point into different address spaces or if they point to
12092 // values with different sizes, we can't do the transformation.
12093 if (!IC.getTargetData() ||
12094 SrcTy->getAddressSpace() !=
12095 cast<PointerType>(CI->getType())->getAddressSpace() ||
12096 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12097 IC.getTargetData()->getTypeSizeInBits(DestPTy))
12100 // Okay, we are casting from one integer or pointer type to another of
12101 // the same size. Instead of casting the pointer before
12102 // the store, cast the value to be stored.
12104 Value *SIOp0 = SI.getOperand(0);
12105 Instruction::CastOps opcode = Instruction::BitCast;
12106 const Type* CastSrcTy = SIOp0->getType();
12107 const Type* CastDstTy = SrcPTy;
12108 if (isa<PointerType>(CastDstTy)) {
12109 if (CastSrcTy->isInteger())
12110 opcode = Instruction::IntToPtr;
12111 } else if (isa<IntegerType>(CastDstTy)) {
12112 if (isa<PointerType>(SIOp0->getType()))
12113 opcode = Instruction::PtrToInt;
12116 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12117 // emit a GEP to index into its first field.
12118 if (!NewGEPIndices.empty())
12119 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12120 NewGEPIndices.end());
12122 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12123 SIOp0->getName()+".c");
12124 return new StoreInst(NewCast, CastOp);
12127 /// equivalentAddressValues - Test if A and B will obviously have the same
12128 /// value. This includes recognizing that %t0 and %t1 will have the same
12129 /// value in code like this:
12130 /// %t0 = getelementptr \@a, 0, 3
12131 /// store i32 0, i32* %t0
12132 /// %t1 = getelementptr \@a, 0, 3
12133 /// %t2 = load i32* %t1
12135 static bool equivalentAddressValues(Value *A, Value *B) {
12136 // Test if the values are trivially equivalent.
12137 if (A == B) return true;
12139 // Test if the values come form identical arithmetic instructions.
12140 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12141 // its only used to compare two uses within the same basic block, which
12142 // means that they'll always either have the same value or one of them
12143 // will have an undefined value.
12144 if (isa<BinaryOperator>(A) ||
12145 isa<CastInst>(A) ||
12147 isa<GetElementPtrInst>(A))
12148 if (Instruction *BI = dyn_cast<Instruction>(B))
12149 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
12152 // Otherwise they may not be equivalent.
12156 // If this instruction has two uses, one of which is a llvm.dbg.declare,
12157 // return the llvm.dbg.declare.
12158 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12159 if (!V->hasNUses(2))
12161 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12163 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12165 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12166 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12173 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12174 Value *Val = SI.getOperand(0);
12175 Value *Ptr = SI.getOperand(1);
12177 // If the RHS is an alloca with a single use, zapify the store, making the
12179 // If the RHS is an alloca with a two uses, the other one being a
12180 // llvm.dbg.declare, zapify the store and the declare, making the
12181 // alloca dead. We must do this to prevent declare's from affecting
12183 if (!SI.isVolatile()) {
12184 if (Ptr->hasOneUse()) {
12185 if (isa<AllocaInst>(Ptr)) {
12186 EraseInstFromFunction(SI);
12190 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12191 if (isa<AllocaInst>(GEP->getOperand(0))) {
12192 if (GEP->getOperand(0)->hasOneUse()) {
12193 EraseInstFromFunction(SI);
12197 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12198 EraseInstFromFunction(*DI);
12199 EraseInstFromFunction(SI);
12206 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12207 EraseInstFromFunction(*DI);
12208 EraseInstFromFunction(SI);
12214 // Attempt to improve the alignment.
12216 unsigned KnownAlign =
12217 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12219 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12220 SI.getAlignment()))
12221 SI.setAlignment(KnownAlign);
12224 // Do really simple DSE, to catch cases where there are several consecutive
12225 // stores to the same location, separated by a few arithmetic operations. This
12226 // situation often occurs with bitfield accesses.
12227 BasicBlock::iterator BBI = &SI;
12228 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12231 // Don't count debug info directives, lest they affect codegen,
12232 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12233 // It is necessary for correctness to skip those that feed into a
12234 // llvm.dbg.declare, as these are not present when debugging is off.
12235 if (isa<DbgInfoIntrinsic>(BBI) ||
12236 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12241 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12242 // Prev store isn't volatile, and stores to the same location?
12243 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12244 SI.getOperand(1))) {
12247 EraseInstFromFunction(*PrevSI);
12253 // If this is a load, we have to stop. However, if the loaded value is from
12254 // the pointer we're loading and is producing the pointer we're storing,
12255 // then *this* store is dead (X = load P; store X -> P).
12256 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
12257 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12258 !SI.isVolatile()) {
12259 EraseInstFromFunction(SI);
12263 // Otherwise, this is a load from some other location. Stores before it
12264 // may not be dead.
12268 // Don't skip over loads or things that can modify memory.
12269 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
12274 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
12276 // store X, null -> turns into 'unreachable' in SimplifyCFG
12277 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
12278 if (!isa<UndefValue>(Val)) {
12279 SI.setOperand(0, UndefValue::get(Val->getType()));
12280 if (Instruction *U = dyn_cast<Instruction>(Val))
12281 Worklist.Add(U); // Dropped a use.
12284 return 0; // Do not modify these!
12287 // store undef, Ptr -> noop
12288 if (isa<UndefValue>(Val)) {
12289 EraseInstFromFunction(SI);
12294 // If the pointer destination is a cast, see if we can fold the cast into the
12296 if (isa<CastInst>(Ptr))
12297 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12299 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
12301 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12305 // If this store is the last instruction in the basic block (possibly
12306 // excepting debug info instructions and the pointer bitcasts that feed
12307 // into them), and if the block ends with an unconditional branch, try
12308 // to move it to the successor block.
12312 } while (isa<DbgInfoIntrinsic>(BBI) ||
12313 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
12314 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
12315 if (BI->isUnconditional())
12316 if (SimplifyStoreAtEndOfBlock(SI))
12317 return 0; // xform done!
12322 /// SimplifyStoreAtEndOfBlock - Turn things like:
12323 /// if () { *P = v1; } else { *P = v2 }
12324 /// into a phi node with a store in the successor.
12326 /// Simplify things like:
12327 /// *P = v1; if () { *P = v2; }
12328 /// into a phi node with a store in the successor.
12330 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12331 BasicBlock *StoreBB = SI.getParent();
12333 // Check to see if the successor block has exactly two incoming edges. If
12334 // so, see if the other predecessor contains a store to the same location.
12335 // if so, insert a PHI node (if needed) and move the stores down.
12336 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12338 // Determine whether Dest has exactly two predecessors and, if so, compute
12339 // the other predecessor.
12340 pred_iterator PI = pred_begin(DestBB);
12341 BasicBlock *OtherBB = 0;
12342 if (*PI != StoreBB)
12345 if (PI == pred_end(DestBB))
12348 if (*PI != StoreBB) {
12353 if (++PI != pred_end(DestBB))
12356 // Bail out if all the relevant blocks aren't distinct (this can happen,
12357 // for example, if SI is in an infinite loop)
12358 if (StoreBB == DestBB || OtherBB == DestBB)
12361 // Verify that the other block ends in a branch and is not otherwise empty.
12362 BasicBlock::iterator BBI = OtherBB->getTerminator();
12363 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12364 if (!OtherBr || BBI == OtherBB->begin())
12367 // If the other block ends in an unconditional branch, check for the 'if then
12368 // else' case. there is an instruction before the branch.
12369 StoreInst *OtherStore = 0;
12370 if (OtherBr->isUnconditional()) {
12372 // Skip over debugging info.
12373 while (isa<DbgInfoIntrinsic>(BBI) ||
12374 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12375 if (BBI==OtherBB->begin())
12379 // If this isn't a store, isn't a store to the same location, or if the
12380 // alignments differ, bail out.
12381 OtherStore = dyn_cast<StoreInst>(BBI);
12382 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12383 OtherStore->getAlignment() != SI.getAlignment())
12386 // Otherwise, the other block ended with a conditional branch. If one of the
12387 // destinations is StoreBB, then we have the if/then case.
12388 if (OtherBr->getSuccessor(0) != StoreBB &&
12389 OtherBr->getSuccessor(1) != StoreBB)
12392 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12393 // if/then triangle. See if there is a store to the same ptr as SI that
12394 // lives in OtherBB.
12396 // Check to see if we find the matching store.
12397 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12398 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12399 OtherStore->getAlignment() != SI.getAlignment())
12403 // If we find something that may be using or overwriting the stored
12404 // value, or if we run out of instructions, we can't do the xform.
12405 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12406 BBI == OtherBB->begin())
12410 // In order to eliminate the store in OtherBr, we have to
12411 // make sure nothing reads or overwrites the stored value in
12413 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12414 // FIXME: This should really be AA driven.
12415 if (I->mayReadFromMemory() || I->mayWriteToMemory())
12420 // Insert a PHI node now if we need it.
12421 Value *MergedVal = OtherStore->getOperand(0);
12422 if (MergedVal != SI.getOperand(0)) {
12423 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12424 PN->reserveOperandSpace(2);
12425 PN->addIncoming(SI.getOperand(0), SI.getParent());
12426 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12427 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12430 // Advance to a place where it is safe to insert the new store and
12432 BBI = DestBB->getFirstNonPHI();
12433 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12434 OtherStore->isVolatile(),
12435 SI.getAlignment()), *BBI);
12437 // Nuke the old stores.
12438 EraseInstFromFunction(SI);
12439 EraseInstFromFunction(*OtherStore);
12445 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12446 // Change br (not X), label True, label False to: br X, label False, True
12448 BasicBlock *TrueDest;
12449 BasicBlock *FalseDest;
12450 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12451 !isa<Constant>(X)) {
12452 // Swap Destinations and condition...
12453 BI.setCondition(X);
12454 BI.setSuccessor(0, FalseDest);
12455 BI.setSuccessor(1, TrueDest);
12459 // Cannonicalize fcmp_one -> fcmp_oeq
12460 FCmpInst::Predicate FPred; Value *Y;
12461 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
12462 TrueDest, FalseDest)) &&
12463 BI.getCondition()->hasOneUse())
12464 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12465 FPred == FCmpInst::FCMP_OGE) {
12466 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12467 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12469 // Swap Destinations and condition.
12470 BI.setSuccessor(0, FalseDest);
12471 BI.setSuccessor(1, TrueDest);
12472 Worklist.Add(Cond);
12476 // Cannonicalize icmp_ne -> icmp_eq
12477 ICmpInst::Predicate IPred;
12478 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12479 TrueDest, FalseDest)) &&
12480 BI.getCondition()->hasOneUse())
12481 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12482 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12483 IPred == ICmpInst::ICMP_SGE) {
12484 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12485 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12486 // Swap Destinations and condition.
12487 BI.setSuccessor(0, FalseDest);
12488 BI.setSuccessor(1, TrueDest);
12489 Worklist.Add(Cond);
12496 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12497 Value *Cond = SI.getCondition();
12498 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12499 if (I->getOpcode() == Instruction::Add)
12500 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12501 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12502 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12504 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12506 SI.setOperand(0, I->getOperand(0));
12514 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12515 Value *Agg = EV.getAggregateOperand();
12517 if (!EV.hasIndices())
12518 return ReplaceInstUsesWith(EV, Agg);
12520 if (Constant *C = dyn_cast<Constant>(Agg)) {
12521 if (isa<UndefValue>(C))
12522 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12524 if (isa<ConstantAggregateZero>(C))
12525 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12527 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12528 // Extract the element indexed by the first index out of the constant
12529 Value *V = C->getOperand(*EV.idx_begin());
12530 if (EV.getNumIndices() > 1)
12531 // Extract the remaining indices out of the constant indexed by the
12533 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12535 return ReplaceInstUsesWith(EV, V);
12537 return 0; // Can't handle other constants
12539 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12540 // We're extracting from an insertvalue instruction, compare the indices
12541 const unsigned *exti, *exte, *insi, *inse;
12542 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12543 exte = EV.idx_end(), inse = IV->idx_end();
12544 exti != exte && insi != inse;
12546 if (*insi != *exti)
12547 // The insert and extract both reference distinctly different elements.
12548 // This means the extract is not influenced by the insert, and we can
12549 // replace the aggregate operand of the extract with the aggregate
12550 // operand of the insert. i.e., replace
12551 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12552 // %E = extractvalue { i32, { i32 } } %I, 0
12554 // %E = extractvalue { i32, { i32 } } %A, 0
12555 return ExtractValueInst::Create(IV->getAggregateOperand(),
12556 EV.idx_begin(), EV.idx_end());
12558 if (exti == exte && insi == inse)
12559 // Both iterators are at the end: Index lists are identical. Replace
12560 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12561 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12563 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12564 if (exti == exte) {
12565 // The extract list is a prefix of the insert list. i.e. replace
12566 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12567 // %E = extractvalue { i32, { i32 } } %I, 1
12569 // %X = extractvalue { i32, { i32 } } %A, 1
12570 // %E = insertvalue { i32 } %X, i32 42, 0
12571 // by switching the order of the insert and extract (though the
12572 // insertvalue should be left in, since it may have other uses).
12573 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12574 EV.idx_begin(), EV.idx_end());
12575 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12579 // The insert list is a prefix of the extract list
12580 // We can simply remove the common indices from the extract and make it
12581 // operate on the inserted value instead of the insertvalue result.
12583 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12584 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12586 // %E extractvalue { i32 } { i32 42 }, 0
12587 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12590 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12591 // We're extracting from an intrinsic, see if we're the only user, which
12592 // allows us to simplify multiple result intrinsics to simpler things that
12593 // just get one value..
12594 if (II->hasOneUse()) {
12595 // Check if we're grabbing the overflow bit or the result of a 'with
12596 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12597 // and replace it with a traditional binary instruction.
12598 switch (II->getIntrinsicID()) {
12599 case Intrinsic::uadd_with_overflow:
12600 case Intrinsic::sadd_with_overflow:
12601 if (*EV.idx_begin() == 0) { // Normal result.
12602 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12603 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12604 EraseInstFromFunction(*II);
12605 return BinaryOperator::CreateAdd(LHS, RHS);
12608 case Intrinsic::usub_with_overflow:
12609 case Intrinsic::ssub_with_overflow:
12610 if (*EV.idx_begin() == 0) { // Normal result.
12611 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12612 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12613 EraseInstFromFunction(*II);
12614 return BinaryOperator::CreateSub(LHS, RHS);
12617 case Intrinsic::umul_with_overflow:
12618 case Intrinsic::smul_with_overflow:
12619 if (*EV.idx_begin() == 0) { // Normal result.
12620 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12621 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12622 EraseInstFromFunction(*II);
12623 return BinaryOperator::CreateMul(LHS, RHS);
12631 // Can't simplify extracts from other values. Note that nested extracts are
12632 // already simplified implicitely by the above (extract ( extract (insert) )
12633 // will be translated into extract ( insert ( extract ) ) first and then just
12634 // the value inserted, if appropriate).
12638 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12639 /// is to leave as a vector operation.
12640 static bool CheapToScalarize(Value *V, bool isConstant) {
12641 if (isa<ConstantAggregateZero>(V))
12643 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12644 if (isConstant) return true;
12645 // If all elts are the same, we can extract.
12646 Constant *Op0 = C->getOperand(0);
12647 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12648 if (C->getOperand(i) != Op0)
12652 Instruction *I = dyn_cast<Instruction>(V);
12653 if (!I) return false;
12655 // Insert element gets simplified to the inserted element or is deleted if
12656 // this is constant idx extract element and its a constant idx insertelt.
12657 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12658 isa<ConstantInt>(I->getOperand(2)))
12660 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12662 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12663 if (BO->hasOneUse() &&
12664 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12665 CheapToScalarize(BO->getOperand(1), isConstant)))
12667 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12668 if (CI->hasOneUse() &&
12669 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12670 CheapToScalarize(CI->getOperand(1), isConstant)))
12676 /// Read and decode a shufflevector mask.
12678 /// It turns undef elements into values that are larger than the number of
12679 /// elements in the input.
12680 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12681 unsigned NElts = SVI->getType()->getNumElements();
12682 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12683 return std::vector<unsigned>(NElts, 0);
12684 if (isa<UndefValue>(SVI->getOperand(2)))
12685 return std::vector<unsigned>(NElts, 2*NElts);
12687 std::vector<unsigned> Result;
12688 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12689 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12690 if (isa<UndefValue>(*i))
12691 Result.push_back(NElts*2); // undef -> 8
12693 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12697 /// FindScalarElement - Given a vector and an element number, see if the scalar
12698 /// value is already around as a register, for example if it were inserted then
12699 /// extracted from the vector.
12700 static Value *FindScalarElement(Value *V, unsigned EltNo,
12701 LLVMContext *Context) {
12702 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12703 const VectorType *PTy = cast<VectorType>(V->getType());
12704 unsigned Width = PTy->getNumElements();
12705 if (EltNo >= Width) // Out of range access.
12706 return UndefValue::get(PTy->getElementType());
12708 if (isa<UndefValue>(V))
12709 return UndefValue::get(PTy->getElementType());
12710 else if (isa<ConstantAggregateZero>(V))
12711 return Constant::getNullValue(PTy->getElementType());
12712 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12713 return CP->getOperand(EltNo);
12714 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12715 // If this is an insert to a variable element, we don't know what it is.
12716 if (!isa<ConstantInt>(III->getOperand(2)))
12718 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12720 // If this is an insert to the element we are looking for, return the
12722 if (EltNo == IIElt)
12723 return III->getOperand(1);
12725 // Otherwise, the insertelement doesn't modify the value, recurse on its
12727 return FindScalarElement(III->getOperand(0), EltNo, Context);
12728 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12729 unsigned LHSWidth =
12730 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12731 unsigned InEl = getShuffleMask(SVI)[EltNo];
12732 if (InEl < LHSWidth)
12733 return FindScalarElement(SVI->getOperand(0), InEl, Context);
12734 else if (InEl < LHSWidth*2)
12735 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12737 return UndefValue::get(PTy->getElementType());
12740 // Otherwise, we don't know.
12744 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12745 // If vector val is undef, replace extract with scalar undef.
12746 if (isa<UndefValue>(EI.getOperand(0)))
12747 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12749 // If vector val is constant 0, replace extract with scalar 0.
12750 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12751 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12753 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12754 // If vector val is constant with all elements the same, replace EI with
12755 // that element. When the elements are not identical, we cannot replace yet
12756 // (we do that below, but only when the index is constant).
12757 Constant *op0 = C->getOperand(0);
12758 for (unsigned i = 1; i != C->getNumOperands(); ++i)
12759 if (C->getOperand(i) != op0) {
12764 return ReplaceInstUsesWith(EI, op0);
12767 // If extracting a specified index from the vector, see if we can recursively
12768 // find a previously computed scalar that was inserted into the vector.
12769 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12770 unsigned IndexVal = IdxC->getZExtValue();
12771 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12773 // If this is extracting an invalid index, turn this into undef, to avoid
12774 // crashing the code below.
12775 if (IndexVal >= VectorWidth)
12776 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12778 // This instruction only demands the single element from the input vector.
12779 // If the input vector has a single use, simplify it based on this use
12781 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12782 APInt UndefElts(VectorWidth, 0);
12783 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12784 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12785 DemandedMask, UndefElts)) {
12786 EI.setOperand(0, V);
12791 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12792 return ReplaceInstUsesWith(EI, Elt);
12794 // If the this extractelement is directly using a bitcast from a vector of
12795 // the same number of elements, see if we can find the source element from
12796 // it. In this case, we will end up needing to bitcast the scalars.
12797 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12798 if (const VectorType *VT =
12799 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12800 if (VT->getNumElements() == VectorWidth)
12801 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12802 IndexVal, Context))
12803 return new BitCastInst(Elt, EI.getType());
12807 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12808 // Push extractelement into predecessor operation if legal and
12809 // profitable to do so
12810 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12811 if (I->hasOneUse() &&
12812 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12814 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12815 EI.getName()+".lhs");
12817 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12818 EI.getName()+".rhs");
12819 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12821 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12822 // Extracting the inserted element?
12823 if (IE->getOperand(2) == EI.getOperand(1))
12824 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12825 // If the inserted and extracted elements are constants, they must not
12826 // be the same value, extract from the pre-inserted value instead.
12827 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12828 Worklist.AddValue(EI.getOperand(0));
12829 EI.setOperand(0, IE->getOperand(0));
12832 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12833 // If this is extracting an element from a shufflevector, figure out where
12834 // it came from and extract from the appropriate input element instead.
12835 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12836 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12838 unsigned LHSWidth =
12839 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12841 if (SrcIdx < LHSWidth)
12842 Src = SVI->getOperand(0);
12843 else if (SrcIdx < LHSWidth*2) {
12844 SrcIdx -= LHSWidth;
12845 Src = SVI->getOperand(1);
12847 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12849 return ExtractElementInst::Create(Src,
12850 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12854 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12859 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12860 /// elements from either LHS or RHS, return the shuffle mask and true.
12861 /// Otherwise, return false.
12862 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12863 std::vector<Constant*> &Mask,
12864 LLVMContext *Context) {
12865 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12866 "Invalid CollectSingleShuffleElements");
12867 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12869 if (isa<UndefValue>(V)) {
12870 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12872 } else if (V == LHS) {
12873 for (unsigned i = 0; i != NumElts; ++i)
12874 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12876 } else if (V == RHS) {
12877 for (unsigned i = 0; i != NumElts; ++i)
12878 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12880 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12881 // If this is an insert of an extract from some other vector, include it.
12882 Value *VecOp = IEI->getOperand(0);
12883 Value *ScalarOp = IEI->getOperand(1);
12884 Value *IdxOp = IEI->getOperand(2);
12886 if (!isa<ConstantInt>(IdxOp))
12888 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12890 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12891 // Okay, we can handle this if the vector we are insertinting into is
12892 // transitively ok.
12893 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12894 // If so, update the mask to reflect the inserted undef.
12895 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12898 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12899 if (isa<ConstantInt>(EI->getOperand(1)) &&
12900 EI->getOperand(0)->getType() == V->getType()) {
12901 unsigned ExtractedIdx =
12902 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12904 // This must be extracting from either LHS or RHS.
12905 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12906 // Okay, we can handle this if the vector we are insertinting into is
12907 // transitively ok.
12908 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12909 // If so, update the mask to reflect the inserted value.
12910 if (EI->getOperand(0) == LHS) {
12911 Mask[InsertedIdx % NumElts] =
12912 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12914 assert(EI->getOperand(0) == RHS);
12915 Mask[InsertedIdx % NumElts] =
12916 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12925 // TODO: Handle shufflevector here!
12930 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12931 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12932 /// that computes V and the LHS value of the shuffle.
12933 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12934 Value *&RHS, LLVMContext *Context) {
12935 assert(isa<VectorType>(V->getType()) &&
12936 (RHS == 0 || V->getType() == RHS->getType()) &&
12937 "Invalid shuffle!");
12938 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12940 if (isa<UndefValue>(V)) {
12941 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12943 } else if (isa<ConstantAggregateZero>(V)) {
12944 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12946 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12947 // If this is an insert of an extract from some other vector, include it.
12948 Value *VecOp = IEI->getOperand(0);
12949 Value *ScalarOp = IEI->getOperand(1);
12950 Value *IdxOp = IEI->getOperand(2);
12952 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12953 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12954 EI->getOperand(0)->getType() == V->getType()) {
12955 unsigned ExtractedIdx =
12956 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12957 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12959 // Either the extracted from or inserted into vector must be RHSVec,
12960 // otherwise we'd end up with a shuffle of three inputs.
12961 if (EI->getOperand(0) == RHS || RHS == 0) {
12962 RHS = EI->getOperand(0);
12963 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12964 Mask[InsertedIdx % NumElts] =
12965 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12969 if (VecOp == RHS) {
12970 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12972 // Everything but the extracted element is replaced with the RHS.
12973 for (unsigned i = 0; i != NumElts; ++i) {
12974 if (i != InsertedIdx)
12975 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12980 // If this insertelement is a chain that comes from exactly these two
12981 // vectors, return the vector and the effective shuffle.
12982 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12984 return EI->getOperand(0);
12989 // TODO: Handle shufflevector here!
12991 // Otherwise, can't do anything fancy. Return an identity vector.
12992 for (unsigned i = 0; i != NumElts; ++i)
12993 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12997 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12998 Value *VecOp = IE.getOperand(0);
12999 Value *ScalarOp = IE.getOperand(1);
13000 Value *IdxOp = IE.getOperand(2);
13002 // Inserting an undef or into an undefined place, remove this.
13003 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13004 ReplaceInstUsesWith(IE, VecOp);
13006 // If the inserted element was extracted from some other vector, and if the
13007 // indexes are constant, try to turn this into a shufflevector operation.
13008 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13009 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13010 EI->getOperand(0)->getType() == IE.getType()) {
13011 unsigned NumVectorElts = IE.getType()->getNumElements();
13012 unsigned ExtractedIdx =
13013 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13014 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13016 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13017 return ReplaceInstUsesWith(IE, VecOp);
13019 if (InsertedIdx >= NumVectorElts) // Out of range insert.
13020 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
13022 // If we are extracting a value from a vector, then inserting it right
13023 // back into the same place, just use the input vector.
13024 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13025 return ReplaceInstUsesWith(IE, VecOp);
13027 // If this insertelement isn't used by some other insertelement, turn it
13028 // (and any insertelements it points to), into one big shuffle.
13029 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13030 std::vector<Constant*> Mask;
13032 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
13033 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
13034 // We now have a shuffle of LHS, RHS, Mask.
13035 return new ShuffleVectorInst(LHS, RHS,
13036 ConstantVector::get(Mask));
13041 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13042 APInt UndefElts(VWidth, 0);
13043 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13044 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13051 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13052 Value *LHS = SVI.getOperand(0);
13053 Value *RHS = SVI.getOperand(1);
13054 std::vector<unsigned> Mask = getShuffleMask(&SVI);
13056 bool MadeChange = false;
13058 // Undefined shuffle mask -> undefined value.
13059 if (isa<UndefValue>(SVI.getOperand(2)))
13060 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
13062 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
13064 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13067 APInt UndefElts(VWidth, 0);
13068 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13069 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
13070 LHS = SVI.getOperand(0);
13071 RHS = SVI.getOperand(1);
13075 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13076 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13077 if (LHS == RHS || isa<UndefValue>(LHS)) {
13078 if (isa<UndefValue>(LHS) && LHS == RHS) {
13079 // shuffle(undef,undef,mask) -> undef.
13080 return ReplaceInstUsesWith(SVI, LHS);
13083 // Remap any references to RHS to use LHS.
13084 std::vector<Constant*> Elts;
13085 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13086 if (Mask[i] >= 2*e)
13087 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13089 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
13090 (Mask[i] < e && isa<UndefValue>(LHS))) {
13091 Mask[i] = 2*e; // Turn into undef.
13092 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13094 Mask[i] = Mask[i] % e; // Force to LHS.
13095 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
13099 SVI.setOperand(0, SVI.getOperand(1));
13100 SVI.setOperand(1, UndefValue::get(RHS->getType()));
13101 SVI.setOperand(2, ConstantVector::get(Elts));
13102 LHS = SVI.getOperand(0);
13103 RHS = SVI.getOperand(1);
13107 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
13108 bool isLHSID = true, isRHSID = true;
13110 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13111 if (Mask[i] >= e*2) continue; // Ignore undef values.
13112 // Is this an identity shuffle of the LHS value?
13113 isLHSID &= (Mask[i] == i);
13115 // Is this an identity shuffle of the RHS value?
13116 isRHSID &= (Mask[i]-e == i);
13119 // Eliminate identity shuffles.
13120 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13121 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
13123 // If the LHS is a shufflevector itself, see if we can combine it with this
13124 // one without producing an unusual shuffle. Here we are really conservative:
13125 // we are absolutely afraid of producing a shuffle mask not in the input
13126 // program, because the code gen may not be smart enough to turn a merged
13127 // shuffle into two specific shuffles: it may produce worse code. As such,
13128 // we only merge two shuffles if the result is one of the two input shuffle
13129 // masks. In this case, merging the shuffles just removes one instruction,
13130 // which we know is safe. This is good for things like turning:
13131 // (splat(splat)) -> splat.
13132 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13133 if (isa<UndefValue>(RHS)) {
13134 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13136 if (LHSMask.size() == Mask.size()) {
13137 std::vector<unsigned> NewMask;
13138 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
13140 NewMask.push_back(2*e);
13142 NewMask.push_back(LHSMask[Mask[i]]);
13144 // If the result mask is equal to the src shuffle or this
13145 // shuffle mask, do the replacement.
13146 if (NewMask == LHSMask || NewMask == Mask) {
13147 unsigned LHSInNElts =
13148 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13150 std::vector<Constant*> Elts;
13151 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13152 if (NewMask[i] >= LHSInNElts*2) {
13153 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13155 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13159 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13160 LHSSVI->getOperand(1),
13161 ConstantVector::get(Elts));
13167 return MadeChange ? &SVI : 0;
13173 /// TryToSinkInstruction - Try to move the specified instruction from its
13174 /// current block into the beginning of DestBlock, which can only happen if it's
13175 /// safe to move the instruction past all of the instructions between it and the
13176 /// end of its block.
13177 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13178 assert(I->hasOneUse() && "Invariants didn't hold!");
13180 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
13181 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
13184 // Do not sink alloca instructions out of the entry block.
13185 if (isa<AllocaInst>(I) && I->getParent() ==
13186 &DestBlock->getParent()->getEntryBlock())
13189 // We can only sink load instructions if there is nothing between the load and
13190 // the end of block that could change the value.
13191 if (I->mayReadFromMemory()) {
13192 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
13194 if (Scan->mayWriteToMemory())
13198 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
13200 CopyPrecedingStopPoint(I, InsertPos);
13201 I->moveBefore(InsertPos);
13207 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13208 /// all reachable code to the worklist.
13210 /// This has a couple of tricks to make the code faster and more powerful. In
13211 /// particular, we constant fold and DCE instructions as we go, to avoid adding
13212 /// them to the worklist (this significantly speeds up instcombine on code where
13213 /// many instructions are dead or constant). Additionally, if we find a branch
13214 /// whose condition is a known constant, we only visit the reachable successors.
13216 static bool AddReachableCodeToWorklist(BasicBlock *BB,
13217 SmallPtrSet<BasicBlock*, 64> &Visited,
13219 const TargetData *TD) {
13220 bool MadeIRChange = false;
13221 SmallVector<BasicBlock*, 256> Worklist;
13222 Worklist.push_back(BB);
13224 std::vector<Instruction*> InstrsForInstCombineWorklist;
13225 InstrsForInstCombineWorklist.reserve(128);
13227 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13229 while (!Worklist.empty()) {
13230 BB = Worklist.back();
13231 Worklist.pop_back();
13233 // We have now visited this block! If we've already been here, ignore it.
13234 if (!Visited.insert(BB)) continue;
13236 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13237 Instruction *Inst = BBI++;
13239 // DCE instruction if trivially dead.
13240 if (isInstructionTriviallyDead(Inst)) {
13242 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
13243 Inst->eraseFromParent();
13247 // ConstantProp instruction if trivially constant.
13248 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
13249 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
13250 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13252 Inst->replaceAllUsesWith(C);
13254 Inst->eraseFromParent();
13261 // See if we can constant fold its operands.
13262 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13264 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13265 if (CE == 0) continue;
13267 // If we already folded this constant, don't try again.
13268 if (!FoldedConstants.insert(CE))
13271 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
13272 if (NewC && NewC != CE) {
13274 MadeIRChange = true;
13280 InstrsForInstCombineWorklist.push_back(Inst);
13283 // Recursively visit successors. If this is a branch or switch on a
13284 // constant, only visit the reachable successor.
13285 TerminatorInst *TI = BB->getTerminator();
13286 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13287 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13288 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
13289 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
13290 Worklist.push_back(ReachableBB);
13293 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13294 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13295 // See if this is an explicit destination.
13296 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13297 if (SI->getCaseValue(i) == Cond) {
13298 BasicBlock *ReachableBB = SI->getSuccessor(i);
13299 Worklist.push_back(ReachableBB);
13303 // Otherwise it is the default destination.
13304 Worklist.push_back(SI->getSuccessor(0));
13309 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13310 Worklist.push_back(TI->getSuccessor(i));
13313 // Once we've found all of the instructions to add to instcombine's worklist,
13314 // add them in reverse order. This way instcombine will visit from the top
13315 // of the function down. This jives well with the way that it adds all uses
13316 // of instructions to the worklist after doing a transformation, thus avoiding
13317 // some N^2 behavior in pathological cases.
13318 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13319 InstrsForInstCombineWorklist.size());
13321 return MadeIRChange;
13324 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
13325 MadeIRChange = false;
13327 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13328 << F.getNameStr() << "\n");
13331 // Do a depth-first traversal of the function, populate the worklist with
13332 // the reachable instructions. Ignore blocks that are not reachable. Keep
13333 // track of which blocks we visit.
13334 SmallPtrSet<BasicBlock*, 64> Visited;
13335 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
13337 // Do a quick scan over the function. If we find any blocks that are
13338 // unreachable, remove any instructions inside of them. This prevents
13339 // the instcombine code from having to deal with some bad special cases.
13340 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13341 if (!Visited.count(BB)) {
13342 Instruction *Term = BB->getTerminator();
13343 while (Term != BB->begin()) { // Remove instrs bottom-up
13344 BasicBlock::iterator I = Term; --I;
13346 DEBUG(errs() << "IC: DCE: " << *I << '\n');
13347 // A debug intrinsic shouldn't force another iteration if we weren't
13348 // going to do one without it.
13349 if (!isa<DbgInfoIntrinsic>(I)) {
13351 MadeIRChange = true;
13354 // If I is not void type then replaceAllUsesWith undef.
13355 // This allows ValueHandlers and custom metadata to adjust itself.
13356 if (!I->getType()->isVoidTy())
13357 I->replaceAllUsesWith(UndefValue::get(I->getType()));
13358 I->eraseFromParent();
13363 while (!Worklist.isEmpty()) {
13364 Instruction *I = Worklist.RemoveOne();
13365 if (I == 0) continue; // skip null values.
13367 // Check to see if we can DCE the instruction.
13368 if (isInstructionTriviallyDead(I)) {
13369 DEBUG(errs() << "IC: DCE: " << *I << '\n');
13370 EraseInstFromFunction(*I);
13372 MadeIRChange = true;
13376 // Instruction isn't dead, see if we can constant propagate it.
13377 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
13378 if (Constant *C = ConstantFoldInstruction(I, TD)) {
13379 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
13381 // Add operands to the worklist.
13382 ReplaceInstUsesWith(*I, C);
13384 EraseInstFromFunction(*I);
13385 MadeIRChange = true;
13389 // See if we can trivially sink this instruction to a successor basic block.
13390 if (I->hasOneUse()) {
13391 BasicBlock *BB = I->getParent();
13392 Instruction *UserInst = cast<Instruction>(I->use_back());
13393 BasicBlock *UserParent;
13395 // Get the block the use occurs in.
13396 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13397 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13399 UserParent = UserInst->getParent();
13401 if (UserParent != BB) {
13402 bool UserIsSuccessor = false;
13403 // See if the user is one of our successors.
13404 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13405 if (*SI == UserParent) {
13406 UserIsSuccessor = true;
13410 // If the user is one of our immediate successors, and if that successor
13411 // only has us as a predecessors (we'd have to split the critical edge
13412 // otherwise), we can keep going.
13413 if (UserIsSuccessor && UserParent->getSinglePredecessor())
13414 // Okay, the CFG is simple enough, try to sink this instruction.
13415 MadeIRChange |= TryToSinkInstruction(I, UserParent);
13419 // Now that we have an instruction, try combining it to simplify it.
13420 Builder->SetInsertPoint(I->getParent(), I);
13425 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
13426 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13428 if (Instruction *Result = visit(*I)) {
13430 // Should we replace the old instruction with a new one?
13432 DEBUG(errs() << "IC: Old = " << *I << '\n'
13433 << " New = " << *Result << '\n');
13435 // Everything uses the new instruction now.
13436 I->replaceAllUsesWith(Result);
13438 // Push the new instruction and any users onto the worklist.
13439 Worklist.Add(Result);
13440 Worklist.AddUsersToWorkList(*Result);
13442 // Move the name to the new instruction first.
13443 Result->takeName(I);
13445 // Insert the new instruction into the basic block...
13446 BasicBlock *InstParent = I->getParent();
13447 BasicBlock::iterator InsertPos = I;
13449 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13450 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13453 InstParent->getInstList().insert(InsertPos, Result);
13455 EraseInstFromFunction(*I);
13458 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13459 << " New = " << *I << '\n');
13462 // If the instruction was modified, it's possible that it is now dead.
13463 // if so, remove it.
13464 if (isInstructionTriviallyDead(I)) {
13465 EraseInstFromFunction(*I);
13468 Worklist.AddUsersToWorkList(*I);
13471 MadeIRChange = true;
13476 return MadeIRChange;
13480 bool InstCombiner::runOnFunction(Function &F) {
13481 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13482 Context = &F.getContext();
13483 TD = getAnalysisIfAvailable<TargetData>();
13486 /// Builder - This is an IRBuilder that automatically inserts new
13487 /// instructions into the worklist when they are created.
13488 IRBuilder<true, TargetFolder, InstCombineIRInserter>
13489 TheBuilder(F.getContext(), TargetFolder(TD),
13490 InstCombineIRInserter(Worklist));
13491 Builder = &TheBuilder;
13493 bool EverMadeChange = false;
13495 // Iterate while there is work to do.
13496 unsigned Iteration = 0;
13497 while (DoOneIteration(F, Iteration++))
13498 EverMadeChange = true;
13501 return EverMadeChange;
13504 FunctionPass *llvm::createInstructionCombiningPass() {
13505 return new InstCombiner();