1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 algebraic
12 // 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. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All SetCC 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/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/ADT/DepthFirstIterator.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
57 using namespace llvm::PatternMatch;
60 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
63 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
64 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
66 class InstCombiner : public FunctionPass,
67 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
72 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
76 void AddUsersToWorkList(Value &I) {
77 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
79 WorkList.push_back(cast<Instruction>(*UI));
82 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
91 // removeFromWorkList - remove all instances of I from the worklist.
92 void removeFromWorkList(Instruction *I);
94 virtual bool runOnFunction(Function &F);
96 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
97 AU.addRequired<TargetData>();
101 TargetData &getTargetData() const { return *TD; }
103 // Visitation implementation - Implement instruction combining for different
104 // instruction types. The semantics are as follows:
106 // null - No change was made
107 // I - Change was made, I is still valid, I may be dead though
108 // otherwise - Change was made, replace I with returned instruction
110 Instruction *visitAdd(BinaryOperator &I);
111 Instruction *visitSub(BinaryOperator &I);
112 Instruction *visitMul(BinaryOperator &I);
113 Instruction *visitDiv(BinaryOperator &I);
114 Instruction *visitRem(BinaryOperator &I);
115 Instruction *visitAnd(BinaryOperator &I);
116 Instruction *visitOr (BinaryOperator &I);
117 Instruction *visitXor(BinaryOperator &I);
118 Instruction *visitSetCondInst(SetCondInst &I);
119 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
121 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
122 Instruction::BinaryOps Cond, Instruction &I);
123 Instruction *visitShiftInst(ShiftInst &I);
124 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
126 Instruction *visitCastInst(CastInst &CI);
127 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
129 Instruction *visitSelectInst(SelectInst &CI);
130 Instruction *visitCallInst(CallInst &CI);
131 Instruction *visitInvokeInst(InvokeInst &II);
132 Instruction *visitPHINode(PHINode &PN);
133 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
134 Instruction *visitAllocationInst(AllocationInst &AI);
135 Instruction *visitFreeInst(FreeInst &FI);
136 Instruction *visitLoadInst(LoadInst &LI);
137 Instruction *visitStoreInst(StoreInst &SI);
138 Instruction *visitBranchInst(BranchInst &BI);
139 Instruction *visitSwitchInst(SwitchInst &SI);
140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
142 // visitInstruction - Specify what to return for unhandled instructions...
143 Instruction *visitInstruction(Instruction &I) { return 0; }
146 Instruction *visitCallSite(CallSite CS);
147 bool transformConstExprCastCall(CallSite CS);
150 // InsertNewInstBefore - insert an instruction New before instruction Old
151 // in the program. Add the new instruction to the worklist.
153 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
154 assert(New && New->getParent() == 0 &&
155 "New instruction already inserted into a basic block!");
156 BasicBlock *BB = Old.getParent();
157 BB->getInstList().insert(&Old, New); // Insert inst
158 WorkList.push_back(New); // Add to worklist
162 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
163 /// This also adds the cast to the worklist. Finally, this returns the
165 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
166 if (V->getType() == Ty) return V;
168 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
169 WorkList.push_back(C);
173 // ReplaceInstUsesWith - This method is to be used when an instruction is
174 // found to be dead, replacable with another preexisting expression. Here
175 // we add all uses of I to the worklist, replace all uses of I with the new
176 // value, then return I, so that the inst combiner will know that I was
179 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
180 AddUsersToWorkList(I); // Add all modified instrs to worklist
182 I.replaceAllUsesWith(V);
185 // If we are replacing the instruction with itself, this must be in a
186 // segment of unreachable code, so just clobber the instruction.
187 I.replaceAllUsesWith(UndefValue::get(I.getType()));
192 // UpdateValueUsesWith - This method is to be used when an value is
193 // found to be replacable with another preexisting expression or was
194 // updated. Here we add all uses of I to the worklist, replace all uses of
195 // I with the new value (unless the instruction was just updated), then
196 // return true, so that the inst combiner will know that I was modified.
198 bool UpdateValueUsesWith(Value *Old, Value *New) {
199 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
201 Old->replaceAllUsesWith(New);
202 if (Instruction *I = dyn_cast<Instruction>(Old))
203 WorkList.push_back(I);
207 // EraseInstFromFunction - When dealing with an instruction that has side
208 // effects or produces a void value, we can't rely on DCE to delete the
209 // instruction. Instead, visit methods should return the value returned by
211 Instruction *EraseInstFromFunction(Instruction &I) {
212 assert(I.use_empty() && "Cannot erase instruction that is used!");
213 AddUsesToWorkList(I);
214 removeFromWorkList(&I);
216 return 0; // Don't do anything with FI
220 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
221 /// InsertBefore instruction. This is specialized a bit to avoid inserting
222 /// casts that are known to not do anything...
224 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
225 Instruction *InsertBefore);
227 // SimplifyCommutative - This performs a few simplifications for commutative
229 bool SimplifyCommutative(BinaryOperator &I);
231 bool SimplifyDemandedBits(Value *V, uint64_t Mask, unsigned Depth = 0);
233 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
234 // PHI node as operand #0, see if we can fold the instruction into the PHI
235 // (which is only possible if all operands to the PHI are constants).
236 Instruction *FoldOpIntoPhi(Instruction &I);
238 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
239 // operator and they all are only used by the PHI, PHI together their
240 // inputs, and do the operation once, to the result of the PHI.
241 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
243 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
244 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
246 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
247 bool isSub, Instruction &I);
248 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
249 bool Inside, Instruction &IB);
250 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
253 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
256 // getComplexity: Assign a complexity or rank value to LLVM Values...
257 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
258 static unsigned getComplexity(Value *V) {
259 if (isa<Instruction>(V)) {
260 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
264 if (isa<Argument>(V)) return 3;
265 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
268 // isOnlyUse - Return true if this instruction will be deleted if we stop using
270 static bool isOnlyUse(Value *V) {
271 return V->hasOneUse() || isa<Constant>(V);
274 // getPromotedType - Return the specified type promoted as it would be to pass
275 // though a va_arg area...
276 static const Type *getPromotedType(const Type *Ty) {
277 switch (Ty->getTypeID()) {
278 case Type::SByteTyID:
279 case Type::ShortTyID: return Type::IntTy;
280 case Type::UByteTyID:
281 case Type::UShortTyID: return Type::UIntTy;
282 case Type::FloatTyID: return Type::DoubleTy;
287 /// isCast - If the specified operand is a CastInst or a constant expr cast,
288 /// return the operand value, otherwise return null.
289 static Value *isCast(Value *V) {
290 if (CastInst *I = dyn_cast<CastInst>(V))
291 return I->getOperand(0);
292 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
293 if (CE->getOpcode() == Instruction::Cast)
294 return CE->getOperand(0);
298 // SimplifyCommutative - This performs a few simplifications for commutative
301 // 1. Order operands such that they are listed from right (least complex) to
302 // left (most complex). This puts constants before unary operators before
305 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
306 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
308 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
309 bool Changed = false;
310 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
311 Changed = !I.swapOperands();
313 if (!I.isAssociative()) return Changed;
314 Instruction::BinaryOps Opcode = I.getOpcode();
315 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
316 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
317 if (isa<Constant>(I.getOperand(1))) {
318 Constant *Folded = ConstantExpr::get(I.getOpcode(),
319 cast<Constant>(I.getOperand(1)),
320 cast<Constant>(Op->getOperand(1)));
321 I.setOperand(0, Op->getOperand(0));
322 I.setOperand(1, Folded);
324 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
325 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
326 isOnlyUse(Op) && isOnlyUse(Op1)) {
327 Constant *C1 = cast<Constant>(Op->getOperand(1));
328 Constant *C2 = cast<Constant>(Op1->getOperand(1));
330 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
331 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
332 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
335 WorkList.push_back(New);
336 I.setOperand(0, New);
337 I.setOperand(1, Folded);
344 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
345 // if the LHS is a constant zero (which is the 'negate' form).
347 static inline Value *dyn_castNegVal(Value *V) {
348 if (BinaryOperator::isNeg(V))
349 return BinaryOperator::getNegArgument(V);
351 // Constants can be considered to be negated values if they can be folded.
352 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
353 return ConstantExpr::getNeg(C);
357 static inline Value *dyn_castNotVal(Value *V) {
358 if (BinaryOperator::isNot(V))
359 return BinaryOperator::getNotArgument(V);
361 // Constants can be considered to be not'ed values...
362 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
363 return ConstantExpr::getNot(C);
367 // dyn_castFoldableMul - If this value is a multiply that can be folded into
368 // other computations (because it has a constant operand), return the
369 // non-constant operand of the multiply, and set CST to point to the multiplier.
370 // Otherwise, return null.
372 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
373 if (V->hasOneUse() && V->getType()->isInteger())
374 if (Instruction *I = dyn_cast<Instruction>(V)) {
375 if (I->getOpcode() == Instruction::Mul)
376 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
377 return I->getOperand(0);
378 if (I->getOpcode() == Instruction::Shl)
379 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
380 // The multiplier is really 1 << CST.
381 Constant *One = ConstantInt::get(V->getType(), 1);
382 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
383 return I->getOperand(0);
389 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
390 /// expression, return it.
391 static User *dyn_castGetElementPtr(Value *V) {
392 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
393 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
394 if (CE->getOpcode() == Instruction::GetElementPtr)
395 return cast<User>(V);
399 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
400 static ConstantInt *AddOne(ConstantInt *C) {
401 return cast<ConstantInt>(ConstantExpr::getAdd(C,
402 ConstantInt::get(C->getType(), 1)));
404 static ConstantInt *SubOne(ConstantInt *C) {
405 return cast<ConstantInt>(ConstantExpr::getSub(C,
406 ConstantInt::get(C->getType(), 1)));
409 /// ComputeMaskedNonZeroBits - Determine which of the bits specified in Mask are
410 /// not known to be zero and return them as a bitmask. The bits that we can
411 /// guarantee to be zero are returned as zero bits in the result.
412 static uint64_t ComputeMaskedNonZeroBits(Value *V, uint64_t Mask,
413 unsigned Depth = 0) {
414 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
415 // we cannot optimize based on the assumption that it is zero without changing
416 // it to be an explicit zero. If we don't change it to zero, other code could
417 // optimized based on the contradictory assumption that it is non-zero.
418 // Because instcombine aggressively folds operations with undef args anyway,
419 // this won't lose us code quality.
420 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
421 return CI->getRawValue() & Mask;
422 if (Depth == 6 || Mask == 0)
423 return Mask; // Limit search depth.
425 if (Instruction *I = dyn_cast<Instruction>(V)) {
426 switch (I->getOpcode()) {
427 case Instruction::And:
428 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
429 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
430 return ComputeMaskedNonZeroBits(I->getOperand(0),
431 CI->getRawValue() & Mask, Depth+1);
432 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
433 Mask = ComputeMaskedNonZeroBits(I->getOperand(1), Mask, Depth+1);
434 Mask = ComputeMaskedNonZeroBits(I->getOperand(0), Mask, Depth+1);
436 case Instruction::Or:
437 case Instruction::Xor:
438 // Any non-zero bits in the LHS or RHS are potentially non-zero in the
440 return ComputeMaskedNonZeroBits(I->getOperand(1), Mask, Depth+1) |
441 ComputeMaskedNonZeroBits(I->getOperand(0), Mask, Depth+1);
442 case Instruction::Select:
443 // Any non-zero bits in the T or F values are potentially non-zero in the
445 return ComputeMaskedNonZeroBits(I->getOperand(2), Mask, Depth+1) |
446 ComputeMaskedNonZeroBits(I->getOperand(1), Mask, Depth+1);
447 case Instruction::Cast: {
448 const Type *SrcTy = I->getOperand(0)->getType();
449 if (SrcTy == Type::BoolTy)
450 return ComputeMaskedNonZeroBits(I->getOperand(0), Mask & 1, Depth+1);
451 if (!SrcTy->isInteger()) return Mask;
453 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
454 if (SrcTy->isUnsigned() || // Only handle zero ext/trunc/noop
455 SrcTy->getPrimitiveSizeInBits() >=
456 I->getType()->getPrimitiveSizeInBits()) {
457 Mask &= SrcTy->getIntegralTypeMask();
458 return ComputeMaskedNonZeroBits(I->getOperand(0), Mask, Depth+1);
461 // FIXME: handle sext casts.
464 case Instruction::Shl:
465 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
466 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
467 return ComputeMaskedNonZeroBits(I->getOperand(0),Mask >> SA->getValue(),
468 Depth+1) << SA->getValue();
470 case Instruction::Shr:
471 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
472 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
473 if (I->getType()->isUnsigned()) {
474 Mask <<= SA->getValue();
475 Mask &= I->getType()->getIntegralTypeMask();
476 return ComputeMaskedNonZeroBits(I->getOperand(0), Mask, Depth+1)
486 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
487 /// this predicate to simplify operations downstream. Mask is known to be zero
488 /// for bits that V cannot have.
489 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
490 return ComputeMaskedNonZeroBits(V, Mask, Depth) == 0;
493 /// SimplifyDemandedBits - Look at V. At this point, we know that only the Mask
494 /// bits of the result of V are ever used downstream. If we can use this
495 /// information to simplify V, return V and set NewVal to the new value we
496 /// should use in V's place.
497 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t Mask,
499 if (!V->hasOneUse()) { // Other users may use these bits.
500 if (Depth != 0) // Not at the root.
502 // If this is the root being simplified, allow it to have multiple uses,
503 // just set the Mask to all bits.
504 Mask = V->getType()->getIntegralTypeMask();
505 } else if (Mask == 0) { // Not demanding any bits from V.
506 if (V != UndefValue::get(V->getType()))
507 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
509 } else if (Depth == 6) { // Limit search depth.
513 Instruction *I = dyn_cast<Instruction>(V);
514 if (!I) return false; // Only analyze instructions.
516 switch (I->getOpcode()) {
518 case Instruction::And:
519 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
520 // Only demanding an intersection of the bits.
521 if (SimplifyDemandedBits(I->getOperand(0), RHS->getRawValue() & Mask,
524 if (~Mask & RHS->getZExtValue()) {
525 // If this is producing any bits that are not needed, simplify the RHS.
526 uint64_t Val = Mask & RHS->getZExtValue();
528 ConstantUInt::get(I->getType()->getUnsignedVersion(), Val);
529 if (I->getType()->isSigned())
530 RHS = ConstantExpr::getCast(RHS, I->getType());
531 I->setOperand(1, RHS);
532 return UpdateValueUsesWith(I, I);
535 // Walk the LHS and the RHS.
536 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1) ||
537 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
538 case Instruction::Or:
539 case Instruction::Xor:
540 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
541 // If none of the [x]or'd in bits are demanded, don't both with the [x]or.
542 if ((Mask & RHS->getRawValue()) == 0)
543 return UpdateValueUsesWith(I, I->getOperand(0));
545 // Otherwise, for an OR, we only demand those bits not set by the OR.
546 if (I->getOpcode() == Instruction::Or)
547 Mask &= ~RHS->getRawValue();
548 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
550 // Walk the LHS and the RHS.
551 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1) ||
552 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
553 case Instruction::Cast: {
554 const Type *SrcTy = I->getOperand(0)->getType();
555 if (SrcTy == Type::BoolTy)
556 return SimplifyDemandedBits(I->getOperand(0), Mask&1, Depth+1);
558 if (!SrcTy->isInteger()) return false;
560 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
561 // If this is a sign-extend, treat specially.
562 if (SrcTy->isSigned() &&
563 SrcBits < I->getType()->getPrimitiveSizeInBits()) {
564 // If none of the top bits are demanded, convert this into an unsigned
565 // extend instead of a sign extend.
566 if ((Mask & ((1ULL << SrcBits)-1)) == 0) {
567 // Convert to unsigned first.
569 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
570 I->getOperand(0)->getName());
571 InsertNewInstBefore(NewVal, *I);
572 NewVal = new CastInst(NewVal, I->getType(), I->getName());
573 InsertNewInstBefore(NewVal, *I);
574 return UpdateValueUsesWith(I, NewVal);
577 // Otherwise, the high-bits *are* demanded. This means that the code
578 // implicitly demands computation of the sign bit of the input, make sure
579 // we explicitly include it in Mask.
580 Mask |= 1ULL << (SrcBits-1);
583 // If this is an extension, the top bits are ignored.
584 Mask &= SrcTy->getIntegralTypeMask();
585 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
587 case Instruction::Select:
588 // Simplify the T and F values if they are not demanded.
589 return SimplifyDemandedBits(I->getOperand(2), Mask, Depth+1) ||
590 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
591 case Instruction::Shl:
592 // We only demand the low bits of the input.
593 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
594 return SimplifyDemandedBits(I->getOperand(0), Mask >> SA->getValue(),
597 case Instruction::Shr:
598 // We only demand the high bits of the input.
599 if (I->getType()->isUnsigned())
600 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
601 Mask <<= SA->getValue();
602 Mask &= I->getType()->getIntegralTypeMask();
603 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
605 // FIXME: handle signed shr, demanding the appropriate bits. If the top
606 // bits aren't demanded, strength reduce to a logical SHR instead.
612 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
613 // true when both operands are equal...
615 static bool isTrueWhenEqual(Instruction &I) {
616 return I.getOpcode() == Instruction::SetEQ ||
617 I.getOpcode() == Instruction::SetGE ||
618 I.getOpcode() == Instruction::SetLE;
621 /// AssociativeOpt - Perform an optimization on an associative operator. This
622 /// function is designed to check a chain of associative operators for a
623 /// potential to apply a certain optimization. Since the optimization may be
624 /// applicable if the expression was reassociated, this checks the chain, then
625 /// reassociates the expression as necessary to expose the optimization
626 /// opportunity. This makes use of a special Functor, which must define
627 /// 'shouldApply' and 'apply' methods.
629 template<typename Functor>
630 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
631 unsigned Opcode = Root.getOpcode();
632 Value *LHS = Root.getOperand(0);
634 // Quick check, see if the immediate LHS matches...
635 if (F.shouldApply(LHS))
636 return F.apply(Root);
638 // Otherwise, if the LHS is not of the same opcode as the root, return.
639 Instruction *LHSI = dyn_cast<Instruction>(LHS);
640 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
641 // Should we apply this transform to the RHS?
642 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
644 // If not to the RHS, check to see if we should apply to the LHS...
645 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
646 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
650 // If the functor wants to apply the optimization to the RHS of LHSI,
651 // reassociate the expression from ((? op A) op B) to (? op (A op B))
653 BasicBlock *BB = Root.getParent();
655 // Now all of the instructions are in the current basic block, go ahead
656 // and perform the reassociation.
657 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
659 // First move the selected RHS to the LHS of the root...
660 Root.setOperand(0, LHSI->getOperand(1));
662 // Make what used to be the LHS of the root be the user of the root...
663 Value *ExtraOperand = TmpLHSI->getOperand(1);
664 if (&Root == TmpLHSI) {
665 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
668 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
669 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
670 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
671 BasicBlock::iterator ARI = &Root; ++ARI;
672 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
675 // Now propagate the ExtraOperand down the chain of instructions until we
677 while (TmpLHSI != LHSI) {
678 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
679 // Move the instruction to immediately before the chain we are
680 // constructing to avoid breaking dominance properties.
681 NextLHSI->getParent()->getInstList().remove(NextLHSI);
682 BB->getInstList().insert(ARI, NextLHSI);
685 Value *NextOp = NextLHSI->getOperand(1);
686 NextLHSI->setOperand(1, ExtraOperand);
688 ExtraOperand = NextOp;
691 // Now that the instructions are reassociated, have the functor perform
692 // the transformation...
693 return F.apply(Root);
696 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
702 // AddRHS - Implements: X + X --> X << 1
705 AddRHS(Value *rhs) : RHS(rhs) {}
706 bool shouldApply(Value *LHS) const { return LHS == RHS; }
707 Instruction *apply(BinaryOperator &Add) const {
708 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
709 ConstantInt::get(Type::UByteTy, 1));
713 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
715 struct AddMaskingAnd {
717 AddMaskingAnd(Constant *c) : C2(c) {}
718 bool shouldApply(Value *LHS) const {
720 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
721 ConstantExpr::getAnd(C1, C2)->isNullValue();
723 Instruction *apply(BinaryOperator &Add) const {
724 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
728 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
730 if (isa<CastInst>(I)) {
731 if (Constant *SOC = dyn_cast<Constant>(SO))
732 return ConstantExpr::getCast(SOC, I.getType());
734 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
735 SO->getName() + ".cast"), I);
738 // Figure out if the constant is the left or the right argument.
739 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
740 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
742 if (Constant *SOC = dyn_cast<Constant>(SO)) {
744 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
745 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
748 Value *Op0 = SO, *Op1 = ConstOperand;
752 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
753 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
754 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
755 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
757 assert(0 && "Unknown binary instruction type!");
760 return IC->InsertNewInstBefore(New, I);
763 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
764 // constant as the other operand, try to fold the binary operator into the
765 // select arguments. This also works for Cast instructions, which obviously do
766 // not have a second operand.
767 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
769 // Don't modify shared select instructions
770 if (!SI->hasOneUse()) return 0;
771 Value *TV = SI->getOperand(1);
772 Value *FV = SI->getOperand(2);
774 if (isa<Constant>(TV) || isa<Constant>(FV)) {
775 // Bool selects with constant operands can be folded to logical ops.
776 if (SI->getType() == Type::BoolTy) return 0;
778 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
779 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
781 return new SelectInst(SI->getCondition(), SelectTrueVal,
788 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
789 /// node as operand #0, see if we can fold the instruction into the PHI (which
790 /// is only possible if all operands to the PHI are constants).
791 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
792 PHINode *PN = cast<PHINode>(I.getOperand(0));
793 unsigned NumPHIValues = PN->getNumIncomingValues();
794 if (!PN->hasOneUse() || NumPHIValues == 0 ||
795 !isa<Constant>(PN->getIncomingValue(0))) return 0;
797 // Check to see if all of the operands of the PHI are constants. If not, we
798 // cannot do the transformation.
799 for (unsigned i = 1; i != NumPHIValues; ++i)
800 if (!isa<Constant>(PN->getIncomingValue(i)))
803 // Okay, we can do the transformation: create the new PHI node.
804 PHINode *NewPN = new PHINode(I.getType(), I.getName());
806 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
807 InsertNewInstBefore(NewPN, *PN);
809 // Next, add all of the operands to the PHI.
810 if (I.getNumOperands() == 2) {
811 Constant *C = cast<Constant>(I.getOperand(1));
812 for (unsigned i = 0; i != NumPHIValues; ++i) {
813 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
814 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
815 PN->getIncomingBlock(i));
818 assert(isa<CastInst>(I) && "Unary op should be a cast!");
819 const Type *RetTy = I.getType();
820 for (unsigned i = 0; i != NumPHIValues; ++i) {
821 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
822 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
823 PN->getIncomingBlock(i));
826 return ReplaceInstUsesWith(I, NewPN);
829 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
830 bool Changed = SimplifyCommutative(I);
831 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
833 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
834 // X + undef -> undef
835 if (isa<UndefValue>(RHS))
836 return ReplaceInstUsesWith(I, RHS);
839 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
840 if (RHSC->isNullValue())
841 return ReplaceInstUsesWith(I, LHS);
842 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
843 if (CFP->isExactlyValue(-0.0))
844 return ReplaceInstUsesWith(I, LHS);
847 // X + (signbit) --> X ^ signbit
848 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
849 uint64_t Val = CI->getZExtValue();
850 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
851 return BinaryOperator::createXor(LHS, RHS);
854 if (isa<PHINode>(LHS))
855 if (Instruction *NV = FoldOpIntoPhi(I))
858 ConstantInt *XorRHS = 0;
860 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
861 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
862 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
863 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
865 uint64_t C0080Val = 1ULL << 31;
866 int64_t CFF80Val = -C0080Val;
869 if (TySizeBits > Size) {
871 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
872 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
873 if (RHSSExt == CFF80Val) {
874 if (XorRHS->getZExtValue() == C0080Val)
876 } else if (RHSZExt == C0080Val) {
877 if (XorRHS->getSExtValue() == CFF80Val)
881 // This is a sign extend if the top bits are known zero.
882 uint64_t Mask = XorLHS->getType()->getIntegralTypeMask();
883 Mask <<= 64-(TySizeBits-Size);
884 if (!MaskedValueIsZero(XorLHS, Mask))
885 Size = 0; // Not a sign ext, but can't be any others either.
895 const Type *MiddleType = 0;
898 case 32: MiddleType = Type::IntTy; break;
899 case 16: MiddleType = Type::ShortTy; break;
900 case 8: MiddleType = Type::SByteTy; break;
903 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
904 InsertNewInstBefore(NewTrunc, I);
905 return new CastInst(NewTrunc, I.getType());
911 if (I.getType()->isInteger()) {
912 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
914 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
915 if (RHSI->getOpcode() == Instruction::Sub)
916 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
917 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
919 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
920 if (LHSI->getOpcode() == Instruction::Sub)
921 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
922 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
927 if (Value *V = dyn_castNegVal(LHS))
928 return BinaryOperator::createSub(RHS, V);
931 if (!isa<Constant>(RHS))
932 if (Value *V = dyn_castNegVal(RHS))
933 return BinaryOperator::createSub(LHS, V);
937 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
938 if (X == RHS) // X*C + X --> X * (C+1)
939 return BinaryOperator::createMul(RHS, AddOne(C2));
941 // X*C1 + X*C2 --> X * (C1+C2)
943 if (X == dyn_castFoldableMul(RHS, C1))
944 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
947 // X + X*C --> X * (C+1)
948 if (dyn_castFoldableMul(RHS, C2) == LHS)
949 return BinaryOperator::createMul(LHS, AddOne(C2));
952 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
953 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
954 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
956 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
958 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
959 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
960 return BinaryOperator::createSub(C, X);
963 // (X & FF00) + xx00 -> (X+xx00) & FF00
964 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
965 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
967 // See if all bits from the first bit set in the Add RHS up are included
968 // in the mask. First, get the rightmost bit.
969 uint64_t AddRHSV = CRHS->getRawValue();
971 // Form a mask of all bits from the lowest bit added through the top.
972 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
973 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
975 // See if the and mask includes all of these bits.
976 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
978 if (AddRHSHighBits == AddRHSHighBitsAnd) {
979 // Okay, the xform is safe. Insert the new add pronto.
980 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
982 return BinaryOperator::createAnd(NewAdd, C2);
987 // Try to fold constant add into select arguments.
988 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
989 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
993 return Changed ? &I : 0;
996 // isSignBit - Return true if the value represented by the constant only has the
997 // highest order bit set.
998 static bool isSignBit(ConstantInt *CI) {
999 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1000 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1003 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1005 static Value *RemoveNoopCast(Value *V) {
1006 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1007 const Type *CTy = CI->getType();
1008 const Type *OpTy = CI->getOperand(0)->getType();
1009 if (CTy->isInteger() && OpTy->isInteger()) {
1010 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1011 return RemoveNoopCast(CI->getOperand(0));
1012 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1013 return RemoveNoopCast(CI->getOperand(0));
1018 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1019 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1021 if (Op0 == Op1) // sub X, X -> 0
1022 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1024 // If this is a 'B = x-(-A)', change to B = x+A...
1025 if (Value *V = dyn_castNegVal(Op1))
1026 return BinaryOperator::createAdd(Op0, V);
1028 if (isa<UndefValue>(Op0))
1029 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1030 if (isa<UndefValue>(Op1))
1031 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1033 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1034 // Replace (-1 - A) with (~A)...
1035 if (C->isAllOnesValue())
1036 return BinaryOperator::createNot(Op1);
1038 // C - ~X == X + (1+C)
1040 if (match(Op1, m_Not(m_Value(X))))
1041 return BinaryOperator::createAdd(X,
1042 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1043 // -((uint)X >> 31) -> ((int)X >> 31)
1044 // -((int)X >> 31) -> ((uint)X >> 31)
1045 if (C->isNullValue()) {
1046 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1047 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1048 if (SI->getOpcode() == Instruction::Shr)
1049 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1051 if (SI->getType()->isSigned())
1052 NewTy = SI->getType()->getUnsignedVersion();
1054 NewTy = SI->getType()->getSignedVersion();
1055 // Check to see if we are shifting out everything but the sign bit.
1056 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
1057 // Ok, the transformation is safe. Insert a cast of the incoming
1058 // value, then the new shift, then the new cast.
1059 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1060 SI->getOperand(0)->getName());
1061 Value *InV = InsertNewInstBefore(FirstCast, I);
1062 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1064 if (NewShift->getType() == I.getType())
1067 InV = InsertNewInstBefore(NewShift, I);
1068 return new CastInst(NewShift, I.getType());
1074 // Try to fold constant sub into select arguments.
1075 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1076 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1079 if (isa<PHINode>(Op0))
1080 if (Instruction *NV = FoldOpIntoPhi(I))
1084 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1085 if (Op1I->getOpcode() == Instruction::Add &&
1086 !Op0->getType()->isFloatingPoint()) {
1087 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
1088 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1089 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
1090 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1091 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1092 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1093 // C1-(X+C2) --> (C1-C2)-X
1094 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1095 Op1I->getOperand(0));
1099 if (Op1I->hasOneUse()) {
1100 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1101 // is not used by anyone else...
1103 if (Op1I->getOpcode() == Instruction::Sub &&
1104 !Op1I->getType()->isFloatingPoint()) {
1105 // Swap the two operands of the subexpr...
1106 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1107 Op1I->setOperand(0, IIOp1);
1108 Op1I->setOperand(1, IIOp0);
1110 // Create the new top level add instruction...
1111 return BinaryOperator::createAdd(Op0, Op1);
1114 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1116 if (Op1I->getOpcode() == Instruction::And &&
1117 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1118 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1121 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
1122 return BinaryOperator::createAnd(Op0, NewNot);
1125 // -(X sdiv C) -> (X sdiv -C)
1126 if (Op1I->getOpcode() == Instruction::Div)
1127 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1128 if (CSI->isNullValue())
1129 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
1130 return BinaryOperator::createDiv(Op1I->getOperand(0),
1131 ConstantExpr::getNeg(DivRHS));
1133 // X - X*C --> X * (1-C)
1134 ConstantInt *C2 = 0;
1135 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1137 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1138 return BinaryOperator::createMul(Op0, CP1);
1143 if (!Op0->getType()->isFloatingPoint())
1144 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1145 if (Op0I->getOpcode() == Instruction::Add) {
1146 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1147 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1148 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1149 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1150 } else if (Op0I->getOpcode() == Instruction::Sub) {
1151 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1152 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
1156 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1157 if (X == Op1) { // X*C - X --> X * (C-1)
1158 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1159 return BinaryOperator::createMul(Op1, CP1);
1162 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1163 if (X == dyn_castFoldableMul(Op1, C2))
1164 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1169 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1170 /// really just returns true if the most significant (sign) bit is set.
1171 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1172 if (RHS->getType()->isSigned()) {
1173 // True if source is LHS < 0 or LHS <= -1
1174 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1175 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1177 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1178 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1179 // the size of the integer type.
1180 if (Opcode == Instruction::SetGE)
1181 return RHSC->getValue() ==
1182 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
1183 if (Opcode == Instruction::SetGT)
1184 return RHSC->getValue() ==
1185 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
1190 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1191 bool Changed = SimplifyCommutative(I);
1192 Value *Op0 = I.getOperand(0);
1194 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1195 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1197 // Simplify mul instructions with a constant RHS...
1198 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1199 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1201 // ((X << C1)*C2) == (X * (C2 << C1))
1202 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1203 if (SI->getOpcode() == Instruction::Shl)
1204 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
1205 return BinaryOperator::createMul(SI->getOperand(0),
1206 ConstantExpr::getShl(CI, ShOp));
1208 if (CI->isNullValue())
1209 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1210 if (CI->equalsInt(1)) // X * 1 == X
1211 return ReplaceInstUsesWith(I, Op0);
1212 if (CI->isAllOnesValue()) // X * -1 == 0 - X
1213 return BinaryOperator::createNeg(Op0, I.getName());
1215 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
1216 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1217 uint64_t C = Log2_64(Val);
1218 return new ShiftInst(Instruction::Shl, Op0,
1219 ConstantUInt::get(Type::UByteTy, C));
1221 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
1222 if (Op1F->isNullValue())
1223 return ReplaceInstUsesWith(I, Op1);
1225 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1226 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1227 if (Op1F->getValue() == 1.0)
1228 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1231 // Try to fold constant mul into select arguments.
1232 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1233 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1236 if (isa<PHINode>(Op0))
1237 if (Instruction *NV = FoldOpIntoPhi(I))
1241 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1242 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
1243 return BinaryOperator::createMul(Op0v, Op1v);
1245 // If one of the operands of the multiply is a cast from a boolean value, then
1246 // we know the bool is either zero or one, so this is a 'masking' multiply.
1247 // See if we can simplify things based on how the boolean was originally
1249 CastInst *BoolCast = 0;
1250 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1251 if (CI->getOperand(0)->getType() == Type::BoolTy)
1254 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1255 if (CI->getOperand(0)->getType() == Type::BoolTy)
1258 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1259 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1260 const Type *SCOpTy = SCIOp0->getType();
1262 // If the setcc is true iff the sign bit of X is set, then convert this
1263 // multiply into a shift/and combination.
1264 if (isa<ConstantInt>(SCIOp1) &&
1265 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
1266 // Shift the X value right to turn it into "all signbits".
1267 Constant *Amt = ConstantUInt::get(Type::UByteTy,
1268 SCOpTy->getPrimitiveSizeInBits()-1);
1269 if (SCIOp0->getType()->isUnsigned()) {
1270 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
1271 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1272 SCIOp0->getName()), I);
1276 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1277 BoolCast->getOperand(0)->getName()+
1280 // If the multiply type is not the same as the source type, sign extend
1281 // or truncate to the multiply type.
1282 if (I.getType() != V->getType())
1283 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
1285 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
1286 return BinaryOperator::createAnd(V, OtherOp);
1291 return Changed ? &I : 0;
1294 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
1295 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1297 if (isa<UndefValue>(Op0)) // undef / X -> 0
1298 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1299 if (isa<UndefValue>(Op1))
1300 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1302 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1304 if (RHS->equalsInt(1))
1305 return ReplaceInstUsesWith(I, Op0);
1308 if (RHS->isAllOnesValue())
1309 return BinaryOperator::createNeg(Op0);
1311 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1312 if (LHS->getOpcode() == Instruction::Div)
1313 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
1314 // (X / C1) / C2 -> X / (C1*C2)
1315 return BinaryOperator::createDiv(LHS->getOperand(0),
1316 ConstantExpr::getMul(RHS, LHSRHS));
1319 // Check to see if this is an unsigned division with an exact power of 2,
1320 // if so, convert to a right shift.
1321 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1322 if (uint64_t Val = C->getValue()) // Don't break X / 0
1323 if (isPowerOf2_64(Val)) {
1324 uint64_t C = Log2_64(Val);
1325 return new ShiftInst(Instruction::Shr, Op0,
1326 ConstantUInt::get(Type::UByteTy, C));
1330 if (RHS->getType()->isSigned())
1331 if (Value *LHSNeg = dyn_castNegVal(Op0))
1332 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1334 if (!RHS->isNullValue()) {
1335 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1336 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1338 if (isa<PHINode>(Op0))
1339 if (Instruction *NV = FoldOpIntoPhi(I))
1344 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1345 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1346 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1347 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1348 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1349 if (STO->getValue() == 0) { // Couldn't be this argument.
1350 I.setOperand(1, SFO);
1352 } else if (SFO->getValue() == 0) {
1353 I.setOperand(1, STO);
1357 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1358 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1359 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
1360 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1361 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1362 TC, SI->getName()+".t");
1363 TSI = InsertNewInstBefore(TSI, I);
1365 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1366 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1367 FC, SI->getName()+".f");
1368 FSI = InsertNewInstBefore(FSI, I);
1369 return new SelectInst(SI->getOperand(0), TSI, FSI);
1373 // 0 / X == 0, we don't need to preserve faults!
1374 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1375 if (LHS->equalsInt(0))
1376 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1378 if (I.getType()->isSigned()) {
1379 // If the sign bits of both operands are zero (i.e. we can prove they are
1380 // unsigned inputs), turn this into a udiv.
1381 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1382 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1383 const Type *NTy = Op0->getType()->getUnsignedVersion();
1384 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1385 InsertNewInstBefore(LHS, I);
1387 if (Constant *R = dyn_cast<Constant>(Op1))
1388 RHS = ConstantExpr::getCast(R, NTy);
1390 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1391 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1392 InsertNewInstBefore(Div, I);
1393 return new CastInst(Div, I.getType());
1396 // Known to be an unsigned division.
1397 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1398 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1399 if (RHSI->getOpcode() == Instruction::Shl &&
1400 isa<ConstantUInt>(RHSI->getOperand(0))) {
1401 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1402 if (isPowerOf2_64(C1)) {
1403 unsigned C2 = Log2_64(C1);
1404 Value *Add = RHSI->getOperand(1);
1406 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1407 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1410 return new ShiftInst(Instruction::Shr, Op0, Add);
1420 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
1421 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1422 if (I.getType()->isSigned()) {
1423 if (Value *RHSNeg = dyn_castNegVal(Op1))
1424 if (!isa<ConstantSInt>(RHSNeg) ||
1425 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
1427 AddUsesToWorkList(I);
1428 I.setOperand(1, RHSNeg);
1432 // If the top bits of both operands are zero (i.e. we can prove they are
1433 // unsigned inputs), turn this into a urem.
1434 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1435 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1436 const Type *NTy = Op0->getType()->getUnsignedVersion();
1437 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1438 InsertNewInstBefore(LHS, I);
1440 if (Constant *R = dyn_cast<Constant>(Op1))
1441 RHS = ConstantExpr::getCast(R, NTy);
1443 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1444 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1445 InsertNewInstBefore(Rem, I);
1446 return new CastInst(Rem, I.getType());
1450 if (isa<UndefValue>(Op0)) // undef % X -> 0
1451 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1452 if (isa<UndefValue>(Op1))
1453 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1455 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1456 if (RHS->equalsInt(1)) // X % 1 == 0
1457 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1459 // Check to see if this is an unsigned remainder with an exact power of 2,
1460 // if so, convert to a bitwise and.
1461 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1462 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
1463 if (!(Val & (Val-1))) // Power of 2
1464 return BinaryOperator::createAnd(Op0,
1465 ConstantUInt::get(I.getType(), Val-1));
1467 if (!RHS->isNullValue()) {
1468 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1469 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1471 if (isa<PHINode>(Op0))
1472 if (Instruction *NV = FoldOpIntoPhi(I))
1477 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1478 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1479 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1480 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1481 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1482 if (STO->getValue() == 0) { // Couldn't be this argument.
1483 I.setOperand(1, SFO);
1485 } else if (SFO->getValue() == 0) {
1486 I.setOperand(1, STO);
1490 if (!(STO->getValue() & (STO->getValue()-1)) &&
1491 !(SFO->getValue() & (SFO->getValue()-1))) {
1492 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1493 SubOne(STO), SI->getName()+".t"), I);
1494 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1495 SubOne(SFO), SI->getName()+".f"), I);
1496 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1500 // 0 % X == 0, we don't need to preserve faults!
1501 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1502 if (LHS->equalsInt(0))
1503 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1506 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1507 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1508 if (I.getType()->isUnsigned() &&
1509 RHSI->getOpcode() == Instruction::Shl &&
1510 isa<ConstantUInt>(RHSI->getOperand(0))) {
1511 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1512 if (isPowerOf2_64(C1)) {
1513 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1514 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1516 return BinaryOperator::createAnd(Op0, Add);
1524 // isMaxValueMinusOne - return true if this is Max-1
1525 static bool isMaxValueMinusOne(const ConstantInt *C) {
1526 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1527 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
1529 const ConstantSInt *CS = cast<ConstantSInt>(C);
1531 // Calculate 0111111111..11111
1532 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1533 int64_t Val = INT64_MAX; // All ones
1534 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1535 return CS->getValue() == Val-1;
1538 // isMinValuePlusOne - return true if this is Min+1
1539 static bool isMinValuePlusOne(const ConstantInt *C) {
1540 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1541 return CU->getValue() == 1;
1543 const ConstantSInt *CS = cast<ConstantSInt>(C);
1545 // Calculate 1111111111000000000000
1546 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1547 int64_t Val = -1; // All ones
1548 Val <<= TypeBits-1; // Shift over to the right spot
1549 return CS->getValue() == Val+1;
1552 // isOneBitSet - Return true if there is exactly one bit set in the specified
1554 static bool isOneBitSet(const ConstantInt *CI) {
1555 uint64_t V = CI->getRawValue();
1556 return V && (V & (V-1)) == 0;
1559 #if 0 // Currently unused
1560 // isLowOnes - Return true if the constant is of the form 0+1+.
1561 static bool isLowOnes(const ConstantInt *CI) {
1562 uint64_t V = CI->getRawValue();
1564 // There won't be bits set in parts that the type doesn't contain.
1565 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1567 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1568 return U && V && (U & V) == 0;
1572 // isHighOnes - Return true if the constant is of the form 1+0+.
1573 // This is the same as lowones(~X).
1574 static bool isHighOnes(const ConstantInt *CI) {
1575 uint64_t V = ~CI->getRawValue();
1576 if (~V == 0) return false; // 0's does not match "1+"
1578 // There won't be bits set in parts that the type doesn't contain.
1579 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1581 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1582 return U && V && (U & V) == 0;
1586 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1587 /// are carefully arranged to allow folding of expressions such as:
1589 /// (A < B) | (A > B) --> (A != B)
1591 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1592 /// represents that the comparison is true if A == B, and bit value '1' is true
1595 static unsigned getSetCondCode(const SetCondInst *SCI) {
1596 switch (SCI->getOpcode()) {
1598 case Instruction::SetGT: return 1;
1599 case Instruction::SetEQ: return 2;
1600 case Instruction::SetGE: return 3;
1601 case Instruction::SetLT: return 4;
1602 case Instruction::SetNE: return 5;
1603 case Instruction::SetLE: return 6;
1606 assert(0 && "Invalid SetCC opcode!");
1611 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
1612 /// opcode and two operands into either a constant true or false, or a brand new
1613 /// SetCC instruction.
1614 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1616 case 0: return ConstantBool::False;
1617 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1618 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1619 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1620 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1621 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1622 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1623 case 7: return ConstantBool::True;
1624 default: assert(0 && "Illegal SetCCCode!"); return 0;
1628 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1629 struct FoldSetCCLogical {
1632 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1633 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1634 bool shouldApply(Value *V) const {
1635 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1636 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1637 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1640 Instruction *apply(BinaryOperator &Log) const {
1641 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1642 if (SCI->getOperand(0) != LHS) {
1643 assert(SCI->getOperand(1) == LHS);
1644 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1647 unsigned LHSCode = getSetCondCode(SCI);
1648 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1650 switch (Log.getOpcode()) {
1651 case Instruction::And: Code = LHSCode & RHSCode; break;
1652 case Instruction::Or: Code = LHSCode | RHSCode; break;
1653 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
1654 default: assert(0 && "Illegal logical opcode!"); return 0;
1657 Value *RV = getSetCCValue(Code, LHS, RHS);
1658 if (Instruction *I = dyn_cast<Instruction>(RV))
1660 // Otherwise, it's a constant boolean value...
1661 return IC.ReplaceInstUsesWith(Log, RV);
1665 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1666 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1667 // guaranteed to be either a shift instruction or a binary operator.
1668 Instruction *InstCombiner::OptAndOp(Instruction *Op,
1669 ConstantIntegral *OpRHS,
1670 ConstantIntegral *AndRHS,
1671 BinaryOperator &TheAnd) {
1672 Value *X = Op->getOperand(0);
1673 Constant *Together = 0;
1674 if (!isa<ShiftInst>(Op))
1675 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
1677 switch (Op->getOpcode()) {
1678 case Instruction::Xor:
1679 if (Op->hasOneUse()) {
1680 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1681 std::string OpName = Op->getName(); Op->setName("");
1682 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
1683 InsertNewInstBefore(And, TheAnd);
1684 return BinaryOperator::createXor(And, Together);
1687 case Instruction::Or:
1688 if (Together == AndRHS) // (X | C) & C --> C
1689 return ReplaceInstUsesWith(TheAnd, AndRHS);
1691 if (Op->hasOneUse() && Together != OpRHS) {
1692 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1693 std::string Op0Name = Op->getName(); Op->setName("");
1694 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1695 InsertNewInstBefore(Or, TheAnd);
1696 return BinaryOperator::createAnd(Or, AndRHS);
1699 case Instruction::Add:
1700 if (Op->hasOneUse()) {
1701 // Adding a one to a single bit bit-field should be turned into an XOR
1702 // of the bit. First thing to check is to see if this AND is with a
1703 // single bit constant.
1704 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
1706 // Clear bits that are not part of the constant.
1707 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
1709 // If there is only one bit set...
1710 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
1711 // Ok, at this point, we know that we are masking the result of the
1712 // ADD down to exactly one bit. If the constant we are adding has
1713 // no bits set below this bit, then we can eliminate the ADD.
1714 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
1716 // Check to see if any bits below the one bit set in AndRHSV are set.
1717 if ((AddRHS & (AndRHSV-1)) == 0) {
1718 // If not, the only thing that can effect the output of the AND is
1719 // the bit specified by AndRHSV. If that bit is set, the effect of
1720 // the XOR is to toggle the bit. If it is clear, then the ADD has
1722 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1723 TheAnd.setOperand(0, X);
1726 std::string Name = Op->getName(); Op->setName("");
1727 // Pull the XOR out of the AND.
1728 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
1729 InsertNewInstBefore(NewAnd, TheAnd);
1730 return BinaryOperator::createXor(NewAnd, AndRHS);
1737 case Instruction::Shl: {
1738 // We know that the AND will not produce any of the bits shifted in, so if
1739 // the anded constant includes them, clear them now!
1741 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1742 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1743 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1745 if (CI == ShlMask) { // Masking out bits that the shift already masks
1746 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1747 } else if (CI != AndRHS) { // Reducing bits set in and.
1748 TheAnd.setOperand(1, CI);
1753 case Instruction::Shr:
1754 // We know that the AND will not produce any of the bits shifted in, so if
1755 // the anded constant includes them, clear them now! This only applies to
1756 // unsigned shifts, because a signed shr may bring in set bits!
1758 if (AndRHS->getType()->isUnsigned()) {
1759 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1760 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1761 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1763 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1764 return ReplaceInstUsesWith(TheAnd, Op);
1765 } else if (CI != AndRHS) {
1766 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
1769 } else { // Signed shr.
1770 // See if this is shifting in some sign extension, then masking it out
1772 if (Op->hasOneUse()) {
1773 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1774 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1775 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1776 if (CI == AndRHS) { // Masking out bits shifted in.
1777 // Make the argument unsigned.
1778 Value *ShVal = Op->getOperand(0);
1779 ShVal = InsertCastBefore(ShVal,
1780 ShVal->getType()->getUnsignedVersion(),
1782 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1783 OpRHS, Op->getName()),
1785 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1786 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1789 return new CastInst(ShVal, Op->getType());
1799 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1800 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1801 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1802 /// insert new instructions.
1803 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1804 bool Inside, Instruction &IB) {
1805 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1806 "Lo is not <= Hi in range emission code!");
1808 if (Lo == Hi) // Trivially false.
1809 return new SetCondInst(Instruction::SetNE, V, V);
1810 if (cast<ConstantIntegral>(Lo)->isMinValue())
1811 return new SetCondInst(Instruction::SetLT, V, Hi);
1813 Constant *AddCST = ConstantExpr::getNeg(Lo);
1814 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1815 InsertNewInstBefore(Add, IB);
1816 // Convert to unsigned for the comparison.
1817 const Type *UnsType = Add->getType()->getUnsignedVersion();
1818 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1819 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1820 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1821 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1824 if (Lo == Hi) // Trivially true.
1825 return new SetCondInst(Instruction::SetEQ, V, V);
1827 Hi = SubOne(cast<ConstantInt>(Hi));
1828 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1829 return new SetCondInst(Instruction::SetGT, V, Hi);
1831 // Emit X-Lo > Hi-Lo-1
1832 Constant *AddCST = ConstantExpr::getNeg(Lo);
1833 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1834 InsertNewInstBefore(Add, IB);
1835 // Convert to unsigned for the comparison.
1836 const Type *UnsType = Add->getType()->getUnsignedVersion();
1837 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1838 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1839 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1840 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1843 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1844 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
1845 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1846 // not, since all 1s are not contiguous.
1847 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1848 uint64_t V = Val->getRawValue();
1849 if (!isShiftedMask_64(V)) return false;
1851 // look for the first zero bit after the run of ones
1852 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1853 // look for the first non-zero bit
1854 ME = 64-CountLeadingZeros_64(V);
1860 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1861 /// where isSub determines whether the operator is a sub. If we can fold one of
1862 /// the following xforms:
1864 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1865 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1866 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1868 /// return (A +/- B).
1870 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1871 ConstantIntegral *Mask, bool isSub,
1873 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1874 if (!LHSI || LHSI->getNumOperands() != 2 ||
1875 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1877 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1879 switch (LHSI->getOpcode()) {
1881 case Instruction::And:
1882 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1883 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1884 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1887 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1888 // part, we don't need any explicit masks to take them out of A. If that
1889 // is all N is, ignore it.
1891 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
1892 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
1894 if (MaskedValueIsZero(RHS, Mask))
1899 case Instruction::Or:
1900 case Instruction::Xor:
1901 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1902 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1903 ConstantExpr::getAnd(N, Mask)->isNullValue())
1910 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1912 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1913 return InsertNewInstBefore(New, I);
1916 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1917 bool Changed = SimplifyCommutative(I);
1918 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1920 if (isa<UndefValue>(Op1)) // X & undef -> 0
1921 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1925 return ReplaceInstUsesWith(I, Op1);
1927 // See if we can simplify any instructions used by the LHS whose sole
1928 // purpose is to compute bits we don't care about.
1929 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask()))
1932 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
1934 if (AndRHS->isAllOnesValue())
1935 return ReplaceInstUsesWith(I, Op0);
1937 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
1938 // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1939 // through many levels of ands.
1941 Value *X = 0; ConstantInt *C1 = 0;
1942 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1943 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1946 if (MaskedValueIsZero(Op0, AndRHS->getZExtValue())) // LHS & RHS == 0
1947 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1949 // If the mask is not masking out any bits, there is no reason to do the
1950 // and in the first place.
1951 uint64_t NotAndRHS = // ~ANDRHS
1952 AndRHS->getZExtValue()^Op0->getType()->getIntegralTypeMask();
1953 if (MaskedValueIsZero(Op0, NotAndRHS))
1954 return ReplaceInstUsesWith(I, Op0);
1956 // Optimize a variety of ((val OP C1) & C2) combinations...
1957 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1958 Instruction *Op0I = cast<Instruction>(Op0);
1959 Value *Op0LHS = Op0I->getOperand(0);
1960 Value *Op0RHS = Op0I->getOperand(1);
1961 switch (Op0I->getOpcode()) {
1962 case Instruction::Xor:
1963 case Instruction::Or:
1964 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1965 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1966 if (MaskedValueIsZero(Op0LHS, AndRHS->getZExtValue()))
1967 return BinaryOperator::createAnd(Op0RHS, AndRHS);
1968 if (MaskedValueIsZero(Op0RHS, AndRHS->getZExtValue()))
1969 return BinaryOperator::createAnd(Op0LHS, AndRHS);
1971 // If the mask is only needed on one incoming arm, push it up.
1972 if (Op0I->hasOneUse()) {
1973 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1974 // Not masking anything out for the LHS, move to RHS.
1975 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1976 Op0RHS->getName()+".masked");
1977 InsertNewInstBefore(NewRHS, I);
1978 return BinaryOperator::create(
1979 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
1981 if (!isa<Constant>(Op0RHS) &&
1982 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1983 // Not masking anything out for the RHS, move to LHS.
1984 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1985 Op0LHS->getName()+".masked");
1986 InsertNewInstBefore(NewLHS, I);
1987 return BinaryOperator::create(
1988 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1993 case Instruction::And:
1994 // (X & V) & C2 --> 0 iff (V & C2) == 0
1995 if (MaskedValueIsZero(Op0LHS, AndRHS->getZExtValue()) ||
1996 MaskedValueIsZero(Op0RHS, AndRHS->getZExtValue()))
1997 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1999 case Instruction::Add:
2000 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2001 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2002 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2003 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2004 return BinaryOperator::createAnd(V, AndRHS);
2005 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2006 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
2009 case Instruction::Sub:
2010 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2011 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2012 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2013 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2014 return BinaryOperator::createAnd(V, AndRHS);
2018 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2019 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2021 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2022 const Type *SrcTy = CI->getOperand(0)->getType();
2024 // If this is an integer truncation or change from signed-to-unsigned, and
2025 // if the source is an and/or with immediate, transform it. This
2026 // frequently occurs for bitfield accesses.
2027 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2028 if (SrcTy->getPrimitiveSizeInBits() >=
2029 I.getType()->getPrimitiveSizeInBits() &&
2030 CastOp->getNumOperands() == 2)
2031 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2032 if (CastOp->getOpcode() == Instruction::And) {
2033 // Change: and (cast (and X, C1) to T), C2
2034 // into : and (cast X to T), trunc(C1)&C2
2035 // This will folds the two ands together, which may allow other
2037 Instruction *NewCast =
2038 new CastInst(CastOp->getOperand(0), I.getType(),
2039 CastOp->getName()+".shrunk");
2040 NewCast = InsertNewInstBefore(NewCast, I);
2042 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2043 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2044 return BinaryOperator::createAnd(NewCast, C3);
2045 } else if (CastOp->getOpcode() == Instruction::Or) {
2046 // Change: and (cast (or X, C1) to T), C2
2047 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2048 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2049 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2050 return ReplaceInstUsesWith(I, AndRHS);
2055 // If this is an integer sign or zero extension instruction.
2056 if (SrcTy->isIntegral() &&
2057 SrcTy->getPrimitiveSizeInBits() <
2058 CI->getType()->getPrimitiveSizeInBits()) {
2060 if (SrcTy->isUnsigned()) {
2061 // See if this and is clearing out bits that are known to be zero
2062 // anyway (due to the zero extension).
2063 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2064 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2065 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
2066 if (Result == Mask) // The "and" isn't doing anything, remove it.
2067 return ReplaceInstUsesWith(I, CI);
2068 if (Result != AndRHS) { // Reduce the and RHS constant.
2069 I.setOperand(1, Result);
2074 if (CI->hasOneUse() && SrcTy->isInteger()) {
2075 // We can only do this if all of the sign bits brought in are masked
2076 // out. Compute this by first getting 0000011111, then inverting
2078 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2079 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2080 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
2081 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
2082 // If the and is clearing all of the sign bits, change this to a
2083 // zero extension cast. To do this, cast the cast input to
2084 // unsigned, then to the requested size.
2085 Value *CastOp = CI->getOperand(0);
2087 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
2088 CI->getName()+".uns");
2089 NC = InsertNewInstBefore(NC, I);
2090 // Finally, insert a replacement for CI.
2091 NC = new CastInst(NC, CI->getType(), CI->getName());
2093 NC = InsertNewInstBefore(NC, I);
2094 WorkList.push_back(CI); // Delete CI later.
2095 I.setOperand(0, NC);
2096 return &I; // The AND operand was modified.
2103 // Try to fold constant and into select arguments.
2104 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2105 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2107 if (isa<PHINode>(Op0))
2108 if (Instruction *NV = FoldOpIntoPhi(I))
2112 Value *Op0NotVal = dyn_castNotVal(Op0);
2113 Value *Op1NotVal = dyn_castNotVal(Op1);
2115 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2116 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2118 // (~A & ~B) == (~(A | B)) - De Morgan's Law
2119 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2120 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2121 I.getName()+".demorgan");
2122 InsertNewInstBefore(Or, I);
2123 return BinaryOperator::createNot(Or);
2126 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2127 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2128 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2131 Value *LHSVal, *RHSVal;
2132 ConstantInt *LHSCst, *RHSCst;
2133 Instruction::BinaryOps LHSCC, RHSCC;
2134 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2135 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2136 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2137 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2138 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2139 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2140 // Ensure that the larger constant is on the RHS.
2141 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2142 SetCondInst *LHS = cast<SetCondInst>(Op0);
2143 if (cast<ConstantBool>(Cmp)->getValue()) {
2144 std::swap(LHS, RHS);
2145 std::swap(LHSCst, RHSCst);
2146 std::swap(LHSCC, RHSCC);
2149 // At this point, we know we have have two setcc instructions
2150 // comparing a value against two constants and and'ing the result
2151 // together. Because of the above check, we know that we only have
2152 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2153 // FoldSetCCLogical check above), that the two constants are not
2155 assert(LHSCst != RHSCst && "Compares not folded above?");
2158 default: assert(0 && "Unknown integer condition code!");
2159 case Instruction::SetEQ:
2161 default: assert(0 && "Unknown integer condition code!");
2162 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2163 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2164 return ReplaceInstUsesWith(I, ConstantBool::False);
2165 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2166 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2167 return ReplaceInstUsesWith(I, LHS);
2169 case Instruction::SetNE:
2171 default: assert(0 && "Unknown integer condition code!");
2172 case Instruction::SetLT:
2173 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2174 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2175 break; // (X != 13 & X < 15) -> no change
2176 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2177 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2178 return ReplaceInstUsesWith(I, RHS);
2179 case Instruction::SetNE:
2180 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2181 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2182 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2183 LHSVal->getName()+".off");
2184 InsertNewInstBefore(Add, I);
2185 const Type *UnsType = Add->getType()->getUnsignedVersion();
2186 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2187 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2188 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2189 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2191 break; // (X != 13 & X != 15) -> no change
2194 case Instruction::SetLT:
2196 default: assert(0 && "Unknown integer condition code!");
2197 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2198 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2199 return ReplaceInstUsesWith(I, ConstantBool::False);
2200 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2201 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2202 return ReplaceInstUsesWith(I, LHS);
2204 case Instruction::SetGT:
2206 default: assert(0 && "Unknown integer condition code!");
2207 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2208 return ReplaceInstUsesWith(I, LHS);
2209 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2210 return ReplaceInstUsesWith(I, RHS);
2211 case Instruction::SetNE:
2212 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2213 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2214 break; // (X > 13 & X != 15) -> no change
2215 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2216 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
2222 return Changed ? &I : 0;
2225 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2226 bool Changed = SimplifyCommutative(I);
2227 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2229 if (isa<UndefValue>(Op1))
2230 return ReplaceInstUsesWith(I, // X | undef -> -1
2231 ConstantIntegral::getAllOnesValue(I.getType()));
2233 // or X, X = X or X, 0 == X
2234 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2235 return ReplaceInstUsesWith(I, Op0);
2238 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2239 // If X is known to only contain bits that already exist in RHS, just
2240 // replace this instruction with RHS directly.
2241 if (MaskedValueIsZero(Op0,
2242 RHS->getZExtValue()^RHS->getType()->getIntegralTypeMask()))
2243 return ReplaceInstUsesWith(I, RHS);
2245 ConstantInt *C1 = 0; Value *X = 0;
2246 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2247 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2248 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2250 InsertNewInstBefore(Or, I);
2251 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2254 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2255 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2256 std::string Op0Name = Op0->getName(); Op0->setName("");
2257 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2258 InsertNewInstBefore(Or, I);
2259 return BinaryOperator::createXor(Or,
2260 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
2263 // Try to fold constant and into select arguments.
2264 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2265 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2267 if (isa<PHINode>(Op0))
2268 if (Instruction *NV = FoldOpIntoPhi(I))
2272 Value *A = 0, *B = 0;
2273 ConstantInt *C1 = 0, *C2 = 0;
2275 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2276 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2277 return ReplaceInstUsesWith(I, Op1);
2278 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2279 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2280 return ReplaceInstUsesWith(I, Op0);
2282 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2283 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2284 MaskedValueIsZero(Op1, C1->getZExtValue())) {
2285 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2287 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2290 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2291 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2292 MaskedValueIsZero(Op0, C1->getZExtValue())) {
2293 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2295 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2298 // (A & C1)|(B & C2)
2299 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2300 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2302 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2303 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2306 // If we have: ((V + N) & C1) | (V & C2)
2307 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2308 // replace with V+N.
2309 if (C1 == ConstantExpr::getNot(C2)) {
2310 Value *V1 = 0, *V2 = 0;
2311 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2312 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2313 // Add commutes, try both ways.
2314 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
2315 return ReplaceInstUsesWith(I, A);
2316 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
2317 return ReplaceInstUsesWith(I, A);
2319 // Or commutes, try both ways.
2320 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2321 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2322 // Add commutes, try both ways.
2323 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
2324 return ReplaceInstUsesWith(I, B);
2325 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
2326 return ReplaceInstUsesWith(I, B);
2331 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2332 if (A == Op1) // ~A | A == -1
2333 return ReplaceInstUsesWith(I,
2334 ConstantIntegral::getAllOnesValue(I.getType()));
2338 // Note, A is still live here!
2339 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2341 return ReplaceInstUsesWith(I,
2342 ConstantIntegral::getAllOnesValue(I.getType()));
2344 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2345 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2346 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2347 I.getName()+".demorgan"), I);
2348 return BinaryOperator::createNot(And);
2352 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
2353 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
2354 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2357 Value *LHSVal, *RHSVal;
2358 ConstantInt *LHSCst, *RHSCst;
2359 Instruction::BinaryOps LHSCC, RHSCC;
2360 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2361 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2362 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2363 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2364 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2365 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2366 // Ensure that the larger constant is on the RHS.
2367 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2368 SetCondInst *LHS = cast<SetCondInst>(Op0);
2369 if (cast<ConstantBool>(Cmp)->getValue()) {
2370 std::swap(LHS, RHS);
2371 std::swap(LHSCst, RHSCst);
2372 std::swap(LHSCC, RHSCC);
2375 // At this point, we know we have have two setcc instructions
2376 // comparing a value against two constants and or'ing the result
2377 // together. Because of the above check, we know that we only have
2378 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2379 // FoldSetCCLogical check above), that the two constants are not
2381 assert(LHSCst != RHSCst && "Compares not folded above?");
2384 default: assert(0 && "Unknown integer condition code!");
2385 case Instruction::SetEQ:
2387 default: assert(0 && "Unknown integer condition code!");
2388 case Instruction::SetEQ:
2389 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2390 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2391 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2392 LHSVal->getName()+".off");
2393 InsertNewInstBefore(Add, I);
2394 const Type *UnsType = Add->getType()->getUnsignedVersion();
2395 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2396 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2397 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2398 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2400 break; // (X == 13 | X == 15) -> no change
2402 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2404 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2405 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2406 return ReplaceInstUsesWith(I, RHS);
2409 case Instruction::SetNE:
2411 default: assert(0 && "Unknown integer condition code!");
2412 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2413 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2414 return ReplaceInstUsesWith(I, LHS);
2415 case Instruction::SetNE: // (X != 13 | X != 15) -> true
2416 case Instruction::SetLT: // (X != 13 | X < 15) -> true
2417 return ReplaceInstUsesWith(I, ConstantBool::True);
2420 case Instruction::SetLT:
2422 default: assert(0 && "Unknown integer condition code!");
2423 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2425 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2426 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
2427 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2428 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2429 return ReplaceInstUsesWith(I, RHS);
2432 case Instruction::SetGT:
2434 default: assert(0 && "Unknown integer condition code!");
2435 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2436 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2437 return ReplaceInstUsesWith(I, LHS);
2438 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2439 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2440 return ReplaceInstUsesWith(I, ConstantBool::True);
2446 return Changed ? &I : 0;
2449 // XorSelf - Implements: X ^ X --> 0
2452 XorSelf(Value *rhs) : RHS(rhs) {}
2453 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2454 Instruction *apply(BinaryOperator &Xor) const {
2460 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2461 bool Changed = SimplifyCommutative(I);
2462 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2464 if (isa<UndefValue>(Op1))
2465 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2467 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2468 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2469 assert(Result == &I && "AssociativeOpt didn't work?");
2470 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2473 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2475 if (RHS->isNullValue())
2476 return ReplaceInstUsesWith(I, Op0);
2478 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2479 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
2480 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
2481 if (RHS == ConstantBool::True && SCI->hasOneUse())
2482 return new SetCondInst(SCI->getInverseCondition(),
2483 SCI->getOperand(0), SCI->getOperand(1));
2485 // ~(c-X) == X-c-1 == X+(-c-1)
2486 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2487 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2488 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2489 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2490 ConstantInt::get(I.getType(), 1));
2491 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
2494 // ~(~X & Y) --> (X | ~Y)
2495 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2496 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2497 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2499 BinaryOperator::createNot(Op0I->getOperand(1),
2500 Op0I->getOperand(1)->getName()+".not");
2501 InsertNewInstBefore(NotY, I);
2502 return BinaryOperator::createOr(Op0NotVal, NotY);
2506 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2507 switch (Op0I->getOpcode()) {
2508 case Instruction::Add:
2509 // ~(X-c) --> (-c-1)-X
2510 if (RHS->isAllOnesValue()) {
2511 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2512 return BinaryOperator::createSub(
2513 ConstantExpr::getSub(NegOp0CI,
2514 ConstantInt::get(I.getType(), 1)),
2515 Op0I->getOperand(0));
2518 case Instruction::And:
2519 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
2520 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2521 return BinaryOperator::createOr(Op0, RHS);
2523 case Instruction::Or:
2524 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
2525 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
2526 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
2532 // Try to fold constant and into select arguments.
2533 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2534 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2536 if (isa<PHINode>(Op0))
2537 if (Instruction *NV = FoldOpIntoPhi(I))
2541 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
2543 return ReplaceInstUsesWith(I,
2544 ConstantIntegral::getAllOnesValue(I.getType()));
2546 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
2548 return ReplaceInstUsesWith(I,
2549 ConstantIntegral::getAllOnesValue(I.getType()));
2551 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
2552 if (Op1I->getOpcode() == Instruction::Or) {
2553 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2554 cast<BinaryOperator>(Op1I)->swapOperands();
2556 std::swap(Op0, Op1);
2557 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2559 std::swap(Op0, Op1);
2561 } else if (Op1I->getOpcode() == Instruction::Xor) {
2562 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2563 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2564 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2565 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2568 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
2569 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
2570 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2571 cast<BinaryOperator>(Op0I)->swapOperands();
2572 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
2573 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2574 Op1->getName()+".not"), I);
2575 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
2577 } else if (Op0I->getOpcode() == Instruction::Xor) {
2578 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2579 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2580 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2581 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2584 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
2585 ConstantInt *C1 = 0, *C2 = 0;
2586 if (match(Op0, m_And(m_Value(), m_ConstantInt(C1))) &&
2587 match(Op1, m_And(m_Value(), m_ConstantInt(C2))) &&
2588 ConstantExpr::getAnd(C1, C2)->isNullValue())
2589 return BinaryOperator::createOr(Op0, Op1);
2591 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2592 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2593 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2596 return Changed ? &I : 0;
2599 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2600 /// overflowed for this type.
2601 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2603 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2604 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2607 static bool isPositive(ConstantInt *C) {
2608 return cast<ConstantSInt>(C)->getValue() >= 0;
2611 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2612 /// overflowed for this type.
2613 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2615 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2617 if (In1->getType()->isUnsigned())
2618 return cast<ConstantUInt>(Result)->getValue() <
2619 cast<ConstantUInt>(In1)->getValue();
2620 if (isPositive(In1) != isPositive(In2))
2622 if (isPositive(In1))
2623 return cast<ConstantSInt>(Result)->getValue() <
2624 cast<ConstantSInt>(In1)->getValue();
2625 return cast<ConstantSInt>(Result)->getValue() >
2626 cast<ConstantSInt>(In1)->getValue();
2629 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2630 /// code necessary to compute the offset from the base pointer (without adding
2631 /// in the base pointer). Return the result as a signed integer of intptr size.
2632 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2633 TargetData &TD = IC.getTargetData();
2634 gep_type_iterator GTI = gep_type_begin(GEP);
2635 const Type *UIntPtrTy = TD.getIntPtrType();
2636 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2637 Value *Result = Constant::getNullValue(SIntPtrTy);
2639 // Build a mask for high order bits.
2640 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
2642 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2643 Value *Op = GEP->getOperand(i);
2644 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
2645 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2647 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2648 if (!OpC->isNullValue()) {
2649 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
2650 Scale = ConstantExpr::getMul(OpC, Scale);
2651 if (Constant *RC = dyn_cast<Constant>(Result))
2652 Result = ConstantExpr::getAdd(RC, Scale);
2654 // Emit an add instruction.
2655 Result = IC.InsertNewInstBefore(
2656 BinaryOperator::createAdd(Result, Scale,
2657 GEP->getName()+".offs"), I);
2661 // Convert to correct type.
2662 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2663 Op->getName()+".c"), I);
2665 // We'll let instcombine(mul) convert this to a shl if possible.
2666 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2667 GEP->getName()+".idx"), I);
2669 // Emit an add instruction.
2670 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
2671 GEP->getName()+".offs"), I);
2677 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2678 /// else. At this point we know that the GEP is on the LHS of the comparison.
2679 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2680 Instruction::BinaryOps Cond,
2682 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
2684 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2685 if (isa<PointerType>(CI->getOperand(0)->getType()))
2686 RHS = CI->getOperand(0);
2688 Value *PtrBase = GEPLHS->getOperand(0);
2689 if (PtrBase == RHS) {
2690 // As an optimization, we don't actually have to compute the actual value of
2691 // OFFSET if this is a seteq or setne comparison, just return whether each
2692 // index is zero or not.
2693 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2694 Instruction *InVal = 0;
2695 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2696 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
2698 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2699 if (isa<UndefValue>(C)) // undef index -> undef.
2700 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2701 if (C->isNullValue())
2703 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2704 EmitIt = false; // This is indexing into a zero sized array?
2705 } else if (isa<ConstantInt>(C))
2706 return ReplaceInstUsesWith(I, // No comparison is needed here.
2707 ConstantBool::get(Cond == Instruction::SetNE));
2712 new SetCondInst(Cond, GEPLHS->getOperand(i),
2713 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2717 InVal = InsertNewInstBefore(InVal, I);
2718 InsertNewInstBefore(Comp, I);
2719 if (Cond == Instruction::SetNE) // True if any are unequal
2720 InVal = BinaryOperator::createOr(InVal, Comp);
2721 else // True if all are equal
2722 InVal = BinaryOperator::createAnd(InVal, Comp);
2730 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2731 ConstantBool::get(Cond == Instruction::SetEQ));
2734 // Only lower this if the setcc is the only user of the GEP or if we expect
2735 // the result to fold to a constant!
2736 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2737 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2738 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2739 return new SetCondInst(Cond, Offset,
2740 Constant::getNullValue(Offset->getType()));
2742 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2743 // If the base pointers are different, but the indices are the same, just
2744 // compare the base pointer.
2745 if (PtrBase != GEPRHS->getOperand(0)) {
2746 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
2747 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
2748 GEPRHS->getOperand(0)->getType();
2750 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2751 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2752 IndicesTheSame = false;
2756 // If all indices are the same, just compare the base pointers.
2758 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2759 GEPRHS->getOperand(0));
2761 // Otherwise, the base pointers are different and the indices are
2762 // different, bail out.
2766 // If one of the GEPs has all zero indices, recurse.
2767 bool AllZeros = true;
2768 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2769 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2770 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2775 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2776 SetCondInst::getSwappedCondition(Cond), I);
2778 // If the other GEP has all zero indices, recurse.
2780 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2781 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2782 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2787 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2789 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2790 // If the GEPs only differ by one index, compare it.
2791 unsigned NumDifferences = 0; // Keep track of # differences.
2792 unsigned DiffOperand = 0; // The operand that differs.
2793 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2794 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2795 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2796 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
2797 // Irreconcilable differences.
2801 if (NumDifferences++) break;
2806 if (NumDifferences == 0) // SAME GEP?
2807 return ReplaceInstUsesWith(I, // No comparison is needed here.
2808 ConstantBool::get(Cond == Instruction::SetEQ));
2809 else if (NumDifferences == 1) {
2810 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2811 Value *RHSV = GEPRHS->getOperand(DiffOperand);
2813 // Convert the operands to signed values to make sure to perform a
2814 // signed comparison.
2815 const Type *NewTy = LHSV->getType()->getSignedVersion();
2816 if (LHSV->getType() != NewTy)
2817 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2818 LHSV->getName()), I);
2819 if (RHSV->getType() != NewTy)
2820 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2821 RHSV->getName()), I);
2822 return new SetCondInst(Cond, LHSV, RHSV);
2826 // Only lower this if the setcc is the only user of the GEP or if we expect
2827 // the result to fold to a constant!
2828 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2829 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2830 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2831 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2832 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2833 return new SetCondInst(Cond, L, R);
2840 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
2841 bool Changed = SimplifyCommutative(I);
2842 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2843 const Type *Ty = Op0->getType();
2847 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
2849 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2850 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2852 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2853 // addresses never equal each other! We already know that Op0 != Op1.
2854 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2855 isa<ConstantPointerNull>(Op0)) &&
2856 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
2857 isa<ConstantPointerNull>(Op1)))
2858 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2860 // setcc's with boolean values can always be turned into bitwise operations
2861 if (Ty == Type::BoolTy) {
2862 switch (I.getOpcode()) {
2863 default: assert(0 && "Invalid setcc instruction!");
2864 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
2865 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
2866 InsertNewInstBefore(Xor, I);
2867 return BinaryOperator::createNot(Xor);
2869 case Instruction::SetNE:
2870 return BinaryOperator::createXor(Op0, Op1);
2872 case Instruction::SetGT:
2873 std::swap(Op0, Op1); // Change setgt -> setlt
2875 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2876 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2877 InsertNewInstBefore(Not, I);
2878 return BinaryOperator::createAnd(Not, Op1);
2880 case Instruction::SetGE:
2881 std::swap(Op0, Op1); // Change setge -> setle
2883 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2884 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2885 InsertNewInstBefore(Not, I);
2886 return BinaryOperator::createOr(Not, Op1);
2891 // See if we are doing a comparison between a constant and an instruction that
2892 // can be folded into the comparison.
2893 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2894 // Check to see if we are comparing against the minimum or maximum value...
2895 if (CI->isMinValue()) {
2896 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2897 return ReplaceInstUsesWith(I, ConstantBool::False);
2898 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2899 return ReplaceInstUsesWith(I, ConstantBool::True);
2900 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2901 return BinaryOperator::createSetEQ(Op0, Op1);
2902 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2903 return BinaryOperator::createSetNE(Op0, Op1);
2905 } else if (CI->isMaxValue()) {
2906 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2907 return ReplaceInstUsesWith(I, ConstantBool::False);
2908 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2909 return ReplaceInstUsesWith(I, ConstantBool::True);
2910 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2911 return BinaryOperator::createSetEQ(Op0, Op1);
2912 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2913 return BinaryOperator::createSetNE(Op0, Op1);
2915 // Comparing against a value really close to min or max?
2916 } else if (isMinValuePlusOne(CI)) {
2917 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2918 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2919 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2920 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2922 } else if (isMaxValueMinusOne(CI)) {
2923 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2924 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2925 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2926 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2929 // If we still have a setle or setge instruction, turn it into the
2930 // appropriate setlt or setgt instruction. Since the border cases have
2931 // already been handled above, this requires little checking.
2933 if (I.getOpcode() == Instruction::SetLE)
2934 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2935 if (I.getOpcode() == Instruction::SetGE)
2936 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2938 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2939 switch (LHSI->getOpcode()) {
2940 case Instruction::And:
2941 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2942 LHSI->getOperand(0)->hasOneUse()) {
2943 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2944 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2945 // happens a LOT in code produced by the C front-end, for bitfield
2947 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2948 ConstantUInt *ShAmt;
2949 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2950 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2951 const Type *Ty = LHSI->getType();
2953 // We can fold this as long as we can't shift unknown bits
2954 // into the mask. This can only happen with signed shift
2955 // rights, as they sign-extend.
2957 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
2958 Shift->getType()->isUnsigned();
2960 // To test for the bad case of the signed shr, see if any
2961 // of the bits shifted in could be tested after the mask.
2962 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2963 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2965 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
2967 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2968 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2974 if (Shift->getOpcode() == Instruction::Shl)
2975 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2977 NewCst = ConstantExpr::getShl(CI, ShAmt);
2979 // Check to see if we are shifting out any of the bits being
2981 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2982 // If we shifted bits out, the fold is not going to work out.
2983 // As a special case, check to see if this means that the
2984 // result is always true or false now.
2985 if (I.getOpcode() == Instruction::SetEQ)
2986 return ReplaceInstUsesWith(I, ConstantBool::False);
2987 if (I.getOpcode() == Instruction::SetNE)
2988 return ReplaceInstUsesWith(I, ConstantBool::True);
2990 I.setOperand(1, NewCst);
2991 Constant *NewAndCST;
2992 if (Shift->getOpcode() == Instruction::Shl)
2993 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2995 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2996 LHSI->setOperand(1, NewAndCST);
2997 LHSI->setOperand(0, Shift->getOperand(0));
2998 WorkList.push_back(Shift); // Shift is dead.
2999 AddUsesToWorkList(I);
3007 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3008 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3009 switch (I.getOpcode()) {
3011 case Instruction::SetEQ:
3012 case Instruction::SetNE: {
3013 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3015 // Check that the shift amount is in range. If not, don't perform
3016 // undefined shifts. When the shift is visited it will be
3018 if (ShAmt->getValue() >= TypeBits)
3021 // If we are comparing against bits always shifted out, the
3022 // comparison cannot succeed.
3024 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3025 if (Comp != CI) {// Comparing against a bit that we know is zero.
3026 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3027 Constant *Cst = ConstantBool::get(IsSetNE);
3028 return ReplaceInstUsesWith(I, Cst);
3031 if (LHSI->hasOneUse()) {
3032 // Otherwise strength reduce the shift into an and.
3033 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3034 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3037 if (CI->getType()->isUnsigned()) {
3038 Mask = ConstantUInt::get(CI->getType(), Val);
3039 } else if (ShAmtVal != 0) {
3040 Mask = ConstantSInt::get(CI->getType(), Val);
3042 Mask = ConstantInt::getAllOnesValue(CI->getType());
3046 BinaryOperator::createAnd(LHSI->getOperand(0),
3047 Mask, LHSI->getName()+".mask");
3048 Value *And = InsertNewInstBefore(AndI, I);
3049 return new SetCondInst(I.getOpcode(), And,
3050 ConstantExpr::getUShr(CI, ShAmt));
3057 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
3058 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3059 switch (I.getOpcode()) {
3061 case Instruction::SetEQ:
3062 case Instruction::SetNE: {
3064 // Check that the shift amount is in range. If not, don't perform
3065 // undefined shifts. When the shift is visited it will be
3067 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3068 if (ShAmt->getValue() >= TypeBits)
3071 // If we are comparing against bits always shifted out, the
3072 // comparison cannot succeed.
3074 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
3076 if (Comp != CI) {// Comparing against a bit that we know is zero.
3077 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3078 Constant *Cst = ConstantBool::get(IsSetNE);
3079 return ReplaceInstUsesWith(I, Cst);
3082 if (LHSI->hasOneUse() || CI->isNullValue()) {
3083 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3085 // Otherwise strength reduce the shift into an and.
3086 uint64_t Val = ~0ULL; // All ones.
3087 Val <<= ShAmtVal; // Shift over to the right spot.
3090 if (CI->getType()->isUnsigned()) {
3091 Val &= ~0ULL >> (64-TypeBits);
3092 Mask = ConstantUInt::get(CI->getType(), Val);
3094 Mask = ConstantSInt::get(CI->getType(), Val);
3098 BinaryOperator::createAnd(LHSI->getOperand(0),
3099 Mask, LHSI->getName()+".mask");
3100 Value *And = InsertNewInstBefore(AndI, I);
3101 return new SetCondInst(I.getOpcode(), And,
3102 ConstantExpr::getShl(CI, ShAmt));
3110 case Instruction::Div:
3111 // Fold: (div X, C1) op C2 -> range check
3112 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3113 // Fold this div into the comparison, producing a range check.
3114 // Determine, based on the divide type, what the range is being
3115 // checked. If there is an overflow on the low or high side, remember
3116 // it, otherwise compute the range [low, hi) bounding the new value.
3117 bool LoOverflow = false, HiOverflow = 0;
3118 ConstantInt *LoBound = 0, *HiBound = 0;
3121 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3123 Instruction::BinaryOps Opcode = I.getOpcode();
3125 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3126 } else if (LHSI->getType()->isUnsigned()) { // udiv
3128 LoOverflow = ProdOV;
3129 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3130 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3131 if (CI->isNullValue()) { // (X / pos) op 0
3133 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3135 } else if (isPositive(CI)) { // (X / pos) op pos
3137 LoOverflow = ProdOV;
3138 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3139 } else { // (X / pos) op neg
3140 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3141 LoOverflow = AddWithOverflow(LoBound, Prod,
3142 cast<ConstantInt>(DivRHSH));
3144 HiOverflow = ProdOV;
3146 } else { // Divisor is < 0.
3147 if (CI->isNullValue()) { // (X / neg) op 0
3148 LoBound = AddOne(DivRHS);
3149 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
3150 if (HiBound == DivRHS)
3151 LoBound = 0; // - INTMIN = INTMIN
3152 } else if (isPositive(CI)) { // (X / neg) op pos
3153 HiOverflow = LoOverflow = ProdOV;
3155 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3156 HiBound = AddOne(Prod);
3157 } else { // (X / neg) op neg
3159 LoOverflow = HiOverflow = ProdOV;
3160 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3163 // Dividing by a negate swaps the condition.
3164 Opcode = SetCondInst::getSwappedCondition(Opcode);
3168 Value *X = LHSI->getOperand(0);
3170 default: assert(0 && "Unhandled setcc opcode!");
3171 case Instruction::SetEQ:
3172 if (LoOverflow && HiOverflow)
3173 return ReplaceInstUsesWith(I, ConstantBool::False);
3174 else if (HiOverflow)
3175 return new SetCondInst(Instruction::SetGE, X, LoBound);
3176 else if (LoOverflow)
3177 return new SetCondInst(Instruction::SetLT, X, HiBound);
3179 return InsertRangeTest(X, LoBound, HiBound, true, I);
3180 case Instruction::SetNE:
3181 if (LoOverflow && HiOverflow)
3182 return ReplaceInstUsesWith(I, ConstantBool::True);
3183 else if (HiOverflow)
3184 return new SetCondInst(Instruction::SetLT, X, LoBound);
3185 else if (LoOverflow)
3186 return new SetCondInst(Instruction::SetGE, X, HiBound);
3188 return InsertRangeTest(X, LoBound, HiBound, false, I);
3189 case Instruction::SetLT:
3191 return ReplaceInstUsesWith(I, ConstantBool::False);
3192 return new SetCondInst(Instruction::SetLT, X, LoBound);
3193 case Instruction::SetGT:
3195 return ReplaceInstUsesWith(I, ConstantBool::False);
3196 return new SetCondInst(Instruction::SetGE, X, HiBound);
3203 // Simplify seteq and setne instructions...
3204 if (I.getOpcode() == Instruction::SetEQ ||
3205 I.getOpcode() == Instruction::SetNE) {
3206 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3208 // If the first operand is (and|or|xor) with a constant, and the second
3209 // operand is a constant, simplify a bit.
3210 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3211 switch (BO->getOpcode()) {
3212 case Instruction::Rem:
3213 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3214 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3216 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3217 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3218 if (isPowerOf2_64(V)) {
3219 unsigned L2 = Log2_64(V);
3220 const Type *UTy = BO->getType()->getUnsignedVersion();
3221 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3223 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3224 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3225 RHSCst, BO->getName()), I);
3226 return BinaryOperator::create(I.getOpcode(), NewRem,
3227 Constant::getNullValue(UTy));
3232 case Instruction::Add:
3233 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3234 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3235 if (BO->hasOneUse())
3236 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3237 ConstantExpr::getSub(CI, BOp1C));
3238 } else if (CI->isNullValue()) {
3239 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3240 // efficiently invertible, or if the add has just this one use.
3241 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3243 if (Value *NegVal = dyn_castNegVal(BOp1))
3244 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3245 else if (Value *NegVal = dyn_castNegVal(BOp0))
3246 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
3247 else if (BO->hasOneUse()) {
3248 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3250 InsertNewInstBefore(Neg, I);
3251 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3255 case Instruction::Xor:
3256 // For the xor case, we can xor two constants together, eliminating
3257 // the explicit xor.
3258 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3259 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
3260 ConstantExpr::getXor(CI, BOC));
3263 case Instruction::Sub:
3264 // Replace (([sub|xor] A, B) != 0) with (A != B)
3265 if (CI->isNullValue())
3266 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3270 case Instruction::Or:
3271 // If bits are being or'd in that are not present in the constant we
3272 // are comparing against, then the comparison could never succeed!
3273 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
3274 Constant *NotCI = ConstantExpr::getNot(CI);
3275 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
3276 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3280 case Instruction::And:
3281 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3282 // If bits are being compared against that are and'd out, then the
3283 // comparison can never succeed!
3284 if (!ConstantExpr::getAnd(CI,
3285 ConstantExpr::getNot(BOC))->isNullValue())
3286 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3288 // If we have ((X & C) == C), turn it into ((X & C) != 0).
3289 if (CI == BOC && isOneBitSet(CI))
3290 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3291 Instruction::SetNE, Op0,
3292 Constant::getNullValue(CI->getType()));
3294 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3295 // to be a signed value as appropriate.
3296 if (isSignBit(BOC)) {
3297 Value *X = BO->getOperand(0);
3298 // If 'X' is not signed, insert a cast now...
3299 if (!BOC->getType()->isSigned()) {
3300 const Type *DestTy = BOC->getType()->getSignedVersion();
3301 X = InsertCastBefore(X, DestTy, I);
3303 return new SetCondInst(isSetNE ? Instruction::SetLT :
3304 Instruction::SetGE, X,
3305 Constant::getNullValue(X->getType()));
3308 // ((X & ~7) == 0) --> X < 8
3309 if (CI->isNullValue() && isHighOnes(BOC)) {
3310 Value *X = BO->getOperand(0);
3311 Constant *NegX = ConstantExpr::getNeg(BOC);
3313 // If 'X' is signed, insert a cast now.
3314 if (NegX->getType()->isSigned()) {
3315 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3316 X = InsertCastBefore(X, DestTy, I);
3317 NegX = ConstantExpr::getCast(NegX, DestTy);
3320 return new SetCondInst(isSetNE ? Instruction::SetGE :
3321 Instruction::SetLT, X, NegX);
3328 } else { // Not a SetEQ/SetNE
3329 // If the LHS is a cast from an integral value of the same size,
3330 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3331 Value *CastOp = Cast->getOperand(0);
3332 const Type *SrcTy = CastOp->getType();
3333 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
3334 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
3335 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
3336 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
3337 "Source and destination signednesses should differ!");
3338 if (Cast->getType()->isSigned()) {
3339 // If this is a signed comparison, check for comparisons in the
3340 // vicinity of zero.
3341 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3343 return BinaryOperator::createSetGT(CastOp,
3344 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
3345 else if (I.getOpcode() == Instruction::SetGT &&
3346 cast<ConstantSInt>(CI)->getValue() == -1)
3347 // X > -1 => x < 128
3348 return BinaryOperator::createSetLT(CastOp,
3349 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
3351 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3352 if (I.getOpcode() == Instruction::SetLT &&
3353 CUI->getValue() == 1ULL << (SrcTySize-1))
3354 // X < 128 => X > -1
3355 return BinaryOperator::createSetGT(CastOp,
3356 ConstantSInt::get(SrcTy, -1));
3357 else if (I.getOpcode() == Instruction::SetGT &&
3358 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
3360 return BinaryOperator::createSetLT(CastOp,
3361 Constant::getNullValue(SrcTy));
3368 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3369 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3370 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3371 switch (LHSI->getOpcode()) {
3372 case Instruction::GetElementPtr:
3373 if (RHSC->isNullValue()) {
3374 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3375 bool isAllZeros = true;
3376 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3377 if (!isa<Constant>(LHSI->getOperand(i)) ||
3378 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3383 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3384 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3388 case Instruction::PHI:
3389 if (Instruction *NV = FoldOpIntoPhi(I))
3392 case Instruction::Select:
3393 // If either operand of the select is a constant, we can fold the
3394 // comparison into the select arms, which will cause one to be
3395 // constant folded and the select turned into a bitwise or.
3396 Value *Op1 = 0, *Op2 = 0;
3397 if (LHSI->hasOneUse()) {
3398 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3399 // Fold the known value into the constant operand.
3400 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3401 // Insert a new SetCC of the other select operand.
3402 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3403 LHSI->getOperand(2), RHSC,
3405 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3406 // Fold the known value into the constant operand.
3407 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3408 // Insert a new SetCC of the other select operand.
3409 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3410 LHSI->getOperand(1), RHSC,
3416 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3421 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3422 if (User *GEP = dyn_castGetElementPtr(Op0))
3423 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3425 if (User *GEP = dyn_castGetElementPtr(Op1))
3426 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3427 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3430 // Test to see if the operands of the setcc are casted versions of other
3431 // values. If the cast can be stripped off both arguments, we do so now.
3432 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3433 Value *CastOp0 = CI->getOperand(0);
3434 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
3435 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
3436 (I.getOpcode() == Instruction::SetEQ ||
3437 I.getOpcode() == Instruction::SetNE)) {
3438 // We keep moving the cast from the left operand over to the right
3439 // operand, where it can often be eliminated completely.
3442 // If operand #1 is a cast instruction, see if we can eliminate it as
3444 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3445 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
3447 Op1 = CI2->getOperand(0);
3449 // If Op1 is a constant, we can fold the cast into the constant.
3450 if (Op1->getType() != Op0->getType())
3451 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3452 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3454 // Otherwise, cast the RHS right before the setcc
3455 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3456 InsertNewInstBefore(cast<Instruction>(Op1), I);
3458 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3461 // Handle the special case of: setcc (cast bool to X), <cst>
3462 // This comes up when you have code like
3465 // For generality, we handle any zero-extension of any operand comparison
3466 // with a constant or another cast from the same type.
3467 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3468 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3471 return Changed ? &I : 0;
3474 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3475 // We only handle extending casts so far.
3477 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3478 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3479 const Type *SrcTy = LHSCIOp->getType();
3480 const Type *DestTy = SCI.getOperand(0)->getType();
3483 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
3486 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3487 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3488 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3490 // Is this a sign or zero extension?
3491 bool isSignSrc = SrcTy->isSigned();
3492 bool isSignDest = DestTy->isSigned();
3494 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3495 // Not an extension from the same type?
3496 RHSCIOp = CI->getOperand(0);
3497 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3498 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3499 // Compute the constant that would happen if we truncated to SrcTy then
3500 // reextended to DestTy.
3501 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3503 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3506 // If the value cannot be represented in the shorter type, we cannot emit
3507 // a simple comparison.
3508 if (SCI.getOpcode() == Instruction::SetEQ)
3509 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3510 if (SCI.getOpcode() == Instruction::SetNE)
3511 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3513 // Evaluate the comparison for LT.
3515 if (DestTy->isSigned()) {
3516 // We're performing a signed comparison.
3518 // Signed extend and signed comparison.
3519 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3520 Result = ConstantBool::False;
3522 Result = ConstantBool::True; // X < (large) --> true
3524 // Unsigned extend and signed comparison.
3525 if (cast<ConstantSInt>(CI)->getValue() < 0)
3526 Result = ConstantBool::False;
3528 Result = ConstantBool::True;
3531 // We're performing an unsigned comparison.
3533 // Unsigned extend & compare -> always true.
3534 Result = ConstantBool::True;
3536 // We're performing an unsigned comp with a sign extended value.
3537 // This is true if the input is >= 0. [aka >s -1]
3538 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3539 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3540 NegOne, SCI.getName()), SCI);
3544 // Finally, return the value computed.
3545 if (SCI.getOpcode() == Instruction::SetLT) {
3546 return ReplaceInstUsesWith(SCI, Result);
3548 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3549 if (Constant *CI = dyn_cast<Constant>(Result))
3550 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3552 return BinaryOperator::createNot(Result);
3559 // Okay, just insert a compare of the reduced operands now!
3560 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3563 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
3564 assert(I.getOperand(1)->getType() == Type::UByteTy);
3565 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3566 bool isLeftShift = I.getOpcode() == Instruction::Shl;
3568 // shl X, 0 == X and shr X, 0 == X
3569 // shl 0, X == 0 and shr 0, X == 0
3570 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
3571 Op0 == Constant::getNullValue(Op0->getType()))
3572 return ReplaceInstUsesWith(I, Op0);
3574 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3575 if (!isLeftShift && I.getType()->isSigned())
3576 return ReplaceInstUsesWith(I, Op0);
3577 else // undef << X -> 0 AND undef >>u X -> 0
3578 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3580 if (isa<UndefValue>(Op1)) {
3581 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
3582 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3584 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3587 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3589 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3590 if (CSI->isAllOnesValue())
3591 return ReplaceInstUsesWith(I, CSI);
3593 // Try to fold constant and into select arguments.
3594 if (isa<Constant>(Op0))
3595 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3596 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3599 // See if we can turn a signed shr into an unsigned shr.
3600 if (!isLeftShift && I.getType()->isSigned()) {
3601 if (MaskedValueIsZero(Op0,
3602 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
3603 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3604 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3606 return new CastInst(V, I.getType());
3610 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3611 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3616 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3618 bool isLeftShift = I.getOpcode() == Instruction::Shl;
3619 bool isSignedShift = Op0->getType()->isSigned();
3620 bool isUnsignedShift = !isSignedShift;
3622 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3623 // of a signed value.
3625 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3626 if (Op1->getValue() >= TypeBits) {
3627 if (isUnsignedShift || isLeftShift)
3628 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3630 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3635 // ((X*C1) << C2) == (X * (C1 << C2))
3636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3637 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3638 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3639 return BinaryOperator::createMul(BO->getOperand(0),
3640 ConstantExpr::getShl(BOOp, Op1));
3642 // Try to fold constant and into select arguments.
3643 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3644 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3646 if (isa<PHINode>(Op0))
3647 if (Instruction *NV = FoldOpIntoPhi(I))
3650 if (Op0->hasOneUse()) {
3651 // If this is a SHL of a sign-extending cast, see if we can turn the input
3652 // into a zero extending cast (a simple strength reduction).
3653 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3654 const Type *SrcTy = CI->getOperand(0)->getType();
3655 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3656 SrcTy->getPrimitiveSizeInBits() <
3657 CI->getType()->getPrimitiveSizeInBits()) {
3658 // We can change it to a zero extension if we are shifting out all of
3659 // the sign extended bits. To check this, form a mask of all of the
3660 // sign extend bits, then shift them left and see if we have anything
3662 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3663 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3664 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3665 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
3666 // If the shift is nuking all of the sign bits, change this to a
3667 // zero extension cast. To do this, cast the cast input to
3668 // unsigned, then to the requested size.
3669 Value *CastOp = CI->getOperand(0);
3671 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3672 CI->getName()+".uns");
3673 NC = InsertNewInstBefore(NC, I);
3674 // Finally, insert a replacement for CI.
3675 NC = new CastInst(NC, CI->getType(), CI->getName());
3677 NC = InsertNewInstBefore(NC, I);
3678 WorkList.push_back(CI); // Delete CI later.
3679 I.setOperand(0, NC);
3680 return &I; // The SHL operand was modified.
3685 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3686 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3689 switch (Op0BO->getOpcode()) {
3691 case Instruction::Add:
3692 case Instruction::And:
3693 case Instruction::Or:
3694 case Instruction::Xor:
3695 // These operators commute.
3696 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
3697 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3698 match(Op0BO->getOperand(1),
3699 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
3700 Instruction *YS = new ShiftInst(Instruction::Shl,
3701 Op0BO->getOperand(0), Op1,
3703 InsertNewInstBefore(YS, I); // (Y << C)
3704 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3706 Op0BO->getOperand(1)->getName());
3707 InsertNewInstBefore(X, I); // (X + (Y << C))
3708 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3709 C2 = ConstantExpr::getShl(C2, Op1);
3710 return BinaryOperator::createAnd(X, C2);
3713 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3714 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3715 match(Op0BO->getOperand(1),
3716 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3717 m_ConstantInt(CC))) && V2 == Op1 &&
3718 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
3719 Instruction *YS = new ShiftInst(Instruction::Shl,
3720 Op0BO->getOperand(0), Op1,
3722 InsertNewInstBefore(YS, I); // (Y << C)
3724 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
3725 V1->getName()+".mask");
3726 InsertNewInstBefore(XM, I); // X & (CC << C)
3728 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3732 case Instruction::Sub:
3733 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3734 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3735 match(Op0BO->getOperand(0),
3736 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
3737 Instruction *YS = new ShiftInst(Instruction::Shl,
3738 Op0BO->getOperand(1), Op1,
3740 InsertNewInstBefore(YS, I); // (Y << C)
3741 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3743 Op0BO->getOperand(0)->getName());
3744 InsertNewInstBefore(X, I); // (X + (Y << C))
3745 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3746 C2 = ConstantExpr::getShl(C2, Op1);
3747 return BinaryOperator::createAnd(X, C2);
3750 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3751 match(Op0BO->getOperand(0),
3752 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3753 m_ConstantInt(CC))) && V2 == Op1 &&
3754 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
3755 Instruction *YS = new ShiftInst(Instruction::Shl,
3756 Op0BO->getOperand(1), Op1,
3758 InsertNewInstBefore(YS, I); // (Y << C)
3760 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
3761 V1->getName()+".mask");
3762 InsertNewInstBefore(XM, I); // X & (CC << C)
3764 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3771 // If the operand is an bitwise operator with a constant RHS, and the
3772 // shift is the only use, we can pull it out of the shift.
3773 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3774 bool isValid = true; // Valid only for And, Or, Xor
3775 bool highBitSet = false; // Transform if high bit of constant set?
3777 switch (Op0BO->getOpcode()) {
3778 default: isValid = false; break; // Do not perform transform!
3779 case Instruction::Add:
3780 isValid = isLeftShift;
3782 case Instruction::Or:
3783 case Instruction::Xor:
3786 case Instruction::And:
3791 // If this is a signed shift right, and the high bit is modified
3792 // by the logical operation, do not perform the transformation.
3793 // The highBitSet boolean indicates the value of the high bit of
3794 // the constant which would cause it to be modified for this
3797 if (isValid && !isLeftShift && isSignedShift) {
3798 uint64_t Val = Op0C->getRawValue();
3799 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3803 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
3805 Instruction *NewShift =
3806 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
3809 InsertNewInstBefore(NewShift, I);
3811 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3818 // Find out if this is a shift of a shift by a constant.
3819 ShiftInst *ShiftOp = 0;
3820 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
3822 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3823 // If this is a noop-integer case of a shift instruction, use the shift.
3824 if (CI->getOperand(0)->getType()->isInteger() &&
3825 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3826 CI->getType()->getPrimitiveSizeInBits() &&
3827 isa<ShiftInst>(CI->getOperand(0))) {
3828 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
3832 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
3833 // Find the operands and properties of the input shift. Note that the
3834 // signedness of the input shift may differ from the current shift if there
3835 // is a noop cast between the two.
3836 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
3837 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
3838 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
3840 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
3842 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3843 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
3845 // Check for (A << c1) << c2 and (A >> c1) >> c2.
3846 if (isLeftShift == isShiftOfLeftShift) {
3847 // Do not fold these shifts if the first one is signed and the second one
3848 // is unsigned and this is a right shift. Further, don't do any folding
3850 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
3853 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
3854 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
3855 Amt = Op0->getType()->getPrimitiveSizeInBits();
3857 Value *Op = ShiftOp->getOperand(0);
3858 if (isShiftOfSignedShift != isSignedShift)
3859 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
3860 return new ShiftInst(I.getOpcode(), Op,
3861 ConstantUInt::get(Type::UByteTy, Amt));
3864 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
3865 // signed types, we can only support the (A >> c1) << c2 configuration,
3866 // because it can not turn an arbitrary bit of A into a sign bit.
3867 if (isUnsignedShift || isLeftShift) {
3868 // Calculate bitmask for what gets shifted off the edge.
3869 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3871 C = ConstantExpr::getShl(C, ShiftAmt1C);
3873 C = ConstantExpr::getUShr(C, ShiftAmt1C);
3875 Value *Op = ShiftOp->getOperand(0);
3876 if (isShiftOfSignedShift != isSignedShift)
3877 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
3880 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
3881 InsertNewInstBefore(Mask, I);
3883 // Figure out what flavor of shift we should use...
3884 if (ShiftAmt1 == ShiftAmt2) {
3885 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3886 } else if (ShiftAmt1 < ShiftAmt2) {
3887 return new ShiftInst(I.getOpcode(), Mask,
3888 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3889 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
3890 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
3891 // Make sure to emit an unsigned shift right, not a signed one.
3892 Mask = InsertNewInstBefore(new CastInst(Mask,
3893 Mask->getType()->getUnsignedVersion(),
3895 Mask = new ShiftInst(Instruction::Shr, Mask,
3896 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3897 InsertNewInstBefore(Mask, I);
3898 return new CastInst(Mask, I.getType());
3900 return new ShiftInst(ShiftOp->getOpcode(), Mask,
3901 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3904 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
3905 Op = InsertNewInstBefore(new CastInst(Mask,
3906 I.getType()->getSignedVersion(),
3907 Mask->getName()), I);
3908 Instruction *Shift =
3909 new ShiftInst(ShiftOp->getOpcode(), Op,
3910 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3911 InsertNewInstBefore(Shift, I);
3913 C = ConstantIntegral::getAllOnesValue(Shift->getType());
3914 C = ConstantExpr::getShl(C, Op1);
3915 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
3916 InsertNewInstBefore(Mask, I);
3917 return new CastInst(Mask, I.getType());
3920 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
3921 // this case, C1 == C2 and C1 is 8, 16, or 32.
3922 if (ShiftAmt1 == ShiftAmt2) {
3923 const Type *SExtType = 0;
3924 switch (ShiftAmt1) {
3925 case 8 : SExtType = Type::SByteTy; break;
3926 case 16: SExtType = Type::ShortTy; break;
3927 case 32: SExtType = Type::IntTy; break;
3931 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
3933 InsertNewInstBefore(NewTrunc, I);
3934 return new CastInst(NewTrunc, I.getType());
3949 /// getCastType - In the future, we will split the cast instruction into these
3950 /// various types. Until then, we have to do the analysis here.
3951 static CastType getCastType(const Type *Src, const Type *Dest) {
3952 assert(Src->isIntegral() && Dest->isIntegral() &&
3953 "Only works on integral types!");
3954 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3955 unsigned DestSize = Dest->getPrimitiveSizeInBits();
3957 if (SrcSize == DestSize) return Noop;
3958 if (SrcSize > DestSize) return Truncate;
3959 if (Src->isSigned()) return Signext;
3964 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3967 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
3968 const Type *DstTy, TargetData *TD) {
3970 // It is legal to eliminate the instruction if casting A->B->A if the sizes
3971 // are identical and the bits don't get reinterpreted (for example
3972 // int->float->int would not be allowed).
3973 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
3976 // If we are casting between pointer and integer types, treat pointers as
3977 // integers of the appropriate size for the code below.
3978 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3979 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3980 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
3982 // Allow free casting and conversion of sizes as long as the sign doesn't
3984 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
3985 CastType FirstCast = getCastType(SrcTy, MidTy);
3986 CastType SecondCast = getCastType(MidTy, DstTy);
3988 // Capture the effect of these two casts. If the result is a legal cast,
3989 // the CastType is stored here, otherwise a special code is used.
3990 static const unsigned CastResult[] = {
3991 // First cast is noop
3993 // First cast is a truncate
3994 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3995 // First cast is a sign ext
3996 2, 5, 2, 4, // signext->zeroext never ok
3997 // First cast is a zero ext
4001 unsigned Result = CastResult[FirstCast*4+SecondCast];
4003 default: assert(0 && "Illegal table value!");
4008 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4009 // truncates, we could eliminate more casts.
4010 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4012 return false; // Not possible to eliminate this here.
4014 // Sign or zero extend followed by truncate is always ok if the result
4015 // is a truncate or noop.
4016 CastType ResultCast = getCastType(SrcTy, DstTy);
4017 if (ResultCast == Noop || ResultCast == Truncate)
4019 // Otherwise we are still growing the value, we are only safe if the
4020 // result will match the sign/zeroextendness of the result.
4021 return ResultCast == FirstCast;
4025 // If this is a cast from 'float -> double -> integer', cast from
4026 // 'float -> integer' directly, as the value isn't changed by the
4027 // float->double conversion.
4028 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4029 DstTy->isIntegral() &&
4030 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4036 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
4037 if (V->getType() == Ty || isa<Constant>(V)) return false;
4038 if (const CastInst *CI = dyn_cast<CastInst>(V))
4039 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4045 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4046 /// InsertBefore instruction. This is specialized a bit to avoid inserting
4047 /// casts that are known to not do anything...
4049 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4050 Instruction *InsertBefore) {
4051 if (V->getType() == DestTy) return V;
4052 if (Constant *C = dyn_cast<Constant>(V))
4053 return ConstantExpr::getCast(C, DestTy);
4055 CastInst *CI = new CastInst(V, DestTy, V->getName());
4056 InsertNewInstBefore(CI, *InsertBefore);
4060 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4061 /// expression. If so, decompose it, returning some value X, such that Val is
4064 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4066 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4067 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4068 Offset = CI->getValue();
4070 return ConstantUInt::get(Type::UIntTy, 0);
4071 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4072 if (I->getNumOperands() == 2) {
4073 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4074 if (I->getOpcode() == Instruction::Shl) {
4075 // This is a value scaled by '1 << the shift amt'.
4076 Scale = 1U << CUI->getValue();
4078 return I->getOperand(0);
4079 } else if (I->getOpcode() == Instruction::Mul) {
4080 // This value is scaled by 'CUI'.
4081 Scale = CUI->getValue();
4083 return I->getOperand(0);
4084 } else if (I->getOpcode() == Instruction::Add) {
4085 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4088 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4090 Offset += CUI->getValue();
4091 if (SubScale > 1 && (Offset % SubScale == 0)) {
4100 // Otherwise, we can't look past this.
4107 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4108 /// try to eliminate the cast by moving the type information into the alloc.
4109 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4110 AllocationInst &AI) {
4111 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
4112 if (!PTy) return 0; // Not casting the allocation to a pointer type.
4114 // Remove any uses of AI that are dead.
4115 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4116 std::vector<Instruction*> DeadUsers;
4117 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4118 Instruction *User = cast<Instruction>(*UI++);
4119 if (isInstructionTriviallyDead(User)) {
4120 while (UI != E && *UI == User)
4121 ++UI; // If this instruction uses AI more than once, don't break UI.
4123 // Add operands to the worklist.
4124 AddUsesToWorkList(*User);
4126 DEBUG(std::cerr << "IC: DCE: " << *User);
4128 User->eraseFromParent();
4129 removeFromWorkList(User);
4133 // Get the type really allocated and the type casted to.
4134 const Type *AllocElTy = AI.getAllocatedType();
4135 const Type *CastElTy = PTy->getElementType();
4136 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
4138 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4139 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4140 if (CastElTyAlign < AllocElTyAlign) return 0;
4142 // If the allocation has multiple uses, only promote it if we are strictly
4143 // increasing the alignment of the resultant allocation. If we keep it the
4144 // same, we open the door to infinite loops of various kinds.
4145 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4147 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4148 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
4149 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
4151 // See if we can satisfy the modulus by pulling a scale out of the array
4153 unsigned ArraySizeScale, ArrayOffset;
4154 Value *NumElements = // See if the array size is a decomposable linear expr.
4155 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4157 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4159 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4160 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
4162 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4167 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4168 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4169 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4170 else if (Scale != 1) {
4171 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4172 Amt = InsertNewInstBefore(Tmp, AI);
4176 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4177 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4178 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4179 Amt = InsertNewInstBefore(Tmp, AI);
4182 std::string Name = AI.getName(); AI.setName("");
4183 AllocationInst *New;
4184 if (isa<MallocInst>(AI))
4185 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
4187 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
4188 InsertNewInstBefore(New, AI);
4190 // If the allocation has multiple uses, insert a cast and change all things
4191 // that used it to use the new cast. This will also hack on CI, but it will
4193 if (!AI.hasOneUse()) {
4194 AddUsesToWorkList(AI);
4195 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4196 InsertNewInstBefore(NewCast, AI);
4197 AI.replaceAllUsesWith(NewCast);
4199 return ReplaceInstUsesWith(CI, New);
4203 // CastInst simplification
4205 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
4206 Value *Src = CI.getOperand(0);
4208 // If the user is casting a value to the same type, eliminate this cast
4210 if (CI.getType() == Src->getType())
4211 return ReplaceInstUsesWith(CI, Src);
4213 if (isa<UndefValue>(Src)) // cast undef -> undef
4214 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4216 // If casting the result of another cast instruction, try to eliminate this
4219 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4220 Value *A = CSrc->getOperand(0);
4221 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4222 CI.getType(), TD)) {
4223 // This instruction now refers directly to the cast's src operand. This
4224 // has a good chance of making CSrc dead.
4225 CI.setOperand(0, CSrc->getOperand(0));
4229 // If this is an A->B->A cast, and we are dealing with integral types, try
4230 // to convert this into a logical 'and' instruction.
4232 if (A->getType()->isInteger() &&
4233 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
4234 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
4235 CSrc->getType()->getPrimitiveSizeInBits() <
4236 CI.getType()->getPrimitiveSizeInBits()&&
4237 A->getType()->getPrimitiveSizeInBits() ==
4238 CI.getType()->getPrimitiveSizeInBits()) {
4239 assert(CSrc->getType() != Type::ULongTy &&
4240 "Cannot have type bigger than ulong!");
4241 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
4242 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4244 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4245 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4246 if (And->getType() != CI.getType()) {
4247 And->setName(CSrc->getName()+".mask");
4248 InsertNewInstBefore(And, CI);
4249 And = new CastInst(And, CI.getType());
4255 // If this is a cast to bool, turn it into the appropriate setne instruction.
4256 if (CI.getType() == Type::BoolTy)
4257 return BinaryOperator::createSetNE(CI.getOperand(0),
4258 Constant::getNullValue(CI.getOperand(0)->getType()));
4260 // See if we can simplify any instructions used by the LHS whose sole
4261 // purpose is to compute bits we don't care about.
4262 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral() &&
4263 SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask()))
4266 // If casting the result of a getelementptr instruction with no offset, turn
4267 // this into a cast of the original pointer!
4269 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
4270 bool AllZeroOperands = true;
4271 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4272 if (!isa<Constant>(GEP->getOperand(i)) ||
4273 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4274 AllZeroOperands = false;
4277 if (AllZeroOperands) {
4278 CI.setOperand(0, GEP->getOperand(0));
4283 // If we are casting a malloc or alloca to a pointer to a type of the same
4284 // size, rewrite the allocation instruction to allocate the "right" type.
4286 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
4287 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4290 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4291 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4293 if (isa<PHINode>(Src))
4294 if (Instruction *NV = FoldOpIntoPhi(CI))
4297 // If the source value is an instruction with only this use, we can attempt to
4298 // propagate the cast into the instruction. Also, only handle integral types
4300 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
4301 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
4302 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4303 const Type *DestTy = CI.getType();
4304 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4305 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
4307 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4308 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4310 switch (SrcI->getOpcode()) {
4311 case Instruction::Add:
4312 case Instruction::Mul:
4313 case Instruction::And:
4314 case Instruction::Or:
4315 case Instruction::Xor:
4316 // If we are discarding information, or just changing the sign, rewrite.
4317 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4318 // Don't insert two casts if they cannot be eliminated. We allow two
4319 // casts to be inserted if the sizes are the same. This could only be
4320 // converting signedness, which is a noop.
4321 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4322 !ValueRequiresCast(Op0, DestTy, TD)) {
4323 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4324 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4325 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4326 ->getOpcode(), Op0c, Op1c);
4330 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4331 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4332 Op1 == ConstantBool::True &&
4333 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4334 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4335 return BinaryOperator::createXor(New,
4336 ConstantInt::get(CI.getType(), 1));
4339 case Instruction::Shl:
4340 // Allow changing the sign of the source operand. Do not allow changing
4341 // the size of the shift, UNLESS the shift amount is a constant. We
4342 // mush not change variable sized shifts to a smaller size, because it
4343 // is undefined to shift more bits out than exist in the value.
4344 if (DestBitSize == SrcBitSize ||
4345 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4346 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4347 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4350 case Instruction::Shr:
4351 // If this is a signed shr, and if all bits shifted in are about to be
4352 // truncated off, turn it into an unsigned shr to allow greater
4354 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4355 isa<ConstantInt>(Op1)) {
4356 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4357 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4358 // Convert to unsigned.
4359 Value *N1 = InsertOperandCastBefore(Op0,
4360 Op0->getType()->getUnsignedVersion(), &CI);
4361 // Insert the new shift, which is now unsigned.
4362 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4363 Op1, Src->getName()), CI);
4364 return new CastInst(N1, CI.getType());
4369 case Instruction::SetNE:
4370 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4371 if (Op1C->getRawValue() == 0) {
4372 // If the input only has the low bit set, simplify directly.
4374 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4375 // cast (X != 0) to int --> X if X&~1 == 0
4376 if (MaskedValueIsZero(Op0,
4377 cast<ConstantIntegral>(Not1)->getZExtValue())) {
4378 if (CI.getType() == Op0->getType())
4379 return ReplaceInstUsesWith(CI, Op0);
4381 return new CastInst(Op0, CI.getType());
4384 // If the input is an and with a single bit, shift then simplify.
4385 ConstantInt *AndRHS;
4386 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4387 if (AndRHS->getRawValue() &&
4388 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
4389 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
4390 // Perform an unsigned shr by shiftamt. Convert input to
4391 // unsigned if it is signed.
4393 if (In->getType()->isSigned())
4394 In = InsertNewInstBefore(new CastInst(In,
4395 In->getType()->getUnsignedVersion(), In->getName()),CI);
4396 // Insert the shift to put the result in the low bit.
4397 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4398 ConstantInt::get(Type::UByteTy, ShiftAmt),
4399 In->getName()+".lobit"), CI);
4400 if (CI.getType() == In->getType())
4401 return ReplaceInstUsesWith(CI, In);
4403 return new CastInst(In, CI.getType());
4408 case Instruction::SetEQ:
4409 // We if we are just checking for a seteq of a single bit and casting it
4410 // to an integer. If so, shift the bit to the appropriate place then
4411 // cast to integer to avoid the comparison.
4412 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4413 // Is Op1C a power of two or zero?
4414 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4415 // cast (X == 1) to int -> X iff X has only the low bit set.
4416 if (Op1C->getRawValue() == 1) {
4418 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4419 if (MaskedValueIsZero(Op0,
4420 cast<ConstantIntegral>(Not1)->getZExtValue())) {
4421 if (CI.getType() == Op0->getType())
4422 return ReplaceInstUsesWith(CI, Op0);
4424 return new CastInst(Op0, CI.getType());
4436 /// GetSelectFoldableOperands - We want to turn code that looks like this:
4438 /// %D = select %cond, %C, %A
4440 /// %C = select %cond, %B, 0
4443 /// Assuming that the specified instruction is an operand to the select, return
4444 /// a bitmask indicating which operands of this instruction are foldable if they
4445 /// equal the other incoming value of the select.
4447 static unsigned GetSelectFoldableOperands(Instruction *I) {
4448 switch (I->getOpcode()) {
4449 case Instruction::Add:
4450 case Instruction::Mul:
4451 case Instruction::And:
4452 case Instruction::Or:
4453 case Instruction::Xor:
4454 return 3; // Can fold through either operand.
4455 case Instruction::Sub: // Can only fold on the amount subtracted.
4456 case Instruction::Shl: // Can only fold on the shift amount.
4457 case Instruction::Shr:
4460 return 0; // Cannot fold
4464 /// GetSelectFoldableConstant - For the same transformation as the previous
4465 /// function, return the identity constant that goes into the select.
4466 static Constant *GetSelectFoldableConstant(Instruction *I) {
4467 switch (I->getOpcode()) {
4468 default: assert(0 && "This cannot happen!"); abort();
4469 case Instruction::Add:
4470 case Instruction::Sub:
4471 case Instruction::Or:
4472 case Instruction::Xor:
4473 return Constant::getNullValue(I->getType());
4474 case Instruction::Shl:
4475 case Instruction::Shr:
4476 return Constant::getNullValue(Type::UByteTy);
4477 case Instruction::And:
4478 return ConstantInt::getAllOnesValue(I->getType());
4479 case Instruction::Mul:
4480 return ConstantInt::get(I->getType(), 1);
4484 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4485 /// have the same opcode and only one use each. Try to simplify this.
4486 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4488 if (TI->getNumOperands() == 1) {
4489 // If this is a non-volatile load or a cast from the same type,
4491 if (TI->getOpcode() == Instruction::Cast) {
4492 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4495 return 0; // unknown unary op.
4498 // Fold this by inserting a select from the input values.
4499 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4500 FI->getOperand(0), SI.getName()+".v");
4501 InsertNewInstBefore(NewSI, SI);
4502 return new CastInst(NewSI, TI->getType());
4505 // Only handle binary operators here.
4506 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4509 // Figure out if the operations have any operands in common.
4510 Value *MatchOp, *OtherOpT, *OtherOpF;
4512 if (TI->getOperand(0) == FI->getOperand(0)) {
4513 MatchOp = TI->getOperand(0);
4514 OtherOpT = TI->getOperand(1);
4515 OtherOpF = FI->getOperand(1);
4516 MatchIsOpZero = true;
4517 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4518 MatchOp = TI->getOperand(1);
4519 OtherOpT = TI->getOperand(0);
4520 OtherOpF = FI->getOperand(0);
4521 MatchIsOpZero = false;
4522 } else if (!TI->isCommutative()) {
4524 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4525 MatchOp = TI->getOperand(0);
4526 OtherOpT = TI->getOperand(1);
4527 OtherOpF = FI->getOperand(0);
4528 MatchIsOpZero = true;
4529 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4530 MatchOp = TI->getOperand(1);
4531 OtherOpT = TI->getOperand(0);
4532 OtherOpF = FI->getOperand(1);
4533 MatchIsOpZero = true;
4538 // If we reach here, they do have operations in common.
4539 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4540 OtherOpF, SI.getName()+".v");
4541 InsertNewInstBefore(NewSI, SI);
4543 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4545 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4547 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4550 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4552 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4556 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
4557 Value *CondVal = SI.getCondition();
4558 Value *TrueVal = SI.getTrueValue();
4559 Value *FalseVal = SI.getFalseValue();
4561 // select true, X, Y -> X
4562 // select false, X, Y -> Y
4563 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
4564 if (C == ConstantBool::True)
4565 return ReplaceInstUsesWith(SI, TrueVal);
4567 assert(C == ConstantBool::False);
4568 return ReplaceInstUsesWith(SI, FalseVal);
4571 // select C, X, X -> X
4572 if (TrueVal == FalseVal)
4573 return ReplaceInstUsesWith(SI, TrueVal);
4575 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4576 return ReplaceInstUsesWith(SI, FalseVal);
4577 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4578 return ReplaceInstUsesWith(SI, TrueVal);
4579 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4580 if (isa<Constant>(TrueVal))
4581 return ReplaceInstUsesWith(SI, TrueVal);
4583 return ReplaceInstUsesWith(SI, FalseVal);
4586 if (SI.getType() == Type::BoolTy)
4587 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4588 if (C == ConstantBool::True) {
4589 // Change: A = select B, true, C --> A = or B, C
4590 return BinaryOperator::createOr(CondVal, FalseVal);
4592 // Change: A = select B, false, C --> A = and !B, C
4594 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4595 "not."+CondVal->getName()), SI);
4596 return BinaryOperator::createAnd(NotCond, FalseVal);
4598 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4599 if (C == ConstantBool::False) {
4600 // Change: A = select B, C, false --> A = and B, C
4601 return BinaryOperator::createAnd(CondVal, TrueVal);
4603 // Change: A = select B, C, true --> A = or !B, C
4605 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4606 "not."+CondVal->getName()), SI);
4607 return BinaryOperator::createOr(NotCond, TrueVal);
4611 // Selecting between two integer constants?
4612 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4613 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4614 // select C, 1, 0 -> cast C to int
4615 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4616 return new CastInst(CondVal, SI.getType());
4617 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4618 // select C, 0, 1 -> cast !C to int
4620 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4621 "not."+CondVal->getName()), SI);
4622 return new CastInst(NotCond, SI.getType());
4625 // If one of the constants is zero (we know they can't both be) and we
4626 // have a setcc instruction with zero, and we have an 'and' with the
4627 // non-constant value, eliminate this whole mess. This corresponds to
4628 // cases like this: ((X & 27) ? 27 : 0)
4629 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4630 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4631 if ((IC->getOpcode() == Instruction::SetEQ ||
4632 IC->getOpcode() == Instruction::SetNE) &&
4633 isa<ConstantInt>(IC->getOperand(1)) &&
4634 cast<Constant>(IC->getOperand(1))->isNullValue())
4635 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4636 if (ICA->getOpcode() == Instruction::And &&
4637 isa<ConstantInt>(ICA->getOperand(1)) &&
4638 (ICA->getOperand(1) == TrueValC ||
4639 ICA->getOperand(1) == FalseValC) &&
4640 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4641 // Okay, now we know that everything is set up, we just don't
4642 // know whether we have a setne or seteq and whether the true or
4643 // false val is the zero.
4644 bool ShouldNotVal = !TrueValC->isNullValue();
4645 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4648 V = InsertNewInstBefore(BinaryOperator::create(
4649 Instruction::Xor, V, ICA->getOperand(1)), SI);
4650 return ReplaceInstUsesWith(SI, V);
4654 // See if we are selecting two values based on a comparison of the two values.
4655 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4656 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4657 // Transform (X == Y) ? X : Y -> Y
4658 if (SCI->getOpcode() == Instruction::SetEQ)
4659 return ReplaceInstUsesWith(SI, FalseVal);
4660 // Transform (X != Y) ? X : Y -> X
4661 if (SCI->getOpcode() == Instruction::SetNE)
4662 return ReplaceInstUsesWith(SI, TrueVal);
4663 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4665 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4666 // Transform (X == Y) ? Y : X -> X
4667 if (SCI->getOpcode() == Instruction::SetEQ)
4668 return ReplaceInstUsesWith(SI, FalseVal);
4669 // Transform (X != Y) ? Y : X -> Y
4670 if (SCI->getOpcode() == Instruction::SetNE)
4671 return ReplaceInstUsesWith(SI, TrueVal);
4672 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4676 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4677 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4678 if (TI->hasOneUse() && FI->hasOneUse()) {
4679 bool isInverse = false;
4680 Instruction *AddOp = 0, *SubOp = 0;
4682 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4683 if (TI->getOpcode() == FI->getOpcode())
4684 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4687 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4688 // even legal for FP.
4689 if (TI->getOpcode() == Instruction::Sub &&
4690 FI->getOpcode() == Instruction::Add) {
4691 AddOp = FI; SubOp = TI;
4692 } else if (FI->getOpcode() == Instruction::Sub &&
4693 TI->getOpcode() == Instruction::Add) {
4694 AddOp = TI; SubOp = FI;
4698 Value *OtherAddOp = 0;
4699 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4700 OtherAddOp = AddOp->getOperand(1);
4701 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4702 OtherAddOp = AddOp->getOperand(0);
4706 // So at this point we know we have:
4707 // select C, (add X, Y), (sub X, ?)
4708 // We can do the transform profitably if either 'Y' = '?' or '?' is
4710 if (SubOp->getOperand(1) == AddOp ||
4711 isa<Constant>(SubOp->getOperand(1))) {
4713 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4714 NegVal = ConstantExpr::getNeg(C);
4716 NegVal = InsertNewInstBefore(
4717 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4720 Value *NewTrueOp = OtherAddOp;
4721 Value *NewFalseOp = NegVal;
4723 std::swap(NewTrueOp, NewFalseOp);
4724 Instruction *NewSel =
4725 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
4727 NewSel = InsertNewInstBefore(NewSel, SI);
4728 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
4734 // See if we can fold the select into one of our operands.
4735 if (SI.getType()->isInteger()) {
4736 // See the comment above GetSelectFoldableOperands for a description of the
4737 // transformation we are doing here.
4738 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4739 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4740 !isa<Constant>(FalseVal))
4741 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4742 unsigned OpToFold = 0;
4743 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4745 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4750 Constant *C = GetSelectFoldableConstant(TVI);
4751 std::string Name = TVI->getName(); TVI->setName("");
4752 Instruction *NewSel =
4753 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4755 InsertNewInstBefore(NewSel, SI);
4756 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4757 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4758 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4759 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4761 assert(0 && "Unknown instruction!!");
4766 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4767 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4768 !isa<Constant>(TrueVal))
4769 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4770 unsigned OpToFold = 0;
4771 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4773 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4778 Constant *C = GetSelectFoldableConstant(FVI);
4779 std::string Name = FVI->getName(); FVI->setName("");
4780 Instruction *NewSel =
4781 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4783 InsertNewInstBefore(NewSel, SI);
4784 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4785 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4786 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4787 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4789 assert(0 && "Unknown instruction!!");
4795 if (BinaryOperator::isNot(CondVal)) {
4796 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4797 SI.setOperand(1, FalseVal);
4798 SI.setOperand(2, TrueVal);
4806 /// visitCallInst - CallInst simplification. This mostly only handles folding
4807 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
4808 /// the heavy lifting.
4810 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
4811 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
4812 if (!II) return visitCallSite(&CI);
4814 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4816 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
4817 bool Changed = false;
4819 // memmove/cpy/set of zero bytes is a noop.
4820 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4821 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4823 // FIXME: Increase alignment here.
4825 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4826 if (CI->getRawValue() == 1) {
4827 // Replace the instruction with just byte operations. We would
4828 // transform other cases to loads/stores, but we don't know if
4829 // alignment is sufficient.
4833 // If we have a memmove and the source operation is a constant global,
4834 // then the source and dest pointers can't alias, so we can change this
4835 // into a call to memcpy.
4836 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
4837 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4838 if (GVSrc->isConstant()) {
4839 Module *M = CI.getParent()->getParent()->getParent();
4840 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4841 CI.getCalledFunction()->getFunctionType());
4842 CI.setOperand(0, MemCpy);
4846 if (Changed) return II;
4847 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
4848 // If this stoppoint is at the same source location as the previous
4849 // stoppoint in the chain, it is not needed.
4850 if (DbgStopPointInst *PrevSPI =
4851 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4852 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4853 SPI->getColNo() == PrevSPI->getColNo()) {
4854 SPI->replaceAllUsesWith(PrevSPI);
4855 return EraseInstFromFunction(CI);
4858 switch (II->getIntrinsicID()) {
4860 case Intrinsic::stackrestore: {
4861 // If the save is right next to the restore, remove the restore. This can
4862 // happen when variable allocas are DCE'd.
4863 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4864 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4865 BasicBlock::iterator BI = SS;
4867 return EraseInstFromFunction(CI);
4871 // If the stack restore is in a return/unwind block and if there are no
4872 // allocas or calls between the restore and the return, nuke the restore.
4873 TerminatorInst *TI = II->getParent()->getTerminator();
4874 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
4875 BasicBlock::iterator BI = II;
4876 bool CannotRemove = false;
4877 for (++BI; &*BI != TI; ++BI) {
4878 if (isa<AllocaInst>(BI) ||
4879 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
4880 CannotRemove = true;
4885 return EraseInstFromFunction(CI);
4892 return visitCallSite(II);
4895 // InvokeInst simplification
4897 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
4898 return visitCallSite(&II);
4901 // visitCallSite - Improvements for call and invoke instructions.
4903 Instruction *InstCombiner::visitCallSite(CallSite CS) {
4904 bool Changed = false;
4906 // If the callee is a constexpr cast of a function, attempt to move the cast
4907 // to the arguments of the call/invoke.
4908 if (transformConstExprCastCall(CS)) return 0;
4910 Value *Callee = CS.getCalledValue();
4912 if (Function *CalleeF = dyn_cast<Function>(Callee))
4913 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4914 Instruction *OldCall = CS.getInstruction();
4915 // If the call and callee calling conventions don't match, this call must
4916 // be unreachable, as the call is undefined.
4917 new StoreInst(ConstantBool::True,
4918 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4919 if (!OldCall->use_empty())
4920 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4921 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4922 return EraseInstFromFunction(*OldCall);
4926 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4927 // This instruction is not reachable, just remove it. We insert a store to
4928 // undef so that we know that this code is not reachable, despite the fact
4929 // that we can't modify the CFG here.
4930 new StoreInst(ConstantBool::True,
4931 UndefValue::get(PointerType::get(Type::BoolTy)),
4932 CS.getInstruction());
4934 if (!CS.getInstruction()->use_empty())
4935 CS.getInstruction()->
4936 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4938 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4939 // Don't break the CFG, insert a dummy cond branch.
4940 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4941 ConstantBool::True, II);
4943 return EraseInstFromFunction(*CS.getInstruction());
4946 const PointerType *PTy = cast<PointerType>(Callee->getType());
4947 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4948 if (FTy->isVarArg()) {
4949 // See if we can optimize any arguments passed through the varargs area of
4951 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4952 E = CS.arg_end(); I != E; ++I)
4953 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4954 // If this cast does not effect the value passed through the varargs
4955 // area, we can eliminate the use of the cast.
4956 Value *Op = CI->getOperand(0);
4957 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4964 return Changed ? CS.getInstruction() : 0;
4967 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
4968 // attempt to move the cast to the arguments of the call/invoke.
4970 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4971 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4972 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
4973 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
4975 Function *Callee = cast<Function>(CE->getOperand(0));
4976 Instruction *Caller = CS.getInstruction();
4978 // Okay, this is a cast from a function to a different type. Unless doing so
4979 // would cause a type conversion of one of our arguments, change this call to
4980 // be a direct call with arguments casted to the appropriate types.
4982 const FunctionType *FT = Callee->getFunctionType();
4983 const Type *OldRetTy = Caller->getType();
4985 // Check to see if we are changing the return type...
4986 if (OldRetTy != FT->getReturnType()) {
4987 if (Callee->isExternal() &&
4988 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4989 !Caller->use_empty())
4990 return false; // Cannot transform this return value...
4992 // If the callsite is an invoke instruction, and the return value is used by
4993 // a PHI node in a successor, we cannot change the return type of the call
4994 // because there is no place to put the cast instruction (without breaking
4995 // the critical edge). Bail out in this case.
4996 if (!Caller->use_empty())
4997 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4998 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5000 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5001 if (PN->getParent() == II->getNormalDest() ||
5002 PN->getParent() == II->getUnwindDest())
5006 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5007 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
5009 CallSite::arg_iterator AI = CS.arg_begin();
5010 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5011 const Type *ParamTy = FT->getParamType(i);
5012 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
5013 if (Callee->isExternal() && !isConvertible) return false;
5016 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5017 Callee->isExternal())
5018 return false; // Do not delete arguments unless we have a function body...
5020 // Okay, we decided that this is a safe thing to do: go ahead and start
5021 // inserting cast instructions as necessary...
5022 std::vector<Value*> Args;
5023 Args.reserve(NumActualArgs);
5025 AI = CS.arg_begin();
5026 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5027 const Type *ParamTy = FT->getParamType(i);
5028 if ((*AI)->getType() == ParamTy) {
5029 Args.push_back(*AI);
5031 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5036 // If the function takes more arguments than the call was taking, add them
5038 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5039 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5041 // If we are removing arguments to the function, emit an obnoxious warning...
5042 if (FT->getNumParams() < NumActualArgs)
5043 if (!FT->isVarArg()) {
5044 std::cerr << "WARNING: While resolving call to function '"
5045 << Callee->getName() << "' arguments were dropped!\n";
5047 // Add all of the arguments in their promoted form to the arg list...
5048 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5049 const Type *PTy = getPromotedType((*AI)->getType());
5050 if (PTy != (*AI)->getType()) {
5051 // Must promote to pass through va_arg area!
5052 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5053 InsertNewInstBefore(Cast, *Caller);
5054 Args.push_back(Cast);
5056 Args.push_back(*AI);
5061 if (FT->getReturnType() == Type::VoidTy)
5062 Caller->setName(""); // Void type should not have a name...
5065 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5066 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
5067 Args, Caller->getName(), Caller);
5068 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
5070 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
5071 if (cast<CallInst>(Caller)->isTailCall())
5072 cast<CallInst>(NC)->setTailCall();
5073 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
5076 // Insert a cast of the return type as necessary...
5078 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5079 if (NV->getType() != Type::VoidTy) {
5080 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
5082 // If this is an invoke instruction, we should insert it after the first
5083 // non-phi, instruction in the normal successor block.
5084 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5085 BasicBlock::iterator I = II->getNormalDest()->begin();
5086 while (isa<PHINode>(I)) ++I;
5087 InsertNewInstBefore(NC, *I);
5089 // Otherwise, it's a call, just insert cast right after the call instr
5090 InsertNewInstBefore(NC, *Caller);
5092 AddUsersToWorkList(*Caller);
5094 NV = UndefValue::get(Caller->getType());
5098 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5099 Caller->replaceAllUsesWith(NV);
5100 Caller->getParent()->getInstList().erase(Caller);
5101 removeFromWorkList(Caller);
5106 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5107 // operator and they all are only used by the PHI, PHI together their
5108 // inputs, and do the operation once, to the result of the PHI.
5109 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5110 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5112 // Scan the instruction, looking for input operations that can be folded away.
5113 // If all input operands to the phi are the same instruction (e.g. a cast from
5114 // the same type or "+42") we can pull the operation through the PHI, reducing
5115 // code size and simplifying code.
5116 Constant *ConstantOp = 0;
5117 const Type *CastSrcTy = 0;
5118 if (isa<CastInst>(FirstInst)) {
5119 CastSrcTy = FirstInst->getOperand(0)->getType();
5120 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5121 // Can fold binop or shift if the RHS is a constant.
5122 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5123 if (ConstantOp == 0) return 0;
5125 return 0; // Cannot fold this operation.
5128 // Check to see if all arguments are the same operation.
5129 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5130 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5131 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5132 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5135 if (I->getOperand(0)->getType() != CastSrcTy)
5136 return 0; // Cast operation must match.
5137 } else if (I->getOperand(1) != ConstantOp) {
5142 // Okay, they are all the same operation. Create a new PHI node of the
5143 // correct type, and PHI together all of the LHS's of the instructions.
5144 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5145 PN.getName()+".in");
5146 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
5148 Value *InVal = FirstInst->getOperand(0);
5149 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
5151 // Add all operands to the new PHI.
5152 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5153 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5154 if (NewInVal != InVal)
5156 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5161 // The new PHI unions all of the same values together. This is really
5162 // common, so we handle it intelligently here for compile-time speed.
5166 InsertNewInstBefore(NewPN, PN);
5170 // Insert and return the new operation.
5171 if (isa<CastInst>(FirstInst))
5172 return new CastInst(PhiVal, PN.getType());
5173 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
5174 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
5176 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
5177 PhiVal, ConstantOp);
5180 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5182 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5183 if (PN->use_empty()) return true;
5184 if (!PN->hasOneUse()) return false;
5186 // Remember this node, and if we find the cycle, return.
5187 if (!PotentiallyDeadPHIs.insert(PN).second)
5190 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5191 return DeadPHICycle(PU, PotentiallyDeadPHIs);
5196 // PHINode simplification
5198 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
5199 if (Value *V = PN.hasConstantValue())
5200 return ReplaceInstUsesWith(PN, V);
5202 // If the only user of this instruction is a cast instruction, and all of the
5203 // incoming values are constants, change this PHI to merge together the casted
5206 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5207 if (CI->getType() != PN.getType()) { // noop casts will be folded
5208 bool AllConstant = true;
5209 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5210 if (!isa<Constant>(PN.getIncomingValue(i))) {
5211 AllConstant = false;
5215 // Make a new PHI with all casted values.
5216 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5217 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5218 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5219 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5220 PN.getIncomingBlock(i));
5223 // Update the cast instruction.
5224 CI->setOperand(0, New);
5225 WorkList.push_back(CI); // revisit the cast instruction to fold.
5226 WorkList.push_back(New); // Make sure to revisit the new Phi
5227 return &PN; // PN is now dead!
5231 // If all PHI operands are the same operation, pull them through the PHI,
5232 // reducing code size.
5233 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5234 PN.getIncomingValue(0)->hasOneUse())
5235 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5238 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5239 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5240 // PHI)... break the cycle.
5242 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5243 std::set<PHINode*> PotentiallyDeadPHIs;
5244 PotentiallyDeadPHIs.insert(&PN);
5245 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5246 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5252 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5253 Instruction *InsertPoint,
5255 unsigned PS = IC->getTargetData().getPointerSize();
5256 const Type *VTy = V->getType();
5257 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5258 // We must insert a cast to ensure we sign-extend.
5259 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5260 V->getName()), *InsertPoint);
5261 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5266 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
5267 Value *PtrOp = GEP.getOperand(0);
5268 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
5269 // If so, eliminate the noop.
5270 if (GEP.getNumOperands() == 1)
5271 return ReplaceInstUsesWith(GEP, PtrOp);
5273 if (isa<UndefValue>(GEP.getOperand(0)))
5274 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5276 bool HasZeroPointerIndex = false;
5277 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5278 HasZeroPointerIndex = C->isNullValue();
5280 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
5281 return ReplaceInstUsesWith(GEP, PtrOp);
5283 // Eliminate unneeded casts for indices.
5284 bool MadeChange = false;
5285 gep_type_iterator GTI = gep_type_begin(GEP);
5286 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5287 if (isa<SequentialType>(*GTI)) {
5288 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5289 Value *Src = CI->getOperand(0);
5290 const Type *SrcTy = Src->getType();
5291 const Type *DestTy = CI->getType();
5292 if (Src->getType()->isInteger()) {
5293 if (SrcTy->getPrimitiveSizeInBits() ==
5294 DestTy->getPrimitiveSizeInBits()) {
5295 // We can always eliminate a cast from ulong or long to the other.
5296 // We can always eliminate a cast from uint to int or the other on
5297 // 32-bit pointer platforms.
5298 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
5300 GEP.setOperand(i, Src);
5302 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5303 SrcTy->getPrimitiveSize() == 4) {
5304 // We can always eliminate a cast from int to [u]long. We can
5305 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5307 if (SrcTy->isSigned() ||
5308 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
5310 GEP.setOperand(i, Src);
5315 // If we are using a wider index than needed for this platform, shrink it
5316 // to what we need. If the incoming value needs a cast instruction,
5317 // insert it. This explicit cast can make subsequent optimizations more
5319 Value *Op = GEP.getOperand(i);
5320 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
5321 if (Constant *C = dyn_cast<Constant>(Op)) {
5322 GEP.setOperand(i, ConstantExpr::getCast(C,
5323 TD->getIntPtrType()->getSignedVersion()));
5326 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5327 Op->getName()), GEP);
5328 GEP.setOperand(i, Op);
5332 // If this is a constant idx, make sure to canonicalize it to be a signed
5333 // operand, otherwise CSE and other optimizations are pessimized.
5334 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5335 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5336 CUI->getType()->getSignedVersion()));
5340 if (MadeChange) return &GEP;
5342 // Combine Indices - If the source pointer to this getelementptr instruction
5343 // is a getelementptr instruction, combine the indices of the two
5344 // getelementptr instructions into a single instruction.
5346 std::vector<Value*> SrcGEPOperands;
5347 if (User *Src = dyn_castGetElementPtr(PtrOp))
5348 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
5350 if (!SrcGEPOperands.empty()) {
5351 // Note that if our source is a gep chain itself that we wait for that
5352 // chain to be resolved before we perform this transformation. This
5353 // avoids us creating a TON of code in some cases.
5355 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5356 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5357 return 0; // Wait until our source is folded to completion.
5359 std::vector<Value *> Indices;
5361 // Find out whether the last index in the source GEP is a sequential idx.
5362 bool EndsWithSequential = false;
5363 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5364 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
5365 EndsWithSequential = !isa<StructType>(*I);
5367 // Can we combine the two pointer arithmetics offsets?
5368 if (EndsWithSequential) {
5369 // Replace: gep (gep %P, long B), long A, ...
5370 // With: T = long A+B; gep %P, T, ...
5372 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
5373 if (SO1 == Constant::getNullValue(SO1->getType())) {
5375 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5378 // If they aren't the same type, convert both to an integer of the
5379 // target's pointer size.
5380 if (SO1->getType() != GO1->getType()) {
5381 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5382 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5383 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5384 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5386 unsigned PS = TD->getPointerSize();
5387 if (SO1->getType()->getPrimitiveSize() == PS) {
5388 // Convert GO1 to SO1's type.
5389 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5391 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5392 // Convert SO1 to GO1's type.
5393 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5395 const Type *PT = TD->getIntPtrType();
5396 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5397 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5401 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5402 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5404 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5405 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
5409 // Recycle the GEP we already have if possible.
5410 if (SrcGEPOperands.size() == 2) {
5411 GEP.setOperand(0, SrcGEPOperands[0]);
5412 GEP.setOperand(1, Sum);
5415 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5416 SrcGEPOperands.end()-1);
5417 Indices.push_back(Sum);
5418 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5420 } else if (isa<Constant>(*GEP.idx_begin()) &&
5421 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
5422 SrcGEPOperands.size() != 1) {
5423 // Otherwise we can do the fold if the first index of the GEP is a zero
5424 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5425 SrcGEPOperands.end());
5426 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5429 if (!Indices.empty())
5430 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
5432 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
5433 // GEP of global variable. If all of the indices for this GEP are
5434 // constants, we can promote this to a constexpr instead of an instruction.
5436 // Scan for nonconstants...
5437 std::vector<Constant*> Indices;
5438 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5439 for (; I != E && isa<Constant>(*I); ++I)
5440 Indices.push_back(cast<Constant>(*I));
5442 if (I == E) { // If they are all constants...
5443 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
5445 // Replace all uses of the GEP with the new constexpr...
5446 return ReplaceInstUsesWith(GEP, CE);
5448 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5449 if (!isa<PointerType>(X->getType())) {
5450 // Not interesting. Source pointer must be a cast from pointer.
5451 } else if (HasZeroPointerIndex) {
5452 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5453 // into : GEP [10 x ubyte]* X, long 0, ...
5455 // This occurs when the program declares an array extern like "int X[];"
5457 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5458 const PointerType *XTy = cast<PointerType>(X->getType());
5459 if (const ArrayType *XATy =
5460 dyn_cast<ArrayType>(XTy->getElementType()))
5461 if (const ArrayType *CATy =
5462 dyn_cast<ArrayType>(CPTy->getElementType()))
5463 if (CATy->getElementType() == XATy->getElementType()) {
5464 // At this point, we know that the cast source type is a pointer
5465 // to an array of the same type as the destination pointer
5466 // array. Because the array type is never stepped over (there
5467 // is a leading zero) we can fold the cast into this GEP.
5468 GEP.setOperand(0, X);
5471 } else if (GEP.getNumOperands() == 2) {
5472 // Transform things like:
5473 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5474 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
5475 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5476 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5477 if (isa<ArrayType>(SrcElTy) &&
5478 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5479 TD->getTypeSize(ResElTy)) {
5480 Value *V = InsertNewInstBefore(
5481 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5482 GEP.getOperand(1), GEP.getName()), GEP);
5483 return new CastInst(V, GEP.getType());
5486 // Transform things like:
5487 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5488 // (where tmp = 8*tmp2) into:
5489 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5491 if (isa<ArrayType>(SrcElTy) &&
5492 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5493 uint64_t ArrayEltSize =
5494 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5496 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5497 // allow either a mul, shift, or constant here.
5499 ConstantInt *Scale = 0;
5500 if (ArrayEltSize == 1) {
5501 NewIdx = GEP.getOperand(1);
5502 Scale = ConstantInt::get(NewIdx->getType(), 1);
5503 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
5504 NewIdx = ConstantInt::get(CI->getType(), 1);
5506 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5507 if (Inst->getOpcode() == Instruction::Shl &&
5508 isa<ConstantInt>(Inst->getOperand(1))) {
5509 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5510 if (Inst->getType()->isSigned())
5511 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5513 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5514 NewIdx = Inst->getOperand(0);
5515 } else if (Inst->getOpcode() == Instruction::Mul &&
5516 isa<ConstantInt>(Inst->getOperand(1))) {
5517 Scale = cast<ConstantInt>(Inst->getOperand(1));
5518 NewIdx = Inst->getOperand(0);
5522 // If the index will be to exactly the right offset with the scale taken
5523 // out, perform the transformation.
5524 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5525 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5526 Scale = ConstantSInt::get(C->getType(),
5527 (int64_t)C->getRawValue() /
5528 (int64_t)ArrayEltSize);
5530 Scale = ConstantUInt::get(Scale->getType(),
5531 Scale->getRawValue() / ArrayEltSize);
5532 if (Scale->getRawValue() != 1) {
5533 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5534 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5535 NewIdx = InsertNewInstBefore(Sc, GEP);
5538 // Insert the new GEP instruction.
5540 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5541 NewIdx, GEP.getName());
5542 Idx = InsertNewInstBefore(Idx, GEP);
5543 return new CastInst(Idx, GEP.getType());
5552 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5553 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5554 if (AI.isArrayAllocation()) // Check C != 1
5555 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5556 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
5557 AllocationInst *New = 0;
5559 // Create and insert the replacement instruction...
5560 if (isa<MallocInst>(AI))
5561 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
5563 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
5564 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
5567 InsertNewInstBefore(New, AI);
5569 // Scan to the end of the allocation instructions, to skip over a block of
5570 // allocas if possible...
5572 BasicBlock::iterator It = New;
5573 while (isa<AllocationInst>(*It)) ++It;
5575 // Now that I is pointing to the first non-allocation-inst in the block,
5576 // insert our getelementptr instruction...
5578 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5579 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5580 New->getName()+".sub", It);
5582 // Now make everything use the getelementptr instead of the original
5584 return ReplaceInstUsesWith(AI, V);
5585 } else if (isa<UndefValue>(AI.getArraySize())) {
5586 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5589 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5590 // Note that we only do this for alloca's, because malloc should allocate and
5591 // return a unique pointer, even for a zero byte allocation.
5592 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
5593 TD->getTypeSize(AI.getAllocatedType()) == 0)
5594 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5599 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5600 Value *Op = FI.getOperand(0);
5602 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5603 if (CastInst *CI = dyn_cast<CastInst>(Op))
5604 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5605 FI.setOperand(0, CI->getOperand(0));
5609 // free undef -> unreachable.
5610 if (isa<UndefValue>(Op)) {
5611 // Insert a new store to null because we cannot modify the CFG here.
5612 new StoreInst(ConstantBool::True,
5613 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5614 return EraseInstFromFunction(FI);
5617 // If we have 'free null' delete the instruction. This can happen in stl code
5618 // when lots of inlining happens.
5619 if (isa<ConstantPointerNull>(Op))
5620 return EraseInstFromFunction(FI);
5626 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
5627 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5628 User *CI = cast<User>(LI.getOperand(0));
5629 Value *CastOp = CI->getOperand(0);
5631 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5632 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5633 const Type *SrcPTy = SrcTy->getElementType();
5635 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5636 // If the source is an array, the code below will not succeed. Check to
5637 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5639 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5640 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5641 if (ASrcTy->getNumElements() != 0) {
5642 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5643 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5644 SrcTy = cast<PointerType>(CastOp->getType());
5645 SrcPTy = SrcTy->getElementType();
5648 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
5649 // Do not allow turning this into a load of an integer, which is then
5650 // casted to a pointer, this pessimizes pointer analysis a lot.
5651 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
5652 IC.getTargetData().getTypeSize(SrcPTy) ==
5653 IC.getTargetData().getTypeSize(DestPTy)) {
5655 // Okay, we are casting from one integer or pointer type to another of
5656 // the same size. Instead of casting the pointer before the load, cast
5657 // the result of the loaded value.
5658 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5660 LI.isVolatile()),LI);
5661 // Now cast the result of the load.
5662 return new CastInst(NewLoad, LI.getType());
5669 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
5670 /// from this value cannot trap. If it is not obviously safe to load from the
5671 /// specified pointer, we do a quick local scan of the basic block containing
5672 /// ScanFrom, to determine if the address is already accessed.
5673 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5674 // If it is an alloca or global variable, it is always safe to load from.
5675 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5677 // Otherwise, be a little bit agressive by scanning the local block where we
5678 // want to check to see if the pointer is already being loaded or stored
5679 // from/to. If so, the previous load or store would have already trapped,
5680 // so there is no harm doing an extra load (also, CSE will later eliminate
5681 // the load entirely).
5682 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5687 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5688 if (LI->getOperand(0) == V) return true;
5689 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5690 if (SI->getOperand(1) == V) return true;
5696 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5697 Value *Op = LI.getOperand(0);
5699 // load (cast X) --> cast (load X) iff safe
5700 if (CastInst *CI = dyn_cast<CastInst>(Op))
5701 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5704 // None of the following transforms are legal for volatile loads.
5705 if (LI.isVolatile()) return 0;
5707 if (&LI.getParent()->front() != &LI) {
5708 BasicBlock::iterator BBI = &LI; --BBI;
5709 // If the instruction immediately before this is a store to the same
5710 // address, do a simple form of store->load forwarding.
5711 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5712 if (SI->getOperand(1) == LI.getOperand(0))
5713 return ReplaceInstUsesWith(LI, SI->getOperand(0));
5714 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5715 if (LIB->getOperand(0) == LI.getOperand(0))
5716 return ReplaceInstUsesWith(LI, LIB);
5719 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5720 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5721 isa<UndefValue>(GEPI->getOperand(0))) {
5722 // Insert a new store to null instruction before the load to indicate
5723 // that this code is not reachable. We do this instead of inserting
5724 // an unreachable instruction directly because we cannot modify the
5726 new StoreInst(UndefValue::get(LI.getType()),
5727 Constant::getNullValue(Op->getType()), &LI);
5728 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5731 if (Constant *C = dyn_cast<Constant>(Op)) {
5732 // load null/undef -> undef
5733 if ((C->isNullValue() || isa<UndefValue>(C))) {
5734 // Insert a new store to null instruction before the load to indicate that
5735 // this code is not reachable. We do this instead of inserting an
5736 // unreachable instruction directly because we cannot modify the CFG.
5737 new StoreInst(UndefValue::get(LI.getType()),
5738 Constant::getNullValue(Op->getType()), &LI);
5739 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5742 // Instcombine load (constant global) into the value loaded.
5743 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5744 if (GV->isConstant() && !GV->isExternal())
5745 return ReplaceInstUsesWith(LI, GV->getInitializer());
5747 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5748 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5749 if (CE->getOpcode() == Instruction::GetElementPtr) {
5750 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5751 if (GV->isConstant() && !GV->isExternal())
5753 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
5754 return ReplaceInstUsesWith(LI, V);
5755 if (CE->getOperand(0)->isNullValue()) {
5756 // Insert a new store to null instruction before the load to indicate
5757 // that this code is not reachable. We do this instead of inserting
5758 // an unreachable instruction directly because we cannot modify the
5760 new StoreInst(UndefValue::get(LI.getType()),
5761 Constant::getNullValue(Op->getType()), &LI);
5762 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5765 } else if (CE->getOpcode() == Instruction::Cast) {
5766 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5771 if (Op->hasOneUse()) {
5772 // Change select and PHI nodes to select values instead of addresses: this
5773 // helps alias analysis out a lot, allows many others simplifications, and
5774 // exposes redundancy in the code.
5776 // Note that we cannot do the transformation unless we know that the
5777 // introduced loads cannot trap! Something like this is valid as long as
5778 // the condition is always false: load (select bool %C, int* null, int* %G),
5779 // but it would not be valid if we transformed it to load from null
5782 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5783 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
5784 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5785 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
5786 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
5787 SI->getOperand(1)->getName()+".val"), LI);
5788 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
5789 SI->getOperand(2)->getName()+".val"), LI);
5790 return new SelectInst(SI->getCondition(), V1, V2);
5793 // load (select (cond, null, P)) -> load P
5794 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5795 if (C->isNullValue()) {
5796 LI.setOperand(0, SI->getOperand(2));
5800 // load (select (cond, P, null)) -> load P
5801 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5802 if (C->isNullValue()) {
5803 LI.setOperand(0, SI->getOperand(1));
5807 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5808 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
5809 bool Safe = PN->getParent() == LI.getParent();
5811 // Scan all of the instructions between the PHI and the load to make
5812 // sure there are no instructions that might possibly alter the value
5813 // loaded from the PHI.
5815 BasicBlock::iterator I = &LI;
5816 for (--I; !isa<PHINode>(I); --I)
5817 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5823 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
5824 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
5825 PN->getIncomingBlock(i)->getTerminator()))
5830 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5831 InsertNewInstBefore(NewPN, *PN);
5832 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5834 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5835 BasicBlock *BB = PN->getIncomingBlock(i);
5836 Value *&TheLoad = LoadMap[BB];
5838 Value *InVal = PN->getIncomingValue(i);
5839 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5840 InVal->getName()+".val"),
5841 *BB->getTerminator());
5843 NewPN->addIncoming(TheLoad, BB);
5845 return ReplaceInstUsesWith(LI, NewPN);
5852 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5854 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5855 User *CI = cast<User>(SI.getOperand(1));
5856 Value *CastOp = CI->getOperand(0);
5858 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5859 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5860 const Type *SrcPTy = SrcTy->getElementType();
5862 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5863 // If the source is an array, the code below will not succeed. Check to
5864 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5866 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5867 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5868 if (ASrcTy->getNumElements() != 0) {
5869 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5870 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5871 SrcTy = cast<PointerType>(CastOp->getType());
5872 SrcPTy = SrcTy->getElementType();
5875 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
5876 IC.getTargetData().getTypeSize(SrcPTy) ==
5877 IC.getTargetData().getTypeSize(DestPTy)) {
5879 // Okay, we are casting from one integer or pointer type to another of
5880 // the same size. Instead of casting the pointer before the store, cast
5881 // the value to be stored.
5883 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5884 NewCast = ConstantExpr::getCast(C, SrcPTy);
5886 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5888 SI.getOperand(0)->getName()+".c"), SI);
5890 return new StoreInst(NewCast, CastOp);
5897 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5898 Value *Val = SI.getOperand(0);
5899 Value *Ptr = SI.getOperand(1);
5901 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5902 EraseInstFromFunction(SI);
5907 // Do really simple DSE, to catch cases where there are several consequtive
5908 // stores to the same location, separated by a few arithmetic operations. This
5909 // situation often occurs with bitfield accesses.
5910 BasicBlock::iterator BBI = &SI;
5911 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
5915 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
5916 // Prev store isn't volatile, and stores to the same location?
5917 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
5920 EraseInstFromFunction(*PrevSI);
5926 // Don't skip over loads or things that can modify memory.
5927 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
5932 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
5934 // store X, null -> turns into 'unreachable' in SimplifyCFG
5935 if (isa<ConstantPointerNull>(Ptr)) {
5936 if (!isa<UndefValue>(Val)) {
5937 SI.setOperand(0, UndefValue::get(Val->getType()));
5938 if (Instruction *U = dyn_cast<Instruction>(Val))
5939 WorkList.push_back(U); // Dropped a use.
5942 return 0; // Do not modify these!
5945 // store undef, Ptr -> noop
5946 if (isa<UndefValue>(Val)) {
5947 EraseInstFromFunction(SI);
5952 // If the pointer destination is a cast, see if we can fold the cast into the
5954 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5955 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5957 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5958 if (CE->getOpcode() == Instruction::Cast)
5959 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5963 // If this store is the last instruction in the basic block, and if the block
5964 // ends with an unconditional branch, try to move it to the successor block.
5966 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5967 if (BI->isUnconditional()) {
5968 // Check to see if the successor block has exactly two incoming edges. If
5969 // so, see if the other predecessor contains a store to the same location.
5970 // if so, insert a PHI node (if needed) and move the stores down.
5971 BasicBlock *Dest = BI->getSuccessor(0);
5973 pred_iterator PI = pred_begin(Dest);
5974 BasicBlock *Other = 0;
5975 if (*PI != BI->getParent())
5978 if (PI != pred_end(Dest)) {
5979 if (*PI != BI->getParent())
5984 if (++PI != pred_end(Dest))
5987 if (Other) { // If only one other pred...
5988 BBI = Other->getTerminator();
5989 // Make sure this other block ends in an unconditional branch and that
5990 // there is an instruction before the branch.
5991 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5992 BBI != Other->begin()) {
5994 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5996 // If this instruction is a store to the same location.
5997 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5998 // Okay, we know we can perform this transformation. Insert a PHI
5999 // node now if we need it.
6000 Value *MergedVal = OtherStore->getOperand(0);
6001 if (MergedVal != SI.getOperand(0)) {
6002 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6003 PN->reserveOperandSpace(2);
6004 PN->addIncoming(SI.getOperand(0), SI.getParent());
6005 PN->addIncoming(OtherStore->getOperand(0), Other);
6006 MergedVal = InsertNewInstBefore(PN, Dest->front());
6009 // Advance to a place where it is safe to insert the new store and
6011 BBI = Dest->begin();
6012 while (isa<PHINode>(BBI)) ++BBI;
6013 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6014 OtherStore->isVolatile()), *BBI);
6016 // Nuke the old stores.
6017 EraseInstFromFunction(SI);
6018 EraseInstFromFunction(*OtherStore);
6030 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6031 // Change br (not X), label True, label False to: br X, label False, True
6033 BasicBlock *TrueDest;
6034 BasicBlock *FalseDest;
6035 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6036 !isa<Constant>(X)) {
6037 // Swap Destinations and condition...
6039 BI.setSuccessor(0, FalseDest);
6040 BI.setSuccessor(1, TrueDest);
6044 // Cannonicalize setne -> seteq
6045 Instruction::BinaryOps Op; Value *Y;
6046 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6047 TrueDest, FalseDest)))
6048 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6049 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6050 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6051 std::string Name = I->getName(); I->setName("");
6052 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6053 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
6054 // Swap Destinations and condition...
6055 BI.setCondition(NewSCC);
6056 BI.setSuccessor(0, FalseDest);
6057 BI.setSuccessor(1, TrueDest);
6058 removeFromWorkList(I);
6059 I->getParent()->getInstList().erase(I);
6060 WorkList.push_back(cast<Instruction>(NewSCC));
6067 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6068 Value *Cond = SI.getCondition();
6069 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6070 if (I->getOpcode() == Instruction::Add)
6071 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6072 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6073 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
6074 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
6076 SI.setOperand(0, I->getOperand(0));
6077 WorkList.push_back(I);
6084 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6085 if (ConstantAggregateZero *C =
6086 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
6087 // If packed val is constant 0, replace extract with scalar 0
6088 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
6089 EI.replaceAllUsesWith(Constant::getNullValue(Ty));
6090 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
6092 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6093 // If packed val is constant with uniform operands, replace EI
6094 // with that operand
6095 Constant *op0 = cast<Constant>(C->getOperand(0));
6096 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6097 if (C->getOperand(i) != op0) return 0;
6098 return ReplaceInstUsesWith(EI, op0);
6100 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6101 if (I->hasOneUse()) {
6102 // Push extractelement into predecessor operation if legal and
6103 // profitable to do so
6104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6105 if (!isa<Constant>(BO->getOperand(0)) &&
6106 !isa<Constant>(BO->getOperand(1)))
6108 ExtractElementInst *newEI0 =
6109 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6111 ExtractElementInst *newEI1 =
6112 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6114 InsertNewInstBefore(newEI0, EI);
6115 InsertNewInstBefore(newEI1, EI);
6116 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6118 switch(I->getOpcode()) {
6119 case Instruction::Load: {
6120 Value *Ptr = InsertCastBefore(I->getOperand(0),
6121 PointerType::get(EI.getType()), EI);
6122 GetElementPtrInst *GEP =
6123 new GetElementPtrInst(Ptr, EI.getOperand(1),
6124 I->getName() + ".gep");
6125 InsertNewInstBefore(GEP, EI);
6126 return new LoadInst(GEP);
6136 void InstCombiner::removeFromWorkList(Instruction *I) {
6137 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6142 /// TryToSinkInstruction - Try to move the specified instruction from its
6143 /// current block into the beginning of DestBlock, which can only happen if it's
6144 /// safe to move the instruction past all of the instructions between it and the
6145 /// end of its block.
6146 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6147 assert(I->hasOneUse() && "Invariants didn't hold!");
6149 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6150 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
6152 // Do not sink alloca instructions out of the entry block.
6153 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6156 // We can only sink load instructions if there is nothing between the load and
6157 // the end of block that could change the value.
6158 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6159 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6161 if (Scan->mayWriteToMemory())
6165 BasicBlock::iterator InsertPos = DestBlock->begin();
6166 while (isa<PHINode>(InsertPos)) ++InsertPos;
6168 I->moveBefore(InsertPos);
6173 bool InstCombiner::runOnFunction(Function &F) {
6174 bool Changed = false;
6175 TD = &getAnalysis<TargetData>();
6178 // Populate the worklist with the reachable instructions.
6179 std::set<BasicBlock*> Visited;
6180 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6181 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6182 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6183 WorkList.push_back(I);
6185 // Do a quick scan over the function. If we find any blocks that are
6186 // unreachable, remove any instructions inside of them. This prevents
6187 // the instcombine code from having to deal with some bad special cases.
6188 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6189 if (!Visited.count(BB)) {
6190 Instruction *Term = BB->getTerminator();
6191 while (Term != BB->begin()) { // Remove instrs bottom-up
6192 BasicBlock::iterator I = Term; --I;
6194 DEBUG(std::cerr << "IC: DCE: " << *I);
6197 if (!I->use_empty())
6198 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6199 I->eraseFromParent();
6204 while (!WorkList.empty()) {
6205 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6206 WorkList.pop_back();
6208 // Check to see if we can DCE or ConstantPropagate the instruction...
6209 // Check to see if we can DIE the instruction...
6210 if (isInstructionTriviallyDead(I)) {
6211 // Add operands to the worklist...
6212 if (I->getNumOperands() < 4)
6213 AddUsesToWorkList(*I);
6216 DEBUG(std::cerr << "IC: DCE: " << *I);
6218 I->eraseFromParent();
6219 removeFromWorkList(I);
6223 // Instruction isn't dead, see if we can constant propagate it...
6224 if (Constant *C = ConstantFoldInstruction(I)) {
6225 Value* Ptr = I->getOperand(0);
6226 if (isa<GetElementPtrInst>(I) &&
6227 cast<Constant>(Ptr)->isNullValue() &&
6228 !isa<ConstantPointerNull>(C) &&
6229 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
6230 // If this is a constant expr gep that is effectively computing an
6231 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6232 bool isFoldableGEP = true;
6233 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6234 if (!isa<ConstantInt>(I->getOperand(i)))
6235 isFoldableGEP = false;
6236 if (isFoldableGEP) {
6237 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
6238 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6239 C = ConstantUInt::get(Type::ULongTy, Offset);
6240 C = ConstantExpr::getCast(C, TD->getIntPtrType());
6241 C = ConstantExpr::getCast(C, I->getType());
6245 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6247 // Add operands to the worklist...
6248 AddUsesToWorkList(*I);
6249 ReplaceInstUsesWith(*I, C);
6252 I->getParent()->getInstList().erase(I);
6253 removeFromWorkList(I);
6257 // See if we can trivially sink this instruction to a successor basic block.
6258 if (I->hasOneUse()) {
6259 BasicBlock *BB = I->getParent();
6260 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6261 if (UserParent != BB) {
6262 bool UserIsSuccessor = false;
6263 // See if the user is one of our successors.
6264 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6265 if (*SI == UserParent) {
6266 UserIsSuccessor = true;
6270 // If the user is one of our immediate successors, and if that successor
6271 // only has us as a predecessors (we'd have to split the critical edge
6272 // otherwise), we can keep going.
6273 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6274 next(pred_begin(UserParent)) == pred_end(UserParent))
6275 // Okay, the CFG is simple enough, try to sink this instruction.
6276 Changed |= TryToSinkInstruction(I, UserParent);
6280 // Now that we have an instruction, try combining it to simplify it...
6281 if (Instruction *Result = visit(*I)) {
6283 // Should we replace the old instruction with a new one?
6285 DEBUG(std::cerr << "IC: Old = " << *I
6286 << " New = " << *Result);
6288 // Everything uses the new instruction now.
6289 I->replaceAllUsesWith(Result);
6291 // Push the new instruction and any users onto the worklist.
6292 WorkList.push_back(Result);
6293 AddUsersToWorkList(*Result);
6295 // Move the name to the new instruction first...
6296 std::string OldName = I->getName(); I->setName("");
6297 Result->setName(OldName);
6299 // Insert the new instruction into the basic block...
6300 BasicBlock *InstParent = I->getParent();
6301 BasicBlock::iterator InsertPos = I;
6303 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6304 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6307 InstParent->getInstList().insert(InsertPos, Result);
6309 // Make sure that we reprocess all operands now that we reduced their
6311 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6312 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6313 WorkList.push_back(OpI);
6315 // Instructions can end up on the worklist more than once. Make sure
6316 // we do not process an instruction that has been deleted.
6317 removeFromWorkList(I);
6319 // Erase the old instruction.
6320 InstParent->getInstList().erase(I);
6322 DEBUG(std::cerr << "IC: MOD = " << *I);
6324 // If the instruction was modified, it's possible that it is now dead.
6325 // if so, remove it.
6326 if (isInstructionTriviallyDead(I)) {
6327 // Make sure we process all operands now that we are reducing their
6329 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6330 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6331 WorkList.push_back(OpI);
6333 // Instructions may end up in the worklist more than once. Erase all
6334 // occurrences of this instruction.
6335 removeFromWorkList(I);
6336 I->eraseFromParent();
6338 WorkList.push_back(Result);
6339 AddUsersToWorkList(*Result);
6349 FunctionPass *llvm::createInstructionCombiningPass() {
6350 return new InstCombiner();