blob: 13df38a27b487a31a5bbe4e8df433473f58602e4 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 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.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000038#include "InstCombine.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000039#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000040#include "llvm/LLVMContext.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000054#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000055#include "llvm/Support/PatternMatch.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000060#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000061using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000062using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000063
Chris Lattner0e5f4992006-12-19 21:40:18 +000064STATISTIC(NumCombined , "Number of insts combined");
65STATISTIC(NumConstProp, "Number of constant folds");
66STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner0e5f4992006-12-19 21:40:18 +000067STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000068
Chris Lattnerdd841ae2002-04-18 17:39:14 +000069
Dan Gohman844731a2008-05-13 00:00:25 +000070char InstCombiner::ID = 0;
71static RegisterPass<InstCombiner>
72X("instcombine", "Combine redundant instructions");
73
Chris Lattnere0b4b722010-01-04 07:17:19 +000074void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addPreservedID(LCSSAID);
76 AU.setPreservesCFG();
77}
78
79
Chris Lattnerc8802d22003-03-11 00:12:48 +000080// isOnlyUse - Return true if this instruction will be deleted if we stop using
81// it.
82static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +000083 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +000084}
85
Chris Lattner4cb170c2004-02-23 06:38:22 +000086// getPromotedType - Return the specified type promoted as it would be to pass
87// though a va_arg area...
88static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +000089 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
90 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +000091 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +000092 }
Reid Spencera54b7cb2007-01-12 07:05:14 +000093 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +000094}
95
Chris Lattnerc22d4d12009-11-10 07:23:37 +000096/// ShouldChangeType - Return true if it is desirable to convert a computation
97/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
98/// type for example, or from a smaller to a larger illegal type.
Chris Lattner80f43d32010-01-04 07:53:58 +000099bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000100 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
101
102 // If we don't have TD, we don't know if the source/dest are legal.
103 if (!TD) return false;
104
105 unsigned FromWidth = From->getPrimitiveSizeInBits();
106 unsigned ToWidth = To->getPrimitiveSizeInBits();
107 bool FromLegal = TD->isLegalInteger(FromWidth);
108 bool ToLegal = TD->isLegalInteger(ToWidth);
109
110 // If this is a legal integer from type, and the result would be an illegal
111 // type, don't do the transformation.
112 if (FromLegal && !ToLegal)
113 return false;
114
115 // Otherwise, if both are illegal, do not increase the size of the result. We
116 // do allow things like i160 -> i64, but not i64 -> i160.
117 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
118 return false;
119
120 return true;
121}
122
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000123/// getBitCastOperand - If the specified operand is a CastInst, a constant
124/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
125/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000126static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000127 if (Operator *O = dyn_cast<Operator>(V)) {
128 if (O->getOpcode() == Instruction::BitCast)
129 return O->getOperand(0);
130 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
131 if (GEP->hasAllZeroIndices())
132 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000133 }
Chris Lattnereed48272005-09-13 00:40:14 +0000134 return 0;
135}
136
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000137
Chris Lattner33a61132006-05-06 09:00:16 +0000138
Chris Lattner4f98c562003-03-10 21:43:22 +0000139// SimplifyCommutative - This performs a few simplifications for commutative
140// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000141//
Chris Lattner4f98c562003-03-10 21:43:22 +0000142// 1. Order operands such that they are listed from right (least complex) to
143// left (most complex). This puts constants before unary operators before
144// binary operators.
145//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000146// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
147// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000148//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000149bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000150 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000151 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000152 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000153
Chris Lattner4f98c562003-03-10 21:43:22 +0000154 if (!I.isAssociative()) return Changed;
155 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000156 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
157 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
158 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000159 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000160 cast<Constant>(I.getOperand(1)),
161 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000162 I.setOperand(0, Op->getOperand(0));
163 I.setOperand(1, Folded);
164 return true;
165 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
166 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
167 isOnlyUse(Op) && isOnlyUse(Op1)) {
168 Constant *C1 = cast<Constant>(Op->getOperand(1));
169 Constant *C2 = cast<Constant>(Op1->getOperand(1));
170
171 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000172 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000173 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000174 Op1->getOperand(0),
175 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000176 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000177 I.setOperand(0, New);
178 I.setOperand(1, Folded);
179 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000180 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000181 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000182 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000183}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000184
Chris Lattner8d969642003-03-10 23:06:50 +0000185// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
186// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000187//
Chris Lattner02446fc2010-01-04 07:37:31 +0000188Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000189 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000190 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000191
Chris Lattner0ce85802004-12-14 20:08:06 +0000192 // Constants can be considered to be negated values if they can be folded.
193 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000194 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000195
196 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
197 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000198 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000199
Chris Lattner8d969642003-03-10 23:06:50 +0000200 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000201}
202
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000203// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
204// instruction if the LHS is a constant negative zero (which is the 'negate'
205// form).
206//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000207Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000208 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000209 return BinaryOperator::getFNegArgument(V);
210
211 // Constants can be considered to be negated values if they can be folded.
212 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000213 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000214
215 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
216 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000217 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000218
219 return 0;
220}
221
Chris Lattner48b59ec2009-10-26 15:40:07 +0000222/// isFreeToInvert - Return true if the specified value is free to invert (apply
223/// ~ to). This happens in cases where the ~ can be eliminated.
224static inline bool isFreeToInvert(Value *V) {
225 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000226 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000227 return true;
228
229 // Constants can be considered to be not'ed values.
230 if (isa<ConstantInt>(V))
231 return true;
232
233 // Compares can be inverted if they have a single use.
234 if (CmpInst *CI = dyn_cast<CmpInst>(V))
235 return CI->hasOneUse();
236
237 return false;
238}
239
240static inline Value *dyn_castNotVal(Value *V) {
241 // If this is not(not(x)) don't return that this is a not: we want the two
242 // not's to be folded first.
243 if (BinaryOperator::isNot(V)) {
244 Value *Operand = BinaryOperator::getNotArgument(V);
245 if (!isFreeToInvert(Operand))
246 return Operand;
247 }
Chris Lattner8d969642003-03-10 23:06:50 +0000248
249 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000250 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000251 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000252 return 0;
253}
254
Chris Lattner48b59ec2009-10-26 15:40:07 +0000255
256
Chris Lattnerc8802d22003-03-11 00:12:48 +0000257// dyn_castFoldableMul - If this value is a multiply that can be folded into
258// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000259// non-constant operand of the multiply, and set CST to point to the multiplier.
260// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000261//
Dan Gohman186a6362009-08-12 16:04:34 +0000262static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000263 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000264 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000265 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000266 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000267 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000268 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000269 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000270 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000271 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000272 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000273 CST = ConstantInt::get(V->getType()->getContext(),
274 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000275 return I->getOperand(0);
276 }
277 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000278 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000279}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000280
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000281/// AddOne - Add one to a ConstantInt.
Dan Gohman186a6362009-08-12 16:04:34 +0000282static Constant *AddOne(Constant *C) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000283 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000284}
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000285/// SubOne - Subtract one from a ConstantInt.
Dan Gohman186a6362009-08-12 16:04:34 +0000286static Constant *SubOne(ConstantInt *C) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000287 return ConstantInt::get(C->getContext(), C->getValue()-1);
Chris Lattner955f3312004-09-28 21:48:02 +0000288}
Reid Spencere7816b52007-03-08 01:52:58 +0000289
Dan Gohman45b4e482008-05-19 22:14:15 +0000290
Chris Lattner564a7272003-08-13 19:01:45 +0000291/// AssociativeOpt - Perform an optimization on an associative operator. This
292/// function is designed to check a chain of associative operators for a
293/// potential to apply a certain optimization. Since the optimization may be
294/// applicable if the expression was reassociated, this checks the chain, then
295/// reassociates the expression as necessary to expose the optimization
296/// opportunity. This makes use of a special Functor, which must define
297/// 'shouldApply' and 'apply' methods.
298///
299template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +0000300static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +0000301 unsigned Opcode = Root.getOpcode();
302 Value *LHS = Root.getOperand(0);
303
304 // Quick check, see if the immediate LHS matches...
305 if (F.shouldApply(LHS))
306 return F.apply(Root);
307
308 // Otherwise, if the LHS is not of the same opcode as the root, return.
309 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000310 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000311 // Should we apply this transform to the RHS?
312 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
313
314 // If not to the RHS, check to see if we should apply to the LHS...
315 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
316 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
317 ShouldApply = true;
318 }
319
320 // If the functor wants to apply the optimization to the RHS of LHSI,
321 // reassociate the expression from ((? op A) op B) to (? op (A op B))
322 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +0000323 // Now all of the instructions are in the current basic block, go ahead
324 // and perform the reassociation.
325 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
326
327 // First move the selected RHS to the LHS of the root...
328 Root.setOperand(0, LHSI->getOperand(1));
329
330 // Make what used to be the LHS of the root be the user of the root...
331 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000332 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000333 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000334 return 0;
335 }
Chris Lattner65725312004-04-16 18:08:07 +0000336 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000337 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000338 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +0000339 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +0000340 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000341
342 // Now propagate the ExtraOperand down the chain of instructions until we
343 // get to LHSI.
344 while (TmpLHSI != LHSI) {
345 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000346 // Move the instruction to immediately before the chain we are
347 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +0000348 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +0000349 ARI = NextLHSI;
350
Chris Lattner564a7272003-08-13 19:01:45 +0000351 Value *NextOp = NextLHSI->getOperand(1);
352 NextLHSI->setOperand(1, ExtraOperand);
353 TmpLHSI = NextLHSI;
354 ExtraOperand = NextOp;
355 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000356
Chris Lattner564a7272003-08-13 19:01:45 +0000357 // Now that the instructions are reassociated, have the functor perform
358 // the transformation...
359 return F.apply(Root);
360 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000361
Chris Lattner564a7272003-08-13 19:01:45 +0000362 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
363 }
364 return 0;
365}
366
Dan Gohman844731a2008-05-13 00:00:25 +0000367namespace {
Chris Lattner564a7272003-08-13 19:01:45 +0000368
Nick Lewycky02d639f2008-05-23 04:34:58 +0000369// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +0000370struct AddRHS {
371 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +0000372 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +0000373 bool shouldApply(Value *LHS) const { return LHS == RHS; }
374 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +0000375 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +0000376 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +0000377 }
378};
379
380// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
381// iff C1&C2 == 0
382struct AddMaskingAnd {
383 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +0000384 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +0000385 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000386 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +0000387 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000388 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000389 }
390 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000391 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000392 }
393};
394
Dan Gohman844731a2008-05-13 00:00:25 +0000395}
396
Chris Lattner6e7ba452005-01-01 16:22:27 +0000397static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000398 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000399 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000400 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000401
Chris Lattner2eefe512004-04-09 19:05:30 +0000402 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000403 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
404 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000405
Chris Lattner2eefe512004-04-09 19:05:30 +0000406 if (Constant *SOC = dyn_cast<Constant>(SO)) {
407 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000408 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
409 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000410 }
411
412 Value *Op0 = SO, *Op1 = ConstOperand;
413 if (!ConstIsRHS)
414 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000415
Chris Lattner6e7ba452005-01-01 16:22:27 +0000416 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000417 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
418 SO->getName()+".op");
419 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
420 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
421 SO->getName()+".cmp");
422 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
423 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
424 SO->getName()+".cmp");
425 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000426}
427
428// FoldOpIntoSelect - Given an instruction with a select as one operand and a
429// constant as the other operand, try to fold the binary operator into the
430// select arguments. This also works for Cast instructions, which obviously do
431// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000432Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000433 // Don't modify shared select instructions
434 if (!SI->hasOneUse()) return 0;
435 Value *TV = SI->getOperand(1);
436 Value *FV = SI->getOperand(2);
437
438 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000439 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +0000440 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000441
Chris Lattner80f43d32010-01-04 07:53:58 +0000442 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
443 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000444
Gabor Greif051a9502008-04-06 20:25:17 +0000445 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
446 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000447 }
448 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000449}
450
Chris Lattner4e998b22004-09-29 05:07:12 +0000451
Chris Lattner5d1704d2009-09-27 19:57:57 +0000452/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
453/// has a PHI node as operand #0, see if we can fold the instruction into the
454/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000455///
456/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
457/// that would normally be unprofitable because they strongly encourage jump
458/// threading.
459Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
460 bool AllowAggressive) {
461 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000462 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000463 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000464 if (NumPHIValues == 0 ||
465 // We normally only transform phis with a single use, unless we're trying
466 // hard to make jump threading happen.
467 (!PN->hasOneUse() && !AllowAggressive))
468 return 0;
469
470
Chris Lattner5d1704d2009-09-27 19:57:57 +0000471 // Check to see if all of the operands of the PHI are simple constants
472 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000473 // remember the BB it is in. If there is more than one or if *it* is a PHI,
474 // bail out. We don't do arbitrary constant expressions here because moving
475 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000476 BasicBlock *NonConstBB = 0;
477 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000478 if (!isa<Constant>(PN->getIncomingValue(i)) ||
479 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000480 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000481 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000482 NonConstBB = PN->getIncomingBlock(i);
483
484 // If the incoming non-constant value is in I's block, we have an infinite
485 // loop.
486 if (NonConstBB == I.getParent())
487 return 0;
488 }
489
490 // If there is exactly one non-constant value, we can insert a copy of the
491 // operation in that block. However, if this is a critical edge, we would be
492 // inserting the computation one some other paths (e.g. inside a loop). Only
493 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000494 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000495 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
496 if (!BI || !BI->isUnconditional()) return 0;
497 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000498
499 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000500 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000501 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000502 InsertNewInstBefore(NewPN, *PN);
503 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000504
505 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000506 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
507 // We only currently try to fold the condition of a select when it is a phi,
508 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000509 Value *TrueV = SI->getTrueValue();
510 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000511 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000512 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000513 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000514 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
515 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000516 Value *InV = 0;
517 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000518 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000519 } else {
520 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000521 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
522 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000523 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000524 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000525 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000526 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000527 }
528 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000529 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000530 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000531 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000532 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000533 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000534 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000535 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000536 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000537 } else {
538 assert(PN->getIncomingBlock(i) == NonConstBB);
539 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000540 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000541 PN->getIncomingValue(i), C, "phitmp",
542 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000543 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000544 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000545 CI->getPredicate(),
546 PN->getIncomingValue(i), C, "phitmp",
547 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000548 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000549 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000550
551 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000552 }
553 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000554 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000555 } else {
556 CastInst *CI = cast<CastInst>(&I);
557 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000558 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000559 Value *InV;
560 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000561 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000562 } else {
563 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000564 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000565 I.getType(), "phitmp",
566 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000567 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000568 }
569 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000570 }
571 }
572 return ReplaceInstUsesWith(I, NewPN);
573}
574
Chris Lattner2454a2e2008-01-29 06:52:45 +0000575
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000576/// WillNotOverflowSignedAdd - Return true if we can prove that:
577/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
578/// This basically requires proving that the add in the original type would not
579/// overflow to change the sign bit or have a carry out.
580bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
581 // There are different heuristics we can use for this. Here are some simple
582 // ones.
583
584 // Add has the property that adding any two 2's complement numbers can only
585 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000586 // have at least two sign bits, we know that the addition of the two values
587 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000588 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
589 return true;
590
591
592 // If one of the operands only has one non-zero bit, and if the other operand
593 // has a known-zero bit in a more significant place than it (not including the
594 // sign bit) the ripple may go up to and fill the zero, but won't change the
595 // sign. For example, (X & ~4) + 1.
596
597 // TODO: Implement.
598
599 return false;
600}
601
Chris Lattner2454a2e2008-01-29 06:52:45 +0000602
Chris Lattner7e708292002-06-25 16:13:24 +0000603Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000604 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000605 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000606
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000607 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
608 I.hasNoUnsignedWrap(), TD))
609 return ReplaceInstUsesWith(I, V);
610
611
Chris Lattner66331a42004-04-10 22:01:55 +0000612 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +0000613 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000614 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000615 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +0000616 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +0000617 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000618 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000619
620 // See if SimplifyDemandedBits can simplify this. This handles stuff like
621 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +0000622 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000623 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +0000624
Eli Friedman709b33d2009-07-13 22:27:52 +0000625 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +0000626 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Chris Lattner4de84762010-01-04 07:02:48 +0000627 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +0000628 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +0000629 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000630
631 if (isa<PHINode>(LHS))
632 if (Instruction *NV = FoldOpIntoPhi(I))
633 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +0000634
Chris Lattner4f637d42006-01-06 17:59:59 +0000635 ConstantInt *XorRHS = 0;
636 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +0000637 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000638 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000639 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000640 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +0000641
Zhou Sheng4351c642007-04-02 08:20:41 +0000642 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000643 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
644 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +0000645 do {
646 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +0000647 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
648 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000649 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
650 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +0000651 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +0000652 if (!MaskedValueIsZero(XorLHS,
653 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +0000654 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000655 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000656 }
657 }
658 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000659 C0080Val = APIntOps::lshr(C0080Val, Size);
660 CFF80Val = APIntOps::ashr(CFF80Val, Size);
661 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +0000662
Reid Spencer35c38852007-03-28 01:36:16 +0000663 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000664 // with funny bit widths then this switch statement should be removed. It
665 // is just here to get the size of the "middle" type back up to something
666 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +0000667 const Type *MiddleType = 0;
668 switch (Size) {
669 default: break;
Chris Lattner4de84762010-01-04 07:02:48 +0000670 case 32:
671 case 16:
672 case 8: MiddleType = IntegerType::get(I.getContext(), Size); break;
Reid Spencer35c38852007-03-28 01:36:16 +0000673 }
674 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +0000675 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +0000676 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +0000677 }
678 }
Chris Lattner66331a42004-04-10 22:01:55 +0000679 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000680
Chris Lattner4de84762010-01-04 07:02:48 +0000681 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000682 return BinaryOperator::CreateXor(LHS, RHS);
683
Nick Lewycky7d26bd82008-05-23 04:39:38 +0000684 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000685 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +0000686 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +0000687 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +0000688
689 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
690 if (RHSI->getOpcode() == Instruction::Sub)
691 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
692 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
693 }
694 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
695 if (LHSI->getOpcode() == Instruction::Sub)
696 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
697 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
698 }
Robert Bocchino71698282004-07-27 21:02:21 +0000699 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000700
Chris Lattner5c4afb92002-05-08 22:46:53 +0000701 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +0000702 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000703 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +0000704 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +0000705 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +0000706 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +0000707 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +0000708 }
Chris Lattnerdd12f962008-02-17 21:03:36 +0000709 }
710
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000711 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +0000712 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000713
714 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000715 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000716 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000717 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000718
Misha Brukmanfd939082005-04-21 23:48:37 +0000719
Chris Lattner50af16a2004-11-13 19:50:12 +0000720 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +0000721 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000722 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000723 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000724
725 // X*C1 + X*C2 --> X * (C1+C2)
726 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +0000727 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000728 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000729 }
730
731 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000732 if (dyn_castFoldableMul(RHS, C2) == LHS)
733 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000734
Chris Lattnere617c9e2007-01-05 02:17:46 +0000735 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +0000736 if (dyn_castNotVal(LHS) == RHS ||
737 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +0000738 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +0000739
Chris Lattnerad3448c2003-02-18 19:57:07 +0000740
Chris Lattner564a7272003-08-13 19:01:45 +0000741 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +0000742 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
743 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +0000744 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +0000745
746 // A+B --> A|B iff A and B have no bits set in common.
747 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
748 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
749 APInt LHSKnownOne(IT->getBitWidth(), 0);
750 APInt LHSKnownZero(IT->getBitWidth(), 0);
751 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
752 if (LHSKnownZero != 0) {
753 APInt RHSKnownOne(IT->getBitWidth(), 0);
754 APInt RHSKnownZero(IT->getBitWidth(), 0);
755 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
756
757 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +0000758 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +0000759 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +0000760 }
761 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000762
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000763 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +0000764 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000765 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +0000766 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
767 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000768 if (W != Y) {
769 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000770 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000771 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000772 std::swap(W, X);
773 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000774 std::swap(Y, Z);
775 std::swap(W, X);
776 }
777 }
778
779 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +0000780 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000781 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000782 }
783 }
784 }
785
Chris Lattner6b032052003-10-02 15:11:26 +0000786 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +0000787 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +0000788 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +0000789 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000790
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000791 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +0000792 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000793 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000794 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000795 if (Anded == CRHS) {
796 // See if all bits from the first bit set in the Add RHS up are included
797 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000798 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000799
800 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000801 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000802
803 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000804 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +0000805
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000806 if (AddRHSHighBits == AddRHSHighBitsAnd) {
807 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +0000808 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000809 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000810 }
811 }
812 }
813
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000814 // Try to fold constant add into select arguments.
815 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner80f43d32010-01-04 07:53:58 +0000816 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000817 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000818 }
819
Chris Lattner42790482007-12-20 01:56:58 +0000820 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +0000821 {
822 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000823 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000824 if (!SI) {
825 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000826 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000827 }
Chris Lattner42790482007-12-20 01:56:58 +0000828 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +0000829 Value *TV = SI->getTrueValue();
830 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +0000831 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000832
833 // Can we fold the add into the argument of the select?
834 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +0000835 if (match(FV, m_Zero()) &&
836 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000837 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000838 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +0000839 if (match(TV, m_Zero()) &&
840 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000841 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000842 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +0000843 }
844 }
Andrew Lenharth16d79552006-09-19 18:24:51 +0000845
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000846 // Check for (add (sext x), y), see if we can merge this into an
847 // integer add followed by a sext.
848 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
849 // (add (sext x), cst) --> (sext (add x, cst'))
850 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
851 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000852 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000853 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000854 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000855 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
856 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000857 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
858 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000859 return new SExtInst(NewAdd, I.getType());
860 }
861 }
862
863 // (add (sext x), (sext y)) --> (sext (add int x, y))
864 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
865 // Only do this if x/y have the same type, if at last one of them has a
866 // single use (so we don't increase the number of sexts), and if the
867 // integer add will not overflow.
868 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
869 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
870 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
871 RHSConv->getOperand(0))) {
872 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000873 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
874 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000875 return new SExtInst(NewAdd, I.getType());
876 }
877 }
878 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000879
880 return Changed ? &I : 0;
881}
882
883Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
884 bool Changed = SimplifyCommutative(I);
885 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
886
887 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
888 // X + 0 --> X
889 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000890 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000891 (I.getType())->getValueAPF()))
892 return ReplaceInstUsesWith(I, LHS);
893 }
894
895 if (isa<PHINode>(LHS))
896 if (Instruction *NV = FoldOpIntoPhi(I))
897 return NV;
898 }
899
900 // -A + B --> B - A
901 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000902 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000903 return BinaryOperator::CreateFSub(RHS, LHSV);
904
905 // A + -B --> A - B
906 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000907 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000908 return BinaryOperator::CreateFSub(LHS, V);
909
910 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
911 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
912 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
913 return ReplaceInstUsesWith(I, LHS);
914
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000915 // Check for (add double (sitofp x), y), see if we can merge this into an
916 // integer add followed by a promotion.
917 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
918 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
919 // ... if the constant fits in the integer value. This is useful for things
920 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
921 // requires a constant pool load, and generally allows the add to be better
922 // instcombined.
923 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
924 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000925 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000926 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000927 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000928 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
929 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000930 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
931 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000932 return new SIToFPInst(NewAdd, I.getType());
933 }
934 }
935
936 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
937 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
938 // Only do this if x/y have the same type, if at last one of them has a
939 // single use (so we don't increase the number of int->fp conversions),
940 // and if the integer add will not overflow.
941 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
942 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
943 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
944 RHSConv->getOperand(0))) {
945 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000946 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +0000947 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000948 return new SIToFPInst(NewAdd, I.getType());
949 }
950 }
951 }
952
Chris Lattner7e708292002-06-25 16:13:24 +0000953 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000954}
955
Chris Lattner092543c2009-11-04 08:05:20 +0000956
957/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
958/// code necessary to compute the offset from the base pointer (without adding
959/// in the base pointer). Return the result as a signed integer of intptr size.
Chris Lattner02446fc2010-01-04 07:37:31 +0000960Value *InstCombiner::EmitGEPOffset(User *GEP) {
961 TargetData &TD = *getTargetData();
Chris Lattner092543c2009-11-04 08:05:20 +0000962 gep_type_iterator GTI = gep_type_begin(GEP);
963 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
964 Value *Result = Constant::getNullValue(IntPtrTy);
965
966 // Build a mask for high order bits.
967 unsigned IntPtrWidth = TD.getPointerSizeInBits();
968 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
969
970 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
971 ++i, ++GTI) {
972 Value *Op = *i;
973 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
974 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
975 if (OpC->isZero()) continue;
976
977 // Handle a struct index, which adds its field offset to the pointer.
978 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
979 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
980
Chris Lattner02446fc2010-01-04 07:37:31 +0000981 Result = Builder->CreateAdd(Result,
982 ConstantInt::get(IntPtrTy, Size),
983 GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +0000984 continue;
985 }
986
987 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
988 Constant *OC =
989 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
990 Scale = ConstantExpr::getMul(OC, Scale);
991 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +0000992 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +0000993 continue;
994 }
995 // Convert to correct type.
996 if (Op->getType() != IntPtrTy)
Chris Lattner02446fc2010-01-04 07:37:31 +0000997 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattner092543c2009-11-04 08:05:20 +0000998 if (Size != 1) {
999 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
1000 // We'll let instcombine(mul) convert this to a shl if possible.
Chris Lattner02446fc2010-01-04 07:37:31 +00001001 Op = Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattner092543c2009-11-04 08:05:20 +00001002 }
1003
1004 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +00001005 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +00001006 }
1007 return Result;
1008}
1009
1010
Chris Lattner092543c2009-11-04 08:05:20 +00001011
1012
1013/// Optimize pointer differences into the same array into a size. Consider:
1014/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1015/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1016///
1017Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1018 const Type *Ty) {
1019 assert(TD && "Must have target data info for this");
1020
1021 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1022 // this.
Chris Lattner0cb1e9e2010-01-04 18:48:26 +00001023 bool Swapped = false;
Chris Lattner85c1c962010-01-01 22:42:29 +00001024 GetElementPtrInst *GEP = 0;
1025 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +00001026
Chris Lattner85c1c962010-01-01 22:42:29 +00001027 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
1028 // For now we require one side to be the base pointer "A" or a constant
1029 // expression derived from it.
1030 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
1031 // (gep X, ...) - X
1032 if (LHSGEP->getOperand(0) == RHS) {
1033 GEP = LHSGEP;
1034 Swapped = false;
1035 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
1036 // (gep X, ...) - (ce_gep X, ...)
1037 if (CE->getOpcode() == Instruction::GetElementPtr &&
1038 LHSGEP->getOperand(0) == CE->getOperand(0)) {
1039 CstGEP = CE;
1040 GEP = LHSGEP;
1041 Swapped = false;
1042 }
1043 }
1044 }
1045
1046 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
1047 // X - (gep X, ...)
1048 if (RHSGEP->getOperand(0) == LHS) {
1049 GEP = RHSGEP;
1050 Swapped = true;
1051 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
1052 // (ce_gep X, ...) - (gep X, ...)
1053 if (CE->getOpcode() == Instruction::GetElementPtr &&
1054 RHSGEP->getOperand(0) == CE->getOperand(0)) {
1055 CstGEP = CE;
1056 GEP = RHSGEP;
1057 Swapped = true;
1058 }
1059 }
1060 }
1061
1062 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00001063 return 0;
1064
Chris Lattner092543c2009-11-04 08:05:20 +00001065 // Emit the offset of the GEP and an intptr_t.
Chris Lattner02446fc2010-01-04 07:37:31 +00001066 Value *Result = EmitGEPOffset(GEP);
Chris Lattner85c1c962010-01-01 22:42:29 +00001067
1068 // If we had a constant expression GEP on the other side offsetting the
1069 // pointer, subtract it from the offset we have.
1070 if (CstGEP) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001071 Value *CstOffset = EmitGEPOffset(CstGEP);
Chris Lattner85c1c962010-01-01 22:42:29 +00001072 Result = Builder->CreateSub(Result, CstOffset);
1073 }
1074
Chris Lattner092543c2009-11-04 08:05:20 +00001075
1076 // If we have p - gep(p, ...) then we have to negate the result.
1077 if (Swapped)
1078 Result = Builder->CreateNeg(Result, "diff.neg");
1079
1080 return Builder->CreateIntCast(Result, Ty, true);
1081}
1082
1083
Chris Lattner7e708292002-06-25 16:13:24 +00001084Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001085 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001086
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001087 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001088 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001089
Chris Lattner3bf68152009-12-21 04:04:05 +00001090 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
1091 if (Value *V = dyn_castNegVal(Op1)) {
1092 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1093 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1094 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1095 return Res;
1096 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001097
Chris Lattnere87597f2004-10-16 18:11:37 +00001098 if (isa<UndefValue>(Op0))
1099 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1100 if (isa<UndefValue>(Op1))
1101 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner4de84762010-01-04 07:02:48 +00001102 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner092543c2009-11-04 08:05:20 +00001103 return BinaryOperator::CreateXor(Op0, Op1);
1104
Chris Lattnerd65460f2003-11-05 01:06:05 +00001105 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00001106 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00001107 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00001108 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001109
Chris Lattnerd65460f2003-11-05 01:06:05 +00001110 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001111 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001112 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00001113 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00001114
Chris Lattner76b7a062007-01-15 07:02:54 +00001115 // -(X >>u 31) -> (X >>s 31)
1116 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00001117 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001118 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001119 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001120 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00001121 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001122 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00001123 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001124 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001125 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00001126 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00001127 }
1128 }
Chris Lattner092543c2009-11-04 08:05:20 +00001129 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001130 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1131 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001132 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00001133 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00001134 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001135 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001136 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00001137 }
1138 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001139 }
1140 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001141 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001142
1143 // Try to fold constant sub into select arguments.
1144 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00001145 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001146 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00001147
1148 // C - zext(bool) -> bool ? C - 1 : C
1149 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattner4de84762010-01-04 07:02:48 +00001150 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +00001151 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00001152 }
1153
Chris Lattner43d84d62005-04-07 16:15:25 +00001154 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001155 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00001156 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001157 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001158 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001159 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001160 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001161 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001162 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1163 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1164 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00001165 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00001166 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00001167 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001168 }
1169
Chris Lattnerfd059242003-10-15 16:48:29 +00001170 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001171 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1172 // is not used by anyone else...
1173 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001174 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00001175 // Swap the two operands of the subexpr...
1176 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1177 Op1I->setOperand(0, IIOp1);
1178 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001179
Chris Lattnera2881962003-02-18 19:28:33 +00001180 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001181 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001182 }
1183
1184 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1185 //
1186 if (Op1I->getOpcode() == Instruction::And &&
1187 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1188 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1189
Chris Lattner74381062009-08-30 07:44:24 +00001190 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001191 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001192 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001193
Reid Spencerac5209e2006-10-16 23:08:08 +00001194 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00001195 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00001196 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00001197 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00001198 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001199 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001200 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00001201
Chris Lattnerad3448c2003-02-18 19:57:07 +00001202 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001203 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00001204 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001205 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001206 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00001207 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001208 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001209 }
Chris Lattner40371712002-05-09 01:29:19 +00001210 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001211 }
Chris Lattnera2881962003-02-18 19:28:33 +00001212
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001213 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1214 if (Op0I->getOpcode() == Instruction::Add) {
1215 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1216 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1217 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1218 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1219 } else if (Op0I->getOpcode() == Instruction::Sub) {
1220 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001221 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001222 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001223 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001224 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001225
Chris Lattner50af16a2004-11-13 19:50:12 +00001226 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00001227 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00001228 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00001229 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001230
Chris Lattner50af16a2004-11-13 19:50:12 +00001231 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00001232 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001233 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00001234 }
Chris Lattner092543c2009-11-04 08:05:20 +00001235
1236 // Optimize pointer differences into the same array into a size. Consider:
1237 // &A[10] - &A[0]: we should compile this to "10".
1238 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00001239 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001240 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1241 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00001242 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1243 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001244
1245 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001246 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1247 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1248 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1249 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001250 }
1251
Chris Lattner3f5b8772002-05-06 16:14:14 +00001252 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001253}
1254
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001255Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1256 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1257
1258 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00001259 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001260 return BinaryOperator::CreateFAdd(Op0, V);
1261
1262 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1263 if (Op1I->getOpcode() == Instruction::FAdd) {
1264 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001265 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001266 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001267 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001268 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001269 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001270 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001271 }
1272
1273 return 0;
1274}
1275
Reid Spencere4d87aa2006-12-23 06:05:41 +00001276/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001277/// are carefully arranged to allow folding of expressions such as:
1278///
1279/// (A < B) | (A > B) --> (A != B)
1280///
Reid Spencere4d87aa2006-12-23 06:05:41 +00001281/// Note that this is only valid if the first and second predicates have the
1282/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001283///
Reid Spencere4d87aa2006-12-23 06:05:41 +00001284/// Three bits are used to represent the condition, as follows:
1285/// 0 A > B
1286/// 1 A == B
1287/// 2 A < B
1288///
1289/// <=> Value Definition
1290/// 000 0 Always false
1291/// 001 1 A > B
1292/// 010 2 A == B
1293/// 011 3 A >= B
1294/// 100 4 A < B
1295/// 101 5 A != B
1296/// 110 6 A <= B
1297/// 111 7 Always true
1298///
1299static unsigned getICmpCode(const ICmpInst *ICI) {
1300 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001301 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00001302 case ICmpInst::ICMP_UGT: return 1; // 001
1303 case ICmpInst::ICMP_SGT: return 1; // 001
1304 case ICmpInst::ICMP_EQ: return 2; // 010
1305 case ICmpInst::ICMP_UGE: return 3; // 011
1306 case ICmpInst::ICMP_SGE: return 3; // 011
1307 case ICmpInst::ICMP_ULT: return 4; // 100
1308 case ICmpInst::ICMP_SLT: return 4; // 100
1309 case ICmpInst::ICMP_NE: return 5; // 101
1310 case ICmpInst::ICMP_ULE: return 6; // 110
1311 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001312 // True -> 7
1313 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001314 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001315 return 0;
1316 }
1317}
1318
Evan Cheng8db90722008-10-14 17:15:11 +00001319/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
1320/// predicate into a three bit mask. It also returns whether it is an ordered
1321/// predicate by reference.
1322static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
1323 isOrdered = false;
1324 switch (CC) {
1325 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
1326 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00001327 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
1328 case FCmpInst::FCMP_UGT: return 1; // 001
1329 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
1330 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00001331 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
1332 case FCmpInst::FCMP_UGE: return 3; // 011
1333 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
1334 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00001335 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
1336 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00001337 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
1338 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00001339 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00001340 default:
1341 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00001342 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00001343 return 0;
1344 }
1345}
1346
Reid Spencere4d87aa2006-12-23 06:05:41 +00001347/// getICmpValue - This is the complement of getICmpCode, which turns an
1348/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00001349/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00001350/// of predicate to use in the new icmp instruction.
Chris Lattner4de84762010-01-04 07:02:48 +00001351static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001352 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001353 default: llvm_unreachable("Illegal ICmp code!");
Chris Lattner4de84762010-01-04 07:02:48 +00001354 case 0: return ConstantInt::getFalse(LHS->getContext());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001355 case 1:
1356 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001357 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001358 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001359 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
1360 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001361 case 3:
1362 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001363 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001364 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001365 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001366 case 4:
1367 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001368 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001369 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001370 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
1371 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001372 case 6:
1373 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001374 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001375 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001376 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00001377 case 7: return ConstantInt::getTrue(LHS->getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001378 }
1379}
1380
Evan Cheng8db90722008-10-14 17:15:11 +00001381/// getFCmpValue - This is the complement of getFCmpCode, which turns an
1382/// opcode and two operands into either a FCmp instruction. isordered is passed
1383/// in to determine which kind of predicate to use in the new fcmp instruction.
1384static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner4de84762010-01-04 07:02:48 +00001385 Value *LHS, Value *RHS) {
Evan Cheng8db90722008-10-14 17:15:11 +00001386 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001387 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00001388 case 0:
1389 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001390 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001391 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001392 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001393 case 1:
1394 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001395 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001396 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001397 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001398 case 2:
1399 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001400 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001401 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001402 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001403 case 3:
1404 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001405 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001406 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001407 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001408 case 4:
1409 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001410 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001411 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001412 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001413 case 5:
1414 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001415 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001416 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001417 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001418 case 6:
1419 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001420 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001421 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001422 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00001423 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng8db90722008-10-14 17:15:11 +00001424 }
1425}
1426
Chris Lattnerb9553d62008-11-16 04:55:20 +00001427/// PredicatesFoldable - Return true if both predicates match sign or if at
1428/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00001429static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00001430 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
1431 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
1432 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001433}
1434
1435namespace {
1436// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
1437struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001438 InstCombiner &IC;
1439 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001440 ICmpInst::Predicate pred;
1441 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
1442 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
1443 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001444 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001445 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
1446 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001447 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
1448 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001449 return false;
1450 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001451 Instruction *apply(Instruction &Log) const {
1452 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
1453 if (ICI->getOperand(0) != LHS) {
1454 assert(ICI->getOperand(1) == LHS);
1455 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001456 }
1457
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00001458 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001459 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00001460 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001461 unsigned Code;
1462 switch (Log.getOpcode()) {
1463 case Instruction::And: Code = LHSCode & RHSCode; break;
1464 case Instruction::Or: Code = LHSCode | RHSCode; break;
1465 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00001466 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001467 }
1468
Nick Lewycky4a134af2009-10-25 05:20:17 +00001469 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Chris Lattner4de84762010-01-04 07:02:48 +00001470 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001471 if (Instruction *I = dyn_cast<Instruction>(RV))
1472 return I;
1473 // Otherwise, it's a constant boolean value...
1474 return IC.ReplaceInstUsesWith(Log, RV);
1475 }
1476};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00001477} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001478
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001479// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1480// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00001481// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001482Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001483 ConstantInt *OpRHS,
1484 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001485 BinaryOperator &TheAnd) {
1486 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001487 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00001488 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001489 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001490
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001491 switch (Op->getOpcode()) {
1492 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001493 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001494 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00001495 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001496 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001497 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001498 }
1499 break;
1500 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001501 if (Together == AndRHS) // (X | C) & C --> C
1502 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001503
Chris Lattner6e7ba452005-01-01 16:22:27 +00001504 if (Op->hasOneUse() && Together != OpRHS) {
1505 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00001506 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00001507 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001508 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001509 }
1510 break;
1511 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001512 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001513 // Adding a one to a single bit bit-field should be turned into an XOR
1514 // of the bit. First thing to check is to see if this AND is with a
1515 // single bit constant.
Chris Lattnerc6334b92010-01-05 06:03:12 +00001516 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001517
Chris Lattnerc6334b92010-01-05 06:03:12 +00001518 // If there is only one bit set.
1519 if (AndRHSV.isPowerOf2()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001520 // Ok, at this point, we know that we are masking the result of the
1521 // ADD down to exactly one bit. If the constant we are adding has
1522 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001523 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001524
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001525 // Check to see if any bits below the one bit set in AndRHSV are set.
1526 if ((AddRHS & (AndRHSV-1)) == 0) {
1527 // If not, the only thing that can effect the output of the AND is
1528 // the bit specified by AndRHSV. If that bit is set, the effect of
1529 // the XOR is to toggle the bit. If it is clear, then the ADD has
1530 // no effect.
1531 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1532 TheAnd.setOperand(0, X);
1533 return &TheAnd;
1534 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001535 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00001536 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001537 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001538 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001539 }
1540 }
1541 }
1542 }
1543 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001544
1545 case Instruction::Shl: {
1546 // We know that the AND will not produce any of the bits shifted in, so if
1547 // the anded constant includes them, clear them now!
1548 //
Zhou Sheng290bec52007-03-29 08:15:12 +00001549 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001550 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00001551 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00001552 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
1553 AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00001554
Zhou Sheng290bec52007-03-29 08:15:12 +00001555 if (CI->getValue() == ShlMask) {
1556 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00001557 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1558 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001559 TheAnd.setOperand(1, CI);
1560 return &TheAnd;
1561 }
1562 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00001563 }
Chris Lattner4de84762010-01-04 07:02:48 +00001564 case Instruction::LShr: {
Chris Lattner62a355c2003-09-19 19:05:02 +00001565 // We know that the AND will not produce any of the bits shifted in, so if
1566 // the anded constant includes them, clear them now! This only applies to
1567 // unsigned shifts, because a signed shr may bring in set bits!
1568 //
Zhou Sheng290bec52007-03-29 08:15:12 +00001569 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001570 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00001571 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00001572 ConstantInt *CI = ConstantInt::get(Op->getContext(),
1573 AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00001574
Zhou Sheng290bec52007-03-29 08:15:12 +00001575 if (CI->getValue() == ShrMask) {
1576 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00001577 return ReplaceInstUsesWith(TheAnd, Op);
1578 } else if (CI != AndRHS) {
1579 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
1580 return &TheAnd;
1581 }
1582 break;
1583 }
1584 case Instruction::AShr:
1585 // Signed shr.
1586 // See if this is shifting in some sign extension, then masking it out
1587 // with an and.
1588 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00001589 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001590 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00001591 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00001592 Constant *C = ConstantInt::get(Op->getContext(),
1593 AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00001594 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00001595 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00001596 // Make the argument unsigned.
1597 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00001598 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001599 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00001600 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001601 }
1602 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001603 }
1604 return 0;
1605}
1606
Chris Lattner8b170942002-08-09 23:47:40 +00001607
Chris Lattnera96879a2004-09-29 17:40:11 +00001608/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1609/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00001610/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
1611/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00001612/// insert new instructions.
1613Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001614 bool isSigned, bool Inside,
1615 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001616 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00001617 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00001618 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001619
Chris Lattnera96879a2004-09-29 17:40:11 +00001620 if (Inside) {
1621 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001622 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00001623
Reid Spencere4d87aa2006-12-23 06:05:41 +00001624 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001625 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00001626 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00001627 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001628 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001629 }
1630
1631 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00001632 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00001633 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001634 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001635 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00001636 }
1637
1638 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001639 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00001640
Reid Spencere4e40032007-03-21 23:19:50 +00001641 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00001642 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001643 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001644 ICmpInst::Predicate pred = (isSigned ?
1645 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001646 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001647 }
Reid Spencerb83eb642006-10-20 07:07:24 +00001648
Reid Spencere4e40032007-03-21 23:19:50 +00001649 // Emit V-Lo >u Hi-1-Lo
1650 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00001651 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00001652 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001653 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001654 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00001655}
1656
Chris Lattner7203e152005-09-18 07:22:02 +00001657// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1658// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1659// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1660// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00001661static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001662 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00001663 uint32_t BitWidth = Val->getType()->getBitWidth();
1664 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00001665
1666 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00001667 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00001668 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00001669 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00001670 return true;
1671}
1672
Chris Lattner7203e152005-09-18 07:22:02 +00001673/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1674/// where isSub determines whether the operator is a sub. If we can fold one of
1675/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00001676///
1677/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1678/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1679/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1680///
1681/// return (A +/- B).
1682///
1683Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001684 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00001685 Instruction &I) {
1686 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1687 if (!LHSI || LHSI->getNumOperands() != 2 ||
1688 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1689
1690 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1691
1692 switch (LHSI->getOpcode()) {
1693 default: return 0;
1694 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00001695 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00001696 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00001697 if ((Mask->getValue().countLeadingZeros() +
1698 Mask->getValue().countPopulation()) ==
1699 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00001700 break;
1701
1702 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1703 // part, we don't need any explicit masks to take them out of A. If that
1704 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001705 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00001706 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00001707 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00001708 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00001709 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00001710 break;
1711 }
1712 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001713 return 0;
1714 case Instruction::Or:
1715 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00001716 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00001717 if ((Mask->getValue().countLeadingZeros() +
1718 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00001719 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00001720 break;
1721 return 0;
1722 }
1723
Chris Lattnerc8e77562005-09-18 04:24:45 +00001724 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00001725 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
1726 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00001727}
1728
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001729/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
1730Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
1731 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00001732 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001733 ConstantInt *LHSCst, *RHSCst;
1734 ICmpInst::Predicate LHSCC, RHSCC;
1735
Chris Lattnerea065fb2008-11-16 05:10:52 +00001736 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001737 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00001738 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001739 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00001740 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001741 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00001742
Chris Lattner3f40e232009-11-29 00:51:17 +00001743 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1744 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
1745 // where C is a power of 2
1746 if (LHSCC == ICmpInst::ICMP_ULT &&
1747 LHSCst->getValue().isPowerOf2()) {
1748 Value *NewOr = Builder->CreateOr(Val, Val2);
1749 return new ICmpInst(LHSCC, NewOr, LHSCst);
1750 }
1751
1752 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
1753 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
1754 Value *NewOr = Builder->CreateOr(Val, Val2);
1755 return new ICmpInst(LHSCC, NewOr, LHSCst);
1756 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00001757 }
1758
1759 // From here on, we only handle:
1760 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
1761 if (Val != Val2) return 0;
1762
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001763 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1764 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1765 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1766 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1767 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1768 return 0;
1769
1770 // We can't fold (ugt x, C) & (sgt x, C2).
1771 if (!PredicatesFoldable(LHSCC, RHSCC))
1772 return 0;
1773
1774 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00001775 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00001776 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001777 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00001778 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00001779 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001780 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00001781 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1782
1783 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001784 std::swap(LHS, RHS);
1785 std::swap(LHSCst, RHSCst);
1786 std::swap(LHSCC, RHSCC);
1787 }
1788
1789 // At this point, we know we have have two icmp instructions
1790 // comparing a value against two constants and and'ing the result
1791 // together. Because of the above check, we know that we only have
1792 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1793 // (from the FoldICmpLogical check above), that the two constants
1794 // are not equal and that the larger constant is on the RHS
1795 assert(LHSCst != RHSCst && "Compares not folded above?");
1796
1797 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001798 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001799 case ICmpInst::ICMP_EQ:
1800 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001801 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001802 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
1803 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
1804 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00001805 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001806 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
1807 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
1808 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
1809 return ReplaceInstUsesWith(I, LHS);
1810 }
1811 case ICmpInst::ICMP_NE:
1812 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001813 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001814 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00001815 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001816 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001817 break; // (X != 13 & X u< 15) -> no change
1818 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00001819 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001820 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001821 break; // (X != 13 & X s< 15) -> no change
1822 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
1823 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
1824 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
1825 return ReplaceInstUsesWith(I, RHS);
1826 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001827 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00001828 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00001829 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001830 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00001831 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001832 }
1833 break; // (X != 13 & X != 15) -> no change
1834 }
1835 break;
1836 case ICmpInst::ICMP_ULT:
1837 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001838 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001839 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
1840 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00001841 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001842 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
1843 break;
1844 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
1845 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
1846 return ReplaceInstUsesWith(I, LHS);
1847 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
1848 break;
1849 }
1850 break;
1851 case ICmpInst::ICMP_SLT:
1852 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001853 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001854 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
1855 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00001856 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001857 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
1858 break;
1859 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
1860 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
1861 return ReplaceInstUsesWith(I, LHS);
1862 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
1863 break;
1864 }
1865 break;
1866 case ICmpInst::ICMP_UGT:
1867 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001868 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001869 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
1870 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
1871 return ReplaceInstUsesWith(I, RHS);
1872 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1873 break;
1874 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001875 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001876 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001877 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00001878 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00001879 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001880 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001881 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1882 break;
1883 }
1884 break;
1885 case ICmpInst::ICMP_SGT:
1886 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001887 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001888 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1889 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
1890 return ReplaceInstUsesWith(I, RHS);
1891 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1892 break;
1893 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001894 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001895 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001896 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00001897 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00001898 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001899 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001900 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1901 break;
1902 }
1903 break;
1904 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001905
1906 return 0;
1907}
1908
Chris Lattner42d1be02009-07-23 05:14:02 +00001909Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
1910 FCmpInst *RHS) {
1911
1912 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1913 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1914 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1915 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1916 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1917 // If either of the constants are nans, then the whole thing returns
1918 // false.
1919 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00001920 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001921 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00001922 LHS->getOperand(0), RHS->getOperand(0));
1923 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00001924
1925 // Handle vector zeros. This occurs because the canonical form of
1926 // "fcmp ord x,x" is "fcmp ord x, 0".
1927 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1928 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001929 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00001930 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00001931 return 0;
1932 }
1933
1934 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1935 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1936 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1937
1938
1939 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1940 // Swap RHS operands to match LHS.
1941 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1942 std::swap(Op1LHS, Op1RHS);
1943 }
1944
1945 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1946 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1947 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001948 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00001949
1950 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner4de84762010-01-04 07:02:48 +00001951 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001952 if (Op0CC == FCmpInst::FCMP_TRUE)
1953 return ReplaceInstUsesWith(I, RHS);
1954 if (Op1CC == FCmpInst::FCMP_TRUE)
1955 return ReplaceInstUsesWith(I, LHS);
1956
1957 bool Op0Ordered;
1958 bool Op1Ordered;
1959 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1960 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1961 if (Op1Pred == 0) {
1962 std::swap(LHS, RHS);
1963 std::swap(Op0Pred, Op1Pred);
1964 std::swap(Op0Ordered, Op1Ordered);
1965 }
1966 if (Op0Pred == 0) {
1967 // uno && ueq -> uno && (uno || eq) -> ueq
1968 // ord && olt -> ord && (ord && lt) -> olt
1969 if (Op0Ordered == Op1Ordered)
1970 return ReplaceInstUsesWith(I, RHS);
1971
1972 // uno && oeq -> uno && (ord && eq) -> false
1973 // uno && ord -> false
1974 if (!Op0Ordered)
Chris Lattner4de84762010-01-04 07:02:48 +00001975 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001976 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner4de84762010-01-04 07:02:48 +00001977 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner42d1be02009-07-23 05:14:02 +00001978 }
1979 }
1980
1981 return 0;
1982}
1983
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001984
Chris Lattner7e708292002-06-25 16:13:24 +00001985Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001986 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001987 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001988
Chris Lattnerd06094f2009-11-10 00:55:12 +00001989 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1990 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001991
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001992 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00001993 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00001994 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00001995 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00001996
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001997 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001998 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001999 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002000
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002001 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002002 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002003 Value *Op0LHS = Op0I->getOperand(0);
2004 Value *Op0RHS = Op0I->getOperand(1);
2005 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002006 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002007 case Instruction::Xor:
2008 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00002009 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002010 if (!Op0I->hasOneUse()) break;
2011
2012 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2013 // Not masking anything out for the LHS, move to RHS.
2014 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
2015 Op0RHS->getName()+".masked");
2016 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
2017 }
2018 if (!isa<Constant>(Op0RHS) &&
2019 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2020 // Not masking anything out for the RHS, move to LHS.
2021 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
2022 Op0LHS->getName()+".masked");
2023 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00002024 }
2025
Chris Lattner6e7ba452005-01-01 16:22:27 +00002026 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00002027 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00002028 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2029 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2030 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2031 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002032 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00002033 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002034 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00002035 break;
2036
2037 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00002038 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2039 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2040 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2041 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002042 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002043
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00002044 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
2045 // has 1's for all bits that the subtraction with A might affect.
2046 if (Op0I->hasOneUse()) {
2047 uint32_t BitWidth = AndRHSMask.getBitWidth();
2048 uint32_t Zeros = AndRHSMask.countLeadingZeros();
2049 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
2050
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002051 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00002052 if (!(A && A->isZero()) && // avoid infinite recursion.
2053 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00002054 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002055 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
2056 }
2057 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002058 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00002059
2060 case Instruction::Shl:
2061 case Instruction::LShr:
2062 // (1 << x) & 1 --> zext(x == 0)
2063 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00002064 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00002065 Value *NewICmp =
2066 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00002067 return new ZExtInst(NewICmp, I.getType());
2068 }
2069 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002070 }
2071
Chris Lattner58403262003-07-23 19:25:52 +00002072 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002073 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002074 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002075 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00002076 // If this is an integer truncation or change from signed-to-unsigned, and
2077 // if the source is an and/or with immediate, transform it. This
2078 // frequently occurs for bitfield accesses.
2079 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002080 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00002081 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00002082 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00002083 if (CastOp->getOpcode() == Instruction::And) {
2084 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00002085 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
2086 // This will fold the two constants together, which may allow
2087 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00002088 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00002089 CastOp->getOperand(0), I.getType(),
2090 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00002091 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00002092 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00002093 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002094 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00002095 } else if (CastOp->getOpcode() == Instruction::Or) {
2096 // Change: and (cast (or X, C1) to T), C2
2097 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00002098 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00002099 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00002100 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00002101 return ReplaceInstUsesWith(I, AndRHS);
2102 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002103 }
Chris Lattner2b83af22005-08-07 07:03:10 +00002104 }
Chris Lattner06782f82003-07-23 19:36:21 +00002105 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002106
2107 // Try to fold constant and into select arguments.
2108 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002109 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002110 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002111 if (isa<PHINode>(Op0))
2112 if (Instruction *NV = FoldOpIntoPhi(I))
2113 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002114 }
2115
Chris Lattner5b62aa72004-06-18 06:07:51 +00002116
Misha Brukmancb6267b2004-07-30 12:50:08 +00002117 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00002118 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2119 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2120 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2121 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
2122 I.getName()+".demorgan");
2123 return BinaryOperator::CreateNot(Or);
2124 }
2125
Chris Lattner2082ad92006-02-13 23:07:23 +00002126 {
Chris Lattner003b6202007-06-15 05:58:24 +00002127 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00002128 // (A|B) & ~(A&B) -> A^B
2129 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2130 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2131 ((A == C && B == D) || (A == D && B == C)))
2132 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00002133
Chris Lattnerd06094f2009-11-10 00:55:12 +00002134 // ~(A&B) & (A|B) -> A^B
2135 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
2136 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2137 ((A == C && B == D) || (A == D && B == C)))
2138 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00002139
2140 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002141 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00002142 if (A == Op1) { // (A^B)&A -> A&(A^B)
2143 I.swapOperands(); // Simplify below
2144 std::swap(Op0, Op1);
2145 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2146 cast<BinaryOperator>(Op0)->swapOperands();
2147 I.swapOperands(); // Simplify below
2148 std::swap(Op0, Op1);
2149 }
2150 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002151
Chris Lattner64daab52006-04-01 08:03:55 +00002152 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002153 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00002154 if (B == Op0) { // B&(A^B) -> B&(B^A)
2155 cast<BinaryOperator>(Op1)->swapOperands();
2156 std::swap(A, B);
2157 }
Chris Lattner74381062009-08-30 07:44:24 +00002158 if (A == Op0) // A&(A^B) -> A & ~B
2159 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00002160 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002161
2162 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00002163 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
2164 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002165 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00002166 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
2167 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002168 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00002169 }
2170
Reid Spencere4d87aa2006-12-23 06:05:41 +00002171 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
2172 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00002173 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002174 return R;
2175
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002176 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
2177 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
2178 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00002179 }
2180
Chris Lattner6fc205f2006-05-05 06:39:07 +00002181 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002182 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
2183 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2184 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
2185 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002186 if (SrcTy == Op1C->getOperand(0)->getType() &&
2187 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002188 // Only do this if the casts both really cause code to be generated.
Chris Lattner80f43d32010-01-04 07:53:58 +00002189 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
2190 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002191 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002192 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002193 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
2194 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002195 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002196 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002197 }
Chris Lattnere511b742006-11-14 07:46:50 +00002198
2199 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00002200 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2201 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2202 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00002203 SI0->getOperand(1) == SI1->getOperand(1) &&
2204 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002205 Value *NewOp =
2206 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
2207 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002208 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00002209 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00002210 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002211 }
2212
Evan Cheng8db90722008-10-14 17:15:11 +00002213 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00002214 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00002215 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2216 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
2217 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002218 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002219
Chris Lattner7e708292002-06-25 16:13:24 +00002220 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002221}
2222
Chris Lattner8c34cd22008-10-05 02:13:19 +00002223/// CollectBSwapParts - Analyze the specified subexpression and see if it is
2224/// capable of providing pieces of a bswap. The subexpression provides pieces
2225/// of a bswap if it is proven that each of the non-zero bytes in the output of
2226/// the expression came from the corresponding "byte swapped" byte in some other
2227/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
2228/// we know that the expression deposits the low byte of %X into the high byte
2229/// of the bswap result and that all other bytes are zero. This expression is
2230/// accepted, the high byte of ByteValues is set to X to indicate a correct
2231/// match.
2232///
2233/// This function returns true if the match was unsuccessful and false if so.
2234/// On entry to the function the "OverallLeftShift" is a signed integer value
2235/// indicating the number of bytes that the subexpression is later shifted. For
2236/// example, if the expression is later right shifted by 16 bits, the
2237/// OverallLeftShift value would be -2 on entry. This is used to specify which
2238/// byte of ByteValues is actually being set.
2239///
2240/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
2241/// byte is masked to zero by a user. For example, in (X & 255), X will be
2242/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
2243/// this function to working on up to 32-byte (256 bit) values. ByteMask is
2244/// always in the local (OverallLeftShift) coordinate space.
2245///
2246static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
2247 SmallVector<Value*, 8> &ByteValues) {
2248 if (Instruction *I = dyn_cast<Instruction>(V)) {
2249 // If this is an or instruction, it may be an inner node of the bswap.
2250 if (I->getOpcode() == Instruction::Or) {
2251 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2252 ByteValues) ||
2253 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
2254 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002255 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00002256
2257 // If this is a logical shift by a constant multiple of 8, recurse with
2258 // OverallLeftShift and ByteMask adjusted.
2259 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2260 unsigned ShAmt =
2261 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2262 // Ensure the shift amount is defined and of a byte value.
2263 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
2264 return true;
2265
2266 unsigned ByteShift = ShAmt >> 3;
2267 if (I->getOpcode() == Instruction::Shl) {
2268 // X << 2 -> collect(X, +2)
2269 OverallLeftShift += ByteShift;
2270 ByteMask >>= ByteShift;
2271 } else {
2272 // X >>u 2 -> collect(X, -2)
2273 OverallLeftShift -= ByteShift;
2274 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00002275 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00002276 }
2277
2278 if (OverallLeftShift >= (int)ByteValues.size()) return true;
2279 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
2280
2281 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2282 ByteValues);
2283 }
2284
2285 // If this is a logical 'and' with a mask that clears bytes, clear the
2286 // corresponding bytes in ByteMask.
2287 if (I->getOpcode() == Instruction::And &&
2288 isa<ConstantInt>(I->getOperand(1))) {
2289 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
2290 unsigned NumBytes = ByteValues.size();
2291 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
2292 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
2293
2294 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
2295 // If this byte is masked out by a later operation, we don't care what
2296 // the and mask is.
2297 if ((ByteMask & (1 << i)) == 0)
2298 continue;
2299
2300 // If the AndMask is all zeros for this byte, clear the bit.
2301 APInt MaskB = AndMask & Byte;
2302 if (MaskB == 0) {
2303 ByteMask &= ~(1U << i);
2304 continue;
2305 }
2306
2307 // If the AndMask is not all ones for this byte, it's not a bytezap.
2308 if (MaskB != Byte)
2309 return true;
2310
2311 // Otherwise, this byte is kept.
2312 }
2313
2314 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2315 ByteValues);
2316 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00002317 }
2318
Chris Lattner8c34cd22008-10-05 02:13:19 +00002319 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
2320 // the input value to the bswap. Some observations: 1) if more than one byte
2321 // is demanded from this input, then it could not be successfully assembled
2322 // into a byteswap. At least one of the two bytes would not be aligned with
2323 // their ultimate destination.
2324 if (!isPowerOf2_32(ByteMask)) return true;
2325 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002326
Chris Lattner8c34cd22008-10-05 02:13:19 +00002327 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
2328 // is demanded, it needs to go into byte 0 of the result. This means that the
2329 // byte needs to be shifted until it lands in the right byte bucket. The
2330 // shift amount depends on the position: if the byte is coming from the high
2331 // part of the value (e.g. byte 3) then it must be shifted right. If from the
2332 // low part, it must be shifted left.
2333 unsigned DestByteNo = InputByteNo + OverallLeftShift;
2334 if (InputByteNo < ByteValues.size()/2) {
2335 if (ByteValues.size()-1-DestByteNo != InputByteNo)
2336 return true;
2337 } else {
2338 if (ByteValues.size()-1-DestByteNo != InputByteNo)
2339 return true;
2340 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00002341
2342 // If the destination byte value is already defined, the values are or'd
2343 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00002344 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00002345 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00002346 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00002347 return false;
2348}
2349
2350/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
2351/// If so, insert the new bswap intrinsic and return it.
2352Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00002353 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00002354 if (!ITy || ITy->getBitWidth() % 16 ||
2355 // ByteMask only allows up to 32-byte values.
2356 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00002357 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00002358
2359 /// ByteValues - For each byte of the result, we keep track of which value
2360 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00002361 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00002362 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002363
2364 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00002365 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
2366 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00002367 return 0;
2368
2369 // Check to see if all of the bytes come from the same value.
2370 Value *V = ByteValues[0];
2371 if (V == 0) return 0; // Didn't find a byte? Must be zero.
2372
2373 // Check to make sure that all of the bytes come from the same value.
2374 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
2375 if (ByteValues[i] != V)
2376 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00002377 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00002378 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00002379 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00002380 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002381}
2382
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002383/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
2384/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
2385/// we can simplify this expression to "cond ? C : D or B".
2386static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner4de84762010-01-04 07:02:48 +00002387 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00002388 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00002389 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002390 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002391 return 0;
2392
Chris Lattnera6a474d2008-11-16 04:26:55 +00002393 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00002394 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002395 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00002396 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002397 return SelectInst::Create(Cond, C, B);
2398 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00002399 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002400 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00002401 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002402 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002403 return 0;
2404}
Chris Lattnerafe91a52006-06-15 19:07:26 +00002405
Chris Lattner69d4ced2008-11-16 05:20:07 +00002406/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
2407Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
2408 ICmpInst *LHS, ICmpInst *RHS) {
2409 Value *Val, *Val2;
2410 ConstantInt *LHSCst, *RHSCst;
2411 ICmpInst::Predicate LHSCC, RHSCC;
2412
2413 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00002414 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
2415 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00002416 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00002417
2418
2419 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
2420 if (LHSCst == RHSCst && LHSCC == RHSCC &&
2421 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
2422 Value *NewOr = Builder->CreateOr(Val, Val2);
2423 return new ICmpInst(LHSCC, NewOr, LHSCst);
2424 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00002425
2426 // From here on, we only handle:
2427 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
2428 if (Val != Val2) return 0;
2429
2430 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
2431 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
2432 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
2433 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
2434 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
2435 return 0;
2436
2437 // We can't fold (ugt x, C) | (sgt x, C2).
2438 if (!PredicatesFoldable(LHSCC, RHSCC))
2439 return 0;
2440
2441 // Ensure that the larger constant is on the RHS.
2442 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00002443 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00002444 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00002445 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00002446 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
2447 else
2448 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
2449
2450 if (ShouldSwap) {
2451 std::swap(LHS, RHS);
2452 std::swap(LHSCst, RHSCst);
2453 std::swap(LHSCC, RHSCC);
2454 }
2455
2456 // At this point, we know we have have two icmp instructions
2457 // comparing a value against two constants and or'ing the result
2458 // together. Because of the above check, we know that we only have
2459 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
2460 // FoldICmpLogical check above), that the two constants are not
2461 // equal.
2462 assert(LHSCst != RHSCst && "Compares not folded above?");
2463
2464 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002465 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002466 case ICmpInst::ICMP_EQ:
2467 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002468 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002469 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00002470 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002471 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00002472 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00002473 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00002474 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002475 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00002476 }
2477 break; // (X == 13 | X == 15) -> no change
2478 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
2479 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
2480 break;
2481 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
2482 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
2483 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
2484 return ReplaceInstUsesWith(I, RHS);
2485 }
2486 break;
2487 case ICmpInst::ICMP_NE:
2488 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002489 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002490 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
2491 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
2492 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
2493 return ReplaceInstUsesWith(I, LHS);
2494 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
2495 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
2496 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00002497 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00002498 }
2499 break;
2500 case ICmpInst::ICMP_ULT:
2501 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002502 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002503 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
2504 break;
2505 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
2506 // If RHSCst is [us]MAXINT, it is always false. Not handling
2507 // this can cause overflow.
2508 if (RHSCst->isMaxValue(false))
2509 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00002510 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002511 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00002512 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
2513 break;
2514 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
2515 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
2516 return ReplaceInstUsesWith(I, RHS);
2517 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
2518 break;
2519 }
2520 break;
2521 case ICmpInst::ICMP_SLT:
2522 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002523 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002524 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
2525 break;
2526 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
2527 // If RHSCst is [us]MAXINT, it is always false. Not handling
2528 // this can cause overflow.
2529 if (RHSCst->isMaxValue(true))
2530 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00002531 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002532 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00002533 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
2534 break;
2535 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
2536 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
2537 return ReplaceInstUsesWith(I, RHS);
2538 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
2539 break;
2540 }
2541 break;
2542 case ICmpInst::ICMP_UGT:
2543 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002544 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002545 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
2546 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
2547 return ReplaceInstUsesWith(I, LHS);
2548 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
2549 break;
2550 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
2551 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00002552 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00002553 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
2554 break;
2555 }
2556 break;
2557 case ICmpInst::ICMP_SGT:
2558 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002559 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002560 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
2561 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
2562 return ReplaceInstUsesWith(I, LHS);
2563 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
2564 break;
2565 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
2566 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00002567 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00002568 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
2569 break;
2570 }
2571 break;
2572 }
2573 return 0;
2574}
2575
Chris Lattner5414cc52009-07-23 05:46:22 +00002576Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
2577 FCmpInst *RHS) {
2578 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
2579 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
2580 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2581 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2582 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2583 // If either of the constants are nans, then the whole thing returns
2584 // true.
2585 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00002586 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00002587
2588 // Otherwise, no need to compare the two constants, compare the
2589 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002590 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00002591 LHS->getOperand(0), RHS->getOperand(0));
2592 }
2593
2594 // Handle vector zeros. This occurs because the canonical form of
2595 // "fcmp uno x,x" is "fcmp uno x, 0".
2596 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2597 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002598 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00002599 LHS->getOperand(0), RHS->getOperand(0));
2600
2601 return 0;
2602 }
2603
2604 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2605 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2606 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2607
2608 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2609 // Swap RHS operands to match LHS.
2610 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2611 std::swap(Op1LHS, Op1RHS);
2612 }
2613 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2614 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2615 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002616 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00002617 Op0LHS, Op0RHS);
2618 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner4de84762010-01-04 07:02:48 +00002619 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00002620 if (Op0CC == FCmpInst::FCMP_FALSE)
2621 return ReplaceInstUsesWith(I, RHS);
2622 if (Op1CC == FCmpInst::FCMP_FALSE)
2623 return ReplaceInstUsesWith(I, LHS);
2624 bool Op0Ordered;
2625 bool Op1Ordered;
2626 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2627 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2628 if (Op0Ordered == Op1Ordered) {
2629 // If both are ordered or unordered, return a new fcmp with
2630 // or'ed predicates.
Chris Lattner4de84762010-01-04 07:02:48 +00002631 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +00002632 if (Instruction *I = dyn_cast<Instruction>(RV))
2633 return I;
2634 // Otherwise, it's a constant boolean value...
2635 return ReplaceInstUsesWith(I, RV);
2636 }
2637 }
2638 return 0;
2639}
2640
Bill Wendlinga698a472008-12-01 08:23:25 +00002641/// FoldOrWithConstants - This helper function folds:
2642///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00002643/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00002644///
2645/// into:
2646///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00002647/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00002648///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00002649/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00002650Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00002651 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00002652 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2653 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00002654
Bill Wendling286a0542008-12-02 06:24:20 +00002655 Value *V1 = 0;
2656 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002657 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00002658
Bill Wendling29976b92008-12-02 06:18:11 +00002659 APInt Xor = CI1->getValue() ^ CI2->getValue();
2660 if (!Xor.isAllOnesValue()) return 0;
2661
Bill Wendling286a0542008-12-02 06:24:20 +00002662 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00002663 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00002664 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00002665 }
2666
2667 return 0;
2668}
2669
Chris Lattner7e708292002-06-25 16:13:24 +00002670Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002671 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002672 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002673
Chris Lattnerd06094f2009-11-10 00:55:12 +00002674 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
2675 return ReplaceInstUsesWith(I, V);
2676
2677
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002678 // See if we can simplify any instructions used by the instruction whose sole
2679 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002680 if (SimplifyDemandedInstructionBits(I))
2681 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00002682
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002683 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002684 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002685 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00002686 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002687 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00002688 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002689 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002690 return BinaryOperator::CreateAnd(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00002691 ConstantInt::get(I.getContext(),
2692 RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002693 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002694
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002695 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00002696 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002697 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00002698 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002699 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002700 return BinaryOperator::CreateXor(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00002701 ConstantInt::get(I.getContext(),
2702 C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002703 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002704
2705 // Try to fold constant and into select arguments.
2706 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002707 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002708 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002709 if (isa<PHINode>(Op0))
2710 if (Instruction *NV = FoldOpIntoPhi(I))
2711 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002712 }
2713
Chris Lattner4f637d42006-01-06 17:59:59 +00002714 Value *A = 0, *B = 0;
2715 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002716
Chris Lattner6423d4c2006-07-10 20:25:24 +00002717 // (A | B) | C and A | (B | C) -> bswap if possible.
2718 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00002719 if (match(Op0, m_Or(m_Value(), m_Value())) ||
2720 match(Op1, m_Or(m_Value(), m_Value())) ||
2721 (match(Op0, m_Shift(m_Value(), m_Value())) &&
2722 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00002723 if (Instruction *BSwap = MatchBSwap(I))
2724 return BSwap;
2725 }
2726
Chris Lattner6e4c6492005-05-09 04:58:36 +00002727 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002728 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002729 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00002730 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00002731 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00002732 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002733 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00002734 }
2735
2736 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002737 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002738 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00002739 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00002740 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00002741 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002742 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00002743 }
2744
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002745 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00002746 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002747 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2748 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00002749 Value *V1 = 0, *V2 = 0, *V3 = 0;
2750 C1 = dyn_cast<ConstantInt>(C);
2751 C2 = dyn_cast<ConstantInt>(D);
2752 if (C1 && C2) { // (A & C1)|(B & C2)
2753 // If we have: ((V + N) & C1) | (V & C2)
2754 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2755 // replace with V+N.
2756 if (C1->getValue() == ~C2->getValue()) {
2757 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00002758 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00002759 // Add commutes, try both ways.
2760 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
2761 return ReplaceInstUsesWith(I, A);
2762 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
2763 return ReplaceInstUsesWith(I, A);
2764 }
2765 // Or commutes, try both ways.
2766 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002767 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00002768 // Add commutes, try both ways.
2769 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
2770 return ReplaceInstUsesWith(I, B);
2771 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
2772 return ReplaceInstUsesWith(I, B);
2773 }
2774 }
Chris Lattnere4412c12010-01-04 06:03:59 +00002775
2776 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2777 // iff (C1&C2) == 0 and (N&~C1) == 0
2778 if ((C1->getValue() & C2->getValue()) == 0) {
2779 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2780 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
2781 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
2782 return BinaryOperator::CreateAnd(A,
2783 ConstantInt::get(A->getContext(),
2784 C1->getValue()|C2->getValue()));
2785 // Or commutes, try both ways.
2786 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2787 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
2788 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
2789 return BinaryOperator::CreateAnd(B,
2790 ConstantInt::get(B->getContext(),
2791 C1->getValue()|C2->getValue()));
2792 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00002793 }
2794
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002795 // Check to see if we have any common things being and'ed. If so, find the
2796 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002797 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
Chris Lattnere4412c12010-01-04 06:03:59 +00002798 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002799 if (A == B) // (A & C)|(A & D) == A & (C|D)
2800 V1 = A, V2 = C, V3 = D;
2801 else if (A == D) // (A & C)|(B & A) == A & (B|C)
2802 V1 = A, V2 = B, V3 = C;
2803 else if (C == B) // (A & C)|(C & D) == C & (A|D)
2804 V1 = C, V2 = A, V3 = D;
2805 else if (C == D) // (A & C)|(B & C) == C & (A|B)
2806 V1 = C, V2 = A, V3 = B;
2807
2808 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00002809 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002810 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002811 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002812 }
Dan Gohmanb493b272008-10-28 22:38:57 +00002813
Dan Gohman1975d032008-10-30 20:40:10 +00002814 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner4de84762010-01-04 07:02:48 +00002815 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002816 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00002817 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002818 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00002819 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002820 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00002821 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002822 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00002823
Bill Wendlingb01865c2008-11-30 13:52:49 +00002824 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002825 if ((match(C, m_Not(m_Specific(D))) &&
2826 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002827 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00002828 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002829 if ((match(A, m_Not(m_Specific(D))) &&
2830 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002831 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00002832 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002833 if ((match(C, m_Not(m_Specific(B))) &&
2834 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002835 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00002836 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002837 if ((match(A, m_Not(m_Specific(B))) &&
2838 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002839 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002840 }
Chris Lattnere511b742006-11-14 07:46:50 +00002841
2842 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00002843 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2844 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2845 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00002846 SI0->getOperand(1) == SI1->getOperand(1) &&
2847 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002848 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
2849 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002850 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00002851 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00002852 }
2853 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002854
Bill Wendlingb3833d12008-12-01 01:07:11 +00002855 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00002856 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
2857 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00002858 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00002859 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00002860 }
2861 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00002862 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
2863 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00002864 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00002865 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00002866 }
2867
Chris Lattnerd06094f2009-11-10 00:55:12 +00002868 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2869 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2870 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2871 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2872 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2873 I.getName()+".demorgan");
2874 return BinaryOperator::CreateNot(And);
2875 }
Chris Lattnera2881962003-02-18 19:28:33 +00002876
Reid Spencere4d87aa2006-12-23 06:05:41 +00002877 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
2878 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00002879 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002880 return R;
2881
Chris Lattner69d4ced2008-11-16 05:20:07 +00002882 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2883 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
2884 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002885 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002886
2887 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00002888 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00002889 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002890 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00002891 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
2892 !isa<ICmpInst>(Op1C->getOperand(0))) {
2893 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002894 if (SrcTy == Op1C->getOperand(0)->getType() &&
2895 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002896 // Only do this if the casts both really cause code to be
2897 // generated.
2898 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002899 I.getType()) &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002900 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002901 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002902 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
2903 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002904 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00002905 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002906 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002907 }
Chris Lattner99c65742007-10-24 05:38:08 +00002908 }
2909
2910
2911 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2912 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00002913 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2914 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
2915 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002916 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002917
Chris Lattner7e708292002-06-25 16:13:24 +00002918 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002919}
2920
Dan Gohman844731a2008-05-13 00:00:25 +00002921namespace {
2922
Chris Lattnerc317d392004-02-16 01:20:27 +00002923// XorSelf - Implements: X ^ X --> 0
2924struct XorSelf {
2925 Value *RHS;
2926 XorSelf(Value *rhs) : RHS(rhs) {}
2927 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2928 Instruction *apply(BinaryOperator &Xor) const {
2929 return &Xor;
2930 }
2931};
Chris Lattner3f5b8772002-05-06 16:14:14 +00002932
Dan Gohman844731a2008-05-13 00:00:25 +00002933}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002934
Chris Lattner7e708292002-06-25 16:13:24 +00002935Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002936 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002937 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002938
Evan Chengd34af782008-03-25 20:07:13 +00002939 if (isa<UndefValue>(Op1)) {
2940 if (isa<UndefValue>(Op0))
2941 // Handle undef ^ undef -> 0 special case. This is a common
2942 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00002943 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002944 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00002945 }
Chris Lattnere87597f2004-10-16 18:11:37 +00002946
Chris Lattnerc317d392004-02-16 01:20:27 +00002947 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00002948 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002949 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00002950 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00002951 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002952
2953 // See if we can simplify any instructions used by the instruction whose sole
2954 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002955 if (SimplifyDemandedInstructionBits(I))
2956 return &I;
2957 if (isa<VectorType>(I.getType()))
2958 if (isa<ConstantAggregateZero>(Op1))
2959 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00002960
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002961 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00002962 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002963 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2964 if (Op0I->getOpcode() == Instruction::And ||
2965 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00002966 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2967 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2968 if (dyn_castNotVal(Op0I->getOperand(1)))
2969 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00002970 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00002971 Value *NotY =
2972 Builder->CreateNot(Op0I->getOperand(1),
2973 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002974 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002975 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00002976 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002977 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00002978
2979 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2980 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2981 if (isFreeToInvert(Op0I->getOperand(0)) &&
2982 isFreeToInvert(Op0I->getOperand(1))) {
2983 Value *NotX =
2984 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2985 Value *NotY =
2986 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2987 if (Op0I->getOpcode() == Instruction::And)
2988 return BinaryOperator::CreateOr(NotX, NotY);
2989 return BinaryOperator::CreateAnd(NotX, NotY);
2990 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002991 }
2992 }
2993 }
2994
2995
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002996 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002997 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00002998 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002999 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003000 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00003001 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00003002
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003003 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003004 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003005 FCI->getOperand(0), FCI->getOperand(1));
3006 }
3007
Nick Lewycky517e1f52008-05-31 19:01:33 +00003008 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
3009 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3010 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
3011 if (CI->hasOneUse() && Op0C->hasOneUse()) {
3012 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00003013 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
3014 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner4de84762010-01-04 07:02:48 +00003015 ConstantInt::getTrue(I.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +00003016 Op0C->getDestTy()))) {
3017 CI->setPredicate(CI->getInversePredicate());
3018 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00003019 }
3020 }
3021 }
3022 }
3023
Reid Spencere4d87aa2006-12-23 06:05:41 +00003024 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00003025 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00003026 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3027 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003028 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3029 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00003030 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003031 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003032 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00003033
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003034 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003035 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00003036 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00003037 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003038 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003039 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00003040 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00003041 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00003042 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00003043 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00003044 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner4de84762010-01-04 07:02:48 +00003045 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00003046 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003047 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00003048
Chris Lattner7c4049c2004-01-12 19:35:11 +00003049 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00003050 } else if (Op0I->getOpcode() == Instruction::Or) {
3051 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00003052 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003053 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00003054 // Anything in both C1 and C2 is known to be zero, remove it from
3055 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003056 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3057 NewRHS = ConstantExpr::getAnd(NewRHS,
3058 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00003059 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00003060 I.setOperand(0, Op0I->getOperand(0));
3061 I.setOperand(1, NewRHS);
3062 return &I;
3063 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003064 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003065 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00003066 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003067
3068 // Try to fold constant and into select arguments.
3069 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00003070 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00003071 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003072 if (isa<PHINode>(Op0))
3073 if (Instruction *NV = FoldOpIntoPhi(I))
3074 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003075 }
3076
Dan Gohman186a6362009-08-12 16:04:34 +00003077 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003078 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00003079 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003080
Dan Gohman186a6362009-08-12 16:04:34 +00003081 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003082 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00003083 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003084
Chris Lattner318bf792007-03-18 22:51:34 +00003085
3086 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
3087 if (Op1I) {
3088 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00003089 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003090 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003091 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00003092 I.swapOperands();
3093 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00003094 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003095 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00003096 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003097 }
Dan Gohman4ae51262009-08-12 16:23:25 +00003098 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003099 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003100 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003101 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003102 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003103 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00003104 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00003105 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00003106 std::swap(A, B);
3107 }
Chris Lattner318bf792007-03-18 22:51:34 +00003108 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00003109 I.swapOperands(); // Simplified below.
3110 std::swap(Op0, Op1);
3111 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003112 }
Chris Lattner318bf792007-03-18 22:51:34 +00003113 }
3114
3115 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
3116 if (Op0I) {
3117 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00003118 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003119 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00003120 if (A == Op1) // (B|A)^B == (A|B)^B
3121 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00003122 if (B == Op1) // (A|B)^B == A & ~B
3123 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00003124 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003125 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003126 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003127 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003128 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003129 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00003130 if (A == Op1) // (A&B)^A -> (B&A)^A
3131 std::swap(A, B);
3132 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00003133 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00003134 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00003135 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003136 }
Chris Lattner318bf792007-03-18 22:51:34 +00003137 }
3138
3139 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3140 if (Op0I && Op1I && Op0I->isShift() &&
3141 Op0I->getOpcode() == Op1I->getOpcode() &&
3142 Op0I->getOperand(1) == Op1I->getOperand(1) &&
3143 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00003144 Value *NewOp =
3145 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
3146 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003147 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00003148 Op1I->getOperand(1));
3149 }
3150
3151 if (Op0I && Op1I) {
3152 Value *A, *B, *C, *D;
3153 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003154 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3155 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003156 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003157 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003158 }
3159 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003160 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
3161 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003162 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003163 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003164 }
3165
3166 // (A & B)^(C & D)
3167 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003168 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3169 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003170 // (X & Y)^(X & Y) -> (Y^Z) & X
3171 Value *X = 0, *Y = 0, *Z = 0;
3172 if (A == C)
3173 X = A, Y = B, Z = D;
3174 else if (A == D)
3175 X = A, Y = B, Z = C;
3176 else if (B == C)
3177 X = B, Y = A, Z = D;
3178 else if (B == D)
3179 X = B, Y = A, Z = C;
3180
3181 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00003182 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003183 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00003184 }
3185 }
3186 }
3187
Reid Spencere4d87aa2006-12-23 06:05:41 +00003188 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3189 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00003190 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003191 return R;
3192
Chris Lattner6fc205f2006-05-05 06:39:07 +00003193 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00003194 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003195 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003196 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
3197 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003198 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003199 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003200 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003201 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00003202 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003203 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00003204 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
3205 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003206 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003207 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003208 }
Chris Lattner99c65742007-10-24 05:38:08 +00003209 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00003210
Chris Lattner7e708292002-06-25 16:13:24 +00003211 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003212}
3213
Chris Lattner3f5b8772002-05-06 16:14:14 +00003214
Reid Spencer832254e2007-02-02 02:16:23 +00003215Instruction *InstCombiner::visitShl(BinaryOperator &I) {
3216 return commonShiftTransforms(I);
3217}
3218
3219Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
3220 return commonShiftTransforms(I);
3221}
3222
3223Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00003224 if (Instruction *R = commonShiftTransforms(I))
3225 return R;
3226
3227 Value *Op0 = I.getOperand(0);
3228
3229 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
3230 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3231 if (CSI->isAllOnesValue())
3232 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00003233
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003234 // See if we can turn a signed shr into an unsigned shr.
3235 if (MaskedValueIsZero(Op0,
3236 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
3237 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
3238
3239 // Arithmetic shifting an all-sign-bit value is a no-op.
3240 unsigned NumSignBits = ComputeNumSignBits(Op0);
3241 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
3242 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00003243
Chris Lattner348f6652007-12-06 01:59:46 +00003244 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003245}
3246
3247Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
3248 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00003249 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003250
3251 // shl X, 0 == X and shr X, 0 == X
3252 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003253 if (Op1 == Constant::getNullValue(Op1->getType()) ||
3254 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00003255 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003256
Reid Spencere4d87aa2006-12-23 06:05:41 +00003257 if (isa<UndefValue>(Op0)) {
3258 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00003259 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003260 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003261 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003262 }
3263 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003264 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
3265 return ReplaceInstUsesWith(I, Op0);
3266 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003267 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003268 }
3269
Dan Gohman9004c8a2009-05-21 02:28:33 +00003270 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00003271 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00003272 return &I;
3273
Chris Lattner2eefe512004-04-09 19:05:30 +00003274 // Try to fold constant and into select arguments.
3275 if (isa<Constant>(Op0))
3276 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00003277 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00003278 return R;
3279
Reid Spencerb83eb642006-10-20 07:07:24 +00003280 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00003281 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3282 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003283 return 0;
3284}
3285
Reid Spencerb83eb642006-10-20 07:07:24 +00003286Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00003287 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00003288 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003289
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003290 // See if we can simplify any instructions used by the instruction whose sole
3291 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003292 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003293
Dan Gohmana119de82009-06-14 23:30:43 +00003294 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
3295 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00003296 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003297 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00003298 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00003299 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00003300 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00003301 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00003302 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00003303 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003304 }
3305
3306 // ((X*C1) << C2) == (X * (C1 << C2))
3307 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3308 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3309 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003310 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003311 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00003312
3313 // Try to fold constant and into select arguments.
3314 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00003315 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner4d5542c2006-01-06 07:12:35 +00003316 return R;
3317 if (isa<PHINode>(Op0))
3318 if (Instruction *NV = FoldOpIntoPhi(I))
3319 return NV;
3320
Chris Lattner8999dd32007-12-22 09:07:47 +00003321 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
3322 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
3323 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
3324 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
3325 // place. Don't try to do this transformation in this case. Also, we
3326 // require that the input operand is a shift-by-constant so that we have
3327 // confidence that the shifts will get folded together. We could do this
3328 // xform in more cases, but it is unlikely to be profitable.
3329 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
3330 isa<ConstantInt>(TrOp->getOperand(1))) {
3331 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003332 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00003333 // (shift2 (shift1 & 0x00FF), c2)
3334 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00003335
3336 // For logical shifts, the truncation has the effect of making the high
3337 // part of the register be zeros. Emulate this by inserting an AND to
3338 // clear the top bits as needed. This 'and' will usually be zapped by
3339 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003340 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
3341 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00003342 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
3343
3344 // The mask we constructed says what the trunc would do if occurring
3345 // between the shifts. We want to know the effect *after* the second
3346 // shift. We know that it is a logical shift by a constant, so adjust the
3347 // mask as appropriate.
3348 if (I.getOpcode() == Instruction::Shl)
3349 MaskV <<= Op1->getZExtValue();
3350 else {
3351 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
3352 MaskV = MaskV.lshr(Op1->getZExtValue());
3353 }
3354
Chris Lattner74381062009-08-30 07:44:24 +00003355 // shift1 & 0x00FF
Chris Lattner4de84762010-01-04 07:02:48 +00003356 Value *And = Builder->CreateAnd(NSh,
3357 ConstantInt::get(I.getContext(), MaskV),
Chris Lattner74381062009-08-30 07:44:24 +00003358 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00003359
3360 // Return the value truncated to the interesting size.
3361 return new TruncInst(And, I.getType());
3362 }
3363 }
3364
Chris Lattner4d5542c2006-01-06 07:12:35 +00003365 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00003366 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3367 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3368 Value *V1, *V2;
3369 ConstantInt *CC;
3370 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00003371 default: break;
3372 case Instruction::Add:
3373 case Instruction::And:
3374 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00003375 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00003376 // These operators commute.
3377 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003378 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003379 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003380 m_Specific(Op1)))) {
3381 Value *YS = // (Y << C)
3382 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
3383 // (X + (Y << C))
3384 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
3385 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00003386 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00003387 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00003388 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00003389 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003390
Chris Lattner150f12a2005-09-18 06:30:59 +00003391 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00003392 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00003393 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00003394 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00003395 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00003396 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00003397 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003398 Value *YS = // (Y << C)
3399 Builder->CreateShl(Op0BO->getOperand(0), Op1,
3400 Op0BO->getName());
3401 // X & (CC << C)
3402 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
3403 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003404 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00003405 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00003406 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003407
Reid Spencera07cb7d2007-02-02 14:41:37 +00003408 // FALL THROUGH.
3409 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00003410 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003411 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003412 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00003413 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003414 Value *YS = // (Y << C)
3415 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
3416 // (X + (Y << C))
3417 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
3418 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00003419 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00003420 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00003421 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00003422 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003423
Chris Lattner13d4ab42006-05-31 21:14:00 +00003424 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003425 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3426 match(Op0BO->getOperand(0),
3427 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00003428 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00003429 cast<BinaryOperator>(Op0BO->getOperand(0))
3430 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003431 Value *YS = // (Y << C)
3432 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
3433 // X & (CC << C)
3434 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
3435 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00003436
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003437 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00003438 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003439
Chris Lattner11021cb2005-09-18 05:12:10 +00003440 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00003441 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003442 }
3443
3444
3445 // If the operand is an bitwise operator with a constant RHS, and the
3446 // shift is the only use, we can pull it out of the shift.
3447 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3448 bool isValid = true; // Valid only for And, Or, Xor
3449 bool highBitSet = false; // Transform if high bit of constant set?
3450
3451 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00003452 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00003453 case Instruction::Add:
3454 isValid = isLeftShift;
3455 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00003456 case Instruction::Or:
3457 case Instruction::Xor:
3458 highBitSet = false;
3459 break;
3460 case Instruction::And:
3461 highBitSet = true;
3462 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003463 }
3464
3465 // If this is a signed shift right, and the high bit is modified
3466 // by the logical operation, do not perform the transformation.
3467 // The highBitSet boolean indicates the value of the high bit of
3468 // the constant which would cause it to be modified for this
3469 // operation.
3470 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00003471 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00003472 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003473
3474 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003475 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00003476
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003477 Value *NewShift =
3478 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00003479 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00003480
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003481 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003482 NewRHS);
3483 }
3484 }
3485 }
3486 }
3487
Chris Lattnerad0124c2006-01-06 07:52:12 +00003488 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00003489 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
3490 if (ShiftOp && !ShiftOp->isShift())
3491 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00003492
Reid Spencerb83eb642006-10-20 07:07:24 +00003493 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003494 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003495 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
3496 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00003497 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
3498 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
3499 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00003500
Zhou Sheng4351c642007-04-02 08:20:41 +00003501 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00003502
3503 const IntegerType *Ty = cast<IntegerType>(I.getType());
3504
3505 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00003506 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00003507 // If this is oversized composite shift, then unsigned shifts get 0, ashr
3508 // saturates.
3509 if (AmtSum >= TypeBits) {
3510 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00003511 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00003512 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
3513 }
3514
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003515 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00003516 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003517 }
3518
3519 if (ShiftOp->getOpcode() == Instruction::LShr &&
3520 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00003521 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00003522 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00003523
Chris Lattnerb87056f2007-02-05 00:57:54 +00003524 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00003525 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003526 }
3527
3528 if (ShiftOp->getOpcode() == Instruction::AShr &&
3529 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00003530 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00003531 if (AmtSum >= TypeBits)
3532 AmtSum = TypeBits-1;
3533
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003534 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003535
Zhou Shenge9e03f62007-03-28 15:02:20 +00003536 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner4de84762010-01-04 07:02:48 +00003537 return BinaryOperator::CreateAnd(Shift,
3538 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00003539 }
3540
Chris Lattnerb87056f2007-02-05 00:57:54 +00003541 // Okay, if we get here, one shift must be left, and the other shift must be
3542 // right. See if the amounts are equal.
3543 if (ShiftAmt1 == ShiftAmt2) {
3544 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
3545 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00003546 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00003547 return BinaryOperator::CreateAnd(X,
3548 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003549 }
3550 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
3551 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003552 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00003553 return BinaryOperator::CreateAnd(X,
3554 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003555 }
3556 // We can simplify ((X << C) >>s C) into a trunc + sext.
3557 // NOTE: we could do this for any C, but that would make 'unusual' integer
3558 // types. For now, just stick to ones well-supported by the code
3559 // generators.
3560 const Type *SExtType = 0;
3561 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00003562 case 1 :
3563 case 8 :
3564 case 16 :
3565 case 32 :
3566 case 64 :
3567 case 128:
Chris Lattner4de84762010-01-04 07:02:48 +00003568 SExtType = IntegerType::get(I.getContext(),
3569 Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00003570 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00003571 default: break;
3572 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003573 if (SExtType)
3574 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00003575 // Otherwise, we can't handle it yet.
3576 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00003577 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00003578
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003579 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003580 if (I.getOpcode() == Instruction::Shl) {
3581 assert(ShiftOp->getOpcode() == Instruction::LShr ||
3582 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003583 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00003584
Reid Spencer55702aa2007-03-25 21:11:44 +00003585 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003586 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003587 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00003588 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00003589
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003590 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003591 if (I.getOpcode() == Instruction::LShr) {
3592 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003593 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00003594
Reid Spencerd5e30f02007-03-26 17:18:58 +00003595 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003596 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003597 ConstantInt::get(I.getContext(),Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00003598 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00003599
3600 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
3601 } else {
3602 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00003603 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00003604
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003605 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003606 if (I.getOpcode() == Instruction::Shl) {
3607 assert(ShiftOp->getOpcode() == Instruction::LShr ||
3608 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003609 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
3610 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003611
Reid Spencer55702aa2007-03-25 21:11:44 +00003612 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003613 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003614 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003615 }
3616
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003617 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003618 if (I.getOpcode() == Instruction::LShr) {
3619 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003620 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003621
Reid Spencer68d27cf2007-03-26 23:45:51 +00003622 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003623 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003624 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003625 }
3626
3627 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00003628 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00003629 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003630 return 0;
3631}
3632
Chris Lattnera1be5662002-05-02 17:06:02 +00003633
Reid Spencer3da59db2006-11-27 01:05:10 +00003634
Chris Lattner46cd5a12009-01-09 05:44:56 +00003635/// FindElementAtOffset - Given a type and a constant offset, determine whether
3636/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00003637/// the specified offset. If so, fill them into NewIndices and return the
3638/// resultant element type, otherwise return null.
Chris Lattner80f43d32010-01-04 07:53:58 +00003639const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
3640 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00003641 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00003642 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003643
3644 // Start with the index over the outer type. Note that the type size
3645 // might be zero (even if the offset isn't zero) if the indexed type
3646 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +00003647 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +00003648 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00003649 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00003650 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00003651 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003652
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003653 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00003654 if (Offset < 0) {
3655 --FirstIdx;
3656 Offset += TySize;
3657 assert(Offset >= 0);
3658 }
3659 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
3660 }
3661
Owen Andersoneed707b2009-07-24 23:12:02 +00003662 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00003663
3664 // Index into the types. If we fail, set OrigBase to null.
3665 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003666 // Indexing into tail padding between struct/array elements.
3667 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00003668 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003669
Chris Lattner46cd5a12009-01-09 05:44:56 +00003670 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
3671 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003672 assert(Offset < (int64_t)SL->getSizeInBytes() &&
3673 "Offset must stay within the indexed type");
3674
Chris Lattner46cd5a12009-01-09 05:44:56 +00003675 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +00003676 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
3677 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00003678
3679 Offset -= SL->getElementOffset(Elt);
3680 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00003681 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00003682 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003683 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00003684 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003685 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00003686 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00003687 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003688 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00003689 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003690 }
3691 }
3692
Chris Lattner3914f722009-01-24 01:00:13 +00003693 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003694}
3695
Chris Lattner8a2a3112001-12-14 16:52:21 +00003696
Dan Gohmaneee962e2008-04-10 18:43:06 +00003697/// EnforceKnownAlignment - If the specified pointer points to an object that
3698/// we control, modify the object's alignment to PrefAlign. This isn't
3699/// often possible though. If alignment is important, a more reliable approach
3700/// is to simply align all global variables and allocation instructions to
3701/// their preferred alignment from the beginning.
3702///
3703static unsigned EnforceKnownAlignment(Value *V,
3704 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00003705
Dan Gohmaneee962e2008-04-10 18:43:06 +00003706 User *U = dyn_cast<User>(V);
3707 if (!U) return Align;
3708
Dan Gohmanca178902009-07-17 20:47:02 +00003709 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00003710 default: break;
3711 case Instruction::BitCast:
3712 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
3713 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00003714 // If all indexes are zero, it is just the alignment of the base pointer.
3715 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00003716 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00003717 if (!isa<Constant>(*i) ||
3718 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00003719 AllZeroOperands = false;
3720 break;
3721 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00003722
3723 if (AllZeroOperands) {
3724 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00003725 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00003726 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00003727 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00003728 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00003729 }
3730
3731 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3732 // If there is a large requested alignment and we can, bump up the alignment
3733 // of the global.
3734 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00003735 if (GV->getAlignment() >= PrefAlign)
3736 Align = GV->getAlignment();
3737 else {
3738 GV->setAlignment(PrefAlign);
3739 Align = PrefAlign;
3740 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00003741 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00003742 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
3743 // If there is a requested alignment and if this is an alloca, round up.
3744 if (AI->getAlignment() >= PrefAlign)
3745 Align = AI->getAlignment();
3746 else {
3747 AI->setAlignment(PrefAlign);
3748 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00003749 }
3750 }
3751
3752 return Align;
3753}
3754
3755/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
3756/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
3757/// and it is more than the alignment of the ultimate object, see if we can
3758/// increase the alignment of the ultimate object, making this check succeed.
3759unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
3760 unsigned PrefAlign) {
3761 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
3762 sizeof(PrefAlign) * CHAR_BIT;
3763 APInt Mask = APInt::getAllOnesValue(BitWidth);
3764 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3765 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
3766 unsigned TrailZ = KnownZero.countTrailingOnes();
3767 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
3768
3769 if (PrefAlign > Align)
3770 Align = EnforceKnownAlignment(V, Align, PrefAlign);
3771
3772 // We don't need to make any adjustment.
3773 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00003774}
3775
Chris Lattnerf497b022008-01-13 23:50:23 +00003776Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00003777 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00003778 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00003779 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003780 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00003781
3782 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003783 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00003784 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00003785 return MI;
3786 }
3787
3788 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
3789 // load/store.
3790 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
3791 if (MemOpLength == 0) return 0;
3792
Chris Lattner37ac6082008-01-14 00:28:35 +00003793 // Source and destination pointer types are always "i8*" for intrinsic. See
3794 // if the size is something we can handle with a single primitive load/store.
3795 // A single load+store correctly handles overlapping memory in the memmove
3796 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00003797 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00003798 if (Size == 0) return MI; // Delete this mem transfer.
3799
3800 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00003801 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00003802
Chris Lattner37ac6082008-01-14 00:28:35 +00003803 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00003804 Type *NewPtrTy =
Chris Lattner4de84762010-01-04 07:02:48 +00003805 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00003806
3807 // Memcpy forces the use of i8* for the source and destination. That means
3808 // that if you're using memcpy to move one double around, you'll get a cast
3809 // from double* to i8*. We'd much rather use a double load+store rather than
3810 // an i64 load+store, here because this improves the odds that the source or
3811 // dest address will be promotable. See if we can find a better type than the
3812 // integer datatype.
3813 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
3814 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00003815 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00003816 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
3817 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00003818 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00003819 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
3820 if (STy->getNumElements() == 1)
3821 SrcETy = STy->getElementType(0);
3822 else
3823 break;
3824 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
3825 if (ATy->getNumElements() == 1)
3826 SrcETy = ATy->getElementType();
3827 else
3828 break;
3829 } else
3830 break;
3831 }
3832
Dan Gohman8f8e2692008-05-23 01:52:21 +00003833 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00003834 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00003835 }
3836 }
3837
3838
Chris Lattnerf497b022008-01-13 23:50:23 +00003839 // If the memcpy/memmove provides better alignment info than we can
3840 // infer, use it.
3841 SrcAlign = std::max(SrcAlign, CopyAlign);
3842 DstAlign = std::max(DstAlign, CopyAlign);
3843
Chris Lattner08142f22009-08-30 19:47:22 +00003844 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
3845 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00003846 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
3847 InsertNewInstBefore(L, *MI);
3848 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
3849
3850 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00003851 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00003852 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00003853}
Chris Lattner3d69f462004-03-12 05:52:32 +00003854
Chris Lattner69ea9d22008-04-30 06:39:11 +00003855Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
3856 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003857 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003858 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00003859 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003860 return MI;
3861 }
3862
3863 // Extract the length and alignment and fill if they are constant.
3864 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
3865 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Chris Lattner4de84762010-01-04 07:02:48 +00003866 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner69ea9d22008-04-30 06:39:11 +00003867 return 0;
3868 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003869 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00003870
3871 // If the length is zero, this is a no-op
3872 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
3873
3874 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
3875 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner4de84762010-01-04 07:02:48 +00003876 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00003877
3878 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00003879 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003880
3881 // Alignment 0 is identity for alignment 1 for memset, but not store.
3882 if (Alignment == 0) Alignment = 1;
3883
3884 // Extract the fill value and store.
3885 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00003886 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00003887 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00003888
3889 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00003890 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003891 return MI;
3892 }
3893
3894 return 0;
3895}
3896
3897
Chris Lattner8b0ea312006-01-13 20:11:04 +00003898/// visitCallInst - CallInst simplification. This mostly only handles folding
3899/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
3900/// the heavy lifting.
3901///
Chris Lattner9fe38862003-06-19 17:00:31 +00003902Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00003903 if (isFreeCall(&CI))
3904 return visitFree(CI);
3905
Chris Lattneraab6ec42009-05-13 17:39:14 +00003906 // If the caller function is nounwind, mark the call as nounwind, even if the
3907 // callee isn't.
3908 if (CI.getParent()->getParent()->doesNotThrow() &&
3909 !CI.doesNotThrow()) {
3910 CI.setDoesNotThrow();
3911 return &CI;
3912 }
3913
Chris Lattner8b0ea312006-01-13 20:11:04 +00003914 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
3915 if (!II) return visitCallSite(&CI);
3916
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003917 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3918 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00003919 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003920 bool Changed = false;
3921
3922 // memmove/cpy/set of zero bytes is a noop.
3923 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3924 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3925
Chris Lattner35b9e482004-10-12 04:52:52 +00003926 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00003927 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003928 // Replace the instruction with just byte operations. We would
3929 // transform other cases to loads/stores, but we don't know if
3930 // alignment is sufficient.
3931 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003932 }
3933
Chris Lattner35b9e482004-10-12 04:52:52 +00003934 // If we have a memmove and the source operation is a constant global,
3935 // then the source and dest pointers can't alias, so we can change this
3936 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00003937 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003938 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3939 if (GVSrc->isConstant()) {
3940 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00003941 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
3942 const Type *Tys[1];
3943 Tys[0] = CI.getOperand(3)->getType();
3944 CI.setOperand(0,
3945 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00003946 Changed = true;
3947 }
Eli Friedman0c826d92009-12-17 21:07:31 +00003948 }
Chris Lattnera935db82008-05-28 05:30:41 +00003949
Eli Friedman0c826d92009-12-17 21:07:31 +00003950 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +00003951 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +00003952 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +00003953 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00003954 }
Chris Lattner35b9e482004-10-12 04:52:52 +00003955
Chris Lattner95a959d2006-03-06 20:18:44 +00003956 // If we can determine a pointer alignment that is bigger than currently
3957 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00003958 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00003959 if (Instruction *I = SimplifyMemTransfer(MI))
3960 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00003961 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
3962 if (Instruction *I = SimplifyMemSet(MSI))
3963 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00003964 }
3965
Chris Lattner8b0ea312006-01-13 20:11:04 +00003966 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00003967 }
3968
3969 switch (II->getIntrinsicID()) {
3970 default: break;
3971 case Intrinsic::bswap:
3972 // bswap(bswap(x)) -> x
3973 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
3974 if (Operand->getIntrinsicID() == Intrinsic::bswap)
3975 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +00003976
3977 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
3978 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
3979 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
3980 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
3981 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
3982 TI->getType()->getPrimitiveSizeInBits();
3983 Value *CV = ConstantInt::get(Operand->getType(), C);
3984 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
3985 return new TruncInst(V, TI->getType());
3986 }
3987 }
3988
Chris Lattner0521e3c2008-06-18 04:33:20 +00003989 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +00003990 case Intrinsic::powi:
3991 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
3992 // powi(x, 0) -> 1.0
3993 if (Power->isZero())
3994 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
3995 // powi(x, 1) -> x
3996 if (Power->isOne())
3997 return ReplaceInstUsesWith(CI, II->getOperand(1));
3998 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +00003999 if (Power->isAllOnesValue())
4000 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
4001 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +00004002 }
4003 break;
4004
Chris Lattner2bbac752009-11-26 21:42:47 +00004005 case Intrinsic::uadd_with_overflow: {
4006 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
4007 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
4008 uint32_t BitWidth = IT->getBitWidth();
4009 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +00004010 APInt LHSKnownZero(BitWidth, 0);
4011 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00004012 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
4013 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
4014 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
4015
4016 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +00004017 APInt RHSKnownZero(BitWidth, 0);
4018 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00004019 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
4020 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
4021 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
4022 if (LHSKnownNegative && RHSKnownNegative) {
4023 // The sign bit is set in both cases: this MUST overflow.
4024 // Create a simple add instruction, and insert it into the struct.
4025 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
4026 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00004027 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00004028 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00004029 };
Chris Lattner4de84762010-01-04 07:02:48 +00004030 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00004031 return InsertValueInst::Create(Struct, Add, 0);
4032 }
4033
4034 if (LHSKnownPositive && RHSKnownPositive) {
4035 // The sign bit is clear in both cases: this CANNOT overflow.
4036 // Create a simple add instruction, and insert it into the struct.
4037 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
4038 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00004039 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00004040 UndefValue::get(LHS->getType()),
4041 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00004042 };
Chris Lattner4de84762010-01-04 07:02:48 +00004043 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00004044 return InsertValueInst::Create(Struct, Add, 0);
4045 }
4046 }
4047 }
4048 // FALL THROUGH uadd into sadd
4049 case Intrinsic::sadd_with_overflow:
4050 // Canonicalize constants into the RHS.
4051 if (isa<Constant>(II->getOperand(1)) &&
4052 !isa<Constant>(II->getOperand(2))) {
4053 Value *LHS = II->getOperand(1);
4054 II->setOperand(1, II->getOperand(2));
4055 II->setOperand(2, LHS);
4056 return II;
4057 }
4058
4059 // X + undef -> undef
4060 if (isa<UndefValue>(II->getOperand(2)))
4061 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
4062
4063 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
4064 // X + 0 -> {X, false}
4065 if (RHS->isZero()) {
4066 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00004067 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00004068 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00004069 };
Chris Lattner4de84762010-01-04 07:02:48 +00004070 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00004071 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
4072 }
4073 }
4074 break;
4075 case Intrinsic::usub_with_overflow:
4076 case Intrinsic::ssub_with_overflow:
4077 // undef - X -> undef
4078 // X - undef -> undef
4079 if (isa<UndefValue>(II->getOperand(1)) ||
4080 isa<UndefValue>(II->getOperand(2)))
4081 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
4082
4083 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
4084 // X - 0 -> {X, false}
4085 if (RHS->isZero()) {
4086 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00004087 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00004088 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00004089 };
Chris Lattner4de84762010-01-04 07:02:48 +00004090 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00004091 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
4092 }
4093 }
4094 break;
4095 case Intrinsic::umul_with_overflow:
4096 case Intrinsic::smul_with_overflow:
4097 // Canonicalize constants into the RHS.
4098 if (isa<Constant>(II->getOperand(1)) &&
4099 !isa<Constant>(II->getOperand(2))) {
4100 Value *LHS = II->getOperand(1);
4101 II->setOperand(1, II->getOperand(2));
4102 II->setOperand(2, LHS);
4103 return II;
4104 }
4105
4106 // X * undef -> undef
4107 if (isa<UndefValue>(II->getOperand(2)))
4108 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
4109
4110 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
4111 // X*0 -> {0, false}
4112 if (RHSI->isZero())
4113 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
4114
4115 // X * 1 -> {X, false}
4116 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +00004117 Constant *V[] = {
4118 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00004119 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00004120 };
Chris Lattner4de84762010-01-04 07:02:48 +00004121 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +00004122 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00004123 }
4124 }
4125 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +00004126 case Intrinsic::ppc_altivec_lvx:
4127 case Intrinsic::ppc_altivec_lvxl:
4128 case Intrinsic::x86_sse_loadu_ps:
4129 case Intrinsic::x86_sse2_loadu_pd:
4130 case Intrinsic::x86_sse2_loadu_dq:
4131 // Turn PPC lvx -> load if the pointer is known aligned.
4132 // Turn X86 loadups -> load if the pointer is known aligned.
4133 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00004134 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
4135 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00004136 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00004137 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004138 break;
4139 case Intrinsic::ppc_altivec_stvx:
4140 case Intrinsic::ppc_altivec_stvxl:
4141 // Turn stvx -> store if the pointer is known aligned.
4142 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
4143 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00004144 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00004145 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00004146 return new StoreInst(II->getOperand(1), Ptr);
4147 }
4148 break;
4149 case Intrinsic::x86_sse_storeu_ps:
4150 case Intrinsic::x86_sse2_storeu_pd:
4151 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00004152 // Turn X86 storeu -> store if the pointer is known aligned.
4153 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
4154 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00004155 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00004156 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00004157 return new StoreInst(II->getOperand(2), Ptr);
4158 }
4159 break;
4160
4161 case Intrinsic::x86_sse_cvttss2si: {
4162 // These intrinsics only demands the 0th element of its input vector. If
4163 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00004164 unsigned VWidth =
4165 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
4166 APInt DemandedElts(VWidth, 1);
4167 APInt UndefElts(VWidth, 0);
4168 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00004169 UndefElts)) {
4170 II->setOperand(1, V);
4171 return II;
4172 }
4173 break;
4174 }
4175
4176 case Intrinsic::ppc_altivec_vperm:
4177 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
4178 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
4179 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00004180
Chris Lattner0521e3c2008-06-18 04:33:20 +00004181 // Check that all of the elements are integer constants or undefs.
4182 bool AllEltsOk = true;
4183 for (unsigned i = 0; i != 16; ++i) {
4184 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
4185 !isa<UndefValue>(Mask->getOperand(i))) {
4186 AllEltsOk = false;
4187 break;
4188 }
4189 }
4190
4191 if (AllEltsOk) {
4192 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00004193 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
4194 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00004195 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00004196
Chris Lattner0521e3c2008-06-18 04:33:20 +00004197 // Only extract each element once.
4198 Value *ExtractedElts[32];
4199 memset(ExtractedElts, 0, sizeof(ExtractedElts));
4200
Chris Lattnere2ed0572006-04-06 19:19:17 +00004201 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00004202 if (isa<UndefValue>(Mask->getOperand(i)))
4203 continue;
4204 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
4205 Idx &= 31; // Match the hardware behavior.
4206
4207 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004208 ExtractedElts[Idx] =
4209 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner4de84762010-01-04 07:02:48 +00004210 ConstantInt::get(Type::getInt32Ty(II->getContext()),
4211 Idx&15, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00004212 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00004213
Chris Lattner0521e3c2008-06-18 04:33:20 +00004214 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004215 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner4de84762010-01-04 07:02:48 +00004216 ConstantInt::get(Type::getInt32Ty(II->getContext()),
4217 i, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00004218 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004219 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00004220 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004221 }
4222 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00004223
Chris Lattner0521e3c2008-06-18 04:33:20 +00004224 case Intrinsic::stackrestore: {
4225 // If the save is right next to the restore, remove the restore. This can
4226 // happen when variable allocas are DCE'd.
4227 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4228 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4229 BasicBlock::iterator BI = SS;
4230 if (&*++BI == II)
4231 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00004232 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004233 }
4234
4235 // Scan down this block to see if there is another stack restore in the
4236 // same block without an intervening call/alloca.
4237 BasicBlock::iterator BI = II;
4238 TerminatorInst *TI = II->getParent()->getTerminator();
4239 bool CannotRemove = false;
4240 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00004241 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00004242 CannotRemove = true;
4243 break;
4244 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00004245 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
4246 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
4247 // If there is a stackrestore below this one, remove this one.
4248 if (II->getIntrinsicID() == Intrinsic::stackrestore)
4249 return EraseInstFromFunction(CI);
4250 // Otherwise, ignore the intrinsic.
4251 } else {
4252 // If we found a non-intrinsic call, we can't remove the stack
4253 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00004254 CannotRemove = true;
4255 break;
4256 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004257 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00004258 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004259
4260 // If the stack restore is in a return/unwind block and if there are no
4261 // allocas or calls between the restore and the return, nuke the restore.
4262 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
4263 return EraseInstFromFunction(CI);
4264 break;
4265 }
Chris Lattner35b9e482004-10-12 04:52:52 +00004266 }
4267
Chris Lattner8b0ea312006-01-13 20:11:04 +00004268 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004269}
4270
4271// InvokeInst simplification
4272//
4273Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00004274 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004275}
4276
Dale Johannesenda30ccb2008-04-25 21:16:07 +00004277/// isSafeToEliminateVarargsCast - If this cast does not affect the value
4278/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00004279static bool isSafeToEliminateVarargsCast(const CallSite CS,
4280 const CastInst * const CI,
4281 const TargetData * const TD,
4282 const int ix) {
4283 if (!CI->isLosslessCast())
4284 return false;
4285
4286 // The size of ByVal arguments is derived from the type, so we
4287 // can't change to a type with a different size. If the size were
4288 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00004289 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00004290 return true;
4291
4292 const Type* SrcTy =
4293 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
4294 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
4295 if (!SrcTy->isSized() || !DstTy->isSized())
4296 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004297 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00004298 return false;
4299 return true;
4300}
4301
Chris Lattnera44d8a22003-10-07 22:32:43 +00004302// visitCallSite - Improvements for call and invoke instructions.
4303//
4304Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00004305 bool Changed = false;
4306
4307 // If the callee is a constexpr cast of a function, attempt to move the cast
4308 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00004309 if (transformConstExprCastCall(CS)) return 0;
4310
Chris Lattner6c266db2003-10-07 22:54:13 +00004311 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00004312
Chris Lattner08b22ec2005-05-13 07:09:09 +00004313 if (Function *CalleeF = dyn_cast<Function>(Callee))
4314 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4315 Instruction *OldCall = CS.getInstruction();
4316 // If the call and callee calling conventions don't match, this call must
4317 // be unreachable, as the call is undefined.
Chris Lattner4de84762010-01-04 07:02:48 +00004318 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4319 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Andersond672ecb2009-07-03 00:17:18 +00004320 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +00004321 // If OldCall dues not return void then replaceAllUsesWith undef.
4322 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00004323 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00004324 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00004325 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4326 return EraseInstFromFunction(*OldCall);
4327 return 0;
4328 }
4329
Chris Lattner17be6352004-10-18 02:59:09 +00004330 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4331 // This instruction is not reachable, just remove it. We insert a store to
4332 // undef so that we know that this code is not reachable, despite the fact
4333 // that we can't modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00004334 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4335 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner17be6352004-10-18 02:59:09 +00004336 CS.getInstruction());
4337
Devang Patel228ebd02009-10-13 22:56:32 +00004338 // If CS dues not return void then replaceAllUsesWith undef.
4339 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00004340 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00004341 CS.getInstruction()->
4342 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00004343
4344 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4345 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00004346 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner4de84762010-01-04 07:02:48 +00004347 ConstantInt::getTrue(Callee->getContext()), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00004348 }
Chris Lattner17be6352004-10-18 02:59:09 +00004349 return EraseInstFromFunction(*CS.getInstruction());
4350 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004351
Duncan Sandscdb6d922007-09-17 10:26:40 +00004352 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
4353 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
4354 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
4355 return transformCallThroughTrampoline(CS);
4356
Chris Lattner6c266db2003-10-07 22:54:13 +00004357 const PointerType *PTy = cast<PointerType>(Callee->getType());
4358 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4359 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00004360 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00004361 // See if we can optimize any arguments passed through the varargs area of
4362 // the call.
4363 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00004364 E = CS.arg_end(); I != E; ++I, ++ix) {
4365 CastInst *CI = dyn_cast<CastInst>(*I);
4366 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
4367 *I = CI->getOperand(0);
4368 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00004369 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00004370 }
Chris Lattner6c266db2003-10-07 22:54:13 +00004371 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004372
Duncan Sandsf0c33542007-12-19 21:13:37 +00004373 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00004374 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00004375 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00004376 Changed = true;
4377 }
4378
Chris Lattner6c266db2003-10-07 22:54:13 +00004379 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00004380}
4381
Chris Lattner9fe38862003-06-19 17:00:31 +00004382// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4383// attempt to move the cast to the arguments of the call/invoke.
4384//
4385bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4386 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4387 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00004388 if (CE->getOpcode() != Instruction::BitCast ||
4389 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00004390 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00004391 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00004392 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00004393 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00004394
4395 // Okay, this is a cast from a function to a different type. Unless doing so
4396 // would cause a type conversion of one of our arguments, change this call to
4397 // be a direct call with arguments casted to the appropriate types.
4398 //
4399 const FunctionType *FT = Callee->getFunctionType();
4400 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004401 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00004402
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004403 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00004404 return false; // TODO: Handle multiple return values.
4405
Chris Lattnerf78616b2004-01-14 06:06:08 +00004406 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004407 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00004408 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004409 // Conversion is ok if changing from one pointer type to another or from
4410 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004411 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00004412 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004413 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00004414 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00004415 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00004416
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004417 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004418 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +00004419 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004420 return false; // Cannot transform this return value.
4421
Chris Lattner58d74912008-03-12 17:45:29 +00004422 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00004423 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00004424 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00004425 return false; // Attribute not compatible with transformed value.
4426 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004427
Chris Lattnerf78616b2004-01-14 06:06:08 +00004428 // If the callsite is an invoke instruction, and the return value is used by
4429 // a PHI node in a successor, we cannot change the return type of the call
4430 // because there is no place to put the cast instruction (without breaking
4431 // the critical edge). Bail out in this case.
4432 if (!Caller->use_empty())
4433 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4434 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4435 UI != E; ++UI)
4436 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4437 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004438 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00004439 return false;
4440 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004441
4442 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4443 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00004444
Chris Lattner9fe38862003-06-19 17:00:31 +00004445 CallSite::arg_iterator AI = CS.arg_begin();
4446 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4447 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00004448 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004449
4450 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004451 return false; // Cannot transform this parameter value.
4452
Devang Patel19c87462008-09-26 22:53:05 +00004453 if (CallerPAL.getParamAttributes(i + 1)
4454 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00004455 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004456
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004457 // Converting from one pointer type to another or between a pointer and an
4458 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00004459 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +00004460 (TD && ((isa<PointerType>(ParamTy) ||
4461 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
4462 (isa<PointerType>(ActTy) ||
4463 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +00004464 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00004465 }
4466
4467 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00004468 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00004469 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00004470
Chris Lattner58d74912008-03-12 17:45:29 +00004471 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
4472 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004473 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00004474 // won't be dropping them. Check that these extra arguments have attributes
4475 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00004476 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
4477 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00004478 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00004479 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00004480 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00004481 return false;
4482 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004483
Chris Lattner9fe38862003-06-19 17:00:31 +00004484 // Okay, we decided that this is a safe thing to do: go ahead and start
4485 // inserting cast instructions as necessary...
4486 std::vector<Value*> Args;
4487 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00004488 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004489 attrVec.reserve(NumCommonArgs);
4490
4491 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00004492 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004493
4494 // If the return value is not being used, the type may not be compatible
4495 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00004496 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004497
4498 // Add the new return attributes.
4499 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00004500 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00004501
4502 AI = CS.arg_begin();
4503 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4504 const Type *ParamTy = FT->getParamType(i);
4505 if ((*AI)->getType() == ParamTy) {
4506 Args.push_back(*AI);
4507 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00004508 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00004509 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004510 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00004511 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004512
4513 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00004514 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00004515 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00004516 }
4517
4518 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004519 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +00004520 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00004521 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +00004522
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004523 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004524 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00004525 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00004526 errs() << "WARNING: While resolving call to function '"
4527 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00004528 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004529 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +00004530 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4531 const Type *PTy = getPromotedType((*AI)->getType());
4532 if (PTy != (*AI)->getType()) {
4533 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004534 Instruction::CastOps opcode =
4535 CastInst::getCastOpcode(*AI, false, PTy, false);
4536 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00004537 } else {
4538 Args.push_back(*AI);
4539 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004540
Duncan Sandse1e520f2008-01-13 08:02:44 +00004541 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00004542 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00004543 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00004544 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004545 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004546 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004547
Devang Patel19c87462008-09-26 22:53:05 +00004548 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
4549 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
4550
Devang Patel9674d152009-10-14 17:29:00 +00004551 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +00004552 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00004553
Eric Christophera66297a2009-07-25 02:45:27 +00004554 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
4555 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004556
Chris Lattner9fe38862003-06-19 17:00:31 +00004557 Instruction *NC;
4558 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00004559 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00004560 Args.begin(), Args.end(),
4561 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00004562 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004563 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00004564 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00004565 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
4566 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00004567 CallInst *CI = cast<CallInst>(Caller);
4568 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00004569 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00004570 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004571 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00004572 }
4573
Chris Lattner6934a042007-02-11 01:23:03 +00004574 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00004575 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004576 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +00004577 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00004578 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004579 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004580 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00004581
4582 // If this is an invoke instruction, we should insert it after the first
4583 // non-phi, instruction in the normal successor block.
4584 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00004585 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00004586 InsertNewInstBefore(NC, *I);
4587 } else {
4588 // Otherwise, it's a call, just insert cast right after the call instr
4589 InsertNewInstBefore(NC, *Caller);
4590 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +00004591 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00004592 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00004593 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00004594 }
4595 }
4596
Devang Patel1bf5ebc2009-10-13 21:41:20 +00004597
Chris Lattner931f8f32009-08-31 05:17:58 +00004598 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +00004599 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +00004600
4601 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00004602 return true;
4603}
4604
Duncan Sandscdb6d922007-09-17 10:26:40 +00004605// transformCallThroughTrampoline - Turn a call to a function created by the
4606// init_trampoline intrinsic into a direct call to the underlying function.
4607//
4608Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
4609 Value *Callee = CS.getCalledValue();
4610 const PointerType *PTy = cast<PointerType>(Callee->getType());
4611 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00004612 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004613
4614 // If the call already has the 'nest' attribute somewhere then give up -
4615 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00004616 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004617 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00004618
4619 IntrinsicInst *Tramp =
4620 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
4621
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00004622 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00004623 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
4624 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
4625
Devang Patel05988662008-09-25 21:00:45 +00004626 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00004627 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00004628 unsigned NestIdx = 1;
4629 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00004630 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00004631
4632 // Look for a parameter marked with the 'nest' attribute.
4633 for (FunctionType::param_iterator I = NestFTy->param_begin(),
4634 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00004635 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00004636 // Record the parameter type and any other attributes.
4637 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00004638 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004639 break;
4640 }
4641
4642 if (NestTy) {
4643 Instruction *Caller = CS.getInstruction();
4644 std::vector<Value*> NewArgs;
4645 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
4646
Devang Patel05988662008-09-25 21:00:45 +00004647 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00004648 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004649
Duncan Sandscdb6d922007-09-17 10:26:40 +00004650 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004651 // mean appending it. Likewise for attributes.
4652
Devang Patel19c87462008-09-26 22:53:05 +00004653 // Add any result attributes.
4654 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00004655 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004656
Duncan Sandscdb6d922007-09-17 10:26:40 +00004657 {
4658 unsigned Idx = 1;
4659 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
4660 do {
4661 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004662 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004663 Value *NestVal = Tramp->getOperand(3);
4664 if (NestVal->getType() != NestTy)
4665 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
4666 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00004667 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00004668 }
4669
4670 if (I == E)
4671 break;
4672
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004673 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004674 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00004675 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004676 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00004677 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00004678
4679 ++Idx, ++I;
4680 } while (1);
4681 }
4682
Devang Patel19c87462008-09-26 22:53:05 +00004683 // Add any function attributes.
4684 if (Attributes Attr = Attrs.getFnAttributes())
4685 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
4686
Duncan Sandscdb6d922007-09-17 10:26:40 +00004687 // The trampoline may have been bitcast to a bogus type (FTy).
4688 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004689 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004690
Duncan Sandscdb6d922007-09-17 10:26:40 +00004691 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00004692 NewTypes.reserve(FTy->getNumParams()+1);
4693
Duncan Sandscdb6d922007-09-17 10:26:40 +00004694 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004695 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004696 {
4697 unsigned Idx = 1;
4698 FunctionType::param_iterator I = FTy->param_begin(),
4699 E = FTy->param_end();
4700
4701 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004702 if (Idx == NestIdx)
4703 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004704 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004705
4706 if (I == E)
4707 break;
4708
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004709 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004710 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004711
4712 ++Idx, ++I;
4713 } while (1);
4714 }
4715
4716 // Replace the trampoline call with a direct call. Let the generic
4717 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +00004718 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +00004719 FTy->isVarArg());
4720 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +00004721 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +00004722 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +00004723 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +00004724 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
4725 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00004726
4727 Instruction *NewCaller;
4728 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00004729 NewCaller = InvokeInst::Create(NewCallee,
4730 II->getNormalDest(), II->getUnwindDest(),
4731 NewArgs.begin(), NewArgs.end(),
4732 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004733 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004734 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004735 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00004736 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
4737 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004738 if (cast<CallInst>(Caller)->isTailCall())
4739 cast<CallInst>(NewCaller)->setTailCall();
4740 cast<CallInst>(NewCaller)->
4741 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004742 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004743 }
Devang Patel9674d152009-10-14 17:29:00 +00004744 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +00004745 Caller->replaceAllUsesWith(NewCaller);
4746 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +00004747 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004748 return 0;
4749 }
4750 }
4751
4752 // Replace the trampoline call with a direct call. Since there is no 'nest'
4753 // parameter, there is no need to adjust the argument list. Let the generic
4754 // code sort out any function type mismatches.
4755 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +00004756 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +00004757 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004758 CS.setCalledFunction(NewCallee);
4759 return CS.getInstruction();
4760}
4761
Reid Spencere4d87aa2006-12-23 06:05:41 +00004762
Chris Lattner473945d2002-05-06 18:06:38 +00004763
Chris Lattner7e708292002-06-25 16:13:24 +00004764Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +00004765 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
4766
4767 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
4768 return ReplaceInstUsesWith(GEP, V);
4769
Chris Lattner620ce142004-05-07 22:09:22 +00004770 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004771
Chris Lattnere87597f2004-10-16 18:11:37 +00004772 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00004773 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004774
Chris Lattner28977af2004-04-05 01:30:19 +00004775 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +00004776 if (TD) {
4777 bool MadeChange = false;
4778 unsigned PtrSize = TD->getPointerSizeInBits();
4779
4780 gep_type_iterator GTI = gep_type_begin(GEP);
4781 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
4782 I != E; ++I, ++GTI) {
4783 if (!isa<SequentialType>(*GTI)) continue;
4784
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004785 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +00004786 // to what we need. If narrower, sign-extend it to what we need. This
4787 // explicit cast can make subsequent optimizations more obvious.
4788 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +00004789 if (OpBits == PtrSize)
4790 continue;
4791
Chris Lattner2345d1d2009-08-30 20:01:10 +00004792 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +00004793 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +00004794 }
Chris Lattnerccf4b342009-08-30 04:49:01 +00004795 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00004796 }
Chris Lattner28977af2004-04-05 01:30:19 +00004797
Chris Lattner90ac28c2002-08-02 19:29:35 +00004798 // Combine Indices - If the source pointer to this getelementptr instruction
4799 // is a getelementptr instruction, combine the indices of the two
4800 // getelementptr instructions into a single instruction.
4801 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +00004802 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +00004803 // Note that if our source is a gep chain itself that we wait for that
4804 // chain to be resolved before we perform this transformation. This
4805 // avoids us creating a TON of code in some cases.
4806 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004807 if (GetElementPtrInst *SrcGEP =
4808 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
4809 if (SrcGEP->getNumOperands() == 2)
4810 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +00004811
Chris Lattner72588fc2007-02-15 22:48:32 +00004812 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00004813
4814 // Find out whether the last index in the source GEP is a sequential idx.
4815 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +00004816 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
4817 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00004818 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00004819
Chris Lattner90ac28c2002-08-02 19:29:35 +00004820 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00004821 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00004822 // Replace: gep (gep %P, long B), long A, ...
4823 // With: T = long A+B; gep %P, T, ...
4824 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004825 Value *Sum;
4826 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
4827 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +00004828 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00004829 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +00004830 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00004831 Sum = SO1;
4832 } else {
Chris Lattnerab984842009-08-30 05:30:55 +00004833 // If they aren't the same type, then the input hasn't been processed
4834 // by the loop above yet (which canonicalizes sequential index types to
4835 // intptr_t). Just avoid transforming this until the input has been
4836 // normalized.
4837 if (SO1->getType() != GO1->getType())
4838 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004839 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +00004840 }
Chris Lattner620ce142004-05-07 22:09:22 +00004841
Chris Lattnerab984842009-08-30 05:30:55 +00004842 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004843 if (Src->getNumOperands() == 2) {
4844 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +00004845 GEP.setOperand(1, Sum);
4846 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +00004847 }
Chris Lattnerab984842009-08-30 05:30:55 +00004848 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +00004849 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +00004850 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +00004851 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00004852 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004853 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00004854 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +00004855 Indices.append(Src->op_begin()+1, Src->op_end());
4856 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00004857 }
4858
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004859 if (!Indices.empty())
4860 return (cast<GEPOperator>(&GEP)->isInBounds() &&
4861 Src->isInBounds()) ?
4862 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
4863 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004864 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +00004865 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +00004866 }
4867
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004868 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
4869 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +00004870 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +00004871
Chris Lattner2de23192009-08-30 20:38:21 +00004872 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
4873 // want to change the gep until the bitcasts are eliminated.
4874 if (getBitCastOperand(X)) {
4875 Worklist.AddValue(PtrOp);
4876 return 0;
4877 }
4878
Chris Lattnerc514c1f2009-11-27 00:29:05 +00004879 bool HasZeroPointerIndex = false;
4880 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
4881 HasZeroPointerIndex = C->isZero();
4882
Chris Lattner963f4ba2009-08-30 20:36:46 +00004883 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
4884 // into : GEP [10 x i8]* X, i32 0, ...
4885 //
4886 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
4887 // into : GEP i8* X, ...
4888 //
4889 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +00004890 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +00004891 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
4892 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004893 if (const ArrayType *CATy =
4894 dyn_cast<ArrayType>(CPTy->getElementType())) {
4895 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
4896 if (CATy->getElementType() == XTy->getElementType()) {
4897 // -> GEP i8* X, ...
4898 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004899 return cast<GEPOperator>(&GEP)->isInBounds() ?
4900 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
4901 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +00004902 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
4903 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +00004904 }
4905
4906 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004907 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +00004908 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004909 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00004910 // At this point, we know that the cast source type is a pointer
4911 // to an array of the same type as the destination pointer
4912 // array. Because the array type is never stepped over (there
4913 // is a leading zero) we can fold the cast into this GEP.
4914 GEP.setOperand(0, X);
4915 return &GEP;
4916 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004917 }
4918 }
Chris Lattnereed48272005-09-13 00:40:14 +00004919 } else if (GEP.getNumOperands() == 2) {
4920 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004921 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
4922 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00004923 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4924 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004925 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +00004926 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4927 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00004928 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00004929 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00004930 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004931 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4932 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004933 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00004934 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004935 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004936 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00004937
4938 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004939 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00004940 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004941 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00004942
Chris Lattner4de84762010-01-04 07:02:48 +00004943 if (TD && isa<ArrayType>(SrcElTy) &&
4944 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00004945 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +00004946 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00004947
4948 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
4949 // allow either a mul, shift, or constant here.
4950 Value *NewIdx = 0;
4951 ConstantInt *Scale = 0;
4952 if (ArrayEltSize == 1) {
4953 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +00004954 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004955 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004956 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004957 Scale = CI;
4958 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
4959 if (Inst->getOpcode() == Instruction::Shl &&
4960 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004961 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
4962 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +00004963 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +00004964 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004965 NewIdx = Inst->getOperand(0);
4966 } else if (Inst->getOpcode() == Instruction::Mul &&
4967 isa<ConstantInt>(Inst->getOperand(1))) {
4968 Scale = cast<ConstantInt>(Inst->getOperand(1));
4969 NewIdx = Inst->getOperand(0);
4970 }
4971 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004972
Chris Lattner7835cdd2005-09-13 18:36:04 +00004973 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004974 // out, perform the transformation. Note, we don't know whether Scale is
4975 // signed or not. We'll use unsigned version of division/modulo
4976 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +00004977 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004978 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004979 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004980 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00004981 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +00004982 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
4983 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004984 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00004985 }
4986
4987 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00004988 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00004989 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00004990 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004991 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4992 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
4993 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00004994 // The NewGEP must be pointer typed, so must the old one -> BitCast
4995 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00004996 }
4997 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004998 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00004999 }
Chris Lattner58407792009-01-09 04:53:57 +00005000
Chris Lattner46cd5a12009-01-09 05:44:56 +00005001 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +00005002 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +00005003 /// Y = gep X, <...constant indices...>
5004 /// into a gep of the original struct. This is important for SROA and alias
5005 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +00005006 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005007 if (TD &&
5008 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00005009 // Determine how much the GEP moves the pointer. We are guaranteed to get
5010 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00005011 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +00005012 int64_t Offset = OffsetV->getSExtValue();
5013
5014 // If this GEP instruction doesn't move the pointer, just replace the GEP
5015 // with a bitcast of the real input to the dest type.
5016 if (Offset == 0) {
5017 // If the bitcast is of an allocation, and the allocation will be
5018 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00005019 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00005020 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00005021 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
5022 if (Instruction *I = visitBitCast(*BCI)) {
5023 if (I != BCI) {
5024 I->takeName(BCI);
5025 BCI->getParent()->getInstList().insert(BCI, I);
5026 ReplaceInstUsesWith(*BCI, I);
5027 }
5028 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00005029 }
Chris Lattner58407792009-01-09 04:53:57 +00005030 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00005031 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00005032 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00005033
5034 // Otherwise, if the offset is non-zero, we need to find out if there is a
5035 // field at Offset in 'A's type. If so, we can pull the cast through the
5036 // GEP.
5037 SmallVector<Value*, 8> NewIndices;
5038 const Type *InTy =
5039 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00005040 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00005041 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
5042 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
5043 NewIndices.end()) :
5044 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
5045 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005046
5047 if (NGEP->getType() == GEP.getType())
5048 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00005049 NGEP->takeName(&GEP);
5050 return new BitCastInst(NGEP, GEP.getType());
5051 }
Chris Lattner58407792009-01-09 04:53:57 +00005052 }
5053 }
5054
Chris Lattner8a2a3112001-12-14 16:52:21 +00005055 return 0;
5056}
5057
Victor Hernandez66284e02009-10-24 04:23:03 +00005058Instruction *InstCombiner::visitFree(Instruction &FI) {
5059 Value *Op = FI.getOperand(1);
5060
5061 // free undef -> unreachable.
5062 if (isa<UndefValue>(Op)) {
5063 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00005064 new StoreInst(ConstantInt::getTrue(FI.getContext()),
5065 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +00005066 return EraseInstFromFunction(FI);
5067 }
5068
5069 // If we have 'free null' delete the instruction. This can happen in stl code
5070 // when lots of inlining happens.
5071 if (isa<ConstantPointerNull>(Op))
5072 return EraseInstFromFunction(FI);
5073
Victor Hernandez046e78c2009-10-26 23:43:48 +00005074 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +00005075 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +00005076 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
5077 if (Op->hasOneUse() && CI->hasOneUse()) {
5078 EraseInstFromFunction(FI);
5079 EraseInstFromFunction(*CI);
5080 return EraseInstFromFunction(*cast<Instruction>(Op));
5081 }
5082 } else {
5083 // Op is a call to malloc
5084 if (Op->hasOneUse()) {
5085 EraseInstFromFunction(FI);
5086 return EraseInstFromFunction(*cast<Instruction>(Op));
5087 }
5088 }
Dan Gohman7f712a12009-10-27 00:11:02 +00005089 }
Victor Hernandez66284e02009-10-24 04:23:03 +00005090
5091 return 0;
5092}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00005093
Chris Lattner3284d1f2007-04-15 00:07:55 +00005094
Chris Lattner2f503e62005-01-31 05:36:43 +00005095
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00005096Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5097 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00005098 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005099 BasicBlock *TrueDest;
5100 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00005101 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005102 !isa<Constant>(X)) {
5103 // Swap Destinations and condition...
5104 BI.setCondition(X);
5105 BI.setSuccessor(0, FalseDest);
5106 BI.setSuccessor(1, TrueDest);
5107 return &BI;
5108 }
5109
Reid Spencere4d87aa2006-12-23 06:05:41 +00005110 // Cannonicalize fcmp_one -> fcmp_oeq
5111 FCmpInst::Predicate FPred; Value *Y;
5112 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00005113 TrueDest, FalseDest)) &&
5114 BI.getCondition()->hasOneUse())
5115 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
5116 FPred == FCmpInst::FCMP_OGE) {
5117 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
5118 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
5119
5120 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005121 BI.setSuccessor(0, FalseDest);
5122 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00005123 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005124 return &BI;
5125 }
5126
5127 // Cannonicalize icmp_ne -> icmp_eq
5128 ICmpInst::Predicate IPred;
5129 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00005130 TrueDest, FalseDest)) &&
5131 BI.getCondition()->hasOneUse())
5132 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
5133 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
5134 IPred == ICmpInst::ICMP_SGE) {
5135 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
5136 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
5137 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00005138 BI.setSuccessor(0, FalseDest);
5139 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00005140 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00005141 return &BI;
5142 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005143
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00005144 return 0;
5145}
Chris Lattner0864acf2002-11-04 16:18:53 +00005146
Chris Lattner46238a62004-07-03 00:26:11 +00005147Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5148 Value *Cond = SI.getCondition();
5149 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5150 if (I->getOpcode() == Instruction::Add)
5151 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5152 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5153 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00005154 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00005155 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00005156 AddRHS));
5157 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005158 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00005159 return &SI;
5160 }
5161 }
5162 return 0;
5163}
5164
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00005165Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005166 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00005167
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005168 if (!EV.hasIndices())
5169 return ReplaceInstUsesWith(EV, Agg);
5170
5171 if (Constant *C = dyn_cast<Constant>(Agg)) {
5172 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005173 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005174
5175 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00005176 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005177
5178 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
5179 // Extract the element indexed by the first index out of the constant
5180 Value *V = C->getOperand(*EV.idx_begin());
5181 if (EV.getNumIndices() > 1)
5182 // Extract the remaining indices out of the constant indexed by the
5183 // first index
5184 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
5185 else
5186 return ReplaceInstUsesWith(EV, V);
5187 }
5188 return 0; // Can't handle other constants
5189 }
5190 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
5191 // We're extracting from an insertvalue instruction, compare the indices
5192 const unsigned *exti, *exte, *insi, *inse;
5193 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
5194 exte = EV.idx_end(), inse = IV->idx_end();
5195 exti != exte && insi != inse;
5196 ++exti, ++insi) {
5197 if (*insi != *exti)
5198 // The insert and extract both reference distinctly different elements.
5199 // This means the extract is not influenced by the insert, and we can
5200 // replace the aggregate operand of the extract with the aggregate
5201 // operand of the insert. i.e., replace
5202 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
5203 // %E = extractvalue { i32, { i32 } } %I, 0
5204 // with
5205 // %E = extractvalue { i32, { i32 } } %A, 0
5206 return ExtractValueInst::Create(IV->getAggregateOperand(),
5207 EV.idx_begin(), EV.idx_end());
5208 }
5209 if (exti == exte && insi == inse)
5210 // Both iterators are at the end: Index lists are identical. Replace
5211 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
5212 // %C = extractvalue { i32, { i32 } } %B, 1, 0
5213 // with "i32 42"
5214 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
5215 if (exti == exte) {
5216 // The extract list is a prefix of the insert list. i.e. replace
5217 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
5218 // %E = extractvalue { i32, { i32 } } %I, 1
5219 // with
5220 // %X = extractvalue { i32, { i32 } } %A, 1
5221 // %E = insertvalue { i32 } %X, i32 42, 0
5222 // by switching the order of the insert and extract (though the
5223 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005224 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
5225 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005226 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
5227 insi, inse);
5228 }
5229 if (insi == inse)
5230 // The insert list is a prefix of the extract list
5231 // We can simply remove the common indices from the extract and make it
5232 // operate on the inserted value instead of the insertvalue result.
5233 // i.e., replace
5234 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
5235 // %E = extractvalue { i32, { i32 } } %I, 1, 0
5236 // with
5237 // %E extractvalue { i32 } { i32 42 }, 0
5238 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
5239 exti, exte);
5240 }
Chris Lattner7e606e22009-11-09 07:07:56 +00005241 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
5242 // We're extracting from an intrinsic, see if we're the only user, which
5243 // allows us to simplify multiple result intrinsics to simpler things that
5244 // just get one value..
5245 if (II->hasOneUse()) {
5246 // Check if we're grabbing the overflow bit or the result of a 'with
5247 // overflow' intrinsic. If it's the latter we can remove the intrinsic
5248 // and replace it with a traditional binary instruction.
5249 switch (II->getIntrinsicID()) {
5250 case Intrinsic::uadd_with_overflow:
5251 case Intrinsic::sadd_with_overflow:
5252 if (*EV.idx_begin() == 0) { // Normal result.
5253 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5254 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5255 EraseInstFromFunction(*II);
5256 return BinaryOperator::CreateAdd(LHS, RHS);
5257 }
5258 break;
5259 case Intrinsic::usub_with_overflow:
5260 case Intrinsic::ssub_with_overflow:
5261 if (*EV.idx_begin() == 0) { // Normal result.
5262 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5263 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5264 EraseInstFromFunction(*II);
5265 return BinaryOperator::CreateSub(LHS, RHS);
5266 }
5267 break;
5268 case Intrinsic::umul_with_overflow:
5269 case Intrinsic::smul_with_overflow:
5270 if (*EV.idx_begin() == 0) { // Normal result.
5271 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5272 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5273 EraseInstFromFunction(*II);
5274 return BinaryOperator::CreateMul(LHS, RHS);
5275 }
5276 break;
5277 default:
5278 break;
5279 }
5280 }
5281 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005282 // Can't simplify extracts from other values. Note that nested extracts are
5283 // already simplified implicitely by the above (extract ( extract (insert) )
5284 // will be translated into extract ( insert ( extract ) ) first and then just
5285 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00005286 return 0;
5287}
5288
Chris Lattnera844fc4c2006-04-10 22:45:52 +00005289
Robert Bocchino1d7456d2006-01-13 22:48:06 +00005290
Chris Lattnerea1c4542004-12-08 23:43:58 +00005291
5292/// TryToSinkInstruction - Try to move the specified instruction from its
5293/// current block into the beginning of DestBlock, which can only happen if it's
5294/// safe to move the instruction past all of the instructions between it and the
5295/// end of its block.
5296static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5297 assert(I->hasOneUse() && "Invariants didn't hold!");
5298
Chris Lattner108e9022005-10-27 17:13:11 +00005299 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00005300 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00005301 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00005302
Chris Lattnerea1c4542004-12-08 23:43:58 +00005303 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00005304 if (isa<AllocaInst>(I) && I->getParent() ==
5305 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00005306 return false;
5307
Chris Lattner96a52a62004-12-09 07:14:34 +00005308 // We can only sink load instructions if there is nothing between the load and
5309 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00005310 if (I->mayReadFromMemory()) {
5311 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00005312 Scan != E; ++Scan)
5313 if (Scan->mayWriteToMemory())
5314 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00005315 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00005316
Dan Gohman02dea8b2008-05-23 21:05:58 +00005317 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00005318
Chris Lattner4bc5f802005-08-08 19:11:57 +00005319 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00005320 ++NumSunkInst;
5321 return true;
5322}
5323
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005324
5325/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
5326/// all reachable code to the worklist.
5327///
5328/// This has a couple of tricks to make the code faster and more powerful. In
5329/// particular, we constant fold and DCE instructions as we go, to avoid adding
5330/// them to the worklist (this significantly speeds up instcombine on code where
5331/// many instructions are dead or constant). Additionally, if we find a branch
5332/// whose condition is a known constant, we only visit the reachable successors.
5333///
Chris Lattner2ee743b2009-10-15 04:59:28 +00005334static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00005335 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00005336 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00005337 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00005338 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00005339 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00005340 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +00005341
5342 std::vector<Instruction*> InstrsForInstCombineWorklist;
5343 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005344
Chris Lattner2ee743b2009-10-15 04:59:28 +00005345 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
5346
Chris Lattner2c7718a2007-03-23 19:17:18 +00005347 while (!Worklist.empty()) {
5348 BB = Worklist.back();
5349 Worklist.pop_back();
5350
5351 // We have now visited this block! If we've already been here, ignore it.
5352 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00005353
Chris Lattner2c7718a2007-03-23 19:17:18 +00005354 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
5355 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005356
Chris Lattner2c7718a2007-03-23 19:17:18 +00005357 // DCE instruction if trivially dead.
5358 if (isInstructionTriviallyDead(Inst)) {
5359 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00005360 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00005361 Inst->eraseFromParent();
5362 continue;
5363 }
5364
5365 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005366 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00005367 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005368 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
5369 << *Inst << '\n');
5370 Inst->replaceAllUsesWith(C);
5371 ++NumConstProp;
5372 Inst->eraseFromParent();
5373 continue;
5374 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00005375
5376
5377
5378 if (TD) {
5379 // See if we can constant fold its operands.
5380 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
5381 i != e; ++i) {
5382 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
5383 if (CE == 0) continue;
5384
5385 // If we already folded this constant, don't try again.
5386 if (!FoldedConstants.insert(CE))
5387 continue;
5388
Chris Lattner7b550cc2009-11-06 04:27:31 +00005389 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00005390 if (NewC && NewC != CE) {
5391 *i = NewC;
5392 MadeIRChange = true;
5393 }
5394 }
5395 }
5396
Devang Patel7fe1dec2008-11-19 18:56:50 +00005397
Chris Lattner67f7d542009-10-12 03:58:40 +00005398 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005399 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00005400
5401 // Recursively visit successors. If this is a branch or switch on a
5402 // constant, only visit the reachable successor.
5403 TerminatorInst *TI = BB->getTerminator();
5404 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
5405 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
5406 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00005407 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00005408 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00005409 continue;
5410 }
5411 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
5412 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
5413 // See if this is an explicit destination.
5414 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
5415 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00005416 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00005417 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00005418 continue;
5419 }
5420
5421 // Otherwise it is the default destination.
5422 Worklist.push_back(SI->getSuccessor(0));
5423 continue;
5424 }
5425 }
5426
5427 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
5428 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005429 }
Chris Lattner67f7d542009-10-12 03:58:40 +00005430
5431 // Once we've found all of the instructions to add to instcombine's worklist,
5432 // add them in reverse order. This way instcombine will visit from the top
5433 // of the function down. This jives well with the way that it adds all uses
5434 // of instructions to the worklist after doing a transformation, thus avoiding
5435 // some N^2 behavior in pathological cases.
5436 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
5437 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00005438
5439 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005440}
5441
Chris Lattnerec9c3582007-03-03 02:04:50 +00005442bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005443 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00005444
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00005445 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
5446 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00005447
Chris Lattnerb3d59702005-07-07 20:40:38 +00005448 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005449 // Do a depth-first traversal of the function, populate the worklist with
5450 // the reachable instructions. Ignore blocks that are not reachable. Keep
5451 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00005452 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00005453 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00005454
Chris Lattnerb3d59702005-07-07 20:40:38 +00005455 // Do a quick scan over the function. If we find any blocks that are
5456 // unreachable, remove any instructions inside of them. This prevents
5457 // the instcombine code from having to deal with some bad special cases.
5458 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5459 if (!Visited.count(BB)) {
5460 Instruction *Term = BB->getTerminator();
5461 while (Term != BB->begin()) { // Remove instrs bottom-up
5462 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00005463
Chris Lattnerbdff5482009-08-23 04:37:46 +00005464 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00005465 // A debug intrinsic shouldn't force another iteration if we weren't
5466 // going to do one without it.
5467 if (!isa<DbgInfoIntrinsic>(I)) {
5468 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005469 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00005470 }
Devang Patel228ebd02009-10-13 22:56:32 +00005471
Devang Patel228ebd02009-10-13 22:56:32 +00005472 // If I is not void type then replaceAllUsesWith undef.
5473 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00005474 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00005475 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00005476 I->eraseFromParent();
5477 }
5478 }
5479 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00005480
Chris Lattner873ff012009-08-30 05:55:36 +00005481 while (!Worklist.isEmpty()) {
5482 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00005483 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00005484
Chris Lattner8c8c66a2006-05-11 17:11:52 +00005485 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00005486 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00005487 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00005488 EraseInstFromFunction(*I);
5489 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005490 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00005491 continue;
5492 }
Chris Lattner62b14df2002-09-02 04:59:56 +00005493
Chris Lattner8c8c66a2006-05-11 17:11:52 +00005494 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005495 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00005496 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005497 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00005498
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005499 // Add operands to the worklist.
5500 ReplaceInstUsesWith(*I, C);
5501 ++NumConstProp;
5502 EraseInstFromFunction(*I);
5503 MadeIRChange = true;
5504 continue;
5505 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00005506
Chris Lattnerea1c4542004-12-08 23:43:58 +00005507 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00005508 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00005509 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00005510 Instruction *UserInst = cast<Instruction>(I->use_back());
5511 BasicBlock *UserParent;
5512
5513 // Get the block the use occurs in.
5514 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
5515 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
5516 else
5517 UserParent = UserInst->getParent();
5518
Chris Lattnerea1c4542004-12-08 23:43:58 +00005519 if (UserParent != BB) {
5520 bool UserIsSuccessor = false;
5521 // See if the user is one of our successors.
5522 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5523 if (*SI == UserParent) {
5524 UserIsSuccessor = true;
5525 break;
5526 }
5527
5528 // If the user is one of our immediate successors, and if that successor
5529 // only has us as a predecessors (we'd have to split the critical edge
5530 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00005531 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00005532 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005533 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00005534 }
5535 }
5536
Chris Lattner74381062009-08-30 07:44:24 +00005537 // Now that we have an instruction, try combining it to simplify it.
5538 Builder->SetInsertPoint(I->getParent(), I);
5539
Reid Spencera9b81012007-03-26 17:44:01 +00005540#ifndef NDEBUG
5541 std::string OrigI;
5542#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00005543 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00005544 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
5545
Chris Lattner90ac28c2002-08-02 19:29:35 +00005546 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00005547 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005548 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005549 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00005550 DEBUG(errs() << "IC: Old = " << *I << '\n'
5551 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00005552
Chris Lattnerf523d062004-06-09 05:08:07 +00005553 // Everything uses the new instruction now.
5554 I->replaceAllUsesWith(Result);
5555
5556 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00005557 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00005558 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005559
Chris Lattner6934a042007-02-11 01:23:03 +00005560 // Move the name to the new instruction first.
5561 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005562
5563 // Insert the new instruction into the basic block...
5564 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00005565 BasicBlock::iterator InsertPos = I;
5566
5567 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5568 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5569 ++InsertPos;
5570
5571 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005572
Chris Lattner7a1e9242009-08-30 06:13:40 +00005573 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00005574 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00005575#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00005576 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
5577 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00005578#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00005579
Chris Lattner90ac28c2002-08-02 19:29:35 +00005580 // If the instruction was modified, it's possible that it is now dead.
5581 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00005582 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00005583 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00005584 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00005585 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00005586 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00005587 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005588 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005589 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005590 }
5591 }
5592
Chris Lattner873ff012009-08-30 05:55:36 +00005593 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005594 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005595}
5596
Chris Lattnerec9c3582007-03-03 02:04:50 +00005597
5598bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00005599 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005600 TD = getAnalysisIfAvailable<TargetData>();
5601
Chris Lattner74381062009-08-30 07:44:24 +00005602
5603 /// Builder - This is an IRBuilder that automatically inserts new
5604 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005605 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00005606 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00005607 InstCombineIRInserter(Worklist));
5608 Builder = &TheBuilder;
5609
Chris Lattnerec9c3582007-03-03 02:04:50 +00005610 bool EverMadeChange = false;
5611
5612 // Iterate while there is work to do.
5613 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00005614 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00005615 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00005616
5617 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00005618 return EverMadeChange;
5619}
5620
Brian Gaeke96d4bf72004-07-27 17:43:21 +00005621FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005622 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005623}