1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG. This pass is where
12 // algebraic simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "InstCombine.h"
39 #include "llvm/IntrinsicInst.h"
40 #include "llvm/LLVMContext.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/InstructionSimplify.h"
46 #include "llvm/Analysis/MemoryBuiltins.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/PatternMatch.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/Statistic.h"
57 #include "llvm/ADT/STLExtras.h"
61 using namespace llvm::PatternMatch;
63 STATISTIC(NumCombined , "Number of insts combined");
64 STATISTIC(NumConstProp, "Number of constant folds");
65 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66 STATISTIC(NumSunkInst , "Number of instructions sunk");
69 char InstCombiner::ID = 0;
70 static RegisterPass<InstCombiner>
71 X("instcombine", "Combine redundant instructions");
73 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.addPreservedID(LCSSAID);
79 /// ShouldChangeType - Return true if it is desirable to convert a computation
80 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
81 /// type for example, or from a smaller to a larger illegal type.
82 bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
83 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
85 // If we don't have TD, we don't know if the source/dest are legal.
86 if (!TD) return false;
88 unsigned FromWidth = From->getPrimitiveSizeInBits();
89 unsigned ToWidth = To->getPrimitiveSizeInBits();
90 bool FromLegal = TD->isLegalInteger(FromWidth);
91 bool ToLegal = TD->isLegalInteger(ToWidth);
93 // If this is a legal integer from type, and the result would be an illegal
94 // type, don't do the transformation.
95 if (FromLegal && !ToLegal)
98 // Otherwise, if both are illegal, do not increase the size of the result. We
99 // do allow things like i160 -> i64, but not i64 -> i160.
100 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
107 // SimplifyCommutative - This performs a few simplifications for commutative
110 // 1. Order operands such that they are listed from right (least complex) to
111 // left (most complex). This puts constants before unary operators before
114 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
115 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
117 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
118 bool Changed = false;
119 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
120 Changed = !I.swapOperands();
122 if (!I.isAssociative()) return Changed;
124 Instruction::BinaryOps Opcode = I.getOpcode();
125 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
126 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
127 if (isa<Constant>(I.getOperand(1))) {
128 Constant *Folded = ConstantExpr::get(I.getOpcode(),
129 cast<Constant>(I.getOperand(1)),
130 cast<Constant>(Op->getOperand(1)));
131 I.setOperand(0, Op->getOperand(0));
132 I.setOperand(1, Folded);
136 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)))
137 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
138 Op->hasOneUse() && Op1->hasOneUse()) {
139 Constant *C1 = cast<Constant>(Op->getOperand(1));
140 Constant *C2 = cast<Constant>(Op1->getOperand(1));
142 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
143 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
144 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
148 I.setOperand(0, New);
149 I.setOperand(1, Folded);
156 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
157 // if the LHS is a constant zero (which is the 'negate' form).
159 Value *InstCombiner::dyn_castNegVal(Value *V) const {
160 if (BinaryOperator::isNeg(V))
161 return BinaryOperator::getNegArgument(V);
163 // Constants can be considered to be negated values if they can be folded.
164 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
165 return ConstantExpr::getNeg(C);
167 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
168 if (C->getType()->getElementType()->isInteger())
169 return ConstantExpr::getNeg(C);
174 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
175 // instruction if the LHS is a constant negative zero (which is the 'negate'
178 Value *InstCombiner::dyn_castFNegVal(Value *V) const {
179 if (BinaryOperator::isFNeg(V))
180 return BinaryOperator::getFNegArgument(V);
182 // Constants can be considered to be negated values if they can be folded.
183 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
184 return ConstantExpr::getFNeg(C);
186 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
187 if (C->getType()->getElementType()->isFloatingPoint())
188 return ConstantExpr::getFNeg(C);
193 /// isFreeToInvert - Return true if the specified value is free to invert (apply
194 /// ~ to). This happens in cases where the ~ can be eliminated.
195 static inline bool isFreeToInvert(Value *V) {
197 if (BinaryOperator::isNot(V))
200 // Constants can be considered to be not'ed values.
201 if (isa<ConstantInt>(V))
204 // Compares can be inverted if they have a single use.
205 if (CmpInst *CI = dyn_cast<CmpInst>(V))
206 return CI->hasOneUse();
211 static inline Value *dyn_castNotVal(Value *V) {
212 // If this is not(not(x)) don't return that this is a not: we want the two
213 // not's to be folded first.
214 if (BinaryOperator::isNot(V)) {
215 Value *Operand = BinaryOperator::getNotArgument(V);
216 if (!isFreeToInvert(Operand))
220 // Constants can be considered to be not'ed values...
221 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
222 return ConstantInt::get(C->getType(), ~C->getValue());
228 /// AddOne - Add one to a ConstantInt.
229 static Constant *AddOne(Constant *C) {
230 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
232 /// SubOne - Subtract one from a ConstantInt.
233 static Constant *SubOne(ConstantInt *C) {
234 return ConstantInt::get(C->getContext(), C->getValue()-1);
238 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
240 if (CastInst *CI = dyn_cast<CastInst>(&I))
241 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
243 // Figure out if the constant is the left or the right argument.
244 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
245 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
247 if (Constant *SOC = dyn_cast<Constant>(SO)) {
249 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
250 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
253 Value *Op0 = SO, *Op1 = ConstOperand;
257 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
258 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
259 SO->getName()+".op");
260 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
261 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
262 SO->getName()+".cmp");
263 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
264 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
265 SO->getName()+".cmp");
266 llvm_unreachable("Unknown binary instruction type!");
269 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
270 // constant as the other operand, try to fold the binary operator into the
271 // select arguments. This also works for Cast instructions, which obviously do
272 // not have a second operand.
273 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
274 // Don't modify shared select instructions
275 if (!SI->hasOneUse()) return 0;
276 Value *TV = SI->getOperand(1);
277 Value *FV = SI->getOperand(2);
279 if (isa<Constant>(TV) || isa<Constant>(FV)) {
280 // Bool selects with constant operands can be folded to logical ops.
281 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
283 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
284 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
286 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
293 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
294 /// has a PHI node as operand #0, see if we can fold the instruction into the
295 /// PHI (which is only possible if all operands to the PHI are constants).
297 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
298 /// that would normally be unprofitable because they strongly encourage jump
300 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
301 bool AllowAggressive) {
302 AllowAggressive = false;
303 PHINode *PN = cast<PHINode>(I.getOperand(0));
304 unsigned NumPHIValues = PN->getNumIncomingValues();
305 if (NumPHIValues == 0 ||
306 // We normally only transform phis with a single use, unless we're trying
307 // hard to make jump threading happen.
308 (!PN->hasOneUse() && !AllowAggressive))
312 // Check to see if all of the operands of the PHI are simple constants
313 // (constantint/constantfp/undef). If there is one non-constant value,
314 // remember the BB it is in. If there is more than one or if *it* is a PHI,
315 // bail out. We don't do arbitrary constant expressions here because moving
316 // their computation can be expensive without a cost model.
317 BasicBlock *NonConstBB = 0;
318 for (unsigned i = 0; i != NumPHIValues; ++i)
319 if (!isa<Constant>(PN->getIncomingValue(i)) ||
320 isa<ConstantExpr>(PN->getIncomingValue(i))) {
321 if (NonConstBB) return 0; // More than one non-const value.
322 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
323 NonConstBB = PN->getIncomingBlock(i);
325 // If the incoming non-constant value is in I's block, we have an infinite
327 if (NonConstBB == I.getParent())
331 // If there is exactly one non-constant value, we can insert a copy of the
332 // operation in that block. However, if this is a critical edge, we would be
333 // inserting the computation one some other paths (e.g. inside a loop). Only
334 // do this if the pred block is unconditionally branching into the phi block.
335 if (NonConstBB != 0 && !AllowAggressive) {
336 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
337 if (!BI || !BI->isUnconditional()) return 0;
340 // Okay, we can do the transformation: create the new PHI node.
341 PHINode *NewPN = PHINode::Create(I.getType(), "");
342 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
343 InsertNewInstBefore(NewPN, *PN);
346 // Next, add all of the operands to the PHI.
347 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
348 // We only currently try to fold the condition of a select when it is a phi,
349 // not the true/false values.
350 Value *TrueV = SI->getTrueValue();
351 Value *FalseV = SI->getFalseValue();
352 BasicBlock *PhiTransBB = PN->getParent();
353 for (unsigned i = 0; i != NumPHIValues; ++i) {
354 BasicBlock *ThisBB = PN->getIncomingBlock(i);
355 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
356 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
358 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
359 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
361 assert(PN->getIncomingBlock(i) == NonConstBB);
362 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
364 "phitmp", NonConstBB->getTerminator());
365 Worklist.Add(cast<Instruction>(InV));
367 NewPN->addIncoming(InV, ThisBB);
369 } else if (I.getNumOperands() == 2) {
370 Constant *C = cast<Constant>(I.getOperand(1));
371 for (unsigned i = 0; i != NumPHIValues; ++i) {
373 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
374 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
375 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
377 InV = ConstantExpr::get(I.getOpcode(), InC, C);
379 assert(PN->getIncomingBlock(i) == NonConstBB);
380 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
381 InV = BinaryOperator::Create(BO->getOpcode(),
382 PN->getIncomingValue(i), C, "phitmp",
383 NonConstBB->getTerminator());
384 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
385 InV = CmpInst::Create(CI->getOpcode(),
387 PN->getIncomingValue(i), C, "phitmp",
388 NonConstBB->getTerminator());
390 llvm_unreachable("Unknown binop!");
392 Worklist.Add(cast<Instruction>(InV));
394 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
397 CastInst *CI = cast<CastInst>(&I);
398 const Type *RetTy = CI->getType();
399 for (unsigned i = 0; i != NumPHIValues; ++i) {
401 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
402 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
404 assert(PN->getIncomingBlock(i) == NonConstBB);
405 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
406 I.getType(), "phitmp",
407 NonConstBB->getTerminator());
408 Worklist.Add(cast<Instruction>(InV));
410 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
413 return ReplaceInstUsesWith(I, NewPN);
417 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
418 /// are carefully arranged to allow folding of expressions such as:
420 /// (A < B) | (A > B) --> (A != B)
422 /// Note that this is only valid if the first and second predicates have the
423 /// same sign. Is illegal to do: (A u< B) | (A s> B)
425 /// Three bits are used to represent the condition, as follows:
430 /// <=> Value Definition
431 /// 000 0 Always false
438 /// 111 7 Always true
440 static unsigned getICmpCode(const ICmpInst *ICI) {
441 switch (ICI->getPredicate()) {
443 case ICmpInst::ICMP_UGT: return 1; // 001
444 case ICmpInst::ICMP_SGT: return 1; // 001
445 case ICmpInst::ICMP_EQ: return 2; // 010
446 case ICmpInst::ICMP_UGE: return 3; // 011
447 case ICmpInst::ICMP_SGE: return 3; // 011
448 case ICmpInst::ICMP_ULT: return 4; // 100
449 case ICmpInst::ICMP_SLT: return 4; // 100
450 case ICmpInst::ICMP_NE: return 5; // 101
451 case ICmpInst::ICMP_ULE: return 6; // 110
452 case ICmpInst::ICMP_SLE: return 6; // 110
455 llvm_unreachable("Invalid ICmp predicate!");
460 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
461 /// predicate into a three bit mask. It also returns whether it is an ordered
462 /// predicate by reference.
463 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
466 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
467 case FCmpInst::FCMP_UNO: return 0; // 000
468 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
469 case FCmpInst::FCMP_UGT: return 1; // 001
470 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
471 case FCmpInst::FCMP_UEQ: return 2; // 010
472 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
473 case FCmpInst::FCMP_UGE: return 3; // 011
474 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
475 case FCmpInst::FCMP_ULT: return 4; // 100
476 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
477 case FCmpInst::FCMP_UNE: return 5; // 101
478 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
479 case FCmpInst::FCMP_ULE: return 6; // 110
482 // Not expecting FCMP_FALSE and FCMP_TRUE;
483 llvm_unreachable("Unexpected FCmp predicate!");
488 /// getICmpValue - This is the complement of getICmpCode, which turns an
489 /// opcode and two operands into either a constant true or false, or a brand
490 /// new ICmp instruction. The sign is passed in to determine which kind
491 /// of predicate to use in the new icmp instruction.
492 static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS) {
494 default: assert(0 && "Illegal ICmp code!");
496 return ConstantInt::getFalse(LHS->getContext());
499 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
500 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
502 return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
505 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
506 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
509 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
510 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
512 return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
515 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
516 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
518 return ConstantInt::getTrue(LHS->getContext());
522 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
523 /// opcode and two operands into either a FCmp instruction. isordered is passed
524 /// in to determine which kind of predicate to use in the new fcmp instruction.
525 static Value *getFCmpValue(bool isordered, unsigned code,
526 Value *LHS, Value *RHS) {
528 default: llvm_unreachable("Illegal FCmp code!");
531 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
533 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
536 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
538 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
541 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
543 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
546 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
548 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
551 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
553 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
556 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
558 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
561 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
563 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
564 case 7: return ConstantInt::getTrue(LHS->getContext());
568 /// PredicatesFoldable - Return true if both predicates match sign or if at
569 /// least one of them is an equality comparison (which is signless).
570 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
571 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
572 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
573 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
576 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
577 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
578 // guaranteed to be a binary operator.
579 Instruction *InstCombiner::OptAndOp(Instruction *Op,
582 BinaryOperator &TheAnd) {
583 Value *X = Op->getOperand(0);
584 Constant *Together = 0;
586 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
588 switch (Op->getOpcode()) {
589 case Instruction::Xor:
590 if (Op->hasOneUse()) {
591 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
592 Value *And = Builder->CreateAnd(X, AndRHS);
594 return BinaryOperator::CreateXor(And, Together);
597 case Instruction::Or:
598 if (Together == AndRHS) // (X | C) & C --> C
599 return ReplaceInstUsesWith(TheAnd, AndRHS);
601 if (Op->hasOneUse() && Together != OpRHS) {
602 // (X | C1) & C2 --> (X | (C1&C2)) & C2
603 Value *Or = Builder->CreateOr(X, Together);
605 return BinaryOperator::CreateAnd(Or, AndRHS);
608 case Instruction::Add:
609 if (Op->hasOneUse()) {
610 // Adding a one to a single bit bit-field should be turned into an XOR
611 // of the bit. First thing to check is to see if this AND is with a
612 // single bit constant.
613 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
615 // If there is only one bit set.
616 if (AndRHSV.isPowerOf2()) {
617 // Ok, at this point, we know that we are masking the result of the
618 // ADD down to exactly one bit. If the constant we are adding has
619 // no bits set below this bit, then we can eliminate the ADD.
620 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
622 // Check to see if any bits below the one bit set in AndRHSV are set.
623 if ((AddRHS & (AndRHSV-1)) == 0) {
624 // If not, the only thing that can effect the output of the AND is
625 // the bit specified by AndRHSV. If that bit is set, the effect of
626 // the XOR is to toggle the bit. If it is clear, then the ADD has
628 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
629 TheAnd.setOperand(0, X);
632 // Pull the XOR out of the AND.
633 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
634 NewAnd->takeName(Op);
635 return BinaryOperator::CreateXor(NewAnd, AndRHS);
642 case Instruction::Shl: {
643 // We know that the AND will not produce any of the bits shifted in, so if
644 // the anded constant includes them, clear them now!
646 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
647 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
648 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
649 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
650 AndRHS->getValue() & ShlMask);
652 if (CI->getValue() == ShlMask) {
653 // Masking out bits that the shift already masks
654 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
655 } else if (CI != AndRHS) { // Reducing bits set in and.
656 TheAnd.setOperand(1, CI);
661 case Instruction::LShr: {
662 // We know that the AND will not produce any of the bits shifted in, so if
663 // the anded constant includes them, clear them now! This only applies to
664 // unsigned shifts, because a signed shr may bring in set bits!
666 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
667 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
668 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
669 ConstantInt *CI = ConstantInt::get(Op->getContext(),
670 AndRHS->getValue() & ShrMask);
672 if (CI->getValue() == ShrMask) {
673 // Masking out bits that the shift already masks.
674 return ReplaceInstUsesWith(TheAnd, Op);
675 } else if (CI != AndRHS) {
676 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
681 case Instruction::AShr:
683 // See if this is shifting in some sign extension, then masking it out
685 if (Op->hasOneUse()) {
686 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
687 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
688 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
689 Constant *C = ConstantInt::get(Op->getContext(),
690 AndRHS->getValue() & ShrMask);
691 if (C == AndRHS) { // Masking out bits shifted in.
692 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
693 // Make the argument unsigned.
694 Value *ShVal = Op->getOperand(0);
695 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
696 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
705 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
706 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
707 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
708 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
709 /// insert new instructions.
710 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
711 bool isSigned, bool Inside,
713 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
714 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
715 "Lo is not <= Hi in range emission code!");
718 if (Lo == Hi) // Trivially false.
719 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
721 // V >= Min && V < Hi --> V < Hi
722 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
723 ICmpInst::Predicate pred = (isSigned ?
724 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
725 return new ICmpInst(pred, V, Hi);
728 // Emit V-Lo <u Hi-Lo
729 Constant *NegLo = ConstantExpr::getNeg(Lo);
730 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
731 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
732 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
735 if (Lo == Hi) // Trivially true.
736 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
738 // V < Min || V >= Hi -> V > Hi-1
739 Hi = SubOne(cast<ConstantInt>(Hi));
740 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
741 ICmpInst::Predicate pred = (isSigned ?
742 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
743 return new ICmpInst(pred, V, Hi);
746 // Emit V-Lo >u Hi-1-Lo
747 // Note that Hi has already had one subtracted from it, above.
748 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
749 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
750 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
751 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
754 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
755 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
756 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
757 // not, since all 1s are not contiguous.
758 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
759 const APInt& V = Val->getValue();
760 uint32_t BitWidth = Val->getType()->getBitWidth();
761 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
763 // look for the first zero bit after the run of ones
764 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
765 // look for the first non-zero bit
766 ME = V.getActiveBits();
770 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
771 /// where isSub determines whether the operator is a sub. If we can fold one of
772 /// the following xforms:
774 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
775 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
776 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
778 /// return (A +/- B).
780 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
781 ConstantInt *Mask, bool isSub,
783 Instruction *LHSI = dyn_cast<Instruction>(LHS);
784 if (!LHSI || LHSI->getNumOperands() != 2 ||
785 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
787 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
789 switch (LHSI->getOpcode()) {
791 case Instruction::And:
792 if (ConstantExpr::getAnd(N, Mask) == Mask) {
793 // If the AndRHS is a power of two minus one (0+1+), this is simple.
794 if ((Mask->getValue().countLeadingZeros() +
795 Mask->getValue().countPopulation()) ==
796 Mask->getValue().getBitWidth())
799 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
800 // part, we don't need any explicit masks to take them out of A. If that
801 // is all N is, ignore it.
802 uint32_t MB = 0, ME = 0;
803 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
804 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
805 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
806 if (MaskedValueIsZero(RHS, Mask))
811 case Instruction::Or:
812 case Instruction::Xor:
813 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
814 if ((Mask->getValue().countLeadingZeros() +
815 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
816 && ConstantExpr::getAnd(N, Mask)->isNullValue())
822 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
823 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
826 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
827 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
828 ICmpInst *LHS, ICmpInst *RHS) {
829 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
831 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
832 if (PredicatesFoldable(LHSCC, RHSCC)) {
833 if (LHS->getOperand(0) == RHS->getOperand(1) &&
834 LHS->getOperand(1) == RHS->getOperand(0))
836 if (LHS->getOperand(0) == RHS->getOperand(0) &&
837 LHS->getOperand(1) == RHS->getOperand(1)) {
838 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
839 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
840 bool isSigned = LHS->isSigned() || RHS->isSigned();
841 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
842 if (Instruction *I = dyn_cast<Instruction>(RV))
844 // Otherwise, it's a constant boolean value.
845 return ReplaceInstUsesWith(I, RV);
849 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
850 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
851 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
852 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
853 if (LHSCst == 0 || RHSCst == 0) return 0;
855 if (LHSCst == RHSCst && LHSCC == RHSCC) {
856 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
857 // where C is a power of 2
858 if (LHSCC == ICmpInst::ICMP_ULT &&
859 LHSCst->getValue().isPowerOf2()) {
860 Value *NewOr = Builder->CreateOr(Val, Val2);
861 return new ICmpInst(LHSCC, NewOr, LHSCst);
864 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
865 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
866 Value *NewOr = Builder->CreateOr(Val, Val2);
867 return new ICmpInst(LHSCC, NewOr, LHSCst);
871 // From here on, we only handle:
872 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
873 if (Val != Val2) return 0;
875 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
876 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
877 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
878 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
879 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
882 // We can't fold (ugt x, C) & (sgt x, C2).
883 if (!PredicatesFoldable(LHSCC, RHSCC))
886 // Ensure that the larger constant is on the RHS.
888 if (CmpInst::isSigned(LHSCC) ||
889 (ICmpInst::isEquality(LHSCC) &&
890 CmpInst::isSigned(RHSCC)))
891 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
893 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
897 std::swap(LHSCst, RHSCst);
898 std::swap(LHSCC, RHSCC);
901 // At this point, we know we have have two icmp instructions
902 // comparing a value against two constants and and'ing the result
903 // together. Because of the above check, we know that we only have
904 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
905 // (from the icmp folding check above), that the two constants
906 // are not equal and that the larger constant is on the RHS
907 assert(LHSCst != RHSCst && "Compares not folded above?");
910 default: llvm_unreachable("Unknown integer condition code!");
911 case ICmpInst::ICMP_EQ:
913 default: llvm_unreachable("Unknown integer condition code!");
914 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
915 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
916 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
917 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
918 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
919 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
920 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
921 return ReplaceInstUsesWith(I, LHS);
923 case ICmpInst::ICMP_NE:
925 default: llvm_unreachable("Unknown integer condition code!");
926 case ICmpInst::ICMP_ULT:
927 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
928 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
929 break; // (X != 13 & X u< 15) -> no change
930 case ICmpInst::ICMP_SLT:
931 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
932 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
933 break; // (X != 13 & X s< 15) -> no change
934 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
935 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
936 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
937 return ReplaceInstUsesWith(I, RHS);
938 case ICmpInst::ICMP_NE:
939 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
940 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
941 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
942 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
943 ConstantInt::get(Add->getType(), 1));
945 break; // (X != 13 & X != 15) -> no change
948 case ICmpInst::ICMP_ULT:
950 default: llvm_unreachable("Unknown integer condition code!");
951 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
952 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
953 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
954 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
956 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
957 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
958 return ReplaceInstUsesWith(I, LHS);
959 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
963 case ICmpInst::ICMP_SLT:
965 default: llvm_unreachable("Unknown integer condition code!");
966 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
967 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
968 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
969 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
971 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
972 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
973 return ReplaceInstUsesWith(I, LHS);
974 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
978 case ICmpInst::ICMP_UGT:
980 default: llvm_unreachable("Unknown integer condition code!");
981 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
982 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
983 return ReplaceInstUsesWith(I, RHS);
984 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
986 case ICmpInst::ICMP_NE:
987 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
988 return new ICmpInst(LHSCC, Val, RHSCst);
989 break; // (X u> 13 & X != 15) -> no change
990 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
991 return InsertRangeTest(Val, AddOne(LHSCst),
992 RHSCst, false, true, I);
993 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
997 case ICmpInst::ICMP_SGT:
999 default: llvm_unreachable("Unknown integer condition code!");
1000 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1001 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
1002 return ReplaceInstUsesWith(I, RHS);
1003 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1005 case ICmpInst::ICMP_NE:
1006 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
1007 return new ICmpInst(LHSCC, Val, RHSCst);
1008 break; // (X s> 13 & X != 15) -> no change
1009 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
1010 return InsertRangeTest(Val, AddOne(LHSCst),
1011 RHSCst, true, true, I);
1012 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1021 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
1024 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1025 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1026 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1027 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1028 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1029 // If either of the constants are nans, then the whole thing returns
1031 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1032 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1033 return new FCmpInst(FCmpInst::FCMP_ORD,
1034 LHS->getOperand(0), RHS->getOperand(0));
1037 // Handle vector zeros. This occurs because the canonical form of
1038 // "fcmp ord x,x" is "fcmp ord x, 0".
1039 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1040 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1041 return new FCmpInst(FCmpInst::FCMP_ORD,
1042 LHS->getOperand(0), RHS->getOperand(0));
1046 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1047 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1048 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1051 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1052 // Swap RHS operands to match LHS.
1053 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1054 std::swap(Op1LHS, Op1RHS);
1057 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1058 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1060 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1062 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
1063 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1064 if (Op0CC == FCmpInst::FCMP_TRUE)
1065 return ReplaceInstUsesWith(I, RHS);
1066 if (Op1CC == FCmpInst::FCMP_TRUE)
1067 return ReplaceInstUsesWith(I, LHS);
1071 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1072 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1074 std::swap(LHS, RHS);
1075 std::swap(Op0Pred, Op1Pred);
1076 std::swap(Op0Ordered, Op1Ordered);
1079 // uno && ueq -> uno && (uno || eq) -> ueq
1080 // ord && olt -> ord && (ord && lt) -> olt
1081 if (Op0Ordered == Op1Ordered)
1082 return ReplaceInstUsesWith(I, RHS);
1084 // uno && oeq -> uno && (ord && eq) -> false
1085 // uno && ord -> false
1087 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1088 // ord && ueq -> ord && (uno || eq) -> oeq
1089 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
1097 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1098 bool Changed = SimplifyCommutative(I);
1099 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1101 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1102 return ReplaceInstUsesWith(I, V);
1104 // See if we can simplify any instructions used by the instruction whose sole
1105 // purpose is to compute bits we don't care about.
1106 if (SimplifyDemandedInstructionBits(I))
1109 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1110 const APInt &AndRHSMask = AndRHS->getValue();
1111 APInt NotAndRHS(~AndRHSMask);
1113 // Optimize a variety of ((val OP C1) & C2) combinations...
1114 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1115 Value *Op0LHS = Op0I->getOperand(0);
1116 Value *Op0RHS = Op0I->getOperand(1);
1117 switch (Op0I->getOpcode()) {
1119 case Instruction::Xor:
1120 case Instruction::Or:
1121 // If the mask is only needed on one incoming arm, push it up.
1122 if (!Op0I->hasOneUse()) break;
1124 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1125 // Not masking anything out for the LHS, move to RHS.
1126 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1127 Op0RHS->getName()+".masked");
1128 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1130 if (!isa<Constant>(Op0RHS) &&
1131 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1132 // Not masking anything out for the RHS, move to LHS.
1133 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1134 Op0LHS->getName()+".masked");
1135 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1139 case Instruction::Add:
1140 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1141 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1142 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1143 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1144 return BinaryOperator::CreateAnd(V, AndRHS);
1145 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1146 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1149 case Instruction::Sub:
1150 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1151 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1152 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1153 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1154 return BinaryOperator::CreateAnd(V, AndRHS);
1156 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1157 // has 1's for all bits that the subtraction with A might affect.
1158 if (Op0I->hasOneUse()) {
1159 uint32_t BitWidth = AndRHSMask.getBitWidth();
1160 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1161 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1163 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
1164 if (!(A && A->isZero()) && // avoid infinite recursion.
1165 MaskedValueIsZero(Op0LHS, Mask)) {
1166 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1167 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1172 case Instruction::Shl:
1173 case Instruction::LShr:
1174 // (1 << x) & 1 --> zext(x == 0)
1175 // (1 >> x) & 1 --> zext(x == 0)
1176 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1178 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1179 return new ZExtInst(NewICmp, I.getType());
1184 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1185 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1187 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1188 // If this is an integer truncation or change from signed-to-unsigned, and
1189 // if the source is an and/or with immediate, transform it. This
1190 // frequently occurs for bitfield accesses.
1191 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1192 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
1193 CastOp->getNumOperands() == 2)
1194 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
1195 if (CastOp->getOpcode() == Instruction::And) {
1196 // Change: and (cast (and X, C1) to T), C2
1197 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
1198 // This will fold the two constants together, which may allow
1199 // other simplifications.
1200 Value *NewCast = Builder->CreateTruncOrBitCast(
1201 CastOp->getOperand(0), I.getType(),
1202 CastOp->getName()+".shrunk");
1203 // trunc_or_bitcast(C1)&C2
1204 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
1205 C3 = ConstantExpr::getAnd(C3, AndRHS);
1206 return BinaryOperator::CreateAnd(NewCast, C3);
1207 } else if (CastOp->getOpcode() == Instruction::Or) {
1208 // Change: and (cast (or X, C1) to T), C2
1209 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1210 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
1211 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
1213 return ReplaceInstUsesWith(I, AndRHS);
1219 // Try to fold constant and into select arguments.
1220 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1221 if (Instruction *R = FoldOpIntoSelect(I, SI))
1223 if (isa<PHINode>(Op0))
1224 if (Instruction *NV = FoldOpIntoPhi(I))
1229 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1230 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1231 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1232 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1233 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1234 I.getName()+".demorgan");
1235 return BinaryOperator::CreateNot(Or);
1239 Value *A = 0, *B = 0, *C = 0, *D = 0;
1240 // (A|B) & ~(A&B) -> A^B
1241 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1242 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1243 ((A == C && B == D) || (A == D && B == C)))
1244 return BinaryOperator::CreateXor(A, B);
1246 // ~(A&B) & (A|B) -> A^B
1247 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1248 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1249 ((A == C && B == D) || (A == D && B == C)))
1250 return BinaryOperator::CreateXor(A, B);
1252 if (Op0->hasOneUse() &&
1253 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1254 if (A == Op1) { // (A^B)&A -> A&(A^B)
1255 I.swapOperands(); // Simplify below
1256 std::swap(Op0, Op1);
1257 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
1258 cast<BinaryOperator>(Op0)->swapOperands();
1259 I.swapOperands(); // Simplify below
1260 std::swap(Op0, Op1);
1264 if (Op1->hasOneUse() &&
1265 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1266 if (B == Op0) { // B&(A^B) -> B&(B^A)
1267 cast<BinaryOperator>(Op1)->swapOperands();
1270 if (A == Op0) // A&(A^B) -> A & ~B
1271 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
1274 // (A&((~A)|B)) -> A&B
1275 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1276 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1277 return BinaryOperator::CreateAnd(A, Op1);
1278 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1279 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1280 return BinaryOperator::CreateAnd(A, Op0);
1283 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1284 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1285 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
1288 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1289 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1290 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1291 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
1292 const Type *SrcTy = Op0C->getOperand(0)->getType();
1293 if (SrcTy == Op1C->getOperand(0)->getType() &&
1294 SrcTy->isIntOrIntVector() &&
1295 // Only do this if the casts both really cause code to be generated.
1296 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
1298 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
1300 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
1301 Op1C->getOperand(0), I.getName());
1302 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1306 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1307 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1308 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1309 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1310 SI0->getOperand(1) == SI1->getOperand(1) &&
1311 (SI0->hasOneUse() || SI1->hasOneUse())) {
1313 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1315 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1316 SI1->getOperand(1));
1320 // If and'ing two fcmp, try combine them into one.
1321 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
1322 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1323 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
1327 return Changed ? &I : 0;
1330 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1331 /// capable of providing pieces of a bswap. The subexpression provides pieces
1332 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1333 /// the expression came from the corresponding "byte swapped" byte in some other
1334 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1335 /// we know that the expression deposits the low byte of %X into the high byte
1336 /// of the bswap result and that all other bytes are zero. This expression is
1337 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1340 /// This function returns true if the match was unsuccessful and false if so.
1341 /// On entry to the function the "OverallLeftShift" is a signed integer value
1342 /// indicating the number of bytes that the subexpression is later shifted. For
1343 /// example, if the expression is later right shifted by 16 bits, the
1344 /// OverallLeftShift value would be -2 on entry. This is used to specify which
1345 /// byte of ByteValues is actually being set.
1347 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1348 /// byte is masked to zero by a user. For example, in (X & 255), X will be
1349 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1350 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
1351 /// always in the local (OverallLeftShift) coordinate space.
1353 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1354 SmallVector<Value*, 8> &ByteValues) {
1355 if (Instruction *I = dyn_cast<Instruction>(V)) {
1356 // If this is an or instruction, it may be an inner node of the bswap.
1357 if (I->getOpcode() == Instruction::Or) {
1358 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1360 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1364 // If this is a logical shift by a constant multiple of 8, recurse with
1365 // OverallLeftShift and ByteMask adjusted.
1366 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1368 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1369 // Ensure the shift amount is defined and of a byte value.
1370 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1373 unsigned ByteShift = ShAmt >> 3;
1374 if (I->getOpcode() == Instruction::Shl) {
1375 // X << 2 -> collect(X, +2)
1376 OverallLeftShift += ByteShift;
1377 ByteMask >>= ByteShift;
1379 // X >>u 2 -> collect(X, -2)
1380 OverallLeftShift -= ByteShift;
1381 ByteMask <<= ByteShift;
1382 ByteMask &= (~0U >> (32-ByteValues.size()));
1385 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1386 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1388 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1392 // If this is a logical 'and' with a mask that clears bytes, clear the
1393 // corresponding bytes in ByteMask.
1394 if (I->getOpcode() == Instruction::And &&
1395 isa<ConstantInt>(I->getOperand(1))) {
1396 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1397 unsigned NumBytes = ByteValues.size();
1398 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1399 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1401 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1402 // If this byte is masked out by a later operation, we don't care what
1404 if ((ByteMask & (1 << i)) == 0)
1407 // If the AndMask is all zeros for this byte, clear the bit.
1408 APInt MaskB = AndMask & Byte;
1410 ByteMask &= ~(1U << i);
1414 // If the AndMask is not all ones for this byte, it's not a bytezap.
1418 // Otherwise, this byte is kept.
1421 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1426 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1427 // the input value to the bswap. Some observations: 1) if more than one byte
1428 // is demanded from this input, then it could not be successfully assembled
1429 // into a byteswap. At least one of the two bytes would not be aligned with
1430 // their ultimate destination.
1431 if (!isPowerOf2_32(ByteMask)) return true;
1432 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1434 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1435 // is demanded, it needs to go into byte 0 of the result. This means that the
1436 // byte needs to be shifted until it lands in the right byte bucket. The
1437 // shift amount depends on the position: if the byte is coming from the high
1438 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1439 // low part, it must be shifted left.
1440 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1441 if (InputByteNo < ByteValues.size()/2) {
1442 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1445 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1449 // If the destination byte value is already defined, the values are or'd
1450 // together, which isn't a bswap (unless it's an or of the same bits).
1451 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1453 ByteValues[DestByteNo] = V;
1457 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1458 /// If so, insert the new bswap intrinsic and return it.
1459 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1460 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1461 if (!ITy || ITy->getBitWidth() % 16 ||
1462 // ByteMask only allows up to 32-byte values.
1463 ITy->getBitWidth() > 32*8)
1464 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1466 /// ByteValues - For each byte of the result, we keep track of which value
1467 /// defines each byte.
1468 SmallVector<Value*, 8> ByteValues;
1469 ByteValues.resize(ITy->getBitWidth()/8);
1471 // Try to find all the pieces corresponding to the bswap.
1472 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1473 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1476 // Check to see if all of the bytes come from the same value.
1477 Value *V = ByteValues[0];
1478 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1480 // Check to make sure that all of the bytes come from the same value.
1481 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1482 if (ByteValues[i] != V)
1484 const Type *Tys[] = { ITy };
1485 Module *M = I.getParent()->getParent()->getParent();
1486 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
1487 return CallInst::Create(F, V);
1490 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1491 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1492 /// we can simplify this expression to "cond ? C : D or B".
1493 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1494 Value *C, Value *D) {
1495 // If A is not a select of -1/0, this cannot match.
1497 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
1500 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1501 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
1502 return SelectInst::Create(Cond, C, B);
1503 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
1504 return SelectInst::Create(Cond, C, B);
1505 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1506 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
1507 return SelectInst::Create(Cond, C, D);
1508 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
1509 return SelectInst::Create(Cond, C, D);
1513 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1514 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
1515 ICmpInst *LHS, ICmpInst *RHS) {
1516 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1518 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1519 if (PredicatesFoldable(LHSCC, RHSCC)) {
1520 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1521 LHS->getOperand(1) == RHS->getOperand(0))
1522 LHS->swapOperands();
1523 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1524 LHS->getOperand(1) == RHS->getOperand(1)) {
1525 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1526 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1527 bool isSigned = LHS->isSigned() || RHS->isSigned();
1528 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
1529 if (Instruction *I = dyn_cast<Instruction>(RV))
1531 // Otherwise, it's a constant boolean value.
1532 return ReplaceInstUsesWith(I, RV);
1536 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1537 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1538 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1539 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1540 if (LHSCst == 0 || RHSCst == 0) return 0;
1542 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1543 if (LHSCst == RHSCst && LHSCC == RHSCC &&
1544 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1545 Value *NewOr = Builder->CreateOr(Val, Val2);
1546 return new ICmpInst(LHSCC, NewOr, LHSCst);
1549 // From here on, we only handle:
1550 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1551 if (Val != Val2) return 0;
1553 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1554 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1555 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1556 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1557 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1560 // We can't fold (ugt x, C) | (sgt x, C2).
1561 if (!PredicatesFoldable(LHSCC, RHSCC))
1564 // Ensure that the larger constant is on the RHS.
1566 if (CmpInst::isSigned(LHSCC) ||
1567 (ICmpInst::isEquality(LHSCC) &&
1568 CmpInst::isSigned(RHSCC)))
1569 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1571 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1574 std::swap(LHS, RHS);
1575 std::swap(LHSCst, RHSCst);
1576 std::swap(LHSCC, RHSCC);
1579 // At this point, we know we have have two icmp instructions
1580 // comparing a value against two constants and or'ing the result
1581 // together. Because of the above check, we know that we only have
1582 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1583 // icmp folding check above), that the two constants are not
1585 assert(LHSCst != RHSCst && "Compares not folded above?");
1588 default: llvm_unreachable("Unknown integer condition code!");
1589 case ICmpInst::ICMP_EQ:
1591 default: llvm_unreachable("Unknown integer condition code!");
1592 case ICmpInst::ICMP_EQ:
1593 if (LHSCst == SubOne(RHSCst)) {
1594 // (X == 13 | X == 14) -> X-13 <u 2
1595 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1596 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1597 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1598 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
1600 break; // (X == 13 | X == 15) -> no change
1601 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1602 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1604 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1605 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1606 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1607 return ReplaceInstUsesWith(I, RHS);
1610 case ICmpInst::ICMP_NE:
1612 default: llvm_unreachable("Unknown integer condition code!");
1613 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1614 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1615 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1616 return ReplaceInstUsesWith(I, LHS);
1617 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1618 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1619 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
1620 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1623 case ICmpInst::ICMP_ULT:
1625 default: llvm_unreachable("Unknown integer condition code!");
1626 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1628 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1629 // If RHSCst is [us]MAXINT, it is always false. Not handling
1630 // this can cause overflow.
1631 if (RHSCst->isMaxValue(false))
1632 return ReplaceInstUsesWith(I, LHS);
1633 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
1635 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1637 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1638 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1639 return ReplaceInstUsesWith(I, RHS);
1640 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1644 case ICmpInst::ICMP_SLT:
1646 default: llvm_unreachable("Unknown integer condition code!");
1647 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1649 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1650 // If RHSCst is [us]MAXINT, it is always false. Not handling
1651 // this can cause overflow.
1652 if (RHSCst->isMaxValue(true))
1653 return ReplaceInstUsesWith(I, LHS);
1654 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
1656 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1658 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1659 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1660 return ReplaceInstUsesWith(I, RHS);
1661 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1665 case ICmpInst::ICMP_UGT:
1667 default: llvm_unreachable("Unknown integer condition code!");
1668 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1669 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1670 return ReplaceInstUsesWith(I, LHS);
1671 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1673 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1674 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
1675 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1676 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1680 case ICmpInst::ICMP_SGT:
1682 default: llvm_unreachable("Unknown integer condition code!");
1683 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1684 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1685 return ReplaceInstUsesWith(I, LHS);
1686 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1688 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1689 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
1690 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1691 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1699 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
1701 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1702 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1703 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1704 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1705 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1706 // If either of the constants are nans, then the whole thing returns
1708 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1709 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1711 // Otherwise, no need to compare the two constants, compare the
1713 return new FCmpInst(FCmpInst::FCMP_UNO,
1714 LHS->getOperand(0), RHS->getOperand(0));
1717 // Handle vector zeros. This occurs because the canonical form of
1718 // "fcmp uno x,x" is "fcmp uno x, 0".
1719 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1720 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1721 return new FCmpInst(FCmpInst::FCMP_UNO,
1722 LHS->getOperand(0), RHS->getOperand(0));
1727 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1728 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1729 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1731 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1732 // Swap RHS operands to match LHS.
1733 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1734 std::swap(Op1LHS, Op1RHS);
1736 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1737 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1739 return new FCmpInst((FCmpInst::Predicate)Op0CC,
1741 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1742 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1743 if (Op0CC == FCmpInst::FCMP_FALSE)
1744 return ReplaceInstUsesWith(I, RHS);
1745 if (Op1CC == FCmpInst::FCMP_FALSE)
1746 return ReplaceInstUsesWith(I, LHS);
1749 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1750 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1751 if (Op0Ordered == Op1Ordered) {
1752 // If both are ordered or unordered, return a new fcmp with
1753 // or'ed predicates.
1754 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
1755 if (Instruction *I = dyn_cast<Instruction>(RV))
1757 // Otherwise, it's a constant boolean value...
1758 return ReplaceInstUsesWith(I, RV);
1764 /// FoldOrWithConstants - This helper function folds:
1766 /// ((A | B) & C1) | (B & C2)
1772 /// when the XOR of the two constants is "all ones" (-1).
1773 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1774 Value *A, Value *B, Value *C) {
1775 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1779 ConstantInt *CI2 = 0;
1780 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1782 APInt Xor = CI1->getValue() ^ CI2->getValue();
1783 if (!Xor.isAllOnesValue()) return 0;
1785 if (V1 == A || V1 == B) {
1786 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1787 return BinaryOperator::CreateOr(NewOp, V1);
1793 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1794 bool Changed = SimplifyCommutative(I);
1795 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1797 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1798 return ReplaceInstUsesWith(I, V);
1801 // See if we can simplify any instructions used by the instruction whose sole
1802 // purpose is to compute bits we don't care about.
1803 if (SimplifyDemandedInstructionBits(I))
1806 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1807 ConstantInt *C1 = 0; Value *X = 0;
1808 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1809 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1811 Value *Or = Builder->CreateOr(X, RHS);
1813 return BinaryOperator::CreateAnd(Or,
1814 ConstantInt::get(I.getContext(),
1815 RHS->getValue() | C1->getValue()));
1818 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1819 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1821 Value *Or = Builder->CreateOr(X, RHS);
1823 return BinaryOperator::CreateXor(Or,
1824 ConstantInt::get(I.getContext(),
1825 C1->getValue() & ~RHS->getValue()));
1828 // Try to fold constant and into select arguments.
1829 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1830 if (Instruction *R = FoldOpIntoSelect(I, SI))
1832 if (isa<PHINode>(Op0))
1833 if (Instruction *NV = FoldOpIntoPhi(I))
1837 Value *A = 0, *B = 0;
1838 ConstantInt *C1 = 0, *C2 = 0;
1840 // (A | B) | C and A | (B | C) -> bswap if possible.
1841 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1842 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1843 match(Op1, m_Or(m_Value(), m_Value())) ||
1844 (match(Op0, m_Shift(m_Value(), m_Value())) &&
1845 match(Op1, m_Shift(m_Value(), m_Value())))) {
1846 if (Instruction *BSwap = MatchBSwap(I))
1850 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1851 if (Op0->hasOneUse() &&
1852 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1853 MaskedValueIsZero(Op1, C1->getValue())) {
1854 Value *NOr = Builder->CreateOr(A, Op1);
1856 return BinaryOperator::CreateXor(NOr, C1);
1859 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1860 if (Op1->hasOneUse() &&
1861 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1862 MaskedValueIsZero(Op0, C1->getValue())) {
1863 Value *NOr = Builder->CreateOr(A, Op0);
1865 return BinaryOperator::CreateXor(NOr, C1);
1869 Value *C = 0, *D = 0;
1870 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1871 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1872 Value *V1 = 0, *V2 = 0, *V3 = 0;
1873 C1 = dyn_cast<ConstantInt>(C);
1874 C2 = dyn_cast<ConstantInt>(D);
1875 if (C1 && C2) { // (A & C1)|(B & C2)
1876 // If we have: ((V + N) & C1) | (V & C2)
1877 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1878 // replace with V+N.
1879 if (C1->getValue() == ~C2->getValue()) {
1880 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1881 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1882 // Add commutes, try both ways.
1883 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1884 return ReplaceInstUsesWith(I, A);
1885 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1886 return ReplaceInstUsesWith(I, A);
1888 // Or commutes, try both ways.
1889 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1890 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1891 // Add commutes, try both ways.
1892 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1893 return ReplaceInstUsesWith(I, B);
1894 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1895 return ReplaceInstUsesWith(I, B);
1899 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1900 // iff (C1&C2) == 0 and (N&~C1) == 0
1901 if ((C1->getValue() & C2->getValue()) == 0) {
1902 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1903 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1904 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1905 return BinaryOperator::CreateAnd(A,
1906 ConstantInt::get(A->getContext(),
1907 C1->getValue()|C2->getValue()));
1908 // Or commutes, try both ways.
1909 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1910 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1911 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1912 return BinaryOperator::CreateAnd(B,
1913 ConstantInt::get(B->getContext(),
1914 C1->getValue()|C2->getValue()));
1918 // Check to see if we have any common things being and'ed. If so, find the
1919 // terms for V1 & (V2|V3).
1920 if (Op0->hasOneUse() || Op1->hasOneUse()) {
1922 if (A == B) // (A & C)|(A & D) == A & (C|D)
1923 V1 = A, V2 = C, V3 = D;
1924 else if (A == D) // (A & C)|(B & A) == A & (B|C)
1925 V1 = A, V2 = B, V3 = C;
1926 else if (C == B) // (A & C)|(C & D) == C & (A|D)
1927 V1 = C, V2 = A, V3 = D;
1928 else if (C == D) // (A & C)|(B & C) == C & (A|B)
1929 V1 = C, V2 = A, V3 = B;
1932 Value *Or = Builder->CreateOr(V2, V3, "tmp");
1933 return BinaryOperator::CreateAnd(V1, Or);
1937 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
1938 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1940 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1942 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1944 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1947 // ((A&~B)|(~A&B)) -> A^B
1948 if ((match(C, m_Not(m_Specific(D))) &&
1949 match(B, m_Not(m_Specific(A)))))
1950 return BinaryOperator::CreateXor(A, D);
1951 // ((~B&A)|(~A&B)) -> A^B
1952 if ((match(A, m_Not(m_Specific(D))) &&
1953 match(B, m_Not(m_Specific(C)))))
1954 return BinaryOperator::CreateXor(C, D);
1955 // ((A&~B)|(B&~A)) -> A^B
1956 if ((match(C, m_Not(m_Specific(B))) &&
1957 match(D, m_Not(m_Specific(A)))))
1958 return BinaryOperator::CreateXor(A, B);
1959 // ((~B&A)|(B&~A)) -> A^B
1960 if ((match(A, m_Not(m_Specific(B))) &&
1961 match(D, m_Not(m_Specific(C)))))
1962 return BinaryOperator::CreateXor(C, B);
1965 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1966 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1967 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1968 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1969 SI0->getOperand(1) == SI1->getOperand(1) &&
1970 (SI0->hasOneUse() || SI1->hasOneUse())) {
1971 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1973 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1974 SI1->getOperand(1));
1978 // ((A|B)&1)|(B&-2) -> (A&1) | B
1979 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
1980 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
1981 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
1982 if (Ret) return Ret;
1984 // (B&-2)|((A|B)&1) -> (A&1) | B
1985 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
1986 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
1987 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
1988 if (Ret) return Ret;
1991 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1992 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1993 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1994 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1995 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1996 I.getName()+".demorgan");
1997 return BinaryOperator::CreateNot(And);
2000 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2001 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2002 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
2005 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2006 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2007 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2008 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
2009 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
2010 !isa<ICmpInst>(Op1C->getOperand(0))) {
2011 const Type *SrcTy = Op0C->getOperand(0)->getType();
2012 if (SrcTy == Op1C->getOperand(0)->getType() &&
2013 SrcTy->isIntOrIntVector() &&
2014 // Only do this if the casts both really cause code to be
2016 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
2018 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
2020 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
2021 Op1C->getOperand(0), I.getName());
2022 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2029 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2030 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
2031 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2032 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
2036 return Changed ? &I : 0;
2039 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2040 bool Changed = SimplifyCommutative(I);
2041 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2043 if (isa<UndefValue>(Op1)) {
2044 if (isa<UndefValue>(Op0))
2045 // Handle undef ^ undef -> 0 special case. This is a common
2047 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2048 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2053 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2055 // See if we can simplify any instructions used by the instruction whose sole
2056 // purpose is to compute bits we don't care about.
2057 if (SimplifyDemandedInstructionBits(I))
2059 if (isa<VectorType>(I.getType()))
2060 if (isa<ConstantAggregateZero>(Op1))
2061 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
2063 // Is this a ~ operation?
2064 if (Value *NotOp = dyn_castNotVal(&I)) {
2065 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2066 if (Op0I->getOpcode() == Instruction::And ||
2067 Op0I->getOpcode() == Instruction::Or) {
2068 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2069 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2070 if (dyn_castNotVal(Op0I->getOperand(1)))
2071 Op0I->swapOperands();
2072 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2074 Builder->CreateNot(Op0I->getOperand(1),
2075 Op0I->getOperand(1)->getName()+".not");
2076 if (Op0I->getOpcode() == Instruction::And)
2077 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2078 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2081 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2082 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2083 if (isFreeToInvert(Op0I->getOperand(0)) &&
2084 isFreeToInvert(Op0I->getOperand(1))) {
2086 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2088 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2089 if (Op0I->getOpcode() == Instruction::And)
2090 return BinaryOperator::CreateOr(NotX, NotY);
2091 return BinaryOperator::CreateAnd(NotX, NotY);
2098 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2099 if (RHS->isOne() && Op0->hasOneUse()) {
2100 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2101 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
2102 return new ICmpInst(ICI->getInversePredicate(),
2103 ICI->getOperand(0), ICI->getOperand(1));
2105 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
2106 return new FCmpInst(FCI->getInversePredicate(),
2107 FCI->getOperand(0), FCI->getOperand(1));
2110 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2111 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2112 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2113 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2114 Instruction::CastOps Opcode = Op0C->getOpcode();
2115 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2116 (RHS == ConstantExpr::getCast(Opcode,
2117 ConstantInt::getTrue(I.getContext()),
2118 Op0C->getDestTy()))) {
2119 CI->setPredicate(CI->getInversePredicate());
2120 return CastInst::Create(Opcode, CI, Op0C->getType());
2126 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2127 // ~(c-X) == X-c-1 == X+(-c-1)
2128 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2129 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2130 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2131 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2132 ConstantInt::get(I.getType(), 1));
2133 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2136 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2137 if (Op0I->getOpcode() == Instruction::Add) {
2138 // ~(X-c) --> (-c-1)-X
2139 if (RHS->isAllOnesValue()) {
2140 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2141 return BinaryOperator::CreateSub(
2142 ConstantExpr::getSub(NegOp0CI,
2143 ConstantInt::get(I.getType(), 1)),
2144 Op0I->getOperand(0));
2145 } else if (RHS->getValue().isSignBit()) {
2146 // (X + C) ^ signbit -> (X + C + signbit)
2147 Constant *C = ConstantInt::get(I.getContext(),
2148 RHS->getValue() + Op0CI->getValue());
2149 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2152 } else if (Op0I->getOpcode() == Instruction::Or) {
2153 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2154 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2155 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2156 // Anything in both C1 and C2 is known to be zero, remove it from
2158 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2159 NewRHS = ConstantExpr::getAnd(NewRHS,
2160 ConstantExpr::getNot(CommonBits));
2162 I.setOperand(0, Op0I->getOperand(0));
2163 I.setOperand(1, NewRHS);
2170 // Try to fold constant and into select arguments.
2171 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2172 if (Instruction *R = FoldOpIntoSelect(I, SI))
2174 if (isa<PHINode>(Op0))
2175 if (Instruction *NV = FoldOpIntoPhi(I))
2179 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
2181 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2183 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
2185 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2188 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2191 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2192 if (A == Op0) { // B^(B|A) == (A|B)^B
2193 Op1I->swapOperands();
2195 std::swap(Op0, Op1);
2196 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2197 I.swapOperands(); // Simplified below.
2198 std::swap(Op0, Op1);
2200 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
2201 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
2202 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
2203 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
2204 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2206 if (A == Op0) { // A^(A&B) -> A^(B&A)
2207 Op1I->swapOperands();
2210 if (B == Op0) { // A^(B&A) -> (B&A)^A
2211 I.swapOperands(); // Simplified below.
2212 std::swap(Op0, Op1);
2217 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2220 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2221 Op0I->hasOneUse()) {
2222 if (A == Op1) // (B|A)^B == (A|B)^B
2224 if (B == Op1) // (A|B)^B == A & ~B
2225 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
2226 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
2227 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
2228 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
2229 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
2230 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2232 if (A == Op1) // (A&B)^A -> (B&A)^A
2234 if (B == Op1 && // (B&A)^A == ~B & A
2235 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
2236 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
2241 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2242 if (Op0I && Op1I && Op0I->isShift() &&
2243 Op0I->getOpcode() == Op1I->getOpcode() &&
2244 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2245 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
2247 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2249 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
2250 Op1I->getOperand(1));
2254 Value *A, *B, *C, *D;
2255 // (A & B)^(A | B) -> A ^ B
2256 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2257 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2258 if ((A == C && B == D) || (A == D && B == C))
2259 return BinaryOperator::CreateXor(A, B);
2261 // (A | B)^(A & B) -> A ^ B
2262 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2263 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2264 if ((A == C && B == D) || (A == D && B == C))
2265 return BinaryOperator::CreateXor(A, B);
2269 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
2270 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2271 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2272 // (X & Y)^(X & Y) -> (Y^Z) & X
2273 Value *X = 0, *Y = 0, *Z = 0;
2275 X = A, Y = B, Z = D;
2277 X = A, Y = B, Z = C;
2279 X = B, Y = A, Z = D;
2281 X = B, Y = A, Z = C;
2284 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
2285 return BinaryOperator::CreateAnd(NewOp, X);
2290 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2291 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2292 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2293 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2294 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2295 LHS->getOperand(1) == RHS->getOperand(0))
2296 LHS->swapOperands();
2297 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2298 LHS->getOperand(1) == RHS->getOperand(1)) {
2299 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2300 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2301 bool isSigned = LHS->isSigned() || RHS->isSigned();
2302 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
2303 if (Instruction *I = dyn_cast<Instruction>(RV))
2305 // Otherwise, it's a constant boolean value.
2306 return ReplaceInstUsesWith(I, RV);
2310 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2311 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2312 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2313 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2314 const Type *SrcTy = Op0C->getOperand(0)->getType();
2315 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
2316 // Only do this if the casts both really cause code to be generated.
2317 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
2319 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
2321 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2322 Op1C->getOperand(0), I.getName());
2323 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2328 return Changed ? &I : 0;
2334 /// FindElementAtOffset - Given a type and a constant offset, determine whether
2335 /// or not there is a sequence of GEP indices into the type that will land us at
2336 /// the specified offset. If so, fill them into NewIndices and return the
2337 /// resultant element type, otherwise return null.
2338 const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
2339 SmallVectorImpl<Value*> &NewIndices) {
2341 if (!Ty->isSized()) return 0;
2343 // Start with the index over the outer type. Note that the type size
2344 // might be zero (even if the offset isn't zero) if the indexed type
2345 // is something like [0 x {int, int}]
2346 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
2347 int64_t FirstIdx = 0;
2348 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
2349 FirstIdx = Offset/TySize;
2350 Offset -= FirstIdx*TySize;
2352 // Handle hosts where % returns negative instead of values [0..TySize).
2356 assert(Offset >= 0);
2358 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
2361 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
2363 // Index into the types. If we fail, set OrigBase to null.
2365 // Indexing into tail padding between struct/array elements.
2366 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
2369 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
2370 const StructLayout *SL = TD->getStructLayout(STy);
2371 assert(Offset < (int64_t)SL->getSizeInBytes() &&
2372 "Offset must stay within the indexed type");
2374 unsigned Elt = SL->getElementContainingOffset(Offset);
2375 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
2378 Offset -= SL->getElementOffset(Elt);
2379 Ty = STy->getElementType(Elt);
2380 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
2381 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
2382 assert(EltSize && "Cannot index into a zero-sized array");
2383 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
2385 Ty = AT->getElementType();
2387 // Otherwise, we can't index into the middle of this atomic type, bail.
2397 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2398 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
2400 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
2401 return ReplaceInstUsesWith(GEP, V);
2403 Value *PtrOp = GEP.getOperand(0);
2405 if (isa<UndefValue>(GEP.getOperand(0)))
2406 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
2408 // Eliminate unneeded casts for indices.
2410 bool MadeChange = false;
2411 unsigned PtrSize = TD->getPointerSizeInBits();
2413 gep_type_iterator GTI = gep_type_begin(GEP);
2414 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
2415 I != E; ++I, ++GTI) {
2416 if (!isa<SequentialType>(*GTI)) continue;
2418 // If we are using a wider index than needed for this platform, shrink it
2419 // to what we need. If narrower, sign-extend it to what we need. This
2420 // explicit cast can make subsequent optimizations more obvious.
2421 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
2422 if (OpBits == PtrSize)
2425 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
2428 if (MadeChange) return &GEP;
2431 // Combine Indices - If the source pointer to this getelementptr instruction
2432 // is a getelementptr instruction, combine the indices of the two
2433 // getelementptr instructions into a single instruction.
2435 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
2436 // Note that if our source is a gep chain itself that we wait for that
2437 // chain to be resolved before we perform this transformation. This
2438 // avoids us creating a TON of code in some cases.
2440 if (GetElementPtrInst *SrcGEP =
2441 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
2442 if (SrcGEP->getNumOperands() == 2)
2443 return 0; // Wait until our source is folded to completion.
2445 SmallVector<Value*, 8> Indices;
2447 // Find out whether the last index in the source GEP is a sequential idx.
2448 bool EndsWithSequential = false;
2449 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
2451 EndsWithSequential = !isa<StructType>(*I);
2453 // Can we combine the two pointer arithmetics offsets?
2454 if (EndsWithSequential) {
2455 // Replace: gep (gep %P, long B), long A, ...
2456 // With: T = long A+B; gep %P, T, ...
2459 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
2460 Value *GO1 = GEP.getOperand(1);
2461 if (SO1 == Constant::getNullValue(SO1->getType())) {
2463 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
2466 // If they aren't the same type, then the input hasn't been processed
2467 // by the loop above yet (which canonicalizes sequential index types to
2468 // intptr_t). Just avoid transforming this until the input has been
2470 if (SO1->getType() != GO1->getType())
2472 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
2475 // Update the GEP in place if possible.
2476 if (Src->getNumOperands() == 2) {
2477 GEP.setOperand(0, Src->getOperand(0));
2478 GEP.setOperand(1, Sum);
2481 Indices.append(Src->op_begin()+1, Src->op_end()-1);
2482 Indices.push_back(Sum);
2483 Indices.append(GEP.op_begin()+2, GEP.op_end());
2484 } else if (isa<Constant>(*GEP.idx_begin()) &&
2485 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
2486 Src->getNumOperands() != 1) {
2487 // Otherwise we can do the fold if the first index of the GEP is a zero
2488 Indices.append(Src->op_begin()+1, Src->op_end());
2489 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
2492 if (!Indices.empty())
2493 return (GEP.isInBounds() && Src->isInBounds()) ?
2494 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
2495 Indices.end(), GEP.getName()) :
2496 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
2497 Indices.end(), GEP.getName());
2500 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
2501 Value *StrippedPtr = PtrOp->stripPointerCasts();
2502 if (StrippedPtr != PtrOp) {
2503 const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
2505 bool HasZeroPointerIndex = false;
2506 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
2507 HasZeroPointerIndex = C->isZero();
2509 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
2510 // into : GEP [10 x i8]* X, i32 0, ...
2512 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
2513 // into : GEP i8* X, ...
2515 // This occurs when the program declares an array extern like "int X[];"
2516 if (HasZeroPointerIndex) {
2517 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
2518 if (const ArrayType *CATy =
2519 dyn_cast<ArrayType>(CPTy->getElementType())) {
2520 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
2521 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
2522 // -> GEP i8* X, ...
2523 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
2524 GetElementPtrInst *Res =
2525 GetElementPtrInst::Create(StrippedPtr, Idx.begin(),
2526 Idx.end(), GEP.getName());
2527 Res->setIsInBounds(GEP.isInBounds());
2531 if (const ArrayType *XATy =
2532 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
2533 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
2534 if (CATy->getElementType() == XATy->getElementType()) {
2535 // -> GEP [10 x i8]* X, i32 0, ...
2536 // At this point, we know that the cast source type is a pointer
2537 // to an array of the same type as the destination pointer
2538 // array. Because the array type is never stepped over (there
2539 // is a leading zero) we can fold the cast into this GEP.
2540 GEP.setOperand(0, StrippedPtr);
2545 } else if (GEP.getNumOperands() == 2) {
2546 // Transform things like:
2547 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
2548 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
2549 const Type *SrcElTy = StrippedPtrTy->getElementType();
2550 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
2551 if (TD && isa<ArrayType>(SrcElTy) &&
2552 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
2553 TD->getTypeAllocSize(ResElTy)) {
2555 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
2556 Idx[1] = GEP.getOperand(1);
2557 Value *NewGEP = GEP.isInBounds() ?
2558 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) :
2559 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
2560 // V and GEP are both pointer types --> BitCast
2561 return new BitCastInst(NewGEP, GEP.getType());
2564 // Transform things like:
2565 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
2566 // (where tmp = 8*tmp2) into:
2567 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
2569 if (TD && isa<ArrayType>(SrcElTy) &&
2570 ResElTy == Type::getInt8Ty(GEP.getContext())) {
2571 uint64_t ArrayEltSize =
2572 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
2574 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
2575 // allow either a mul, shift, or constant here.
2577 ConstantInt *Scale = 0;
2578 if (ArrayEltSize == 1) {
2579 NewIdx = GEP.getOperand(1);
2580 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
2581 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
2582 NewIdx = ConstantInt::get(CI->getType(), 1);
2584 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
2585 if (Inst->getOpcode() == Instruction::Shl &&
2586 isa<ConstantInt>(Inst->getOperand(1))) {
2587 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
2588 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
2589 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
2591 NewIdx = Inst->getOperand(0);
2592 } else if (Inst->getOpcode() == Instruction::Mul &&
2593 isa<ConstantInt>(Inst->getOperand(1))) {
2594 Scale = cast<ConstantInt>(Inst->getOperand(1));
2595 NewIdx = Inst->getOperand(0);
2599 // If the index will be to exactly the right offset with the scale taken
2600 // out, perform the transformation. Note, we don't know whether Scale is
2601 // signed or not. We'll use unsigned version of division/modulo
2602 // operation after making sure Scale doesn't have the sign bit set.
2603 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
2604 Scale->getZExtValue() % ArrayEltSize == 0) {
2605 Scale = ConstantInt::get(Scale->getType(),
2606 Scale->getZExtValue() / ArrayEltSize);
2607 if (Scale->getZExtValue() != 1) {
2608 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
2610 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
2613 // Insert the new GEP instruction.
2615 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
2617 Value *NewGEP = GEP.isInBounds() ?
2618 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()):
2619 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
2620 // The NewGEP must be pointer typed, so must the old one -> BitCast
2621 return new BitCastInst(NewGEP, GEP.getType());
2627 /// See if we can simplify:
2628 /// X = bitcast A* to B*
2629 /// Y = gep X, <...constant indices...>
2630 /// into a gep of the original struct. This is important for SROA and alias
2631 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
2632 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
2634 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
2635 // Determine how much the GEP moves the pointer. We are guaranteed to get
2636 // a constant back from EmitGEPOffset.
2637 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
2638 int64_t Offset = OffsetV->getSExtValue();
2640 // If this GEP instruction doesn't move the pointer, just replace the GEP
2641 // with a bitcast of the real input to the dest type.
2643 // If the bitcast is of an allocation, and the allocation will be
2644 // converted to match the type of the cast, don't touch this.
2645 if (isa<AllocaInst>(BCI->getOperand(0)) ||
2646 isMalloc(BCI->getOperand(0))) {
2647 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
2648 if (Instruction *I = visitBitCast(*BCI)) {
2651 BCI->getParent()->getInstList().insert(BCI, I);
2652 ReplaceInstUsesWith(*BCI, I);
2657 return new BitCastInst(BCI->getOperand(0), GEP.getType());
2660 // Otherwise, if the offset is non-zero, we need to find out if there is a
2661 // field at Offset in 'A's type. If so, we can pull the cast through the
2663 SmallVector<Value*, 8> NewIndices;
2665 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
2666 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
2667 Value *NGEP = GEP.isInBounds() ?
2668 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
2670 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
2673 if (NGEP->getType() == GEP.getType())
2674 return ReplaceInstUsesWith(GEP, NGEP);
2675 NGEP->takeName(&GEP);
2676 return new BitCastInst(NGEP, GEP.getType());
2684 Instruction *InstCombiner::visitFree(Instruction &FI) {
2685 Value *Op = FI.getOperand(1);
2687 // free undef -> unreachable.
2688 if (isa<UndefValue>(Op)) {
2689 // Insert a new store to null because we cannot modify the CFG here.
2690 new StoreInst(ConstantInt::getTrue(FI.getContext()),
2691 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
2692 return EraseInstFromFunction(FI);
2695 // If we have 'free null' delete the instruction. This can happen in stl code
2696 // when lots of inlining happens.
2697 if (isa<ConstantPointerNull>(Op))
2698 return EraseInstFromFunction(FI);
2700 // If we have a malloc call whose only use is a free call, delete both.
2702 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
2703 if (Op->hasOneUse() && CI->hasOneUse()) {
2704 EraseInstFromFunction(FI);
2705 EraseInstFromFunction(*CI);
2706 return EraseInstFromFunction(*cast<Instruction>(Op));
2709 // Op is a call to malloc
2710 if (Op->hasOneUse()) {
2711 EraseInstFromFunction(FI);
2712 return EraseInstFromFunction(*cast<Instruction>(Op));
2722 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2723 // Change br (not X), label True, label False to: br X, label False, True
2725 BasicBlock *TrueDest;
2726 BasicBlock *FalseDest;
2727 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2728 !isa<Constant>(X)) {
2729 // Swap Destinations and condition...
2731 BI.setSuccessor(0, FalseDest);
2732 BI.setSuccessor(1, TrueDest);
2736 // Cannonicalize fcmp_one -> fcmp_oeq
2737 FCmpInst::Predicate FPred; Value *Y;
2738 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2739 TrueDest, FalseDest)) &&
2740 BI.getCondition()->hasOneUse())
2741 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2742 FPred == FCmpInst::FCMP_OGE) {
2743 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2744 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2746 // Swap Destinations and condition.
2747 BI.setSuccessor(0, FalseDest);
2748 BI.setSuccessor(1, TrueDest);
2753 // Cannonicalize icmp_ne -> icmp_eq
2754 ICmpInst::Predicate IPred;
2755 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2756 TrueDest, FalseDest)) &&
2757 BI.getCondition()->hasOneUse())
2758 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2759 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2760 IPred == ICmpInst::ICMP_SGE) {
2761 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2762 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2763 // Swap Destinations and condition.
2764 BI.setSuccessor(0, FalseDest);
2765 BI.setSuccessor(1, TrueDest);
2773 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2774 Value *Cond = SI.getCondition();
2775 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2776 if (I->getOpcode() == Instruction::Add)
2777 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2778 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
2779 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
2781 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
2783 SI.setOperand(0, I->getOperand(0));
2791 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2792 Value *Agg = EV.getAggregateOperand();
2794 if (!EV.hasIndices())
2795 return ReplaceInstUsesWith(EV, Agg);
2797 if (Constant *C = dyn_cast<Constant>(Agg)) {
2798 if (isa<UndefValue>(C))
2799 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
2801 if (isa<ConstantAggregateZero>(C))
2802 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
2804 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
2805 // Extract the element indexed by the first index out of the constant
2806 Value *V = C->getOperand(*EV.idx_begin());
2807 if (EV.getNumIndices() > 1)
2808 // Extract the remaining indices out of the constant indexed by the
2810 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
2812 return ReplaceInstUsesWith(EV, V);
2814 return 0; // Can't handle other constants
2816 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2817 // We're extracting from an insertvalue instruction, compare the indices
2818 const unsigned *exti, *exte, *insi, *inse;
2819 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2820 exte = EV.idx_end(), inse = IV->idx_end();
2821 exti != exte && insi != inse;
2824 // The insert and extract both reference distinctly different elements.
2825 // This means the extract is not influenced by the insert, and we can
2826 // replace the aggregate operand of the extract with the aggregate
2827 // operand of the insert. i.e., replace
2828 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2829 // %E = extractvalue { i32, { i32 } } %I, 0
2831 // %E = extractvalue { i32, { i32 } } %A, 0
2832 return ExtractValueInst::Create(IV->getAggregateOperand(),
2833 EV.idx_begin(), EV.idx_end());
2835 if (exti == exte && insi == inse)
2836 // Both iterators are at the end: Index lists are identical. Replace
2837 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2838 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2840 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2842 // The extract list is a prefix of the insert list. i.e. replace
2843 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2844 // %E = extractvalue { i32, { i32 } } %I, 1
2846 // %X = extractvalue { i32, { i32 } } %A, 1
2847 // %E = insertvalue { i32 } %X, i32 42, 0
2848 // by switching the order of the insert and extract (though the
2849 // insertvalue should be left in, since it may have other uses).
2850 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2851 EV.idx_begin(), EV.idx_end());
2852 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2856 // The insert list is a prefix of the extract list
2857 // We can simply remove the common indices from the extract and make it
2858 // operate on the inserted value instead of the insertvalue result.
2860 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2861 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2863 // %E extractvalue { i32 } { i32 42 }, 0
2864 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2867 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2868 // We're extracting from an intrinsic, see if we're the only user, which
2869 // allows us to simplify multiple result intrinsics to simpler things that
2870 // just get one value..
2871 if (II->hasOneUse()) {
2872 // Check if we're grabbing the overflow bit or the result of a 'with
2873 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2874 // and replace it with a traditional binary instruction.
2875 switch (II->getIntrinsicID()) {
2876 case Intrinsic::uadd_with_overflow:
2877 case Intrinsic::sadd_with_overflow:
2878 if (*EV.idx_begin() == 0) { // Normal result.
2879 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
2880 II->replaceAllUsesWith(UndefValue::get(II->getType()));
2881 EraseInstFromFunction(*II);
2882 return BinaryOperator::CreateAdd(LHS, RHS);
2885 case Intrinsic::usub_with_overflow:
2886 case Intrinsic::ssub_with_overflow:
2887 if (*EV.idx_begin() == 0) { // Normal result.
2888 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
2889 II->replaceAllUsesWith(UndefValue::get(II->getType()));
2890 EraseInstFromFunction(*II);
2891 return BinaryOperator::CreateSub(LHS, RHS);
2894 case Intrinsic::umul_with_overflow:
2895 case Intrinsic::smul_with_overflow:
2896 if (*EV.idx_begin() == 0) { // Normal result.
2897 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
2898 II->replaceAllUsesWith(UndefValue::get(II->getType()));
2899 EraseInstFromFunction(*II);
2900 return BinaryOperator::CreateMul(LHS, RHS);
2908 // Can't simplify extracts from other values. Note that nested extracts are
2909 // already simplified implicitely by the above (extract ( extract (insert) )
2910 // will be translated into extract ( insert ( extract ) ) first and then just
2911 // the value inserted, if appropriate).
2918 /// TryToSinkInstruction - Try to move the specified instruction from its
2919 /// current block into the beginning of DestBlock, which can only happen if it's
2920 /// safe to move the instruction past all of the instructions between it and the
2921 /// end of its block.
2922 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2923 assert(I->hasOneUse() && "Invariants didn't hold!");
2925 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2926 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
2929 // Do not sink alloca instructions out of the entry block.
2930 if (isa<AllocaInst>(I) && I->getParent() ==
2931 &DestBlock->getParent()->getEntryBlock())
2934 // We can only sink load instructions if there is nothing between the load and
2935 // the end of block that could change the value.
2936 if (I->mayReadFromMemory()) {
2937 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
2939 if (Scan->mayWriteToMemory())
2943 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
2945 I->moveBefore(InsertPos);
2951 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2952 /// all reachable code to the worklist.
2954 /// This has a couple of tricks to make the code faster and more powerful. In
2955 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2956 /// them to the worklist (this significantly speeds up instcombine on code where
2957 /// many instructions are dead or constant). Additionally, if we find a branch
2958 /// whose condition is a known constant, we only visit the reachable successors.
2960 static bool AddReachableCodeToWorklist(BasicBlock *BB,
2961 SmallPtrSet<BasicBlock*, 64> &Visited,
2963 const TargetData *TD) {
2964 bool MadeIRChange = false;
2965 SmallVector<BasicBlock*, 256> Worklist;
2966 Worklist.push_back(BB);
2968 std::vector<Instruction*> InstrsForInstCombineWorklist;
2969 InstrsForInstCombineWorklist.reserve(128);
2971 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
2973 while (!Worklist.empty()) {
2974 BB = Worklist.back();
2975 Worklist.pop_back();
2977 // We have now visited this block! If we've already been here, ignore it.
2978 if (!Visited.insert(BB)) continue;
2980 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2981 Instruction *Inst = BBI++;
2983 // DCE instruction if trivially dead.
2984 if (isInstructionTriviallyDead(Inst)) {
2986 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
2987 Inst->eraseFromParent();
2991 // ConstantProp instruction if trivially constant.
2992 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
2993 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
2994 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
2996 Inst->replaceAllUsesWith(C);
2998 Inst->eraseFromParent();
3005 // See if we can constant fold its operands.
3006 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
3008 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
3009 if (CE == 0) continue;
3011 // If we already folded this constant, don't try again.
3012 if (!FoldedConstants.insert(CE))
3015 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
3016 if (NewC && NewC != CE) {
3018 MadeIRChange = true;
3024 InstrsForInstCombineWorklist.push_back(Inst);
3027 // Recursively visit successors. If this is a branch or switch on a
3028 // constant, only visit the reachable successor.
3029 TerminatorInst *TI = BB->getTerminator();
3030 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3031 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3032 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3033 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3034 Worklist.push_back(ReachableBB);
3037 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3038 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3039 // See if this is an explicit destination.
3040 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
3041 if (SI->getCaseValue(i) == Cond) {
3042 BasicBlock *ReachableBB = SI->getSuccessor(i);
3043 Worklist.push_back(ReachableBB);
3047 // Otherwise it is the default destination.
3048 Worklist.push_back(SI->getSuccessor(0));
3053 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
3054 Worklist.push_back(TI->getSuccessor(i));
3057 // Once we've found all of the instructions to add to instcombine's worklist,
3058 // add them in reverse order. This way instcombine will visit from the top
3059 // of the function down. This jives well with the way that it adds all uses
3060 // of instructions to the worklist after doing a transformation, thus avoiding
3061 // some N^2 behavior in pathological cases.
3062 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
3063 InstrsForInstCombineWorklist.size());
3065 return MadeIRChange;
3068 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
3069 MadeIRChange = false;
3071 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3072 << F.getNameStr() << "\n");
3075 // Do a depth-first traversal of the function, populate the worklist with
3076 // the reachable instructions. Ignore blocks that are not reachable. Keep
3077 // track of which blocks we visit.
3078 SmallPtrSet<BasicBlock*, 64> Visited;
3079 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
3081 // Do a quick scan over the function. If we find any blocks that are
3082 // unreachable, remove any instructions inside of them. This prevents
3083 // the instcombine code from having to deal with some bad special cases.
3084 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3085 if (!Visited.count(BB)) {
3086 Instruction *Term = BB->getTerminator();
3087 while (Term != BB->begin()) { // Remove instrs bottom-up
3088 BasicBlock::iterator I = Term; --I;
3090 DEBUG(errs() << "IC: DCE: " << *I << '\n');
3091 // A debug intrinsic shouldn't force another iteration if we weren't
3092 // going to do one without it.
3093 if (!isa<DbgInfoIntrinsic>(I)) {
3095 MadeIRChange = true;
3098 // If I is not void type then replaceAllUsesWith undef.
3099 // This allows ValueHandlers and custom metadata to adjust itself.
3100 if (!I->getType()->isVoidTy())
3101 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3102 I->eraseFromParent();
3107 while (!Worklist.isEmpty()) {
3108 Instruction *I = Worklist.RemoveOne();
3109 if (I == 0) continue; // skip null values.
3111 // Check to see if we can DCE the instruction.
3112 if (isInstructionTriviallyDead(I)) {
3113 DEBUG(errs() << "IC: DCE: " << *I << '\n');
3114 EraseInstFromFunction(*I);
3116 MadeIRChange = true;
3120 // Instruction isn't dead, see if we can constant propagate it.
3121 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
3122 if (Constant *C = ConstantFoldInstruction(I, TD)) {
3123 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
3125 // Add operands to the worklist.
3126 ReplaceInstUsesWith(*I, C);
3128 EraseInstFromFunction(*I);
3129 MadeIRChange = true;
3133 // See if we can trivially sink this instruction to a successor basic block.
3134 if (I->hasOneUse()) {
3135 BasicBlock *BB = I->getParent();
3136 Instruction *UserInst = cast<Instruction>(I->use_back());
3137 BasicBlock *UserParent;
3139 // Get the block the use occurs in.
3140 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
3141 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
3143 UserParent = UserInst->getParent();
3145 if (UserParent != BB) {
3146 bool UserIsSuccessor = false;
3147 // See if the user is one of our successors.
3148 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
3149 if (*SI == UserParent) {
3150 UserIsSuccessor = true;
3154 // If the user is one of our immediate successors, and if that successor
3155 // only has us as a predecessors (we'd have to split the critical edge
3156 // otherwise), we can keep going.
3157 if (UserIsSuccessor && UserParent->getSinglePredecessor())
3158 // Okay, the CFG is simple enough, try to sink this instruction.
3159 MadeIRChange |= TryToSinkInstruction(I, UserParent);
3163 // Now that we have an instruction, try combining it to simplify it.
3164 Builder->SetInsertPoint(I->getParent(), I);
3169 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
3170 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
3172 if (Instruction *Result = visit(*I)) {
3174 // Should we replace the old instruction with a new one?
3176 DEBUG(errs() << "IC: Old = " << *I << '\n'
3177 << " New = " << *Result << '\n');
3179 // Everything uses the new instruction now.
3180 I->replaceAllUsesWith(Result);
3182 // Push the new instruction and any users onto the worklist.
3183 Worklist.Add(Result);
3184 Worklist.AddUsersToWorkList(*Result);
3186 // Move the name to the new instruction first.
3187 Result->takeName(I);
3189 // Insert the new instruction into the basic block...
3190 BasicBlock *InstParent = I->getParent();
3191 BasicBlock::iterator InsertPos = I;
3193 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
3194 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
3197 InstParent->getInstList().insert(InsertPos, Result);
3199 EraseInstFromFunction(*I);
3202 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
3203 << " New = " << *I << '\n');
3206 // If the instruction was modified, it's possible that it is now dead.
3207 // if so, remove it.
3208 if (isInstructionTriviallyDead(I)) {
3209 EraseInstFromFunction(*I);
3212 Worklist.AddUsersToWorkList(*I);
3215 MadeIRChange = true;
3220 return MadeIRChange;
3224 bool InstCombiner::runOnFunction(Function &F) {
3225 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
3226 TD = getAnalysisIfAvailable<TargetData>();
3229 /// Builder - This is an IRBuilder that automatically inserts new
3230 /// instructions into the worklist when they are created.
3231 IRBuilder<true, TargetFolder, InstCombineIRInserter>
3232 TheBuilder(F.getContext(), TargetFolder(TD),
3233 InstCombineIRInserter(Worklist));
3234 Builder = &TheBuilder;
3236 bool EverMadeChange = false;
3238 // Iterate while there is work to do.
3239 unsigned Iteration = 0;
3240 while (DoOneIteration(F, Iteration++))
3241 EverMadeChange = true;
3244 return EverMadeChange;
3247 FunctionPass *llvm::createInstructionCombiningPass() {
3248 return new InstCombiner();