blob: 3393f9b3dd8b856c7be478babf27c63917a098c2 [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");
67STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000069
Chris Lattnerdd841ae2002-04-18 17:39:14 +000070
Dan Gohman844731a2008-05-13 00:00:25 +000071char InstCombiner::ID = 0;
72static RegisterPass<InstCombiner>
73X("instcombine", "Combine redundant instructions");
74
Chris Lattnere0b4b722010-01-04 07:17:19 +000075void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addPreservedID(LCSSAID);
77 AU.setPreservesCFG();
78}
79
80
Chris Lattnerc8802d22003-03-11 00:12:48 +000081// isOnlyUse - Return true if this instruction will be deleted if we stop using
82// it.
83static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +000084 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +000085}
86
Chris Lattner4cb170c2004-02-23 06:38:22 +000087// getPromotedType - Return the specified type promoted as it would be to pass
88// though a va_arg area...
89static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +000090 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
91 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +000092 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +000093 }
Reid Spencera54b7cb2007-01-12 07:05:14 +000094 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +000095}
96
Chris Lattnerc22d4d12009-11-10 07:23:37 +000097/// ShouldChangeType - Return true if it is desirable to convert a computation
98/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
99/// type for example, or from a smaller to a larger illegal type.
Chris Lattner80f43d32010-01-04 07:53:58 +0000100bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000101 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
102
103 // If we don't have TD, we don't know if the source/dest are legal.
104 if (!TD) return false;
105
106 unsigned FromWidth = From->getPrimitiveSizeInBits();
107 unsigned ToWidth = To->getPrimitiveSizeInBits();
108 bool FromLegal = TD->isLegalInteger(FromWidth);
109 bool ToLegal = TD->isLegalInteger(ToWidth);
110
111 // If this is a legal integer from type, and the result would be an illegal
112 // type, don't do the transformation.
113 if (FromLegal && !ToLegal)
114 return false;
115
116 // Otherwise, if both are illegal, do not increase the size of the result. We
117 // do allow things like i160 -> i64, but not i64 -> i160.
118 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
119 return false;
120
121 return true;
122}
123
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000124/// getBitCastOperand - If the specified operand is a CastInst, a constant
125/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
126/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000127static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000128 if (Operator *O = dyn_cast<Operator>(V)) {
129 if (O->getOpcode() == Instruction::BitCast)
130 return O->getOperand(0);
131 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
132 if (GEP->hasAllZeroIndices())
133 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000134 }
Chris Lattnereed48272005-09-13 00:40:14 +0000135 return 0;
136}
137
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000138
Chris Lattner33a61132006-05-06 09:00:16 +0000139
Chris Lattner4f98c562003-03-10 21:43:22 +0000140// SimplifyCommutative - This performs a few simplifications for commutative
141// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000142//
Chris Lattner4f98c562003-03-10 21:43:22 +0000143// 1. Order operands such that they are listed from right (least complex) to
144// left (most complex). This puts constants before unary operators before
145// binary operators.
146//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000147// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
148// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000149//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000150bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000151 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000152 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000153 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000154
Chris Lattner4f98c562003-03-10 21:43:22 +0000155 if (!I.isAssociative()) return Changed;
156 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000157 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
158 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
159 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000160 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000161 cast<Constant>(I.getOperand(1)),
162 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000163 I.setOperand(0, Op->getOperand(0));
164 I.setOperand(1, Folded);
165 return true;
166 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
167 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
168 isOnlyUse(Op) && isOnlyUse(Op1)) {
169 Constant *C1 = cast<Constant>(Op->getOperand(1));
170 Constant *C2 = cast<Constant>(Op1->getOperand(1));
171
172 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000173 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000174 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000175 Op1->getOperand(0),
176 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000177 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000178 I.setOperand(0, New);
179 I.setOperand(1, Folded);
180 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000181 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000182 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000183 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000184}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000185
Chris Lattner8d969642003-03-10 23:06:50 +0000186// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
187// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000188//
Chris Lattner02446fc2010-01-04 07:37:31 +0000189Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000190 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000191 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000192
Chris Lattner0ce85802004-12-14 20:08:06 +0000193 // Constants can be considered to be negated values if they can be folded.
194 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000195 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000196
197 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
198 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000199 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000200
Chris Lattner8d969642003-03-10 23:06:50 +0000201 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000202}
203
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000204// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
205// instruction if the LHS is a constant negative zero (which is the 'negate'
206// form).
207//
Dan Gohman186a6362009-08-12 16:04:34 +0000208static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000209 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000210 return BinaryOperator::getFNegArgument(V);
211
212 // Constants can be considered to be negated values if they can be folded.
213 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000214 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000215
216 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
217 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000218 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000219
220 return 0;
221}
222
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000223/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
224/// returning the kind and providing the out parameter results if we
225/// successfully match.
226static SelectPatternFlavor
227MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
228 SelectInst *SI = dyn_cast<SelectInst>(V);
229 if (SI == 0) return SPF_UNKNOWN;
230
231 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
232 if (ICI == 0) return SPF_UNKNOWN;
233
234 LHS = ICI->getOperand(0);
235 RHS = ICI->getOperand(1);
236
237 // (icmp X, Y) ? X : Y
238 if (SI->getTrueValue() == ICI->getOperand(0) &&
239 SI->getFalseValue() == ICI->getOperand(1)) {
240 switch (ICI->getPredicate()) {
241 default: return SPF_UNKNOWN; // Equality.
242 case ICmpInst::ICMP_UGT:
243 case ICmpInst::ICMP_UGE: return SPF_UMAX;
244 case ICmpInst::ICMP_SGT:
245 case ICmpInst::ICMP_SGE: return SPF_SMAX;
246 case ICmpInst::ICMP_ULT:
247 case ICmpInst::ICMP_ULE: return SPF_UMIN;
248 case ICmpInst::ICMP_SLT:
249 case ICmpInst::ICMP_SLE: return SPF_SMIN;
250 }
251 }
252
253 // (icmp X, Y) ? Y : X
254 if (SI->getTrueValue() == ICI->getOperand(1) &&
255 SI->getFalseValue() == ICI->getOperand(0)) {
256 switch (ICI->getPredicate()) {
257 default: return SPF_UNKNOWN; // Equality.
258 case ICmpInst::ICMP_UGT:
259 case ICmpInst::ICMP_UGE: return SPF_UMIN;
260 case ICmpInst::ICMP_SGT:
261 case ICmpInst::ICMP_SGE: return SPF_SMIN;
262 case ICmpInst::ICMP_ULT:
263 case ICmpInst::ICMP_ULE: return SPF_UMAX;
264 case ICmpInst::ICMP_SLT:
265 case ICmpInst::ICMP_SLE: return SPF_SMAX;
266 }
267 }
268
269 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
270
271 return SPF_UNKNOWN;
272}
273
Chris Lattner48b59ec2009-10-26 15:40:07 +0000274/// isFreeToInvert - Return true if the specified value is free to invert (apply
275/// ~ to). This happens in cases where the ~ can be eliminated.
276static inline bool isFreeToInvert(Value *V) {
277 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000278 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000279 return true;
280
281 // Constants can be considered to be not'ed values.
282 if (isa<ConstantInt>(V))
283 return true;
284
285 // Compares can be inverted if they have a single use.
286 if (CmpInst *CI = dyn_cast<CmpInst>(V))
287 return CI->hasOneUse();
288
289 return false;
290}
291
292static inline Value *dyn_castNotVal(Value *V) {
293 // If this is not(not(x)) don't return that this is a not: we want the two
294 // not's to be folded first.
295 if (BinaryOperator::isNot(V)) {
296 Value *Operand = BinaryOperator::getNotArgument(V);
297 if (!isFreeToInvert(Operand))
298 return Operand;
299 }
Chris Lattner8d969642003-03-10 23:06:50 +0000300
301 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000302 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000303 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000304 return 0;
305}
306
Chris Lattner48b59ec2009-10-26 15:40:07 +0000307
308
Chris Lattnerc8802d22003-03-11 00:12:48 +0000309// dyn_castFoldableMul - If this value is a multiply that can be folded into
310// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000311// non-constant operand of the multiply, and set CST to point to the multiplier.
312// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000313//
Dan Gohman186a6362009-08-12 16:04:34 +0000314static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000315 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000316 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000317 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000318 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000319 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000320 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000321 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000322 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000323 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000324 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000325 CST = ConstantInt::get(V->getType()->getContext(),
326 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000327 return I->getOperand(0);
328 }
329 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000330 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000331}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000332
Reid Spencer7177c3a2007-03-25 05:33:51 +0000333/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000334static Constant *AddOne(Constant *C) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000335 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000336}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000337/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000338static Constant *SubOne(ConstantInt *C) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000339 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000340}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000341/// MultiplyOverflows - True if the multiply can not be expressed in an int
342/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000343static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000344 uint32_t W = C1->getBitWidth();
345 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
346 if (sign) {
347 LHSExt.sext(W * 2);
348 RHSExt.sext(W * 2);
349 } else {
350 LHSExt.zext(W * 2);
351 RHSExt.zext(W * 2);
352 }
353
354 APInt MulExt = LHSExt * RHSExt;
355
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000356 if (!sign)
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000357 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000358
359 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
360 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
361 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000362}
Chris Lattner955f3312004-09-28 21:48:02 +0000363
Reid Spencere7816b52007-03-08 01:52:58 +0000364
Dan Gohman45b4e482008-05-19 22:14:15 +0000365
Chris Lattner564a7272003-08-13 19:01:45 +0000366/// AssociativeOpt - Perform an optimization on an associative operator. This
367/// function is designed to check a chain of associative operators for a
368/// potential to apply a certain optimization. Since the optimization may be
369/// applicable if the expression was reassociated, this checks the chain, then
370/// reassociates the expression as necessary to expose the optimization
371/// opportunity. This makes use of a special Functor, which must define
372/// 'shouldApply' and 'apply' methods.
373///
374template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +0000375static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +0000376 unsigned Opcode = Root.getOpcode();
377 Value *LHS = Root.getOperand(0);
378
379 // Quick check, see if the immediate LHS matches...
380 if (F.shouldApply(LHS))
381 return F.apply(Root);
382
383 // Otherwise, if the LHS is not of the same opcode as the root, return.
384 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000385 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000386 // Should we apply this transform to the RHS?
387 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
388
389 // If not to the RHS, check to see if we should apply to the LHS...
390 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
391 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
392 ShouldApply = true;
393 }
394
395 // If the functor wants to apply the optimization to the RHS of LHSI,
396 // reassociate the expression from ((? op A) op B) to (? op (A op B))
397 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +0000398 // Now all of the instructions are in the current basic block, go ahead
399 // and perform the reassociation.
400 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
401
402 // First move the selected RHS to the LHS of the root...
403 Root.setOperand(0, LHSI->getOperand(1));
404
405 // Make what used to be the LHS of the root be the user of the root...
406 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000407 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000408 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000409 return 0;
410 }
Chris Lattner65725312004-04-16 18:08:07 +0000411 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000412 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000413 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +0000414 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +0000415 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000416
417 // Now propagate the ExtraOperand down the chain of instructions until we
418 // get to LHSI.
419 while (TmpLHSI != LHSI) {
420 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000421 // Move the instruction to immediately before the chain we are
422 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +0000423 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +0000424 ARI = NextLHSI;
425
Chris Lattner564a7272003-08-13 19:01:45 +0000426 Value *NextOp = NextLHSI->getOperand(1);
427 NextLHSI->setOperand(1, ExtraOperand);
428 TmpLHSI = NextLHSI;
429 ExtraOperand = NextOp;
430 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000431
Chris Lattner564a7272003-08-13 19:01:45 +0000432 // Now that the instructions are reassociated, have the functor perform
433 // the transformation...
434 return F.apply(Root);
435 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000436
Chris Lattner564a7272003-08-13 19:01:45 +0000437 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
438 }
439 return 0;
440}
441
Dan Gohman844731a2008-05-13 00:00:25 +0000442namespace {
Chris Lattner564a7272003-08-13 19:01:45 +0000443
Nick Lewycky02d639f2008-05-23 04:34:58 +0000444// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +0000445struct AddRHS {
446 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +0000447 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +0000448 bool shouldApply(Value *LHS) const { return LHS == RHS; }
449 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +0000450 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +0000451 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +0000452 }
453};
454
455// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
456// iff C1&C2 == 0
457struct AddMaskingAnd {
458 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +0000459 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +0000460 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000461 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +0000462 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000463 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000464 }
465 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000466 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000467 }
468};
469
Dan Gohman844731a2008-05-13 00:00:25 +0000470}
471
Chris Lattner6e7ba452005-01-01 16:22:27 +0000472static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000473 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000474 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000475 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000476
Chris Lattner2eefe512004-04-09 19:05:30 +0000477 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000478 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
479 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000480
Chris Lattner2eefe512004-04-09 19:05:30 +0000481 if (Constant *SOC = dyn_cast<Constant>(SO)) {
482 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000483 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
484 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000485 }
486
487 Value *Op0 = SO, *Op1 = ConstOperand;
488 if (!ConstIsRHS)
489 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000490
Chris Lattner6e7ba452005-01-01 16:22:27 +0000491 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000492 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
493 SO->getName()+".op");
494 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
495 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
496 SO->getName()+".cmp");
497 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
498 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
499 SO->getName()+".cmp");
500 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000501}
502
503// FoldOpIntoSelect - Given an instruction with a select as one operand and a
504// constant as the other operand, try to fold the binary operator into the
505// select arguments. This also works for Cast instructions, which obviously do
506// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000507Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000508 // Don't modify shared select instructions
509 if (!SI->hasOneUse()) return 0;
510 Value *TV = SI->getOperand(1);
511 Value *FV = SI->getOperand(2);
512
513 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000514 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +0000515 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000516
Chris Lattner80f43d32010-01-04 07:53:58 +0000517 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
518 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000519
Gabor Greif051a9502008-04-06 20:25:17 +0000520 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
521 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000522 }
523 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000524}
525
Chris Lattner4e998b22004-09-29 05:07:12 +0000526
Chris Lattner5d1704d2009-09-27 19:57:57 +0000527/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
528/// has a PHI node as operand #0, see if we can fold the instruction into the
529/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000530///
531/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
532/// that would normally be unprofitable because they strongly encourage jump
533/// threading.
534Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
535 bool AllowAggressive) {
536 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000537 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000538 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000539 if (NumPHIValues == 0 ||
540 // We normally only transform phis with a single use, unless we're trying
541 // hard to make jump threading happen.
542 (!PN->hasOneUse() && !AllowAggressive))
543 return 0;
544
545
Chris Lattner5d1704d2009-09-27 19:57:57 +0000546 // Check to see if all of the operands of the PHI are simple constants
547 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000548 // remember the BB it is in. If there is more than one or if *it* is a PHI,
549 // bail out. We don't do arbitrary constant expressions here because moving
550 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000551 BasicBlock *NonConstBB = 0;
552 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000553 if (!isa<Constant>(PN->getIncomingValue(i)) ||
554 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000555 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000556 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000557 NonConstBB = PN->getIncomingBlock(i);
558
559 // If the incoming non-constant value is in I's block, we have an infinite
560 // loop.
561 if (NonConstBB == I.getParent())
562 return 0;
563 }
564
565 // If there is exactly one non-constant value, we can insert a copy of the
566 // operation in that block. However, if this is a critical edge, we would be
567 // inserting the computation one some other paths (e.g. inside a loop). Only
568 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000569 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000570 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
571 if (!BI || !BI->isUnconditional()) return 0;
572 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000573
574 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000575 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000576 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000577 InsertNewInstBefore(NewPN, *PN);
578 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000579
580 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000581 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
582 // We only currently try to fold the condition of a select when it is a phi,
583 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000584 Value *TrueV = SI->getTrueValue();
585 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000586 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000587 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000588 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000589 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
590 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000591 Value *InV = 0;
592 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000593 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000594 } else {
595 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000596 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
597 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000598 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000599 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000600 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000601 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000602 }
603 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000604 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000605 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000606 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000607 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000608 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000609 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000610 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000611 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000612 } else {
613 assert(PN->getIncomingBlock(i) == NonConstBB);
614 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000615 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000616 PN->getIncomingValue(i), C, "phitmp",
617 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000618 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000619 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000620 CI->getPredicate(),
621 PN->getIncomingValue(i), C, "phitmp",
622 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000623 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000624 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000625
626 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000627 }
628 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000629 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000630 } else {
631 CastInst *CI = cast<CastInst>(&I);
632 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000633 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000634 Value *InV;
635 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000636 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000637 } else {
638 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000639 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000640 I.getType(), "phitmp",
641 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000642 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000643 }
644 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000645 }
646 }
647 return ReplaceInstUsesWith(I, NewPN);
648}
649
Chris Lattner2454a2e2008-01-29 06:52:45 +0000650
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000651/// WillNotOverflowSignedAdd - Return true if we can prove that:
652/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
653/// This basically requires proving that the add in the original type would not
654/// overflow to change the sign bit or have a carry out.
655bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
656 // There are different heuristics we can use for this. Here are some simple
657 // ones.
658
659 // Add has the property that adding any two 2's complement numbers can only
660 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000661 // have at least two sign bits, we know that the addition of the two values
662 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000663 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
664 return true;
665
666
667 // If one of the operands only has one non-zero bit, and if the other operand
668 // has a known-zero bit in a more significant place than it (not including the
669 // sign bit) the ripple may go up to and fill the zero, but won't change the
670 // sign. For example, (X & ~4) + 1.
671
672 // TODO: Implement.
673
674 return false;
675}
676
Chris Lattner2454a2e2008-01-29 06:52:45 +0000677
Chris Lattner7e708292002-06-25 16:13:24 +0000678Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000679 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000680 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000681
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000682 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
683 I.hasNoUnsignedWrap(), TD))
684 return ReplaceInstUsesWith(I, V);
685
686
Chris Lattner66331a42004-04-10 22:01:55 +0000687 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +0000688 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000689 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000690 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +0000691 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +0000692 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000693 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000694
695 // See if SimplifyDemandedBits can simplify this. This handles stuff like
696 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +0000697 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000698 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +0000699
Eli Friedman709b33d2009-07-13 22:27:52 +0000700 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +0000701 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Chris Lattner4de84762010-01-04 07:02:48 +0000702 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +0000703 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +0000704 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000705
706 if (isa<PHINode>(LHS))
707 if (Instruction *NV = FoldOpIntoPhi(I))
708 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +0000709
Chris Lattner4f637d42006-01-06 17:59:59 +0000710 ConstantInt *XorRHS = 0;
711 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +0000712 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000713 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000714 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000715 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +0000716
Zhou Sheng4351c642007-04-02 08:20:41 +0000717 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000718 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
719 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +0000720 do {
721 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +0000722 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
723 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000724 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
725 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +0000726 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +0000727 if (!MaskedValueIsZero(XorLHS,
728 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +0000729 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000730 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000731 }
732 }
733 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000734 C0080Val = APIntOps::lshr(C0080Val, Size);
735 CFF80Val = APIntOps::ashr(CFF80Val, Size);
736 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +0000737
Reid Spencer35c38852007-03-28 01:36:16 +0000738 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000739 // with funny bit widths then this switch statement should be removed. It
740 // is just here to get the size of the "middle" type back up to something
741 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +0000742 const Type *MiddleType = 0;
743 switch (Size) {
744 default: break;
Chris Lattner4de84762010-01-04 07:02:48 +0000745 case 32:
746 case 16:
747 case 8: MiddleType = IntegerType::get(I.getContext(), Size); break;
Reid Spencer35c38852007-03-28 01:36:16 +0000748 }
749 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +0000750 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +0000751 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +0000752 }
753 }
Chris Lattner66331a42004-04-10 22:01:55 +0000754 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000755
Chris Lattner4de84762010-01-04 07:02:48 +0000756 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000757 return BinaryOperator::CreateXor(LHS, RHS);
758
Nick Lewycky7d26bd82008-05-23 04:39:38 +0000759 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000760 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +0000761 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +0000762 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +0000763
764 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
765 if (RHSI->getOpcode() == Instruction::Sub)
766 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
767 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
768 }
769 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
770 if (LHSI->getOpcode() == Instruction::Sub)
771 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
772 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
773 }
Robert Bocchino71698282004-07-27 21:02:21 +0000774 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000775
Chris Lattner5c4afb92002-05-08 22:46:53 +0000776 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +0000777 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000778 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +0000779 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +0000780 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +0000781 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +0000782 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +0000783 }
Chris Lattnerdd12f962008-02-17 21:03:36 +0000784 }
785
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000786 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +0000787 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000788
789 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000790 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000791 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000792 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000793
Misha Brukmanfd939082005-04-21 23:48:37 +0000794
Chris Lattner50af16a2004-11-13 19:50:12 +0000795 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +0000796 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000797 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000798 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000799
800 // X*C1 + X*C2 --> X * (C1+C2)
801 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +0000802 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000803 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000804 }
805
806 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000807 if (dyn_castFoldableMul(RHS, C2) == LHS)
808 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000809
Chris Lattnere617c9e2007-01-05 02:17:46 +0000810 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +0000811 if (dyn_castNotVal(LHS) == RHS ||
812 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +0000813 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +0000814
Chris Lattnerad3448c2003-02-18 19:57:07 +0000815
Chris Lattner564a7272003-08-13 19:01:45 +0000816 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +0000817 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
818 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +0000819 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +0000820
821 // A+B --> A|B iff A and B have no bits set in common.
822 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
823 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
824 APInt LHSKnownOne(IT->getBitWidth(), 0);
825 APInt LHSKnownZero(IT->getBitWidth(), 0);
826 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
827 if (LHSKnownZero != 0) {
828 APInt RHSKnownOne(IT->getBitWidth(), 0);
829 APInt RHSKnownZero(IT->getBitWidth(), 0);
830 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
831
832 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +0000833 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +0000834 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +0000835 }
836 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000837
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000838 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +0000839 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000840 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +0000841 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
842 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000843 if (W != Y) {
844 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000845 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000846 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000847 std::swap(W, X);
848 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000849 std::swap(Y, Z);
850 std::swap(W, X);
851 }
852 }
853
854 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +0000855 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000856 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000857 }
858 }
859 }
860
Chris Lattner6b032052003-10-02 15:11:26 +0000861 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +0000862 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +0000863 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +0000864 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000865
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000866 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +0000867 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000868 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000869 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000870 if (Anded == CRHS) {
871 // See if all bits from the first bit set in the Add RHS up are included
872 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000873 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000874
875 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000876 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000877
878 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000879 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +0000880
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000881 if (AddRHSHighBits == AddRHSHighBitsAnd) {
882 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +0000883 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000884 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000885 }
886 }
887 }
888
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000889 // Try to fold constant add into select arguments.
890 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner80f43d32010-01-04 07:53:58 +0000891 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000892 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000893 }
894
Chris Lattner42790482007-12-20 01:56:58 +0000895 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +0000896 {
897 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000898 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000899 if (!SI) {
900 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000901 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000902 }
Chris Lattner42790482007-12-20 01:56:58 +0000903 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +0000904 Value *TV = SI->getTrueValue();
905 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +0000906 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000907
908 // Can we fold the add into the argument of the select?
909 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +0000910 if (match(FV, m_Zero()) &&
911 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000912 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000913 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +0000914 if (match(TV, m_Zero()) &&
915 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000916 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000917 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +0000918 }
919 }
Andrew Lenharth16d79552006-09-19 18:24:51 +0000920
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000921 // Check for (add (sext x), y), see if we can merge this into an
922 // integer add followed by a sext.
923 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
924 // (add (sext x), cst) --> (sext (add x, cst'))
925 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
926 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000927 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000928 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000929 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000930 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
931 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000932 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
933 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000934 return new SExtInst(NewAdd, I.getType());
935 }
936 }
937
938 // (add (sext x), (sext y)) --> (sext (add int x, y))
939 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
940 // Only do this if x/y have the same type, if at last one of them has a
941 // single use (so we don't increase the number of sexts), and if the
942 // integer add will not overflow.
943 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
944 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
945 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
946 RHSConv->getOperand(0))) {
947 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000948 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
949 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000950 return new SExtInst(NewAdd, I.getType());
951 }
952 }
953 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000954
955 return Changed ? &I : 0;
956}
957
958Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
959 bool Changed = SimplifyCommutative(I);
960 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
961
962 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
963 // X + 0 --> X
964 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000965 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000966 (I.getType())->getValueAPF()))
967 return ReplaceInstUsesWith(I, LHS);
968 }
969
970 if (isa<PHINode>(LHS))
971 if (Instruction *NV = FoldOpIntoPhi(I))
972 return NV;
973 }
974
975 // -A + B --> B - A
976 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000977 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000978 return BinaryOperator::CreateFSub(RHS, LHSV);
979
980 // A + -B --> A - B
981 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000982 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000983 return BinaryOperator::CreateFSub(LHS, V);
984
985 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
986 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
987 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
988 return ReplaceInstUsesWith(I, LHS);
989
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000990 // Check for (add double (sitofp x), y), see if we can merge this into an
991 // integer add followed by a promotion.
992 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
993 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
994 // ... if the constant fits in the integer value. This is useful for things
995 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
996 // requires a constant pool load, and generally allows the add to be better
997 // instcombined.
998 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
999 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001000 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001001 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001002 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001003 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1004 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00001005 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1006 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001007 return new SIToFPInst(NewAdd, I.getType());
1008 }
1009 }
1010
1011 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1012 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1013 // Only do this if x/y have the same type, if at last one of them has a
1014 // single use (so we don't increase the number of int->fp conversions),
1015 // and if the integer add will not overflow.
1016 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1017 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1018 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1019 RHSConv->getOperand(0))) {
1020 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00001021 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00001022 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001023 return new SIToFPInst(NewAdd, I.getType());
1024 }
1025 }
1026 }
1027
Chris Lattner7e708292002-06-25 16:13:24 +00001028 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001029}
1030
Chris Lattner092543c2009-11-04 08:05:20 +00001031
1032/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
1033/// code necessary to compute the offset from the base pointer (without adding
1034/// in the base pointer). Return the result as a signed integer of intptr size.
Chris Lattner02446fc2010-01-04 07:37:31 +00001035Value *InstCombiner::EmitGEPOffset(User *GEP) {
1036 TargetData &TD = *getTargetData();
Chris Lattner092543c2009-11-04 08:05:20 +00001037 gep_type_iterator GTI = gep_type_begin(GEP);
1038 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
1039 Value *Result = Constant::getNullValue(IntPtrTy);
1040
1041 // Build a mask for high order bits.
1042 unsigned IntPtrWidth = TD.getPointerSizeInBits();
1043 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
1044
1045 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
1046 ++i, ++GTI) {
1047 Value *Op = *i;
1048 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
1049 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
1050 if (OpC->isZero()) continue;
1051
1052 // Handle a struct index, which adds its field offset to the pointer.
1053 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1054 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1055
Chris Lattner02446fc2010-01-04 07:37:31 +00001056 Result = Builder->CreateAdd(Result,
1057 ConstantInt::get(IntPtrTy, Size),
1058 GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +00001059 continue;
1060 }
1061
1062 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
1063 Constant *OC =
1064 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
1065 Scale = ConstantExpr::getMul(OC, Scale);
1066 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +00001067 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +00001068 continue;
1069 }
1070 // Convert to correct type.
1071 if (Op->getType() != IntPtrTy)
Chris Lattner02446fc2010-01-04 07:37:31 +00001072 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattner092543c2009-11-04 08:05:20 +00001073 if (Size != 1) {
1074 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
1075 // We'll let instcombine(mul) convert this to a shl if possible.
Chris Lattner02446fc2010-01-04 07:37:31 +00001076 Op = Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattner092543c2009-11-04 08:05:20 +00001077 }
1078
1079 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +00001080 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +00001081 }
1082 return Result;
1083}
1084
1085
Chris Lattner092543c2009-11-04 08:05:20 +00001086
1087
1088/// Optimize pointer differences into the same array into a size. Consider:
1089/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1090/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1091///
1092Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1093 const Type *Ty) {
1094 assert(TD && "Must have target data info for this");
1095
1096 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1097 // this.
1098 bool Swapped;
Chris Lattner85c1c962010-01-01 22:42:29 +00001099 GetElementPtrInst *GEP = 0;
1100 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +00001101
Chris Lattner85c1c962010-01-01 22:42:29 +00001102 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
1103 // For now we require one side to be the base pointer "A" or a constant
1104 // expression derived from it.
1105 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
1106 // (gep X, ...) - X
1107 if (LHSGEP->getOperand(0) == RHS) {
1108 GEP = LHSGEP;
1109 Swapped = false;
1110 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
1111 // (gep X, ...) - (ce_gep X, ...)
1112 if (CE->getOpcode() == Instruction::GetElementPtr &&
1113 LHSGEP->getOperand(0) == CE->getOperand(0)) {
1114 CstGEP = CE;
1115 GEP = LHSGEP;
1116 Swapped = false;
1117 }
1118 }
1119 }
1120
1121 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
1122 // X - (gep X, ...)
1123 if (RHSGEP->getOperand(0) == LHS) {
1124 GEP = RHSGEP;
1125 Swapped = true;
1126 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
1127 // (ce_gep X, ...) - (gep X, ...)
1128 if (CE->getOpcode() == Instruction::GetElementPtr &&
1129 RHSGEP->getOperand(0) == CE->getOperand(0)) {
1130 CstGEP = CE;
1131 GEP = RHSGEP;
1132 Swapped = true;
1133 }
1134 }
1135 }
1136
1137 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00001138 return 0;
1139
Chris Lattner092543c2009-11-04 08:05:20 +00001140 // Emit the offset of the GEP and an intptr_t.
Chris Lattner02446fc2010-01-04 07:37:31 +00001141 Value *Result = EmitGEPOffset(GEP);
Chris Lattner85c1c962010-01-01 22:42:29 +00001142
1143 // If we had a constant expression GEP on the other side offsetting the
1144 // pointer, subtract it from the offset we have.
1145 if (CstGEP) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001146 Value *CstOffset = EmitGEPOffset(CstGEP);
Chris Lattner85c1c962010-01-01 22:42:29 +00001147 Result = Builder->CreateSub(Result, CstOffset);
1148 }
1149
Chris Lattner092543c2009-11-04 08:05:20 +00001150
1151 // If we have p - gep(p, ...) then we have to negate the result.
1152 if (Swapped)
1153 Result = Builder->CreateNeg(Result, "diff.neg");
1154
1155 return Builder->CreateIntCast(Result, Ty, true);
1156}
1157
1158
Chris Lattner7e708292002-06-25 16:13:24 +00001159Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001160 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001161
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001162 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001163 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001164
Chris Lattner3bf68152009-12-21 04:04:05 +00001165 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
1166 if (Value *V = dyn_castNegVal(Op1)) {
1167 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1168 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1169 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1170 return Res;
1171 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001172
Chris Lattnere87597f2004-10-16 18:11:37 +00001173 if (isa<UndefValue>(Op0))
1174 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1175 if (isa<UndefValue>(Op1))
1176 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner4de84762010-01-04 07:02:48 +00001177 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner092543c2009-11-04 08:05:20 +00001178 return BinaryOperator::CreateXor(Op0, Op1);
1179
Chris Lattnerd65460f2003-11-05 01:06:05 +00001180 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00001181 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00001182 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00001183 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001184
Chris Lattnerd65460f2003-11-05 01:06:05 +00001185 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001186 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001187 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00001188 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00001189
Chris Lattner76b7a062007-01-15 07:02:54 +00001190 // -(X >>u 31) -> (X >>s 31)
1191 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00001192 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001193 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001194 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001195 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00001196 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001197 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00001198 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001199 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001200 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00001201 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00001202 }
1203 }
Chris Lattner092543c2009-11-04 08:05:20 +00001204 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001205 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1206 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001207 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00001208 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00001209 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001210 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001211 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00001212 }
1213 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001214 }
1215 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001216 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001217
1218 // Try to fold constant sub into select arguments.
1219 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00001220 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001221 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00001222
1223 // C - zext(bool) -> bool ? C - 1 : C
1224 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattner4de84762010-01-04 07:02:48 +00001225 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +00001226 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00001227 }
1228
Chris Lattner43d84d62005-04-07 16:15:25 +00001229 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001230 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00001231 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001232 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001233 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001234 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001235 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001236 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001237 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1238 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1239 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00001240 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00001241 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00001242 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001243 }
1244
Chris Lattnerfd059242003-10-15 16:48:29 +00001245 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001246 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1247 // is not used by anyone else...
1248 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001249 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00001250 // Swap the two operands of the subexpr...
1251 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1252 Op1I->setOperand(0, IIOp1);
1253 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001254
Chris Lattnera2881962003-02-18 19:28:33 +00001255 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001256 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001257 }
1258
1259 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1260 //
1261 if (Op1I->getOpcode() == Instruction::And &&
1262 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1263 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1264
Chris Lattner74381062009-08-30 07:44:24 +00001265 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001266 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001267 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001268
Reid Spencerac5209e2006-10-16 23:08:08 +00001269 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00001270 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00001271 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00001272 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00001273 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001274 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001275 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00001276
Chris Lattnerad3448c2003-02-18 19:57:07 +00001277 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001278 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00001279 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001280 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001281 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00001282 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001283 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001284 }
Chris Lattner40371712002-05-09 01:29:19 +00001285 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001286 }
Chris Lattnera2881962003-02-18 19:28:33 +00001287
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001288 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1289 if (Op0I->getOpcode() == Instruction::Add) {
1290 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1291 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1292 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1293 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1294 } else if (Op0I->getOpcode() == Instruction::Sub) {
1295 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001296 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001297 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001298 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001299 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001300
Chris Lattner50af16a2004-11-13 19:50:12 +00001301 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00001302 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00001303 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00001304 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001305
Chris Lattner50af16a2004-11-13 19:50:12 +00001306 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00001307 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001308 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00001309 }
Chris Lattner092543c2009-11-04 08:05:20 +00001310
1311 // Optimize pointer differences into the same array into a size. Consider:
1312 // &A[10] - &A[0]: we should compile this to "10".
1313 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00001314 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001315 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1316 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00001317 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1318 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001319
1320 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001321 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1322 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1323 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1324 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001325 }
1326
Chris Lattner3f5b8772002-05-06 16:14:14 +00001327 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001328}
1329
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001330Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1331 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1332
1333 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00001334 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001335 return BinaryOperator::CreateFAdd(Op0, V);
1336
1337 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1338 if (Op1I->getOpcode() == Instruction::FAdd) {
1339 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001340 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001341 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001342 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001343 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001344 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001345 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001346 }
1347
1348 return 0;
1349}
1350
Chris Lattner7e708292002-06-25 16:13:24 +00001351Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001352 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00001353 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001354
Chris Lattnera2498472009-10-11 21:36:10 +00001355 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001356 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00001357
Chris Lattner8af304a2009-10-11 07:53:15 +00001358 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00001359 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1360 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001361
1362 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00001363 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00001364 if (SI->getOpcode() == Instruction::Shl)
1365 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001366 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001367 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001368
Zhou Sheng843f07672007-04-19 05:39:12 +00001369 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00001370 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00001371 if (CI->equalsInt(1)) // X * 1 == X
1372 return ReplaceInstUsesWith(I, Op0);
1373 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00001374 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001375
Zhou Sheng97b52c22007-03-29 01:57:21 +00001376 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00001377 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001378 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00001379 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001380 }
Chris Lattnera2498472009-10-11 21:36:10 +00001381 } else if (isa<VectorType>(Op1C->getType())) {
1382 if (Op1C->isNullValue())
1383 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00001384
Chris Lattnera2498472009-10-11 21:36:10 +00001385 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00001386 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00001387 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00001388
1389 // As above, vector X*splat(1.0) -> X in all defined cases.
1390 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00001391 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
1392 if (CI->equalsInt(1))
1393 return ReplaceInstUsesWith(I, Op0);
1394 }
1395 }
Chris Lattnera2881962003-02-18 19:28:33 +00001396 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001397
1398 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1399 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00001400 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001401 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00001402 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
1403 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001404 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001405
1406 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001407
1408 // Try to fold constant mul into select arguments.
1409 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001410 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001411 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001412
1413 if (isa<PHINode>(Op0))
1414 if (Instruction *NV = FoldOpIntoPhi(I))
1415 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001416 }
1417
Dan Gohman186a6362009-08-12 16:04:34 +00001418 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00001419 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001420 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001421
Nick Lewycky0c730792008-11-21 07:33:58 +00001422 // (X / Y) * Y = X - (X % Y)
1423 // (X / Y) * -Y = (X % Y) - X
1424 {
Chris Lattnera2498472009-10-11 21:36:10 +00001425 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00001426 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
1427 if (!BO ||
1428 (BO->getOpcode() != Instruction::UDiv &&
1429 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00001430 Op1C = Op0;
1431 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00001432 }
Chris Lattnera2498472009-10-11 21:36:10 +00001433 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00001434 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00001435 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00001436 (BO->getOpcode() == Instruction::UDiv ||
1437 BO->getOpcode() == Instruction::SDiv)) {
1438 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
1439
Dan Gohmanfa94b942009-08-12 16:33:09 +00001440 // If the division is exact, X % Y is zero.
1441 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
1442 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00001443 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00001444 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00001445 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00001446 }
1447
Chris Lattner74381062009-08-30 07:44:24 +00001448 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00001449 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00001450 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00001451 else
Chris Lattner74381062009-08-30 07:44:24 +00001452 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00001453 Rem->takeName(BO);
1454
Chris Lattnera2498472009-10-11 21:36:10 +00001455 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00001456 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00001457 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00001458 }
1459 }
1460
Chris Lattner8af304a2009-10-11 07:53:15 +00001461 /// i1 mul -> i1 and.
Chris Lattner4de84762010-01-04 07:02:48 +00001462 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattnera2498472009-10-11 21:36:10 +00001463 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001464
Chris Lattner8af304a2009-10-11 07:53:15 +00001465 // X*(1 << Y) --> X << Y
1466 // (1 << Y)*X --> X << Y
1467 {
1468 Value *Y;
1469 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00001470 return BinaryOperator::CreateShl(Op1, Y);
1471 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00001472 return BinaryOperator::CreateShl(Op0, Y);
1473 }
1474
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001475 // If one of the operands of the multiply is a cast from a boolean value, then
1476 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00001477 // X * Y (where Y is 0 or 1) -> X & (0-Y)
1478 if (!isa<VectorType>(I.getType())) {
1479 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00001480 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00001481
Chris Lattnerd2c58362009-10-11 21:29:45 +00001482 Value *BoolCast = 0, *OtherOp = 0;
1483 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00001484 BoolCast = Op0, OtherOp = Op1;
1485 else if (MaskedValueIsZero(Op1, Negative2))
1486 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00001487
Chris Lattner0036e3a2009-10-11 21:22:21 +00001488 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00001489 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
1490 BoolCast, "tmp");
1491 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001492 }
1493 }
1494
Chris Lattner7e708292002-06-25 16:13:24 +00001495 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001496}
1497
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001498Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
1499 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00001500 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001501
1502 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00001503 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1504 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001505 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1506 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1507 if (Op1F->isExactlyValue(1.0))
1508 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00001509 } else if (isa<VectorType>(Op1C->getType())) {
1510 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001511 // As above, vector X*splat(1.0) -> X in all defined cases.
1512 if (Constant *Splat = Op1V->getSplatValue()) {
1513 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
1514 if (F->isExactlyValue(1.0))
1515 return ReplaceInstUsesWith(I, Op0);
1516 }
1517 }
1518 }
1519
1520 // Try to fold constant mul into select arguments.
1521 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001522 if (Instruction *R = FoldOpIntoSelect(I, SI))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001523 return R;
1524
1525 if (isa<PHINode>(Op0))
1526 if (Instruction *NV = FoldOpIntoPhi(I))
1527 return NV;
1528 }
1529
Dan Gohman186a6362009-08-12 16:04:34 +00001530 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00001531 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001532 return BinaryOperator::CreateFMul(Op0v, Op1v);
1533
1534 return Changed ? &I : 0;
1535}
1536
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001537/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
1538/// instruction.
1539bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
1540 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
1541
1542 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
1543 int NonNullOperand = -1;
1544 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
1545 if (ST->isNullValue())
1546 NonNullOperand = 2;
1547 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
1548 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
1549 if (ST->isNullValue())
1550 NonNullOperand = 1;
1551
1552 if (NonNullOperand == -1)
1553 return false;
1554
1555 Value *SelectCond = SI->getOperand(0);
1556
1557 // Change the div/rem to use 'Y' instead of the select.
1558 I.setOperand(1, SI->getOperand(NonNullOperand));
1559
1560 // Okay, we know we replace the operand of the div/rem with 'Y' with no
1561 // problem. However, the select, or the condition of the select may have
1562 // multiple uses. Based on our knowledge that the operand must be non-zero,
1563 // propagate the known value for the select into other uses of it, and
1564 // propagate a known value of the condition into its other users.
1565
1566 // If the select and condition only have a single use, don't bother with this,
1567 // early exit.
1568 if (SI->use_empty() && SelectCond->hasOneUse())
1569 return true;
1570
1571 // Scan the current block backward, looking for other uses of SI.
1572 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
1573
1574 while (BBI != BBFront) {
1575 --BBI;
1576 // If we found a call to a function, we can't assume it will return, so
1577 // information from below it cannot be propagated above it.
1578 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
1579 break;
1580
1581 // Replace uses of the select or its condition with the known values.
1582 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
1583 I != E; ++I) {
1584 if (*I == SI) {
1585 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001586 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001587 } else if (*I == SelectCond) {
Chris Lattner4de84762010-01-04 07:02:48 +00001588 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
1589 ConstantInt::getFalse(BBI->getContext());
Chris Lattner7a1e9242009-08-30 06:13:40 +00001590 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001591 }
1592 }
1593
1594 // If we past the instruction, quit looking for it.
1595 if (&*BBI == SI)
1596 SI = 0;
1597 if (&*BBI == SelectCond)
1598 SelectCond = 0;
1599
1600 // If we ran out of things to eliminate, break out of the loop.
1601 if (SelectCond == 0 && SI == 0)
1602 break;
1603
1604 }
1605 return true;
1606}
1607
1608
Reid Spencer1628cec2006-10-26 06:15:43 +00001609/// This function implements the transforms on div instructions that work
1610/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
1611/// used by the visitors to those instructions.
1612/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00001613Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001614 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001615
Chris Lattner50b2ca42008-02-19 06:12:18 +00001616 // undef / X -> 0 for integer.
1617 // undef / X -> undef for FP (the undef could be a snan).
1618 if (isa<UndefValue>(Op0)) {
1619 if (Op0->getType()->isFPOrFPVector())
1620 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00001621 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00001622 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001623
1624 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00001625 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00001626 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001627
Reid Spencer1628cec2006-10-26 06:15:43 +00001628 return 0;
1629}
Misha Brukmanfd939082005-04-21 23:48:37 +00001630
Reid Spencer1628cec2006-10-26 06:15:43 +00001631/// This function implements the transforms common to both integer division
1632/// instructions (udiv and sdiv). It is called by the visitors to those integer
1633/// division instructions.
1634/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00001635Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001636 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1637
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00001638 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001639 if (Op0 == Op1) {
1640 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001641 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001642 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001643 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001644 }
1645
Owen Andersoneed707b2009-07-24 23:12:02 +00001646 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001647 return ReplaceInstUsesWith(I, CI);
1648 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00001649
Reid Spencer1628cec2006-10-26 06:15:43 +00001650 if (Instruction *Common = commonDivTransforms(I))
1651 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001652
1653 // Handle cases involving: [su]div X, (select Cond, Y, Z)
1654 // This does not apply for fdiv.
1655 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1656 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00001657
1658 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1659 // div X, 1 == X
1660 if (RHS->equalsInt(1))
1661 return ReplaceInstUsesWith(I, Op0);
1662
1663 // (X / C1) / C2 -> X / (C1*C2)
1664 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1665 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
1666 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001667 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00001668 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00001669 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00001670 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001671 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001672 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00001673 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001674
Reid Spencerbca0e382007-03-23 20:05:17 +00001675 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00001676 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001677 if (Instruction *R = FoldOpIntoSelect(I, SI))
Reid Spencer1628cec2006-10-26 06:15:43 +00001678 return R;
1679 if (isa<PHINode>(Op0))
1680 if (Instruction *NV = FoldOpIntoPhi(I))
1681 return NV;
1682 }
Chris Lattner8e49e082006-09-09 20:26:32 +00001683 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001684
Chris Lattnera2881962003-02-18 19:28:33 +00001685 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001686 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001687 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00001688 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00001689
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001690 // It can't be division by zero, hence it must be division by one.
Chris Lattner4de84762010-01-04 07:02:48 +00001691 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001692 return ReplaceInstUsesWith(I, Op0);
1693
Nick Lewycky895f0852008-11-27 20:21:08 +00001694 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
1695 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
1696 // div X, 1 == X
1697 if (X->isOne())
1698 return ReplaceInstUsesWith(I, Op0);
1699 }
1700
Reid Spencer1628cec2006-10-26 06:15:43 +00001701 return 0;
1702}
1703
1704Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1705 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1706
1707 // Handle the integer div common cases
1708 if (Instruction *Common = commonIDivTransforms(I))
1709 return Common;
1710
Reid Spencer1628cec2006-10-26 06:15:43 +00001711 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00001712 // X udiv C^2 -> X >> C
1713 // Check to see if this is an unsigned division with an exact power of 2,
1714 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00001715 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001716 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00001717 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00001718
1719 // X udiv C, where C >= signbit
1720 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00001721 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00001722 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00001723 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00001724 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001725 }
1726
1727 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00001728 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001729 if (RHSI->getOpcode() == Instruction::Shl &&
1730 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001731 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00001732 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001733 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00001734 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00001735 if (uint32_t C2 = C1.logBase2())
1736 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001737 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001738 }
1739 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001740 }
1741
Reid Spencer1628cec2006-10-26 06:15:43 +00001742 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
1743 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001744 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00001745 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001746 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001747 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00001748 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001749 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00001750 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001751 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00001752 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00001753 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001754
1755 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00001756 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00001757 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00001758
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001759 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00001760 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00001761 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001762 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001763 return 0;
1764}
1765
Reid Spencer1628cec2006-10-26 06:15:43 +00001766Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1767 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1768
1769 // Handle the integer div common cases
1770 if (Instruction *Common = commonIDivTransforms(I))
1771 return Common;
1772
1773 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1774 // sdiv X, -1 == -X
1775 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00001776 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00001777
Dan Gohmanfa94b942009-08-12 16:33:09 +00001778 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00001779 if (cast<SDivOperator>(&I)->isExact() &&
1780 RHS->getValue().isNonNegative() &&
1781 RHS->getValue().isPowerOf2()) {
1782 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1783 RHS->getValue().exactLogBase2());
1784 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
1785 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00001786
1787 // -X/C --> X/-C provided the negation doesn't overflow.
1788 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
1789 if (isa<Constant>(Sub->getOperand(0)) &&
1790 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00001791 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00001792 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1793 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00001794 }
1795
1796 // If the sign bits of both operands are zero (i.e. we can prove they are
1797 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00001798 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00001799 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00001800 if (MaskedValueIsZero(Op0, Mask)) {
1801 if (MaskedValueIsZero(Op1, Mask)) {
1802 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1803 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1804 }
1805 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00001806 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00001807 ShiftedInt->getValue().isPowerOf2()) {
1808 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1809 // Safe because the only negative value (1 << Y) can take on is
1810 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1811 // the sign bit set.
1812 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1813 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001814 }
Eli Friedman8be17392009-07-18 09:53:21 +00001815 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001816
1817 return 0;
1818}
1819
1820Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1821 return commonDivTransforms(I);
1822}
Chris Lattner3f5b8772002-05-06 16:14:14 +00001823
Reid Spencer0a783f72006-11-02 01:53:59 +00001824/// This function implements the transforms on rem instructions that work
1825/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
1826/// is used by the visitors to those instructions.
1827/// @brief Transforms common to all three rem instructions
1828Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001829 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00001830
Chris Lattner50b2ca42008-02-19 06:12:18 +00001831 if (isa<UndefValue>(Op0)) { // undef % X -> 0
1832 if (I.getType()->isFPOrFPVector())
1833 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00001834 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00001835 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001836 if (isa<UndefValue>(Op1))
1837 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00001838
1839 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001840 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1841 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00001842
Reid Spencer0a783f72006-11-02 01:53:59 +00001843 return 0;
1844}
1845
1846/// This function implements the transforms common to both integer remainder
1847/// instructions (urem and srem). It is called by the visitors to those integer
1848/// remainder instructions.
1849/// @brief Common integer remainder transforms
1850Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1851 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1852
1853 if (Instruction *common = commonRemTransforms(I))
1854 return common;
1855
Dale Johannesened6af242009-01-21 00:35:19 +00001856 // 0 % X == 0 for integer, we don't need to preserve faults!
1857 if (Constant *LHS = dyn_cast<Constant>(Op0))
1858 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00001859 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00001860
Chris Lattner857e8cd2004-12-12 21:48:58 +00001861 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001862 // X % 0 == undef, we don't need to preserve faults!
1863 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001864 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001865
Chris Lattnera2881962003-02-18 19:28:33 +00001866 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001867 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00001868
Chris Lattner97943922006-02-28 05:49:21 +00001869 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1870 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
Chris Lattner80f43d32010-01-04 07:53:58 +00001871 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner97943922006-02-28 05:49:21 +00001872 return R;
1873 } else if (isa<PHINode>(Op0I)) {
1874 if (Instruction *NV = FoldOpIntoPhi(I))
1875 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00001876 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001877
1878 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001879 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001880 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00001881 }
Chris Lattnera2881962003-02-18 19:28:33 +00001882 }
1883
Reid Spencer0a783f72006-11-02 01:53:59 +00001884 return 0;
1885}
1886
1887Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1888 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1889
1890 if (Instruction *common = commonIRemTransforms(I))
1891 return common;
1892
1893 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1894 // X urem C^2 -> X and C
1895 // Check to see if this is an unsigned remainder with an exact power of 2,
1896 // if so, convert to a bitwise and.
1897 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00001898 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00001899 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00001900 }
1901
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001902 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00001903 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
1904 if (RHSI->getOpcode() == Instruction::Shl &&
1905 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00001906 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001907 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00001908 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001909 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001910 }
1911 }
Reid Spencer0a783f72006-11-02 01:53:59 +00001912 }
Chris Lattner8e49e082006-09-09 20:26:32 +00001913
Reid Spencer0a783f72006-11-02 01:53:59 +00001914 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
1915 // where C1&C2 are powers of two.
1916 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
1917 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
1918 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
1919 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00001920 if ((STO->getValue().isPowerOf2()) &&
1921 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00001922 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
1923 SI->getName()+".t");
1924 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
1925 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00001926 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00001927 }
1928 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001929 }
1930
Chris Lattner3f5b8772002-05-06 16:14:14 +00001931 return 0;
1932}
1933
Reid Spencer0a783f72006-11-02 01:53:59 +00001934Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1935 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1936
Dan Gohmancff55092007-11-05 23:16:33 +00001937 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001938 if (Instruction *Common = commonIRemTransforms(I))
1939 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00001940
Dan Gohman186a6362009-08-12 16:04:34 +00001941 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00001942 if (!isa<Constant>(RHSNeg) ||
1943 (isa<ConstantInt>(RHSNeg) &&
1944 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00001945 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00001946 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00001947 I.setOperand(1, RHSNeg);
1948 return &I;
1949 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00001950
Dan Gohmancff55092007-11-05 23:16:33 +00001951 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00001952 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00001953 if (I.getType()->isInteger()) {
1954 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1955 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1956 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001957 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00001958 }
Reid Spencer0a783f72006-11-02 01:53:59 +00001959 }
1960
Nick Lewycky2a8f6592008-12-18 06:31:11 +00001961 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00001962 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
1963 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00001964
Nick Lewycky9dce8732008-12-20 16:48:00 +00001965 bool hasNegative = false;
1966 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
1967 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
1968 if (RHS->getValue().isNegative())
1969 hasNegative = true;
1970
1971 if (hasNegative) {
1972 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00001973 for (unsigned i = 0; i != VWidth; ++i) {
1974 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
1975 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001976 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00001977 else
1978 Elts[i] = RHS;
1979 }
1980 }
1981
Owen Andersonaf7ec972009-07-28 21:19:26 +00001982 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00001983 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00001984 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00001985 I.setOperand(1, NewRHSV);
1986 return &I;
1987 }
1988 }
1989 }
1990
Reid Spencer0a783f72006-11-02 01:53:59 +00001991 return 0;
1992}
1993
1994Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00001995 return commonRemTransforms(I);
1996}
1997
Chris Lattner457dd822004-06-09 07:59:58 +00001998// isOneBitSet - Return true if there is exactly one bit set in the specified
1999// constant.
2000static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002001 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002002}
2003
Reid Spencere4d87aa2006-12-23 06:05:41 +00002004/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002005/// are carefully arranged to allow folding of expressions such as:
2006///
2007/// (A < B) | (A > B) --> (A != B)
2008///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002009/// Note that this is only valid if the first and second predicates have the
2010/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002011///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002012/// Three bits are used to represent the condition, as follows:
2013/// 0 A > B
2014/// 1 A == B
2015/// 2 A < B
2016///
2017/// <=> Value Definition
2018/// 000 0 Always false
2019/// 001 1 A > B
2020/// 010 2 A == B
2021/// 011 3 A >= B
2022/// 100 4 A < B
2023/// 101 5 A != B
2024/// 110 6 A <= B
2025/// 111 7 Always true
2026///
2027static unsigned getICmpCode(const ICmpInst *ICI) {
2028 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002029 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002030 case ICmpInst::ICMP_UGT: return 1; // 001
2031 case ICmpInst::ICMP_SGT: return 1; // 001
2032 case ICmpInst::ICMP_EQ: return 2; // 010
2033 case ICmpInst::ICMP_UGE: return 3; // 011
2034 case ICmpInst::ICMP_SGE: return 3; // 011
2035 case ICmpInst::ICMP_ULT: return 4; // 100
2036 case ICmpInst::ICMP_SLT: return 4; // 100
2037 case ICmpInst::ICMP_NE: return 5; // 101
2038 case ICmpInst::ICMP_ULE: return 6; // 110
2039 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002040 // True -> 7
2041 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00002042 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002043 return 0;
2044 }
2045}
2046
Evan Cheng8db90722008-10-14 17:15:11 +00002047/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
2048/// predicate into a three bit mask. It also returns whether it is an ordered
2049/// predicate by reference.
2050static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
2051 isOrdered = false;
2052 switch (CC) {
2053 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
2054 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00002055 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
2056 case FCmpInst::FCMP_UGT: return 1; // 001
2057 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
2058 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00002059 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
2060 case FCmpInst::FCMP_UGE: return 3; // 011
2061 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
2062 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00002063 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
2064 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00002065 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
2066 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00002067 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00002068 default:
2069 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00002070 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00002071 return 0;
2072 }
2073}
2074
Reid Spencere4d87aa2006-12-23 06:05:41 +00002075/// getICmpValue - This is the complement of getICmpCode, which turns an
2076/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00002077/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00002078/// of predicate to use in the new icmp instruction.
Chris Lattner4de84762010-01-04 07:02:48 +00002079static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002080 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002081 default: llvm_unreachable("Illegal ICmp code!");
Chris Lattner4de84762010-01-04 07:02:48 +00002082 case 0: return ConstantInt::getFalse(LHS->getContext());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002083 case 1:
2084 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002085 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002086 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002087 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2088 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002089 case 3:
2090 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002091 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002092 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002093 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002094 case 4:
2095 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002096 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002097 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002098 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2099 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002100 case 6:
2101 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002102 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002103 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002104 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00002105 case 7: return ConstantInt::getTrue(LHS->getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002106 }
2107}
2108
Evan Cheng8db90722008-10-14 17:15:11 +00002109/// getFCmpValue - This is the complement of getFCmpCode, which turns an
2110/// opcode and two operands into either a FCmp instruction. isordered is passed
2111/// in to determine which kind of predicate to use in the new fcmp instruction.
2112static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner4de84762010-01-04 07:02:48 +00002113 Value *LHS, Value *RHS) {
Evan Cheng8db90722008-10-14 17:15:11 +00002114 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002115 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00002116 case 0:
2117 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002118 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002119 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002120 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002121 case 1:
2122 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002123 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002124 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002125 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002126 case 2:
2127 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002128 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002129 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002130 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002131 case 3:
2132 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002133 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002134 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002135 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002136 case 4:
2137 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002138 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002139 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002140 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002141 case 5:
2142 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002143 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002144 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002145 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002146 case 6:
2147 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002148 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002149 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002150 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00002151 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng8db90722008-10-14 17:15:11 +00002152 }
2153}
2154
Chris Lattnerb9553d62008-11-16 04:55:20 +00002155/// PredicatesFoldable - Return true if both predicates match sign or if at
2156/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00002157static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00002158 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
2159 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
2160 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002161}
2162
2163namespace {
2164// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2165struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002166 InstCombiner &IC;
2167 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002168 ICmpInst::Predicate pred;
2169 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2170 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2171 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002172 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002173 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2174 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002175 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
2176 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002177 return false;
2178 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00002179 Instruction *apply(Instruction &Log) const {
2180 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2181 if (ICI->getOperand(0) != LHS) {
2182 assert(ICI->getOperand(1) == LHS);
2183 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002184 }
2185
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002186 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002187 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002188 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002189 unsigned Code;
2190 switch (Log.getOpcode()) {
2191 case Instruction::And: Code = LHSCode & RHSCode; break;
2192 case Instruction::Or: Code = LHSCode | RHSCode; break;
2193 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00002194 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002195 }
2196
Nick Lewycky4a134af2009-10-25 05:20:17 +00002197 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Chris Lattner4de84762010-01-04 07:02:48 +00002198 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002199 if (Instruction *I = dyn_cast<Instruction>(RV))
2200 return I;
2201 // Otherwise, it's a constant boolean value...
2202 return IC.ReplaceInstUsesWith(Log, RV);
2203 }
2204};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00002205} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002206
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002207// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2208// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00002209// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002210Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002211 ConstantInt *OpRHS,
2212 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002213 BinaryOperator &TheAnd) {
2214 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002215 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00002216 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002217 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002218
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002219 switch (Op->getOpcode()) {
2220 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002221 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002222 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00002223 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002224 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002225 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002226 }
2227 break;
2228 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002229 if (Together == AndRHS) // (X | C) & C --> C
2230 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002231
Chris Lattner6e7ba452005-01-01 16:22:27 +00002232 if (Op->hasOneUse() && Together != OpRHS) {
2233 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00002234 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00002235 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002236 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002237 }
2238 break;
2239 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002240 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002241 // Adding a one to a single bit bit-field should be turned into an XOR
2242 // of the bit. First thing to check is to see if this AND is with a
2243 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002244 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002245
2246 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002247 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002248 // Ok, at this point, we know that we are masking the result of the
2249 // ADD down to exactly one bit. If the constant we are adding has
2250 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002251 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002252
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002253 // Check to see if any bits below the one bit set in AndRHSV are set.
2254 if ((AddRHS & (AndRHSV-1)) == 0) {
2255 // If not, the only thing that can effect the output of the AND is
2256 // the bit specified by AndRHSV. If that bit is set, the effect of
2257 // the XOR is to toggle the bit. If it is clear, then the ADD has
2258 // no effect.
2259 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2260 TheAnd.setOperand(0, X);
2261 return &TheAnd;
2262 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002263 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00002264 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002265 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002266 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002267 }
2268 }
2269 }
2270 }
2271 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002272
2273 case Instruction::Shl: {
2274 // We know that the AND will not produce any of the bits shifted in, so if
2275 // the anded constant includes them, clear them now!
2276 //
Zhou Sheng290bec52007-03-29 08:15:12 +00002277 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002278 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00002279 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00002280 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
2281 AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002282
Zhou Sheng290bec52007-03-29 08:15:12 +00002283 if (CI->getValue() == ShlMask) {
2284 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00002285 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2286 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002287 TheAnd.setOperand(1, CI);
2288 return &TheAnd;
2289 }
2290 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002291 }
Chris Lattner4de84762010-01-04 07:02:48 +00002292 case Instruction::LShr: {
Chris Lattner62a355c2003-09-19 19:05:02 +00002293 // We know that the AND will not produce any of the bits shifted in, so if
2294 // the anded constant includes them, clear them now! This only applies to
2295 // unsigned shifts, because a signed shr may bring in set bits!
2296 //
Zhou Sheng290bec52007-03-29 08:15:12 +00002297 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002298 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00002299 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00002300 ConstantInt *CI = ConstantInt::get(Op->getContext(),
2301 AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00002302
Zhou Sheng290bec52007-03-29 08:15:12 +00002303 if (CI->getValue() == ShrMask) {
2304 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00002305 return ReplaceInstUsesWith(TheAnd, Op);
2306 } else if (CI != AndRHS) {
2307 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2308 return &TheAnd;
2309 }
2310 break;
2311 }
2312 case Instruction::AShr:
2313 // Signed shr.
2314 // See if this is shifting in some sign extension, then masking it out
2315 // with an and.
2316 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00002317 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002318 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00002319 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00002320 Constant *C = ConstantInt::get(Op->getContext(),
2321 AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00002322 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00002323 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00002324 // Make the argument unsigned.
2325 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00002326 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002327 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00002328 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002329 }
2330 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002331 }
2332 return 0;
2333}
2334
Chris Lattner8b170942002-08-09 23:47:40 +00002335
Chris Lattnera96879a2004-09-29 17:40:11 +00002336/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2337/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00002338/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2339/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00002340/// insert new instructions.
2341Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002342 bool isSigned, bool Inside,
2343 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002344 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00002345 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00002346 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002347
Chris Lattnera96879a2004-09-29 17:40:11 +00002348 if (Inside) {
2349 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002350 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00002351
Reid Spencere4d87aa2006-12-23 06:05:41 +00002352 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002353 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00002354 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00002355 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002356 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002357 }
2358
2359 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00002360 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00002361 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002362 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002363 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00002364 }
2365
2366 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002367 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00002368
Reid Spencere4e40032007-03-21 23:19:50 +00002369 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00002370 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002371 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002372 ICmpInst::Predicate pred = (isSigned ?
2373 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002374 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002375 }
Reid Spencerb83eb642006-10-20 07:07:24 +00002376
Reid Spencere4e40032007-03-21 23:19:50 +00002377 // Emit V-Lo >u Hi-1-Lo
2378 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00002379 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00002380 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002381 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002382 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00002383}
2384
Chris Lattner7203e152005-09-18 07:22:02 +00002385// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2386// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2387// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2388// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00002389static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002390 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00002391 uint32_t BitWidth = Val->getType()->getBitWidth();
2392 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00002393
2394 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00002395 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00002396 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00002397 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00002398 return true;
2399}
2400
Chris Lattner7203e152005-09-18 07:22:02 +00002401/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2402/// where isSub determines whether the operator is a sub. If we can fold one of
2403/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00002404///
2405/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2406/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2407/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2408///
2409/// return (A +/- B).
2410///
2411Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002412 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00002413 Instruction &I) {
2414 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2415 if (!LHSI || LHSI->getNumOperands() != 2 ||
2416 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2417
2418 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2419
2420 switch (LHSI->getOpcode()) {
2421 default: return 0;
2422 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00002423 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00002424 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00002425 if ((Mask->getValue().countLeadingZeros() +
2426 Mask->getValue().countPopulation()) ==
2427 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00002428 break;
2429
2430 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2431 // part, we don't need any explicit masks to take them out of A. If that
2432 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00002433 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00002434 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00002435 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00002436 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00002437 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00002438 break;
2439 }
2440 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002441 return 0;
2442 case Instruction::Or:
2443 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00002444 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00002445 if ((Mask->getValue().countLeadingZeros() +
2446 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00002447 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00002448 break;
2449 return 0;
2450 }
2451
Chris Lattnerc8e77562005-09-18 04:24:45 +00002452 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00002453 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
2454 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00002455}
2456
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002457/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
2458Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
2459 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00002460 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002461 ConstantInt *LHSCst, *RHSCst;
2462 ICmpInst::Predicate LHSCC, RHSCC;
2463
Chris Lattnerea065fb2008-11-16 05:10:52 +00002464 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002465 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00002466 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002467 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00002468 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002469 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00002470
Chris Lattner3f40e232009-11-29 00:51:17 +00002471 if (LHSCst == RHSCst && LHSCC == RHSCC) {
2472 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
2473 // where C is a power of 2
2474 if (LHSCC == ICmpInst::ICMP_ULT &&
2475 LHSCst->getValue().isPowerOf2()) {
2476 Value *NewOr = Builder->CreateOr(Val, Val2);
2477 return new ICmpInst(LHSCC, NewOr, LHSCst);
2478 }
2479
2480 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
2481 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
2482 Value *NewOr = Builder->CreateOr(Val, Val2);
2483 return new ICmpInst(LHSCC, NewOr, LHSCst);
2484 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00002485 }
2486
2487 // From here on, we only handle:
2488 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
2489 if (Val != Val2) return 0;
2490
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002491 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
2492 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
2493 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
2494 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
2495 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
2496 return 0;
2497
2498 // We can't fold (ugt x, C) & (sgt x, C2).
2499 if (!PredicatesFoldable(LHSCC, RHSCC))
2500 return 0;
2501
2502 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00002503 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00002504 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002505 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00002506 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00002507 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002508 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00002509 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
2510
2511 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002512 std::swap(LHS, RHS);
2513 std::swap(LHSCst, RHSCst);
2514 std::swap(LHSCC, RHSCC);
2515 }
2516
2517 // At this point, we know we have have two icmp instructions
2518 // comparing a value against two constants and and'ing the result
2519 // together. Because of the above check, we know that we only have
2520 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
2521 // (from the FoldICmpLogical check above), that the two constants
2522 // are not equal and that the larger constant is on the RHS
2523 assert(LHSCst != RHSCst && "Compares not folded above?");
2524
2525 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002526 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002527 case ICmpInst::ICMP_EQ:
2528 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002529 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002530 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
2531 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
2532 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00002533 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002534 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
2535 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
2536 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
2537 return ReplaceInstUsesWith(I, LHS);
2538 }
2539 case ICmpInst::ICMP_NE:
2540 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002541 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002542 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00002543 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002544 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002545 break; // (X != 13 & X u< 15) -> no change
2546 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00002547 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002548 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002549 break; // (X != 13 & X s< 15) -> no change
2550 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
2551 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
2552 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
2553 return ReplaceInstUsesWith(I, RHS);
2554 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00002555 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00002556 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00002557 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002558 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00002559 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002560 }
2561 break; // (X != 13 & X != 15) -> no change
2562 }
2563 break;
2564 case ICmpInst::ICMP_ULT:
2565 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002566 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002567 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
2568 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00002569 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002570 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
2571 break;
2572 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
2573 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
2574 return ReplaceInstUsesWith(I, LHS);
2575 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
2576 break;
2577 }
2578 break;
2579 case ICmpInst::ICMP_SLT:
2580 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002581 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002582 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
2583 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00002584 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002585 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
2586 break;
2587 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
2588 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
2589 return ReplaceInstUsesWith(I, LHS);
2590 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
2591 break;
2592 }
2593 break;
2594 case ICmpInst::ICMP_UGT:
2595 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002596 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002597 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
2598 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
2599 return ReplaceInstUsesWith(I, RHS);
2600 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
2601 break;
2602 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00002603 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002604 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002605 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00002606 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00002607 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002608 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002609 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
2610 break;
2611 }
2612 break;
2613 case ICmpInst::ICMP_SGT:
2614 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002615 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002616 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
2617 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
2618 return ReplaceInstUsesWith(I, RHS);
2619 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
2620 break;
2621 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00002622 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002623 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002624 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00002625 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00002626 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002627 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002628 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
2629 break;
2630 }
2631 break;
2632 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002633
2634 return 0;
2635}
2636
Chris Lattner42d1be02009-07-23 05:14:02 +00002637Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
2638 FCmpInst *RHS) {
2639
2640 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
2641 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
2642 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
2643 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2644 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2645 // If either of the constants are nans, then the whole thing returns
2646 // false.
2647 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00002648 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002649 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00002650 LHS->getOperand(0), RHS->getOperand(0));
2651 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00002652
2653 // Handle vector zeros. This occurs because the canonical form of
2654 // "fcmp ord x,x" is "fcmp ord x, 0".
2655 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2656 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002657 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00002658 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00002659 return 0;
2660 }
2661
2662 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2663 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2664 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2665
2666
2667 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2668 // Swap RHS operands to match LHS.
2669 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2670 std::swap(Op1LHS, Op1RHS);
2671 }
2672
2673 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2674 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
2675 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002676 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00002677
2678 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner4de84762010-01-04 07:02:48 +00002679 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00002680 if (Op0CC == FCmpInst::FCMP_TRUE)
2681 return ReplaceInstUsesWith(I, RHS);
2682 if (Op1CC == FCmpInst::FCMP_TRUE)
2683 return ReplaceInstUsesWith(I, LHS);
2684
2685 bool Op0Ordered;
2686 bool Op1Ordered;
2687 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2688 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2689 if (Op1Pred == 0) {
2690 std::swap(LHS, RHS);
2691 std::swap(Op0Pred, Op1Pred);
2692 std::swap(Op0Ordered, Op1Ordered);
2693 }
2694 if (Op0Pred == 0) {
2695 // uno && ueq -> uno && (uno || eq) -> ueq
2696 // ord && olt -> ord && (ord && lt) -> olt
2697 if (Op0Ordered == Op1Ordered)
2698 return ReplaceInstUsesWith(I, RHS);
2699
2700 // uno && oeq -> uno && (ord && eq) -> false
2701 // uno && ord -> false
2702 if (!Op0Ordered)
Chris Lattner4de84762010-01-04 07:02:48 +00002703 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00002704 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner4de84762010-01-04 07:02:48 +00002705 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner42d1be02009-07-23 05:14:02 +00002706 }
2707 }
2708
2709 return 0;
2710}
2711
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002712
Chris Lattner7e708292002-06-25 16:13:24 +00002713Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002714 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002715 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002716
Chris Lattnerd06094f2009-11-10 00:55:12 +00002717 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
2718 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002719
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002720 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00002721 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002722 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00002723 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00002724
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002725 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002726 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002727 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002728
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002729 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002730 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002731 Value *Op0LHS = Op0I->getOperand(0);
2732 Value *Op0RHS = Op0I->getOperand(1);
2733 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002734 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002735 case Instruction::Xor:
2736 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00002737 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002738 if (!Op0I->hasOneUse()) break;
2739
2740 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2741 // Not masking anything out for the LHS, move to RHS.
2742 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
2743 Op0RHS->getName()+".masked");
2744 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
2745 }
2746 if (!isa<Constant>(Op0RHS) &&
2747 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2748 // Not masking anything out for the RHS, move to LHS.
2749 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
2750 Op0LHS->getName()+".masked");
2751 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00002752 }
2753
Chris Lattner6e7ba452005-01-01 16:22:27 +00002754 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00002755 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00002756 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2757 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2758 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2759 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002760 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00002761 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002762 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00002763 break;
2764
2765 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00002766 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2767 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2768 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2769 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002770 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002771
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00002772 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
2773 // has 1's for all bits that the subtraction with A might affect.
2774 if (Op0I->hasOneUse()) {
2775 uint32_t BitWidth = AndRHSMask.getBitWidth();
2776 uint32_t Zeros = AndRHSMask.countLeadingZeros();
2777 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
2778
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002779 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00002780 if (!(A && A->isZero()) && // avoid infinite recursion.
2781 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00002782 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002783 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
2784 }
2785 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002786 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00002787
2788 case Instruction::Shl:
2789 case Instruction::LShr:
2790 // (1 << x) & 1 --> zext(x == 0)
2791 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00002792 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00002793 Value *NewICmp =
2794 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00002795 return new ZExtInst(NewICmp, I.getType());
2796 }
2797 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002798 }
2799
Chris Lattner58403262003-07-23 19:25:52 +00002800 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002801 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002802 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002803 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00002804 // If this is an integer truncation or change from signed-to-unsigned, and
2805 // if the source is an and/or with immediate, transform it. This
2806 // frequently occurs for bitfield accesses.
2807 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002808 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00002809 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00002810 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00002811 if (CastOp->getOpcode() == Instruction::And) {
2812 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00002813 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
2814 // This will fold the two constants together, which may allow
2815 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00002816 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00002817 CastOp->getOperand(0), I.getType(),
2818 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00002819 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00002820 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00002821 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002822 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00002823 } else if (CastOp->getOpcode() == Instruction::Or) {
2824 // Change: and (cast (or X, C1) to T), C2
2825 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00002826 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00002827 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00002828 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00002829 return ReplaceInstUsesWith(I, AndRHS);
2830 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002831 }
Chris Lattner2b83af22005-08-07 07:03:10 +00002832 }
Chris Lattner06782f82003-07-23 19:36:21 +00002833 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002834
2835 // Try to fold constant and into select arguments.
2836 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002837 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002838 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002839 if (isa<PHINode>(Op0))
2840 if (Instruction *NV = FoldOpIntoPhi(I))
2841 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002842 }
2843
Chris Lattner5b62aa72004-06-18 06:07:51 +00002844
Misha Brukmancb6267b2004-07-30 12:50:08 +00002845 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00002846 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2847 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2848 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2849 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
2850 I.getName()+".demorgan");
2851 return BinaryOperator::CreateNot(Or);
2852 }
2853
Chris Lattner2082ad92006-02-13 23:07:23 +00002854 {
Chris Lattner003b6202007-06-15 05:58:24 +00002855 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00002856 // (A|B) & ~(A&B) -> A^B
2857 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2858 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2859 ((A == C && B == D) || (A == D && B == C)))
2860 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00002861
Chris Lattnerd06094f2009-11-10 00:55:12 +00002862 // ~(A&B) & (A|B) -> A^B
2863 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
2864 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
2865 ((A == C && B == D) || (A == D && B == C)))
2866 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00002867
2868 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002869 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00002870 if (A == Op1) { // (A^B)&A -> A&(A^B)
2871 I.swapOperands(); // Simplify below
2872 std::swap(Op0, Op1);
2873 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2874 cast<BinaryOperator>(Op0)->swapOperands();
2875 I.swapOperands(); // Simplify below
2876 std::swap(Op0, Op1);
2877 }
2878 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002879
Chris Lattner64daab52006-04-01 08:03:55 +00002880 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002881 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00002882 if (B == Op0) { // B&(A^B) -> B&(B^A)
2883 cast<BinaryOperator>(Op1)->swapOperands();
2884 std::swap(A, B);
2885 }
Chris Lattner74381062009-08-30 07:44:24 +00002886 if (A == Op0) // A&(A^B) -> A & ~B
2887 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00002888 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002889
2890 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00002891 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
2892 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002893 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00002894 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
2895 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002896 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00002897 }
2898
Reid Spencere4d87aa2006-12-23 06:05:41 +00002899 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
2900 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00002901 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002902 return R;
2903
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002904 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
2905 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
2906 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00002907 }
2908
Chris Lattner6fc205f2006-05-05 06:39:07 +00002909 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002910 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
2911 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2912 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
2913 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002914 if (SrcTy == Op1C->getOperand(0)->getType() &&
2915 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002916 // Only do this if the casts both really cause code to be generated.
Chris Lattner80f43d32010-01-04 07:53:58 +00002917 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
2918 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002919 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002920 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002921 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
2922 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002923 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002924 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002925 }
Chris Lattnere511b742006-11-14 07:46:50 +00002926
2927 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00002928 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2929 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2930 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00002931 SI0->getOperand(1) == SI1->getOperand(1) &&
2932 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002933 Value *NewOp =
2934 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
2935 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002936 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00002937 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00002938 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002939 }
2940
Evan Cheng8db90722008-10-14 17:15:11 +00002941 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00002942 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00002943 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2944 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
2945 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002946 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002947
Chris Lattner7e708292002-06-25 16:13:24 +00002948 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002949}
2950
Chris Lattner8c34cd22008-10-05 02:13:19 +00002951/// CollectBSwapParts - Analyze the specified subexpression and see if it is
2952/// capable of providing pieces of a bswap. The subexpression provides pieces
2953/// of a bswap if it is proven that each of the non-zero bytes in the output of
2954/// the expression came from the corresponding "byte swapped" byte in some other
2955/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
2956/// we know that the expression deposits the low byte of %X into the high byte
2957/// of the bswap result and that all other bytes are zero. This expression is
2958/// accepted, the high byte of ByteValues is set to X to indicate a correct
2959/// match.
2960///
2961/// This function returns true if the match was unsuccessful and false if so.
2962/// On entry to the function the "OverallLeftShift" is a signed integer value
2963/// indicating the number of bytes that the subexpression is later shifted. For
2964/// example, if the expression is later right shifted by 16 bits, the
2965/// OverallLeftShift value would be -2 on entry. This is used to specify which
2966/// byte of ByteValues is actually being set.
2967///
2968/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
2969/// byte is masked to zero by a user. For example, in (X & 255), X will be
2970/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
2971/// this function to working on up to 32-byte (256 bit) values. ByteMask is
2972/// always in the local (OverallLeftShift) coordinate space.
2973///
2974static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
2975 SmallVector<Value*, 8> &ByteValues) {
2976 if (Instruction *I = dyn_cast<Instruction>(V)) {
2977 // If this is an or instruction, it may be an inner node of the bswap.
2978 if (I->getOpcode() == Instruction::Or) {
2979 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2980 ByteValues) ||
2981 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
2982 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002983 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00002984
2985 // If this is a logical shift by a constant multiple of 8, recurse with
2986 // OverallLeftShift and ByteMask adjusted.
2987 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2988 unsigned ShAmt =
2989 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2990 // Ensure the shift amount is defined and of a byte value.
2991 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
2992 return true;
2993
2994 unsigned ByteShift = ShAmt >> 3;
2995 if (I->getOpcode() == Instruction::Shl) {
2996 // X << 2 -> collect(X, +2)
2997 OverallLeftShift += ByteShift;
2998 ByteMask >>= ByteShift;
2999 } else {
3000 // X >>u 2 -> collect(X, -2)
3001 OverallLeftShift -= ByteShift;
3002 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00003003 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00003004 }
3005
3006 if (OverallLeftShift >= (int)ByteValues.size()) return true;
3007 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
3008
3009 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3010 ByteValues);
3011 }
3012
3013 // If this is a logical 'and' with a mask that clears bytes, clear the
3014 // corresponding bytes in ByteMask.
3015 if (I->getOpcode() == Instruction::And &&
3016 isa<ConstantInt>(I->getOperand(1))) {
3017 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
3018 unsigned NumBytes = ByteValues.size();
3019 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
3020 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
3021
3022 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
3023 // If this byte is masked out by a later operation, we don't care what
3024 // the and mask is.
3025 if ((ByteMask & (1 << i)) == 0)
3026 continue;
3027
3028 // If the AndMask is all zeros for this byte, clear the bit.
3029 APInt MaskB = AndMask & Byte;
3030 if (MaskB == 0) {
3031 ByteMask &= ~(1U << i);
3032 continue;
3033 }
3034
3035 // If the AndMask is not all ones for this byte, it's not a bytezap.
3036 if (MaskB != Byte)
3037 return true;
3038
3039 // Otherwise, this byte is kept.
3040 }
3041
3042 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3043 ByteValues);
3044 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00003045 }
3046
Chris Lattner8c34cd22008-10-05 02:13:19 +00003047 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
3048 // the input value to the bswap. Some observations: 1) if more than one byte
3049 // is demanded from this input, then it could not be successfully assembled
3050 // into a byteswap. At least one of the two bytes would not be aligned with
3051 // their ultimate destination.
3052 if (!isPowerOf2_32(ByteMask)) return true;
3053 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003054
Chris Lattner8c34cd22008-10-05 02:13:19 +00003055 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
3056 // is demanded, it needs to go into byte 0 of the result. This means that the
3057 // byte needs to be shifted until it lands in the right byte bucket. The
3058 // shift amount depends on the position: if the byte is coming from the high
3059 // part of the value (e.g. byte 3) then it must be shifted right. If from the
3060 // low part, it must be shifted left.
3061 unsigned DestByteNo = InputByteNo + OverallLeftShift;
3062 if (InputByteNo < ByteValues.size()/2) {
3063 if (ByteValues.size()-1-DestByteNo != InputByteNo)
3064 return true;
3065 } else {
3066 if (ByteValues.size()-1-DestByteNo != InputByteNo)
3067 return true;
3068 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00003069
3070 // If the destination byte value is already defined, the values are or'd
3071 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00003072 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003073 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00003074 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003075 return false;
3076}
3077
3078/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3079/// If so, insert the new bswap intrinsic and return it.
3080Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003081 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00003082 if (!ITy || ITy->getBitWidth() % 16 ||
3083 // ByteMask only allows up to 32-byte values.
3084 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00003085 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003086
3087 /// ByteValues - For each byte of the result, we keep track of which value
3088 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003089 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003090 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003091
3092 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00003093 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
3094 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00003095 return 0;
3096
3097 // Check to see if all of the bytes come from the same value.
3098 Value *V = ByteValues[0];
3099 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3100
3101 // Check to make sure that all of the bytes come from the same value.
3102 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3103 if (ByteValues[i] != V)
3104 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003105 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003106 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003107 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00003108 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003109}
3110
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003111/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
3112/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
3113/// we can simplify this expression to "cond ? C : D or B".
3114static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner4de84762010-01-04 07:02:48 +00003115 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00003116 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00003117 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00003118 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003119 return 0;
3120
Chris Lattnera6a474d2008-11-16 04:26:55 +00003121 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00003122 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003123 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00003124 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003125 return SelectInst::Create(Cond, C, B);
3126 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00003127 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003128 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00003129 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003130 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003131 return 0;
3132}
Chris Lattnerafe91a52006-06-15 19:07:26 +00003133
Chris Lattner69d4ced2008-11-16 05:20:07 +00003134/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
3135Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
3136 ICmpInst *LHS, ICmpInst *RHS) {
3137 Value *Val, *Val2;
3138 ConstantInt *LHSCst, *RHSCst;
3139 ICmpInst::Predicate LHSCC, RHSCC;
3140
3141 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00003142 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3143 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00003144 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00003145
3146
3147 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
3148 if (LHSCst == RHSCst && LHSCC == RHSCC &&
3149 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
3150 Value *NewOr = Builder->CreateOr(Val, Val2);
3151 return new ICmpInst(LHSCC, NewOr, LHSCst);
3152 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00003153
3154 // From here on, we only handle:
3155 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
3156 if (Val != Val2) return 0;
3157
3158 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3159 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3160 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3161 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3162 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3163 return 0;
3164
3165 // We can't fold (ugt x, C) | (sgt x, C2).
3166 if (!PredicatesFoldable(LHSCC, RHSCC))
3167 return 0;
3168
3169 // Ensure that the larger constant is on the RHS.
3170 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00003171 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00003172 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00003173 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00003174 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3175 else
3176 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3177
3178 if (ShouldSwap) {
3179 std::swap(LHS, RHS);
3180 std::swap(LHSCst, RHSCst);
3181 std::swap(LHSCC, RHSCC);
3182 }
3183
3184 // At this point, we know we have have two icmp instructions
3185 // comparing a value against two constants and or'ing the result
3186 // together. Because of the above check, we know that we only have
3187 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3188 // FoldICmpLogical check above), that the two constants are not
3189 // equal.
3190 assert(LHSCst != RHSCst && "Compares not folded above?");
3191
3192 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003193 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003194 case ICmpInst::ICMP_EQ:
3195 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003196 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003197 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00003198 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003199 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00003200 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003201 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00003202 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003203 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00003204 }
3205 break; // (X == 13 | X == 15) -> no change
3206 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3207 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
3208 break;
3209 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3210 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3211 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
3212 return ReplaceInstUsesWith(I, RHS);
3213 }
3214 break;
3215 case ICmpInst::ICMP_NE:
3216 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003217 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003218 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3219 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3220 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
3221 return ReplaceInstUsesWith(I, LHS);
3222 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3223 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3224 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00003225 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00003226 }
3227 break;
3228 case ICmpInst::ICMP_ULT:
3229 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003230 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003231 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
3232 break;
3233 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
3234 // If RHSCst is [us]MAXINT, it is always false. Not handling
3235 // this can cause overflow.
3236 if (RHSCst->isMaxValue(false))
3237 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00003238 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003239 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00003240 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3241 break;
3242 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3243 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
3244 return ReplaceInstUsesWith(I, RHS);
3245 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3246 break;
3247 }
3248 break;
3249 case ICmpInst::ICMP_SLT:
3250 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003251 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003252 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3253 break;
3254 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
3255 // If RHSCst is [us]MAXINT, it is always false. Not handling
3256 // this can cause overflow.
3257 if (RHSCst->isMaxValue(true))
3258 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00003259 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003260 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00003261 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3262 break;
3263 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3264 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3265 return ReplaceInstUsesWith(I, RHS);
3266 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3267 break;
3268 }
3269 break;
3270 case ICmpInst::ICMP_UGT:
3271 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003272 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003273 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3274 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3275 return ReplaceInstUsesWith(I, LHS);
3276 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3277 break;
3278 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3279 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00003280 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00003281 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3282 break;
3283 }
3284 break;
3285 case ICmpInst::ICMP_SGT:
3286 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003287 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003288 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3289 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3290 return ReplaceInstUsesWith(I, LHS);
3291 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3292 break;
3293 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3294 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00003295 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00003296 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3297 break;
3298 }
3299 break;
3300 }
3301 return 0;
3302}
3303
Chris Lattner5414cc52009-07-23 05:46:22 +00003304Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
3305 FCmpInst *RHS) {
3306 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
3307 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
3308 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
3309 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3310 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3311 // If either of the constants are nans, then the whole thing returns
3312 // true.
3313 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00003314 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00003315
3316 // Otherwise, no need to compare the two constants, compare the
3317 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003318 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00003319 LHS->getOperand(0), RHS->getOperand(0));
3320 }
3321
3322 // Handle vector zeros. This occurs because the canonical form of
3323 // "fcmp uno x,x" is "fcmp uno x, 0".
3324 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3325 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003326 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00003327 LHS->getOperand(0), RHS->getOperand(0));
3328
3329 return 0;
3330 }
3331
3332 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3333 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3334 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3335
3336 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3337 // Swap RHS operands to match LHS.
3338 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3339 std::swap(Op1LHS, Op1RHS);
3340 }
3341 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3342 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
3343 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003344 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00003345 Op0LHS, Op0RHS);
3346 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner4de84762010-01-04 07:02:48 +00003347 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00003348 if (Op0CC == FCmpInst::FCMP_FALSE)
3349 return ReplaceInstUsesWith(I, RHS);
3350 if (Op1CC == FCmpInst::FCMP_FALSE)
3351 return ReplaceInstUsesWith(I, LHS);
3352 bool Op0Ordered;
3353 bool Op1Ordered;
3354 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3355 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3356 if (Op0Ordered == Op1Ordered) {
3357 // If both are ordered or unordered, return a new fcmp with
3358 // or'ed predicates.
Chris Lattner4de84762010-01-04 07:02:48 +00003359 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +00003360 if (Instruction *I = dyn_cast<Instruction>(RV))
3361 return I;
3362 // Otherwise, it's a constant boolean value...
3363 return ReplaceInstUsesWith(I, RV);
3364 }
3365 }
3366 return 0;
3367}
3368
Bill Wendlinga698a472008-12-01 08:23:25 +00003369/// FoldOrWithConstants - This helper function folds:
3370///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00003371/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00003372///
3373/// into:
3374///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00003375/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00003376///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00003377/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00003378Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00003379 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00003380 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
3381 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00003382
Bill Wendling286a0542008-12-02 06:24:20 +00003383 Value *V1 = 0;
3384 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00003385 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00003386
Bill Wendling29976b92008-12-02 06:18:11 +00003387 APInt Xor = CI1->getValue() ^ CI2->getValue();
3388 if (!Xor.isAllOnesValue()) return 0;
3389
Bill Wendling286a0542008-12-02 06:24:20 +00003390 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00003391 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00003392 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00003393 }
3394
3395 return 0;
3396}
3397
Chris Lattner7e708292002-06-25 16:13:24 +00003398Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003399 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003400 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003401
Chris Lattnerd06094f2009-11-10 00:55:12 +00003402 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
3403 return ReplaceInstUsesWith(I, V);
3404
3405
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003406 // See if we can simplify any instructions used by the instruction whose sole
3407 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003408 if (SimplifyDemandedInstructionBits(I))
3409 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003410
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003411 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003412 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003413 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00003414 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003415 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00003416 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003417 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003418 return BinaryOperator::CreateAnd(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00003419 ConstantInt::get(I.getContext(),
3420 RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003421 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003422
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003423 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00003424 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003425 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00003426 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003427 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003428 return BinaryOperator::CreateXor(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00003429 ConstantInt::get(I.getContext(),
3430 C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003431 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003432
3433 // Try to fold constant and into select arguments.
3434 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00003435 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00003436 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003437 if (isa<PHINode>(Op0))
3438 if (Instruction *NV = FoldOpIntoPhi(I))
3439 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003440 }
3441
Chris Lattner4f637d42006-01-06 17:59:59 +00003442 Value *A = 0, *B = 0;
3443 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003444
Chris Lattner6423d4c2006-07-10 20:25:24 +00003445 // (A | B) | C and A | (B | C) -> bswap if possible.
3446 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00003447 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3448 match(Op1, m_Or(m_Value(), m_Value())) ||
3449 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3450 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003451 if (Instruction *BSwap = MatchBSwap(I))
3452 return BSwap;
3453 }
3454
Chris Lattner6e4c6492005-05-09 04:58:36 +00003455 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003456 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003457 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003458 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00003459 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00003460 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003461 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003462 }
3463
3464 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003465 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003466 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003467 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00003468 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00003469 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003470 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003471 }
3472
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003473 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00003474 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00003475 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3476 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003477 Value *V1 = 0, *V2 = 0, *V3 = 0;
3478 C1 = dyn_cast<ConstantInt>(C);
3479 C2 = dyn_cast<ConstantInt>(D);
3480 if (C1 && C2) { // (A & C1)|(B & C2)
3481 // If we have: ((V + N) & C1) | (V & C2)
3482 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3483 // replace with V+N.
3484 if (C1->getValue() == ~C2->getValue()) {
3485 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00003486 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003487 // Add commutes, try both ways.
3488 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3489 return ReplaceInstUsesWith(I, A);
3490 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3491 return ReplaceInstUsesWith(I, A);
3492 }
3493 // Or commutes, try both ways.
3494 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003495 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003496 // Add commutes, try both ways.
3497 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3498 return ReplaceInstUsesWith(I, B);
3499 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3500 return ReplaceInstUsesWith(I, B);
3501 }
3502 }
Chris Lattnere4412c12010-01-04 06:03:59 +00003503
3504 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
3505 // iff (C1&C2) == 0 and (N&~C1) == 0
3506 if ((C1->getValue() & C2->getValue()) == 0) {
3507 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
3508 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
3509 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
3510 return BinaryOperator::CreateAnd(A,
3511 ConstantInt::get(A->getContext(),
3512 C1->getValue()|C2->getValue()));
3513 // Or commutes, try both ways.
3514 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
3515 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
3516 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
3517 return BinaryOperator::CreateAnd(B,
3518 ConstantInt::get(B->getContext(),
3519 C1->getValue()|C2->getValue()));
3520 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00003521 }
3522
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003523 // Check to see if we have any common things being and'ed. If so, find the
3524 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003525 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
Chris Lattnere4412c12010-01-04 06:03:59 +00003526 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003527 if (A == B) // (A & C)|(A & D) == A & (C|D)
3528 V1 = A, V2 = C, V3 = D;
3529 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3530 V1 = A, V2 = B, V3 = C;
3531 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3532 V1 = C, V2 = A, V3 = D;
3533 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3534 V1 = C, V2 = A, V3 = B;
3535
3536 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00003537 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003538 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003539 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003540 }
Dan Gohmanb493b272008-10-28 22:38:57 +00003541
Dan Gohman1975d032008-10-30 20:40:10 +00003542 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner4de84762010-01-04 07:02:48 +00003543 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003544 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00003545 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003546 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00003547 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003548 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00003549 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003550 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00003551
Bill Wendlingb01865c2008-11-30 13:52:49 +00003552 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003553 if ((match(C, m_Not(m_Specific(D))) &&
3554 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003555 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00003556 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003557 if ((match(A, m_Not(m_Specific(D))) &&
3558 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003559 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00003560 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003561 if ((match(C, m_Not(m_Specific(B))) &&
3562 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003563 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00003564 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003565 if ((match(A, m_Not(m_Specific(B))) &&
3566 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003567 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003568 }
Chris Lattnere511b742006-11-14 07:46:50 +00003569
3570 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003571 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3572 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3573 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003574 SI0->getOperand(1) == SI1->getOperand(1) &&
3575 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00003576 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
3577 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003578 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003579 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003580 }
3581 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003582
Bill Wendlingb3833d12008-12-01 01:07:11 +00003583 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00003584 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
3585 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00003586 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00003587 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00003588 }
3589 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00003590 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
3591 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00003592 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00003593 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00003594 }
3595
Chris Lattnerd06094f2009-11-10 00:55:12 +00003596 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3597 if (Value *Op0NotVal = dyn_castNotVal(Op0))
3598 if (Value *Op1NotVal = dyn_castNotVal(Op1))
3599 if (Op0->hasOneUse() && Op1->hasOneUse()) {
3600 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
3601 I.getName()+".demorgan");
3602 return BinaryOperator::CreateNot(And);
3603 }
Chris Lattnera2881962003-02-18 19:28:33 +00003604
Reid Spencere4d87aa2006-12-23 06:05:41 +00003605 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3606 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00003607 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003608 return R;
3609
Chris Lattner69d4ced2008-11-16 05:20:07 +00003610 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
3611 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
3612 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003613 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003614
3615 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00003616 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003617 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003618 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00003619 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
3620 !isa<ICmpInst>(Op1C->getOperand(0))) {
3621 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00003622 if (SrcTy == Op1C->getOperand(0)->getType() &&
3623 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00003624 // Only do this if the casts both really cause code to be
3625 // generated.
3626 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003627 I.getType()) &&
Evan Chengb98a10e2008-03-24 00:21:34 +00003628 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003629 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00003630 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
3631 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003632 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00003633 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003634 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003635 }
Chris Lattner99c65742007-10-24 05:38:08 +00003636 }
3637
3638
3639 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
3640 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00003641 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
3642 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
3643 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00003644 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003645
Chris Lattner7e708292002-06-25 16:13:24 +00003646 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003647}
3648
Dan Gohman844731a2008-05-13 00:00:25 +00003649namespace {
3650
Chris Lattnerc317d392004-02-16 01:20:27 +00003651// XorSelf - Implements: X ^ X --> 0
3652struct XorSelf {
3653 Value *RHS;
3654 XorSelf(Value *rhs) : RHS(rhs) {}
3655 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3656 Instruction *apply(BinaryOperator &Xor) const {
3657 return &Xor;
3658 }
3659};
Chris Lattner3f5b8772002-05-06 16:14:14 +00003660
Dan Gohman844731a2008-05-13 00:00:25 +00003661}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003662
Chris Lattner7e708292002-06-25 16:13:24 +00003663Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003664 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003665 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003666
Evan Chengd34af782008-03-25 20:07:13 +00003667 if (isa<UndefValue>(Op1)) {
3668 if (isa<UndefValue>(Op0))
3669 // Handle undef ^ undef -> 0 special case. This is a common
3670 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00003671 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003672 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00003673 }
Chris Lattnere87597f2004-10-16 18:11:37 +00003674
Chris Lattnerc317d392004-02-16 01:20:27 +00003675 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00003676 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00003677 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00003678 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00003679 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003680
3681 // See if we can simplify any instructions used by the instruction whose sole
3682 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003683 if (SimplifyDemandedInstructionBits(I))
3684 return &I;
3685 if (isa<VectorType>(I.getType()))
3686 if (isa<ConstantAggregateZero>(Op1))
3687 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00003688
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003689 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00003690 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003691 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
3692 if (Op0I->getOpcode() == Instruction::And ||
3693 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00003694 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
3695 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
3696 if (dyn_castNotVal(Op0I->getOperand(1)))
3697 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00003698 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00003699 Value *NotY =
3700 Builder->CreateNot(Op0I->getOperand(1),
3701 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003702 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003703 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00003704 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003705 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00003706
3707 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
3708 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
3709 if (isFreeToInvert(Op0I->getOperand(0)) &&
3710 isFreeToInvert(Op0I->getOperand(1))) {
3711 Value *NotX =
3712 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
3713 Value *NotY =
3714 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
3715 if (Op0I->getOpcode() == Instruction::And)
3716 return BinaryOperator::CreateOr(NotX, NotY);
3717 return BinaryOperator::CreateAnd(NotX, NotY);
3718 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003719 }
3720 }
3721 }
3722
3723
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003724 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00003725 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00003726 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003727 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003728 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00003729 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00003730
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003731 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003732 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003733 FCI->getOperand(0), FCI->getOperand(1));
3734 }
3735
Nick Lewycky517e1f52008-05-31 19:01:33 +00003736 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
3737 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3738 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
3739 if (CI->hasOneUse() && Op0C->hasOneUse()) {
3740 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00003741 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
3742 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner4de84762010-01-04 07:02:48 +00003743 ConstantInt::getTrue(I.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +00003744 Op0C->getDestTy()))) {
3745 CI->setPredicate(CI->getInversePredicate());
3746 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00003747 }
3748 }
3749 }
3750 }
3751
Reid Spencere4d87aa2006-12-23 06:05:41 +00003752 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00003753 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00003754 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3755 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003756 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3757 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00003758 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003759 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003760 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00003761
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003762 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003763 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00003764 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00003765 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003766 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003767 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00003768 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00003769 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00003770 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00003771 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00003772 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner4de84762010-01-04 07:02:48 +00003773 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00003774 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003775 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00003776
Chris Lattner7c4049c2004-01-12 19:35:11 +00003777 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00003778 } else if (Op0I->getOpcode() == Instruction::Or) {
3779 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00003780 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003781 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00003782 // Anything in both C1 and C2 is known to be zero, remove it from
3783 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003784 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3785 NewRHS = ConstantExpr::getAnd(NewRHS,
3786 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00003787 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00003788 I.setOperand(0, Op0I->getOperand(0));
3789 I.setOperand(1, NewRHS);
3790 return &I;
3791 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003792 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003793 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00003794 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003795
3796 // Try to fold constant and into select arguments.
3797 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00003798 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00003799 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003800 if (isa<PHINode>(Op0))
3801 if (Instruction *NV = FoldOpIntoPhi(I))
3802 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003803 }
3804
Dan Gohman186a6362009-08-12 16:04:34 +00003805 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003806 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00003807 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003808
Dan Gohman186a6362009-08-12 16:04:34 +00003809 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003810 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00003811 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003812
Chris Lattner318bf792007-03-18 22:51:34 +00003813
3814 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
3815 if (Op1I) {
3816 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00003817 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003818 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003819 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00003820 I.swapOperands();
3821 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00003822 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003823 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00003824 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003825 }
Dan Gohman4ae51262009-08-12 16:23:25 +00003826 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003827 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003828 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003829 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003830 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003831 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00003832 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00003833 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00003834 std::swap(A, B);
3835 }
Chris Lattner318bf792007-03-18 22:51:34 +00003836 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00003837 I.swapOperands(); // Simplified below.
3838 std::swap(Op0, Op1);
3839 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003840 }
Chris Lattner318bf792007-03-18 22:51:34 +00003841 }
3842
3843 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
3844 if (Op0I) {
3845 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00003846 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003847 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00003848 if (A == Op1) // (B|A)^B == (A|B)^B
3849 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00003850 if (B == Op1) // (A|B)^B == A & ~B
3851 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00003852 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003853 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003854 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00003855 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00003856 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003857 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00003858 if (A == Op1) // (A&B)^A -> (B&A)^A
3859 std::swap(A, B);
3860 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00003861 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00003862 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00003863 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003864 }
Chris Lattner318bf792007-03-18 22:51:34 +00003865 }
3866
3867 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3868 if (Op0I && Op1I && Op0I->isShift() &&
3869 Op0I->getOpcode() == Op1I->getOpcode() &&
3870 Op0I->getOperand(1) == Op1I->getOperand(1) &&
3871 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00003872 Value *NewOp =
3873 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
3874 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003875 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00003876 Op1I->getOperand(1));
3877 }
3878
3879 if (Op0I && Op1I) {
3880 Value *A, *B, *C, *D;
3881 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003882 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3883 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003884 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003885 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003886 }
3887 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003888 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
3889 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003890 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003891 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003892 }
3893
3894 // (A & B)^(C & D)
3895 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003896 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3897 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003898 // (X & Y)^(X & Y) -> (Y^Z) & X
3899 Value *X = 0, *Y = 0, *Z = 0;
3900 if (A == C)
3901 X = A, Y = B, Z = D;
3902 else if (A == D)
3903 X = A, Y = B, Z = C;
3904 else if (B == C)
3905 X = B, Y = A, Z = D;
3906 else if (B == D)
3907 X = B, Y = A, Z = C;
3908
3909 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00003910 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003911 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00003912 }
3913 }
3914 }
3915
Reid Spencere4d87aa2006-12-23 06:05:41 +00003916 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3917 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00003918 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003919 return R;
3920
Chris Lattner6fc205f2006-05-05 06:39:07 +00003921 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00003922 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003923 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003924 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
3925 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003926 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003927 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003928 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003929 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00003930 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003931 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00003932 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
3933 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003934 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003935 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003936 }
Chris Lattner99c65742007-10-24 05:38:08 +00003937 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00003938
Chris Lattner7e708292002-06-25 16:13:24 +00003939 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003940}
3941
Chris Lattner3f5b8772002-05-06 16:14:14 +00003942
Reid Spencer832254e2007-02-02 02:16:23 +00003943Instruction *InstCombiner::visitShl(BinaryOperator &I) {
3944 return commonShiftTransforms(I);
3945}
3946
3947Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
3948 return commonShiftTransforms(I);
3949}
3950
3951Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00003952 if (Instruction *R = commonShiftTransforms(I))
3953 return R;
3954
3955 Value *Op0 = I.getOperand(0);
3956
3957 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
3958 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3959 if (CSI->isAllOnesValue())
3960 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00003961
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003962 // See if we can turn a signed shr into an unsigned shr.
3963 if (MaskedValueIsZero(Op0,
3964 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
3965 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
3966
3967 // Arithmetic shifting an all-sign-bit value is a no-op.
3968 unsigned NumSignBits = ComputeNumSignBits(Op0);
3969 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
3970 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00003971
Chris Lattner348f6652007-12-06 01:59:46 +00003972 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003973}
3974
3975Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
3976 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00003977 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003978
3979 // shl X, 0 == X and shr X, 0 == X
3980 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003981 if (Op1 == Constant::getNullValue(Op1->getType()) ||
3982 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00003983 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003984
Reid Spencere4d87aa2006-12-23 06:05:41 +00003985 if (isa<UndefValue>(Op0)) {
3986 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00003987 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003988 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003989 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003990 }
3991 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003992 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
3993 return ReplaceInstUsesWith(I, Op0);
3994 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003995 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003996 }
3997
Dan Gohman9004c8a2009-05-21 02:28:33 +00003998 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00003999 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00004000 return &I;
4001
Chris Lattner2eefe512004-04-09 19:05:30 +00004002 // Try to fold constant and into select arguments.
4003 if (isa<Constant>(Op0))
4004 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00004005 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00004006 return R;
4007
Reid Spencerb83eb642006-10-20 07:07:24 +00004008 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00004009 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4010 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004011 return 0;
4012}
4013
Reid Spencerb83eb642006-10-20 07:07:24 +00004014Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00004015 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00004016 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004017
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004018 // See if we can simplify any instructions used by the instruction whose sole
4019 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00004020 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004021
Dan Gohmana119de82009-06-14 23:30:43 +00004022 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
4023 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00004024 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004025 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00004026 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00004027 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00004028 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00004029 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00004030 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00004031 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004032 }
4033
4034 // ((X*C1) << C2) == (X * (C1 << C2))
4035 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4036 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4037 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004038 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00004039 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00004040
4041 // Try to fold constant and into select arguments.
4042 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00004043 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner4d5542c2006-01-06 07:12:35 +00004044 return R;
4045 if (isa<PHINode>(Op0))
4046 if (Instruction *NV = FoldOpIntoPhi(I))
4047 return NV;
4048
Chris Lattner8999dd32007-12-22 09:07:47 +00004049 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
4050 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
4051 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
4052 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
4053 // place. Don't try to do this transformation in this case. Also, we
4054 // require that the input operand is a shift-by-constant so that we have
4055 // confidence that the shifts will get folded together. We could do this
4056 // xform in more cases, but it is unlikely to be profitable.
4057 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
4058 isa<ConstantInt>(TrOp->getOperand(1))) {
4059 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00004060 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00004061 // (shift2 (shift1 & 0x00FF), c2)
4062 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00004063
4064 // For logical shifts, the truncation has the effect of making the high
4065 // part of the register be zeros. Emulate this by inserting an AND to
4066 // clear the top bits as needed. This 'and' will usually be zapped by
4067 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00004068 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
4069 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00004070 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
4071
4072 // The mask we constructed says what the trunc would do if occurring
4073 // between the shifts. We want to know the effect *after* the second
4074 // shift. We know that it is a logical shift by a constant, so adjust the
4075 // mask as appropriate.
4076 if (I.getOpcode() == Instruction::Shl)
4077 MaskV <<= Op1->getZExtValue();
4078 else {
4079 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
4080 MaskV = MaskV.lshr(Op1->getZExtValue());
4081 }
4082
Chris Lattner74381062009-08-30 07:44:24 +00004083 // shift1 & 0x00FF
Chris Lattner4de84762010-01-04 07:02:48 +00004084 Value *And = Builder->CreateAnd(NSh,
4085 ConstantInt::get(I.getContext(), MaskV),
Chris Lattner74381062009-08-30 07:44:24 +00004086 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00004087
4088 // Return the value truncated to the interesting size.
4089 return new TruncInst(And, I.getType());
4090 }
4091 }
4092
Chris Lattner4d5542c2006-01-06 07:12:35 +00004093 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004094 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4095 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4096 Value *V1, *V2;
4097 ConstantInt *CC;
4098 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00004099 default: break;
4100 case Instruction::Add:
4101 case Instruction::And:
4102 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00004103 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00004104 // These operators commute.
4105 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004106 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004107 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004108 m_Specific(Op1)))) {
4109 Value *YS = // (Y << C)
4110 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
4111 // (X + (Y << C))
4112 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
4113 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00004114 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00004115 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00004116 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00004117 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004118
Chris Lattner150f12a2005-09-18 06:30:59 +00004119 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00004120 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00004121 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00004122 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00004123 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00004124 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00004125 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004126 Value *YS = // (Y << C)
4127 Builder->CreateShl(Op0BO->getOperand(0), Op1,
4128 Op0BO->getName());
4129 // X & (CC << C)
4130 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
4131 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004132 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00004133 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00004134 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004135
Reid Spencera07cb7d2007-02-02 14:41:37 +00004136 // FALL THROUGH.
4137 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00004138 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004139 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004140 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00004141 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004142 Value *YS = // (Y << C)
4143 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
4144 // (X + (Y << C))
4145 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
4146 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00004147 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00004148 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00004149 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00004150 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004151
Chris Lattner13d4ab42006-05-31 21:14:00 +00004152 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004153 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4154 match(Op0BO->getOperand(0),
4155 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00004156 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004157 cast<BinaryOperator>(Op0BO->getOperand(0))
4158 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004159 Value *YS = // (Y << C)
4160 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
4161 // X & (CC << C)
4162 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
4163 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00004164
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004165 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00004166 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004167
Chris Lattner11021cb2005-09-18 05:12:10 +00004168 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00004169 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004170 }
4171
4172
4173 // If the operand is an bitwise operator with a constant RHS, and the
4174 // shift is the only use, we can pull it out of the shift.
4175 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4176 bool isValid = true; // Valid only for And, Or, Xor
4177 bool highBitSet = false; // Transform if high bit of constant set?
4178
4179 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00004180 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00004181 case Instruction::Add:
4182 isValid = isLeftShift;
4183 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00004184 case Instruction::Or:
4185 case Instruction::Xor:
4186 highBitSet = false;
4187 break;
4188 case Instruction::And:
4189 highBitSet = true;
4190 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004191 }
4192
4193 // If this is a signed shift right, and the high bit is modified
4194 // by the logical operation, do not perform the transformation.
4195 // The highBitSet boolean indicates the value of the high bit of
4196 // the constant which would cause it to be modified for this
4197 // operation.
4198 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00004199 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00004200 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004201
4202 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004203 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00004204
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004205 Value *NewShift =
4206 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004207 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00004208
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004209 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004210 NewRHS);
4211 }
4212 }
4213 }
4214 }
4215
Chris Lattnerad0124c2006-01-06 07:52:12 +00004216 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00004217 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
4218 if (ShiftOp && !ShiftOp->isShift())
4219 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00004220
Reid Spencerb83eb642006-10-20 07:07:24 +00004221 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004222 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004223 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
4224 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00004225 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
4226 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
4227 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00004228
Zhou Sheng4351c642007-04-02 08:20:41 +00004229 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00004230
4231 const IntegerType *Ty = cast<IntegerType>(I.getType());
4232
4233 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00004234 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00004235 // If this is oversized composite shift, then unsigned shifts get 0, ashr
4236 // saturates.
4237 if (AmtSum >= TypeBits) {
4238 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00004239 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00004240 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
4241 }
4242
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004243 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00004244 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004245 }
4246
4247 if (ShiftOp->getOpcode() == Instruction::LShr &&
4248 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00004249 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00004250 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00004251
Chris Lattnerb87056f2007-02-05 00:57:54 +00004252 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00004253 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004254 }
4255
4256 if (ShiftOp->getOpcode() == Instruction::AShr &&
4257 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00004258 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00004259 if (AmtSum >= TypeBits)
4260 AmtSum = TypeBits-1;
4261
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004262 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004263
Zhou Shenge9e03f62007-03-28 15:02:20 +00004264 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner4de84762010-01-04 07:02:48 +00004265 return BinaryOperator::CreateAnd(Shift,
4266 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00004267 }
4268
Chris Lattnerb87056f2007-02-05 00:57:54 +00004269 // Okay, if we get here, one shift must be left, and the other shift must be
4270 // right. See if the amounts are equal.
4271 if (ShiftAmt1 == ShiftAmt2) {
4272 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
4273 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00004274 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00004275 return BinaryOperator::CreateAnd(X,
4276 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004277 }
4278 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
4279 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004280 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00004281 return BinaryOperator::CreateAnd(X,
4282 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004283 }
4284 // We can simplify ((X << C) >>s C) into a trunc + sext.
4285 // NOTE: we could do this for any C, but that would make 'unusual' integer
4286 // types. For now, just stick to ones well-supported by the code
4287 // generators.
4288 const Type *SExtType = 0;
4289 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00004290 case 1 :
4291 case 8 :
4292 case 16 :
4293 case 32 :
4294 case 64 :
4295 case 128:
Chris Lattner4de84762010-01-04 07:02:48 +00004296 SExtType = IntegerType::get(I.getContext(),
4297 Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00004298 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00004299 default: break;
4300 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004301 if (SExtType)
4302 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00004303 // Otherwise, we can't handle it yet.
4304 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00004305 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00004306
Chris Lattnerb0b991a2007-02-05 05:57:49 +00004307 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00004308 if (I.getOpcode() == Instruction::Shl) {
4309 assert(ShiftOp->getOpcode() == Instruction::LShr ||
4310 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004311 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00004312
Reid Spencer55702aa2007-03-25 21:11:44 +00004313 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00004314 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00004315 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00004316 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00004317
Chris Lattnerb0b991a2007-02-05 05:57:49 +00004318 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00004319 if (I.getOpcode() == Instruction::LShr) {
4320 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004321 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00004322
Reid Spencerd5e30f02007-03-26 17:18:58 +00004323 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00004324 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00004325 ConstantInt::get(I.getContext(),Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00004326 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00004327
4328 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
4329 } else {
4330 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00004331 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00004332
Chris Lattnerb0b991a2007-02-05 05:57:49 +00004333 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00004334 if (I.getOpcode() == Instruction::Shl) {
4335 assert(ShiftOp->getOpcode() == Instruction::LShr ||
4336 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004337 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
4338 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004339
Reid Spencer55702aa2007-03-25 21:11:44 +00004340 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00004341 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00004342 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004343 }
4344
Chris Lattnerb0b991a2007-02-05 05:57:49 +00004345 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00004346 if (I.getOpcode() == Instruction::LShr) {
4347 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004348 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004349
Reid Spencer68d27cf2007-03-26 23:45:51 +00004350 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00004351 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00004352 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00004353 }
4354
4355 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00004356 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00004357 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004358 return 0;
4359}
4360
Chris Lattnera1be5662002-05-02 17:06:02 +00004361
Chris Lattnercfd65102005-10-29 04:36:15 +00004362/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4363/// expression. If so, decompose it, returning some value X, such that Val is
4364/// X*Scale+Offset.
4365///
4366static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Chris Lattner4de84762010-01-04 07:02:48 +00004367 int &Offset) {
4368 assert(Val->getType() == Type::getInt32Ty(Val->getContext()) &&
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004369 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00004370 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00004371 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00004372 Scale = 0;
Chris Lattner4de84762010-01-04 07:02:48 +00004373 return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00004374 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
4375 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4376 if (I->getOpcode() == Instruction::Shl) {
4377 // This is a value scaled by '1 << the shift amt'.
4378 Scale = 1U << RHS->getZExtValue();
4379 Offset = 0;
4380 return I->getOperand(0);
4381 } else if (I->getOpcode() == Instruction::Mul) {
4382 // This value is scaled by 'RHS'.
4383 Scale = RHS->getZExtValue();
4384 Offset = 0;
4385 return I->getOperand(0);
4386 } else if (I->getOpcode() == Instruction::Add) {
4387 // We have X+C. Check to see if we really have (X*C2)+C1,
4388 // where C1 is divisible by C2.
4389 unsigned SubScale;
4390 Value *SubVal =
Chris Lattner4de84762010-01-04 07:02:48 +00004391 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
Chris Lattner6a94de22007-10-12 05:30:59 +00004392 Offset += RHS->getZExtValue();
4393 Scale = SubScale;
4394 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00004395 }
4396 }
4397 }
4398
4399 // Otherwise, we can't look past this.
4400 Scale = 1;
4401 Offset = 0;
4402 return Val;
4403}
4404
4405
Chris Lattnerb3f83972005-10-24 06:03:58 +00004406/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4407/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00004408Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00004409 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00004410 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00004411
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004412 BuilderTy AllocaBuilder(*Builder);
4413 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
4414
Chris Lattnerb53c2382005-10-24 06:22:12 +00004415 // Remove any uses of AI that are dead.
4416 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00004417
Chris Lattnerb53c2382005-10-24 06:22:12 +00004418 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4419 Instruction *User = cast<Instruction>(*UI++);
4420 if (isInstructionTriviallyDead(User)) {
4421 while (UI != E && *UI == User)
4422 ++UI; // If this instruction uses AI more than once, don't break UI.
4423
Chris Lattnerb53c2382005-10-24 06:22:12 +00004424 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00004425 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00004426 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00004427 }
4428 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004429
4430 // This requires TargetData to get the alloca alignment and size information.
4431 if (!TD) return 0;
4432
Chris Lattnerb3f83972005-10-24 06:03:58 +00004433 // Get the type really allocated and the type casted to.
4434 const Type *AllocElTy = AI.getAllocatedType();
4435 const Type *CastElTy = PTy->getElementType();
4436 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004437
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004438 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
4439 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00004440 if (CastElTyAlign < AllocElTyAlign) return 0;
4441
Chris Lattner39387a52005-10-24 06:35:18 +00004442 // If the allocation has multiple uses, only promote it if we are strictly
4443 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00004444 // same, we open the door to infinite loops of various kinds. (A reference
4445 // from a dbg.declare doesn't count as a use for this purpose.)
4446 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
4447 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00004448
Duncan Sands777d2302009-05-09 07:06:46 +00004449 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
4450 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004451 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004452
Chris Lattner455fcc82005-10-29 03:19:53 +00004453 // See if we can satisfy the modulus by pulling a scale out of the array
4454 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00004455 unsigned ArraySizeScale;
4456 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00004457 Value *NumElements = // See if the array size is a decomposable linear expr.
Chris Lattner4de84762010-01-04 07:02:48 +00004458 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
Chris Lattnercfd65102005-10-29 04:36:15 +00004459
Chris Lattner455fcc82005-10-29 03:19:53 +00004460 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4461 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00004462 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4463 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00004464
Chris Lattner455fcc82005-10-29 03:19:53 +00004465 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4466 Value *Amt = 0;
4467 if (Scale == 1) {
4468 Amt = NumElements;
4469 } else {
Chris Lattner4de84762010-01-04 07:02:48 +00004470 Amt = ConstantInt::get(Type::getInt32Ty(CI.getContext()), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004471 // Insert before the alloca, not before the cast.
4472 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004473 }
4474
Jeff Cohen86796be2007-04-04 16:58:57 +00004475 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Chris Lattner4de84762010-01-04 07:02:48 +00004476 Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
4477 Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004478 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00004479 }
4480
Victor Hernandez7b929da2009-10-23 21:09:37 +00004481 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004482 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00004483 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00004484
Dale Johannesena0a66372009-03-05 00:39:02 +00004485 // If the allocation has one real use plus a dbg.declare, just remove the
4486 // declare.
4487 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
4488 EraseInstFromFunction(*DI);
4489 }
4490 // If the allocation has multiple real uses, insert a cast and change all
4491 // things that used it to use the new cast. This will also hack on CI, but it
4492 // will die soon.
4493 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004494 // New is the allocation instruction, pointer typed. AI is the original
4495 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004496 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00004497 AI.replaceAllUsesWith(NewCast);
4498 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00004499 return ReplaceInstUsesWith(CI, New);
4500}
4501
Reid Spencer3da59db2006-11-27 01:05:10 +00004502
Chris Lattner46cd5a12009-01-09 05:44:56 +00004503/// FindElementAtOffset - Given a type and a constant offset, determine whether
4504/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00004505/// the specified offset. If so, fill them into NewIndices and return the
4506/// resultant element type, otherwise return null.
Chris Lattner80f43d32010-01-04 07:53:58 +00004507const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
4508 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004509 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00004510 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00004511
4512 // Start with the index over the outer type. Note that the type size
4513 // might be zero (even if the offset isn't zero) if the indexed type
4514 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +00004515 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +00004516 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00004517 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00004518 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00004519 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00004520
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004521 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00004522 if (Offset < 0) {
4523 --FirstIdx;
4524 Offset += TySize;
4525 assert(Offset >= 0);
4526 }
4527 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
4528 }
4529
Owen Andersoneed707b2009-07-24 23:12:02 +00004530 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00004531
4532 // Index into the types. If we fail, set OrigBase to null.
4533 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004534 // Indexing into tail padding between struct/array elements.
4535 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00004536 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004537
Chris Lattner46cd5a12009-01-09 05:44:56 +00004538 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
4539 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004540 assert(Offset < (int64_t)SL->getSizeInBytes() &&
4541 "Offset must stay within the indexed type");
4542
Chris Lattner46cd5a12009-01-09 05:44:56 +00004543 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +00004544 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
4545 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00004546
4547 Offset -= SL->getElementOffset(Elt);
4548 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00004549 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00004550 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004551 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00004552 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004553 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00004554 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00004555 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00004556 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00004557 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00004558 }
4559 }
4560
Chris Lattner3914f722009-01-24 01:00:13 +00004561 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00004562}
4563
Chris Lattner8a2a3112001-12-14 16:52:21 +00004564
Chris Lattnere576b912004-04-09 23:46:01 +00004565/// GetSelectFoldableOperands - We want to turn code that looks like this:
4566/// %C = or %A, %B
4567/// %D = select %cond, %C, %A
4568/// into:
4569/// %C = select %cond, %B, 0
4570/// %D = or %A, %C
4571///
4572/// Assuming that the specified instruction is an operand to the select, return
4573/// a bitmask indicating which operands of this instruction are foldable if they
4574/// equal the other incoming value of the select.
4575///
4576static unsigned GetSelectFoldableOperands(Instruction *I) {
4577 switch (I->getOpcode()) {
4578 case Instruction::Add:
4579 case Instruction::Mul:
4580 case Instruction::And:
4581 case Instruction::Or:
4582 case Instruction::Xor:
4583 return 3; // Can fold through either operand.
4584 case Instruction::Sub: // Can only fold on the amount subtracted.
4585 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00004586 case Instruction::LShr:
4587 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00004588 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00004589 default:
4590 return 0; // Cannot fold
4591 }
4592}
4593
4594/// GetSelectFoldableConstant - For the same transformation as the previous
4595/// function, return the identity constant that goes into the select.
Chris Lattner4de84762010-01-04 07:02:48 +00004596static Constant *GetSelectFoldableConstant(Instruction *I) {
Chris Lattnere576b912004-04-09 23:46:01 +00004597 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004598 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00004599 case Instruction::Add:
4600 case Instruction::Sub:
4601 case Instruction::Or:
4602 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00004603 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00004604 case Instruction::LShr:
4605 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00004606 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00004607 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00004608 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00004609 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00004610 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00004611 }
4612}
4613
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004614/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4615/// have the same opcode and only one use each. Try to simplify this.
4616Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4617 Instruction *FI) {
4618 if (TI->getNumOperands() == 1) {
4619 // If this is a non-volatile load or a cast from the same type,
4620 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00004621 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004622 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4623 return 0;
4624 } else {
4625 return 0; // unknown unary op.
4626 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004627
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004628 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00004629 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00004630 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004631 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004632 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00004633 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004634 }
4635
Reid Spencer832254e2007-02-02 02:16:23 +00004636 // Only handle binary operators here.
4637 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004638 return 0;
4639
4640 // Figure out if the operations have any operands in common.
4641 Value *MatchOp, *OtherOpT, *OtherOpF;
4642 bool MatchIsOpZero;
4643 if (TI->getOperand(0) == FI->getOperand(0)) {
4644 MatchOp = TI->getOperand(0);
4645 OtherOpT = TI->getOperand(1);
4646 OtherOpF = FI->getOperand(1);
4647 MatchIsOpZero = true;
4648 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4649 MatchOp = TI->getOperand(1);
4650 OtherOpT = TI->getOperand(0);
4651 OtherOpF = FI->getOperand(0);
4652 MatchIsOpZero = false;
4653 } else if (!TI->isCommutative()) {
4654 return 0;
4655 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4656 MatchOp = TI->getOperand(0);
4657 OtherOpT = TI->getOperand(1);
4658 OtherOpF = FI->getOperand(0);
4659 MatchIsOpZero = true;
4660 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4661 MatchOp = TI->getOperand(1);
4662 OtherOpT = TI->getOperand(0);
4663 OtherOpF = FI->getOperand(1);
4664 MatchIsOpZero = true;
4665 } else {
4666 return 0;
4667 }
4668
4669 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00004670 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
4671 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004672 InsertNewInstBefore(NewSI, SI);
4673
4674 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4675 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004676 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004677 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004678 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004679 }
Torok Edwinc23197a2009-07-14 16:55:14 +00004680 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00004681 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004682}
4683
Evan Chengde621922009-03-31 20:42:45 +00004684static bool isSelect01(Constant *C1, Constant *C2) {
4685 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
4686 if (!C1I)
4687 return false;
4688 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
4689 if (!C2I)
4690 return false;
4691 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
4692}
4693
4694/// FoldSelectIntoOp - Try fold the select into one of the operands to
4695/// facilitate further optimization.
4696Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
4697 Value *FalseVal) {
4698 // See the comment above GetSelectFoldableOperands for a description of the
4699 // transformation we are doing here.
4700 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
4701 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4702 !isa<Constant>(FalseVal)) {
4703 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4704 unsigned OpToFold = 0;
4705 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4706 OpToFold = 1;
4707 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4708 OpToFold = 2;
4709 }
4710
4711 if (OpToFold) {
Chris Lattner4de84762010-01-04 07:02:48 +00004712 Constant *C = GetSelectFoldableConstant(TVI);
Evan Chengde621922009-03-31 20:42:45 +00004713 Value *OOp = TVI->getOperand(2-OpToFold);
4714 // Avoid creating select between 2 constants unless it's selecting
4715 // between 0 and 1.
4716 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
4717 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
4718 InsertNewInstBefore(NewSel, SI);
4719 NewSel->takeName(TVI);
4720 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4721 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00004722 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00004723 }
4724 }
4725 }
4726 }
4727 }
4728
4729 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
4730 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4731 !isa<Constant>(TrueVal)) {
4732 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4733 unsigned OpToFold = 0;
4734 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4735 OpToFold = 1;
4736 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4737 OpToFold = 2;
4738 }
4739
4740 if (OpToFold) {
Chris Lattner4de84762010-01-04 07:02:48 +00004741 Constant *C = GetSelectFoldableConstant(FVI);
Evan Chengde621922009-03-31 20:42:45 +00004742 Value *OOp = FVI->getOperand(2-OpToFold);
4743 // Avoid creating select between 2 constants unless it's selecting
4744 // between 0 and 1.
4745 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
4746 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
4747 InsertNewInstBefore(NewSel, SI);
4748 NewSel->takeName(FVI);
4749 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4750 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00004751 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00004752 }
4753 }
4754 }
4755 }
4756 }
4757
4758 return 0;
4759}
4760
Dan Gohman81b28ce2008-09-16 18:46:06 +00004761/// visitSelectInstWithICmp - Visit a SelectInst that has an
4762/// ICmpInst as its first operand.
4763///
4764Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
4765 ICmpInst *ICI) {
4766 bool Changed = false;
4767 ICmpInst::Predicate Pred = ICI->getPredicate();
4768 Value *CmpLHS = ICI->getOperand(0);
4769 Value *CmpRHS = ICI->getOperand(1);
4770 Value *TrueVal = SI.getTrueValue();
4771 Value *FalseVal = SI.getFalseValue();
4772
4773 // Check cases where the comparison is with a constant that
4774 // can be adjusted to fit the min/max idiom. We may edit ICI in
4775 // place here, so make sure the select is the only user.
4776 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00004777 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00004778 switch (Pred) {
4779 default: break;
4780 case ICmpInst::ICMP_ULT:
4781 case ICmpInst::ICMP_SLT: {
4782 // X < MIN ? T : F --> F
4783 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
4784 return ReplaceInstUsesWith(SI, FalseVal);
4785 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00004786 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00004787 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
4788 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
4789 Pred = ICmpInst::getSwappedPredicate(Pred);
4790 CmpRHS = AdjustedRHS;
4791 std::swap(FalseVal, TrueVal);
4792 ICI->setPredicate(Pred);
4793 ICI->setOperand(1, CmpRHS);
4794 SI.setOperand(1, TrueVal);
4795 SI.setOperand(2, FalseVal);
4796 Changed = true;
4797 }
4798 break;
4799 }
4800 case ICmpInst::ICMP_UGT:
4801 case ICmpInst::ICMP_SGT: {
4802 // X > MAX ? T : F --> F
4803 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
4804 return ReplaceInstUsesWith(SI, FalseVal);
4805 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00004806 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00004807 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
4808 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
4809 Pred = ICmpInst::getSwappedPredicate(Pred);
4810 CmpRHS = AdjustedRHS;
4811 std::swap(FalseVal, TrueVal);
4812 ICI->setPredicate(Pred);
4813 ICI->setOperand(1, CmpRHS);
4814 SI.setOperand(1, TrueVal);
4815 SI.setOperand(2, FalseVal);
4816 Changed = true;
4817 }
4818 break;
4819 }
4820 }
4821
Dan Gohman1975d032008-10-30 20:40:10 +00004822 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
4823 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00004824 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00004825 if (match(TrueVal, m_ConstantInt<-1>()) &&
4826 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00004827 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00004828 else if (match(TrueVal, m_ConstantInt<0>()) &&
4829 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00004830 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
4831
Dan Gohman1975d032008-10-30 20:40:10 +00004832 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
4833 // If we are just checking for a icmp eq of a single bit and zext'ing it
4834 // to an integer, then shift the bit to the appropriate place and then
4835 // cast to integer to avoid the comparison.
4836 const APInt &Op1CV = CI->getValue();
4837
4838 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
4839 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
4840 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00004841 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00004842 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00004843 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00004844 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00004845 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00004846 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00004847 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00004848 if (In->getType() != SI.getType())
4849 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00004850 true/*SExt*/, "tmp", ICI);
4851
4852 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00004853 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00004854 In->getName()+".not"), *ICI);
4855
4856 return ReplaceInstUsesWith(SI, In);
4857 }
4858 }
4859 }
4860
Dan Gohman81b28ce2008-09-16 18:46:06 +00004861 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
4862 // Transform (X == Y) ? X : Y -> Y
4863 if (Pred == ICmpInst::ICMP_EQ)
4864 return ReplaceInstUsesWith(SI, FalseVal);
4865 // Transform (X != Y) ? X : Y -> X
4866 if (Pred == ICmpInst::ICMP_NE)
4867 return ReplaceInstUsesWith(SI, TrueVal);
4868 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
4869
4870 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
4871 // Transform (X == Y) ? Y : X -> X
4872 if (Pred == ICmpInst::ICMP_EQ)
4873 return ReplaceInstUsesWith(SI, FalseVal);
4874 // Transform (X != Y) ? Y : X -> Y
4875 if (Pred == ICmpInst::ICMP_NE)
4876 return ReplaceInstUsesWith(SI, TrueVal);
4877 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
4878 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00004879 return Changed ? &SI : 0;
4880}
4881
Chris Lattnerc6df8f42009-09-27 20:18:49 +00004882
Chris Lattner7f239582009-10-22 00:17:26 +00004883/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
4884/// PHI node (but the two may be in different blocks). See if the true/false
4885/// values (V) are live in all of the predecessor blocks of the PHI. For
4886/// example, cases like this cannot be mapped:
4887///
4888/// X = phi [ C1, BB1], [C2, BB2]
4889/// Y = add
4890/// Z = select X, Y, 0
4891///
4892/// because Y is not live in BB1/BB2.
4893///
4894static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
4895 const SelectInst &SI) {
4896 // If the value is a non-instruction value like a constant or argument, it
4897 // can always be mapped.
4898 const Instruction *I = dyn_cast<Instruction>(V);
4899 if (I == 0) return true;
4900
4901 // If V is a PHI node defined in the same block as the condition PHI, we can
4902 // map the arguments.
4903 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
4904
4905 if (const PHINode *VP = dyn_cast<PHINode>(I))
4906 if (VP->getParent() == CondPHI->getParent())
4907 return true;
4908
4909 // Otherwise, if the PHI and select are defined in the same block and if V is
4910 // defined in a different block, then we can transform it.
4911 if (SI.getParent() == CondPHI->getParent() &&
4912 I->getParent() != CondPHI->getParent())
4913 return true;
4914
4915 // Otherwise we have a 'hard' case and we can't tell without doing more
4916 // detailed dominator based analysis, punt.
4917 return false;
4918}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00004919
Chris Lattnerb109b5c2009-12-21 06:03:05 +00004920/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
4921/// SPF2(SPF1(A, B), C)
4922Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
4923 SelectPatternFlavor SPF1,
4924 Value *A, Value *B,
4925 Instruction &Outer,
4926 SelectPatternFlavor SPF2, Value *C) {
4927 if (C == A || C == B) {
4928 // MAX(MAX(A, B), B) -> MAX(A, B)
4929 // MIN(MIN(a, b), a) -> MIN(a, b)
4930 if (SPF1 == SPF2)
4931 return ReplaceInstUsesWith(Outer, Inner);
4932
4933 // MAX(MIN(a, b), a) -> a
4934 // MIN(MAX(a, b), a) -> a
Daniel Dunbareddfaaf2009-12-21 23:27:57 +00004935 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
4936 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
4937 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
4938 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattnerb109b5c2009-12-21 06:03:05 +00004939 return ReplaceInstUsesWith(Outer, C);
4940 }
4941
4942 // TODO: MIN(MIN(A, 23), 97)
4943 return 0;
4944}
4945
4946
4947
4948
Chris Lattner3d69f462004-03-12 05:52:32 +00004949Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004950 Value *CondVal = SI.getCondition();
4951 Value *TrueVal = SI.getTrueValue();
4952 Value *FalseVal = SI.getFalseValue();
4953
4954 // select true, X, Y -> X
4955 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004956 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00004957 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004958
4959 // select C, X, X -> X
4960 if (TrueVal == FalseVal)
4961 return ReplaceInstUsesWith(SI, TrueVal);
4962
Chris Lattnere87597f2004-10-16 18:11:37 +00004963 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4964 return ReplaceInstUsesWith(SI, FalseVal);
4965 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4966 return ReplaceInstUsesWith(SI, TrueVal);
4967 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4968 if (isa<Constant>(TrueVal))
4969 return ReplaceInstUsesWith(SI, TrueVal);
4970 else
4971 return ReplaceInstUsesWith(SI, FalseVal);
4972 }
4973
Chris Lattner4de84762010-01-04 07:02:48 +00004974 if (SI.getType() == Type::getInt1Ty(SI.getContext())) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00004975 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00004976 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00004977 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004978 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004979 } else {
4980 // Change: A = select B, false, C --> A = and !B, C
4981 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00004982 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00004983 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004984 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004985 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00004986 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00004987 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00004988 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004989 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004990 } else {
4991 // Change: A = select B, C, true --> A = or !B, C
4992 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00004993 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00004994 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004995 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004996 }
4997 }
Chris Lattnercfa59752007-11-25 21:27:53 +00004998
4999 // select a, b, a -> a&b
5000 // select a, a, b -> a|b
5001 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005002 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00005003 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005004 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005005 }
Chris Lattner0c199a72004-04-08 04:43:23 +00005006
Chris Lattner2eefe512004-04-09 19:05:30 +00005007 // Selecting between two integer constants?
5008 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5009 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00005010 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00005011 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005012 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00005013 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00005014 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00005015 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00005016 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00005017 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005018 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00005019 }
Chris Lattner457dd822004-06-09 07:59:58 +00005020
Reid Spencere4d87aa2006-12-23 06:05:41 +00005021 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00005022 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00005023 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00005024 // non-constant value, eliminate this whole mess. This corresponds to
5025 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00005026 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00005027 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00005028 cast<Constant>(IC->getOperand(1))->isNullValue())
5029 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5030 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005031 isa<ConstantInt>(ICA->getOperand(1)) &&
5032 (ICA->getOperand(1) == TrueValC ||
5033 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00005034 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5035 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00005036 // know whether we have a icmp_ne or icmp_eq and whether the
5037 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00005038 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005039 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00005040 Value *V = ICA;
5041 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005042 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00005043 Instruction::Xor, V, ICA->getOperand(1)), SI);
5044 return ReplaceInstUsesWith(SI, V);
5045 }
Chris Lattnerb8456462006-09-20 04:44:59 +00005046 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005047 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00005048
5049 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005050 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
5051 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00005052 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00005053 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
5054 // This is not safe in general for floating point:
5055 // consider X== -0, Y== +0.
5056 // It becomes safe if either operand is a nonzero constant.
5057 ConstantFP *CFPt, *CFPf;
5058 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
5059 !CFPt->getValueAPF().isZero()) ||
5060 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
5061 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00005062 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00005063 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00005064 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00005065 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00005066 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00005067 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00005068
Reid Spencere4d87aa2006-12-23 06:05:41 +00005069 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00005070 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00005071 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
5072 // This is not safe in general for floating point:
5073 // consider X== -0, Y== +0.
5074 // It becomes safe if either operand is a nonzero constant.
5075 ConstantFP *CFPt, *CFPf;
5076 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
5077 !CFPt->getValueAPF().isZero()) ||
5078 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
5079 !CFPf->getValueAPF().isZero()))
5080 return ReplaceInstUsesWith(SI, FalseVal);
5081 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00005082 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00005083 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
5084 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00005085 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00005086 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00005087 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00005088 }
5089
5090 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00005091 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
5092 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
5093 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00005094
Chris Lattner87875da2005-01-13 22:52:24 +00005095 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5096 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5097 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00005098 Instruction *AddOp = 0, *SubOp = 0;
5099
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005100 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5101 if (TI->getOpcode() == FI->getOpcode())
5102 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5103 return IV;
5104
5105 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5106 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00005107 if ((TI->getOpcode() == Instruction::Sub &&
5108 FI->getOpcode() == Instruction::Add) ||
5109 (TI->getOpcode() == Instruction::FSub &&
5110 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00005111 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00005112 } else if ((FI->getOpcode() == Instruction::Sub &&
5113 TI->getOpcode() == Instruction::Add) ||
5114 (FI->getOpcode() == Instruction::FSub &&
5115 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00005116 AddOp = TI; SubOp = FI;
5117 }
5118
5119 if (AddOp) {
5120 Value *OtherAddOp = 0;
5121 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5122 OtherAddOp = AddOp->getOperand(1);
5123 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5124 OtherAddOp = AddOp->getOperand(0);
5125 }
5126
5127 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00005128 // So at this point we know we have (Y -> OtherAddOp):
5129 // select C, (add X, Y), (sub X, Z)
5130 Value *NegVal; // Compute -Z
5131 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005132 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00005133 } else {
5134 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00005135 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00005136 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00005137 }
Chris Lattner97f37a42006-02-24 18:05:58 +00005138
5139 Value *NewTrueOp = OtherAddOp;
5140 Value *NewFalseOp = NegVal;
5141 if (AddOp != TI)
5142 std::swap(NewTrueOp, NewFalseOp);
5143 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00005144 SelectInst::Create(CondVal, NewTrueOp,
5145 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00005146
5147 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005148 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00005149 }
5150 }
5151 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005152
Chris Lattnere576b912004-04-09 23:46:01 +00005153 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00005154 if (SI.getType()->isInteger()) {
Chris Lattnerb109b5c2009-12-21 06:03:05 +00005155 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Chengde621922009-03-31 20:42:45 +00005156 return FoldI;
Chris Lattnerb109b5c2009-12-21 06:03:05 +00005157
5158 // MAX(MAX(a, b), a) -> MAX(a, b)
5159 // MIN(MIN(a, b), a) -> MIN(a, b)
5160 // MAX(MIN(a, b), a) -> a
5161 // MIN(MAX(a, b), a) -> a
5162 Value *LHS, *RHS, *LHS2, *RHS2;
5163 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
5164 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
5165 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
5166 SI, SPF, RHS))
5167 return R;
5168 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
5169 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
5170 SI, SPF, LHS))
5171 return R;
5172 }
5173
5174 // TODO.
5175 // ABS(-X) -> ABS(X)
5176 // ABS(ABS(X)) -> ABS(X)
Chris Lattnere576b912004-04-09 23:46:01 +00005177 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00005178
Chris Lattner7f239582009-10-22 00:17:26 +00005179 // See if we can fold the select into a phi node if the condition is a select.
5180 if (isa<PHINode>(SI.getCondition()))
5181 // The true/false values have to be live in the PHI predecessor's blocks.
5182 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
5183 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
5184 if (Instruction *NV = FoldOpIntoPhi(SI))
5185 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00005186
Chris Lattnera1df33c2005-04-24 07:30:14 +00005187 if (BinaryOperator::isNot(CondVal)) {
5188 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5189 SI.setOperand(1, FalseVal);
5190 SI.setOperand(2, TrueVal);
5191 return &SI;
5192 }
5193
Chris Lattner3d69f462004-03-12 05:52:32 +00005194 return 0;
5195}
5196
Dan Gohmaneee962e2008-04-10 18:43:06 +00005197/// EnforceKnownAlignment - If the specified pointer points to an object that
5198/// we control, modify the object's alignment to PrefAlign. This isn't
5199/// often possible though. If alignment is important, a more reliable approach
5200/// is to simply align all global variables and allocation instructions to
5201/// their preferred alignment from the beginning.
5202///
5203static unsigned EnforceKnownAlignment(Value *V,
5204 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00005205
Dan Gohmaneee962e2008-04-10 18:43:06 +00005206 User *U = dyn_cast<User>(V);
5207 if (!U) return Align;
5208
Dan Gohmanca178902009-07-17 20:47:02 +00005209 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00005210 default: break;
5211 case Instruction::BitCast:
5212 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
5213 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00005214 // If all indexes are zero, it is just the alignment of the base pointer.
5215 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00005216 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00005217 if (!isa<Constant>(*i) ||
5218 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00005219 AllZeroOperands = false;
5220 break;
5221 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00005222
5223 if (AllZeroOperands) {
5224 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00005225 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00005226 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00005227 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00005228 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00005229 }
5230
5231 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
5232 // If there is a large requested alignment and we can, bump up the alignment
5233 // of the global.
5234 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00005235 if (GV->getAlignment() >= PrefAlign)
5236 Align = GV->getAlignment();
5237 else {
5238 GV->setAlignment(PrefAlign);
5239 Align = PrefAlign;
5240 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00005241 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00005242 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
5243 // If there is a requested alignment and if this is an alloca, round up.
5244 if (AI->getAlignment() >= PrefAlign)
5245 Align = AI->getAlignment();
5246 else {
5247 AI->setAlignment(PrefAlign);
5248 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00005249 }
5250 }
5251
5252 return Align;
5253}
5254
5255/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
5256/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
5257/// and it is more than the alignment of the ultimate object, see if we can
5258/// increase the alignment of the ultimate object, making this check succeed.
5259unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
5260 unsigned PrefAlign) {
5261 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
5262 sizeof(PrefAlign) * CHAR_BIT;
5263 APInt Mask = APInt::getAllOnesValue(BitWidth);
5264 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5265 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
5266 unsigned TrailZ = KnownZero.countTrailingOnes();
5267 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
5268
5269 if (PrefAlign > Align)
5270 Align = EnforceKnownAlignment(V, Align, PrefAlign);
5271
5272 // We don't need to make any adjustment.
5273 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00005274}
5275
Chris Lattnerf497b022008-01-13 23:50:23 +00005276Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00005277 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00005278 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00005279 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00005280 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00005281
5282 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005283 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00005284 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00005285 return MI;
5286 }
5287
5288 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
5289 // load/store.
5290 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
5291 if (MemOpLength == 0) return 0;
5292
Chris Lattner37ac6082008-01-14 00:28:35 +00005293 // Source and destination pointer types are always "i8*" for intrinsic. See
5294 // if the size is something we can handle with a single primitive load/store.
5295 // A single load+store correctly handles overlapping memory in the memmove
5296 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00005297 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00005298 if (Size == 0) return MI; // Delete this mem transfer.
5299
5300 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00005301 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00005302
Chris Lattner37ac6082008-01-14 00:28:35 +00005303 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00005304 Type *NewPtrTy =
Chris Lattner4de84762010-01-04 07:02:48 +00005305 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00005306
5307 // Memcpy forces the use of i8* for the source and destination. That means
5308 // that if you're using memcpy to move one double around, you'll get a cast
5309 // from double* to i8*. We'd much rather use a double load+store rather than
5310 // an i64 load+store, here because this improves the odds that the source or
5311 // dest address will be promotable. See if we can find a better type than the
5312 // integer datatype.
5313 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
5314 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005315 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00005316 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
5317 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00005318 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00005319 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
5320 if (STy->getNumElements() == 1)
5321 SrcETy = STy->getElementType(0);
5322 else
5323 break;
5324 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
5325 if (ATy->getNumElements() == 1)
5326 SrcETy = ATy->getElementType();
5327 else
5328 break;
5329 } else
5330 break;
5331 }
5332
Dan Gohman8f8e2692008-05-23 01:52:21 +00005333 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00005334 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00005335 }
5336 }
5337
5338
Chris Lattnerf497b022008-01-13 23:50:23 +00005339 // If the memcpy/memmove provides better alignment info than we can
5340 // infer, use it.
5341 SrcAlign = std::max(SrcAlign, CopyAlign);
5342 DstAlign = std::max(DstAlign, CopyAlign);
5343
Chris Lattner08142f22009-08-30 19:47:22 +00005344 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
5345 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00005346 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
5347 InsertNewInstBefore(L, *MI);
5348 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
5349
5350 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00005351 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00005352 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00005353}
Chris Lattner3d69f462004-03-12 05:52:32 +00005354
Chris Lattner69ea9d22008-04-30 06:39:11 +00005355Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
5356 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00005357 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005358 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00005359 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00005360 return MI;
5361 }
5362
5363 // Extract the length and alignment and fill if they are constant.
5364 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
5365 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Chris Lattner4de84762010-01-04 07:02:48 +00005366 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner69ea9d22008-04-30 06:39:11 +00005367 return 0;
5368 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00005369 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00005370
5371 // If the length is zero, this is a no-op
5372 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
5373
5374 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
5375 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner4de84762010-01-04 07:02:48 +00005376 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00005377
5378 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00005379 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00005380
5381 // Alignment 0 is identity for alignment 1 for memset, but not store.
5382 if (Alignment == 0) Alignment = 1;
5383
5384 // Extract the fill value and store.
5385 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00005386 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00005387 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00005388
5389 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00005390 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00005391 return MI;
5392 }
5393
5394 return 0;
5395}
5396
5397
Chris Lattner8b0ea312006-01-13 20:11:04 +00005398/// visitCallInst - CallInst simplification. This mostly only handles folding
5399/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5400/// the heavy lifting.
5401///
Chris Lattner9fe38862003-06-19 17:00:31 +00005402Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00005403 if (isFreeCall(&CI))
5404 return visitFree(CI);
5405
Chris Lattneraab6ec42009-05-13 17:39:14 +00005406 // If the caller function is nounwind, mark the call as nounwind, even if the
5407 // callee isn't.
5408 if (CI.getParent()->getParent()->doesNotThrow() &&
5409 !CI.doesNotThrow()) {
5410 CI.setDoesNotThrow();
5411 return &CI;
5412 }
5413
Chris Lattner8b0ea312006-01-13 20:11:04 +00005414 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5415 if (!II) return visitCallSite(&CI);
5416
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005417 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5418 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00005419 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005420 bool Changed = false;
5421
5422 // memmove/cpy/set of zero bytes is a noop.
5423 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5424 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5425
Chris Lattner35b9e482004-10-12 04:52:52 +00005426 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00005427 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005428 // Replace the instruction with just byte operations. We would
5429 // transform other cases to loads/stores, but we don't know if
5430 // alignment is sufficient.
5431 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005432 }
5433
Chris Lattner35b9e482004-10-12 04:52:52 +00005434 // If we have a memmove and the source operation is a constant global,
5435 // then the source and dest pointers can't alias, so we can change this
5436 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00005437 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005438 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5439 if (GVSrc->isConstant()) {
5440 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00005441 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
5442 const Type *Tys[1];
5443 Tys[0] = CI.getOperand(3)->getType();
5444 CI.setOperand(0,
5445 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00005446 Changed = true;
5447 }
Eli Friedman0c826d92009-12-17 21:07:31 +00005448 }
Chris Lattnera935db82008-05-28 05:30:41 +00005449
Eli Friedman0c826d92009-12-17 21:07:31 +00005450 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +00005451 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +00005452 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +00005453 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00005454 }
Chris Lattner35b9e482004-10-12 04:52:52 +00005455
Chris Lattner95a959d2006-03-06 20:18:44 +00005456 // If we can determine a pointer alignment that is bigger than currently
5457 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00005458 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00005459 if (Instruction *I = SimplifyMemTransfer(MI))
5460 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00005461 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
5462 if (Instruction *I = SimplifyMemSet(MSI))
5463 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00005464 }
5465
Chris Lattner8b0ea312006-01-13 20:11:04 +00005466 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00005467 }
5468
5469 switch (II->getIntrinsicID()) {
5470 default: break;
5471 case Intrinsic::bswap:
5472 // bswap(bswap(x)) -> x
5473 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
5474 if (Operand->getIntrinsicID() == Intrinsic::bswap)
5475 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +00005476
5477 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
5478 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
5479 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
5480 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
5481 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
5482 TI->getType()->getPrimitiveSizeInBits();
5483 Value *CV = ConstantInt::get(Operand->getType(), C);
5484 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
5485 return new TruncInst(V, TI->getType());
5486 }
5487 }
5488
Chris Lattner0521e3c2008-06-18 04:33:20 +00005489 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +00005490 case Intrinsic::powi:
5491 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
5492 // powi(x, 0) -> 1.0
5493 if (Power->isZero())
5494 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
5495 // powi(x, 1) -> x
5496 if (Power->isOne())
5497 return ReplaceInstUsesWith(CI, II->getOperand(1));
5498 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +00005499 if (Power->isAllOnesValue())
5500 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
5501 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +00005502 }
5503 break;
5504
Chris Lattner2bbac752009-11-26 21:42:47 +00005505 case Intrinsic::uadd_with_overflow: {
5506 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5507 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
5508 uint32_t BitWidth = IT->getBitWidth();
5509 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +00005510 APInt LHSKnownZero(BitWidth, 0);
5511 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00005512 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
5513 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
5514 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
5515
5516 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +00005517 APInt RHSKnownZero(BitWidth, 0);
5518 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00005519 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
5520 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
5521 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
5522 if (LHSKnownNegative && RHSKnownNegative) {
5523 // The sign bit is set in both cases: this MUST overflow.
5524 // Create a simple add instruction, and insert it into the struct.
5525 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
5526 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00005527 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00005528 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00005529 };
Chris Lattner4de84762010-01-04 07:02:48 +00005530 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00005531 return InsertValueInst::Create(Struct, Add, 0);
5532 }
5533
5534 if (LHSKnownPositive && RHSKnownPositive) {
5535 // The sign bit is clear in both cases: this CANNOT overflow.
5536 // Create a simple add instruction, and insert it into the struct.
5537 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
5538 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00005539 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00005540 UndefValue::get(LHS->getType()),
5541 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00005542 };
Chris Lattner4de84762010-01-04 07:02:48 +00005543 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00005544 return InsertValueInst::Create(Struct, Add, 0);
5545 }
5546 }
5547 }
5548 // FALL THROUGH uadd into sadd
5549 case Intrinsic::sadd_with_overflow:
5550 // Canonicalize constants into the RHS.
5551 if (isa<Constant>(II->getOperand(1)) &&
5552 !isa<Constant>(II->getOperand(2))) {
5553 Value *LHS = II->getOperand(1);
5554 II->setOperand(1, II->getOperand(2));
5555 II->setOperand(2, LHS);
5556 return II;
5557 }
5558
5559 // X + undef -> undef
5560 if (isa<UndefValue>(II->getOperand(2)))
5561 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
5562
5563 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
5564 // X + 0 -> {X, false}
5565 if (RHS->isZero()) {
5566 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00005567 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00005568 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00005569 };
Chris Lattner4de84762010-01-04 07:02:48 +00005570 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00005571 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
5572 }
5573 }
5574 break;
5575 case Intrinsic::usub_with_overflow:
5576 case Intrinsic::ssub_with_overflow:
5577 // undef - X -> undef
5578 // X - undef -> undef
5579 if (isa<UndefValue>(II->getOperand(1)) ||
5580 isa<UndefValue>(II->getOperand(2)))
5581 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
5582
5583 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
5584 // X - 0 -> {X, false}
5585 if (RHS->isZero()) {
5586 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00005587 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00005588 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00005589 };
Chris Lattner4de84762010-01-04 07:02:48 +00005590 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00005591 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
5592 }
5593 }
5594 break;
5595 case Intrinsic::umul_with_overflow:
5596 case Intrinsic::smul_with_overflow:
5597 // Canonicalize constants into the RHS.
5598 if (isa<Constant>(II->getOperand(1)) &&
5599 !isa<Constant>(II->getOperand(2))) {
5600 Value *LHS = II->getOperand(1);
5601 II->setOperand(1, II->getOperand(2));
5602 II->setOperand(2, LHS);
5603 return II;
5604 }
5605
5606 // X * undef -> undef
5607 if (isa<UndefValue>(II->getOperand(2)))
5608 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
5609
5610 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
5611 // X*0 -> {0, false}
5612 if (RHSI->isZero())
5613 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
5614
5615 // X * 1 -> {X, false}
5616 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +00005617 Constant *V[] = {
5618 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00005619 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00005620 };
Chris Lattner4de84762010-01-04 07:02:48 +00005621 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +00005622 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00005623 }
5624 }
5625 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +00005626 case Intrinsic::ppc_altivec_lvx:
5627 case Intrinsic::ppc_altivec_lvxl:
5628 case Intrinsic::x86_sse_loadu_ps:
5629 case Intrinsic::x86_sse2_loadu_pd:
5630 case Intrinsic::x86_sse2_loadu_dq:
5631 // Turn PPC lvx -> load if the pointer is known aligned.
5632 // Turn X86 loadups -> load if the pointer is known aligned.
5633 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00005634 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
5635 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00005636 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00005637 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00005638 break;
5639 case Intrinsic::ppc_altivec_stvx:
5640 case Intrinsic::ppc_altivec_stvxl:
5641 // Turn stvx -> store if the pointer is known aligned.
5642 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
5643 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00005644 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00005645 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00005646 return new StoreInst(II->getOperand(1), Ptr);
5647 }
5648 break;
5649 case Intrinsic::x86_sse_storeu_ps:
5650 case Intrinsic::x86_sse2_storeu_pd:
5651 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00005652 // Turn X86 storeu -> store if the pointer is known aligned.
5653 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
5654 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00005655 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00005656 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00005657 return new StoreInst(II->getOperand(2), Ptr);
5658 }
5659 break;
5660
5661 case Intrinsic::x86_sse_cvttss2si: {
5662 // These intrinsics only demands the 0th element of its input vector. If
5663 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00005664 unsigned VWidth =
5665 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
5666 APInt DemandedElts(VWidth, 1);
5667 APInt UndefElts(VWidth, 0);
5668 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00005669 UndefElts)) {
5670 II->setOperand(1, V);
5671 return II;
5672 }
5673 break;
5674 }
5675
5676 case Intrinsic::ppc_altivec_vperm:
5677 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5678 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
5679 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00005680
Chris Lattner0521e3c2008-06-18 04:33:20 +00005681 // Check that all of the elements are integer constants or undefs.
5682 bool AllEltsOk = true;
5683 for (unsigned i = 0; i != 16; ++i) {
5684 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5685 !isa<UndefValue>(Mask->getOperand(i))) {
5686 AllEltsOk = false;
5687 break;
5688 }
5689 }
5690
5691 if (AllEltsOk) {
5692 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00005693 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
5694 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005695 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00005696
Chris Lattner0521e3c2008-06-18 04:33:20 +00005697 // Only extract each element once.
5698 Value *ExtractedElts[32];
5699 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5700
Chris Lattnere2ed0572006-04-06 19:19:17 +00005701 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00005702 if (isa<UndefValue>(Mask->getOperand(i)))
5703 continue;
5704 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
5705 Idx &= 31; // Match the hardware behavior.
5706
5707 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005708 ExtractedElts[Idx] =
5709 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner4de84762010-01-04 07:02:48 +00005710 ConstantInt::get(Type::getInt32Ty(II->getContext()),
5711 Idx&15, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00005712 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00005713
Chris Lattner0521e3c2008-06-18 04:33:20 +00005714 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005715 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner4de84762010-01-04 07:02:48 +00005716 ConstantInt::get(Type::getInt32Ty(II->getContext()),
5717 i, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00005718 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00005719 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00005720 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00005721 }
5722 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00005723
Chris Lattner0521e3c2008-06-18 04:33:20 +00005724 case Intrinsic::stackrestore: {
5725 // If the save is right next to the restore, remove the restore. This can
5726 // happen when variable allocas are DCE'd.
5727 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5728 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5729 BasicBlock::iterator BI = SS;
5730 if (&*++BI == II)
5731 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00005732 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00005733 }
5734
5735 // Scan down this block to see if there is another stack restore in the
5736 // same block without an intervening call/alloca.
5737 BasicBlock::iterator BI = II;
5738 TerminatorInst *TI = II->getParent()->getTerminator();
5739 bool CannotRemove = false;
5740 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00005741 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00005742 CannotRemove = true;
5743 break;
5744 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00005745 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
5746 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
5747 // If there is a stackrestore below this one, remove this one.
5748 if (II->getIntrinsicID() == Intrinsic::stackrestore)
5749 return EraseInstFromFunction(CI);
5750 // Otherwise, ignore the intrinsic.
5751 } else {
5752 // If we found a non-intrinsic call, we can't remove the stack
5753 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00005754 CannotRemove = true;
5755 break;
5756 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00005757 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00005758 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00005759
5760 // If the stack restore is in a return/unwind block and if there are no
5761 // allocas or calls between the restore and the return, nuke the restore.
5762 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
5763 return EraseInstFromFunction(CI);
5764 break;
5765 }
Chris Lattner35b9e482004-10-12 04:52:52 +00005766 }
5767
Chris Lattner8b0ea312006-01-13 20:11:04 +00005768 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00005769}
5770
5771// InvokeInst simplification
5772//
5773Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00005774 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00005775}
5776
Dale Johannesenda30ccb2008-04-25 21:16:07 +00005777/// isSafeToEliminateVarargsCast - If this cast does not affect the value
5778/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00005779static bool isSafeToEliminateVarargsCast(const CallSite CS,
5780 const CastInst * const CI,
5781 const TargetData * const TD,
5782 const int ix) {
5783 if (!CI->isLosslessCast())
5784 return false;
5785
5786 // The size of ByVal arguments is derived from the type, so we
5787 // can't change to a type with a different size. If the size were
5788 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00005789 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00005790 return true;
5791
5792 const Type* SrcTy =
5793 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
5794 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
5795 if (!SrcTy->isSized() || !DstTy->isSized())
5796 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005797 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00005798 return false;
5799 return true;
5800}
5801
Chris Lattnera44d8a22003-10-07 22:32:43 +00005802// visitCallSite - Improvements for call and invoke instructions.
5803//
5804Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00005805 bool Changed = false;
5806
5807 // If the callee is a constexpr cast of a function, attempt to move the cast
5808 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00005809 if (transformConstExprCastCall(CS)) return 0;
5810
Chris Lattner6c266db2003-10-07 22:54:13 +00005811 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00005812
Chris Lattner08b22ec2005-05-13 07:09:09 +00005813 if (Function *CalleeF = dyn_cast<Function>(Callee))
5814 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5815 Instruction *OldCall = CS.getInstruction();
5816 // If the call and callee calling conventions don't match, this call must
5817 // be unreachable, as the call is undefined.
Chris Lattner4de84762010-01-04 07:02:48 +00005818 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
5819 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Andersond672ecb2009-07-03 00:17:18 +00005820 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +00005821 // If OldCall dues not return void then replaceAllUsesWith undef.
5822 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00005823 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00005824 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00005825 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5826 return EraseInstFromFunction(*OldCall);
5827 return 0;
5828 }
5829
Chris Lattner17be6352004-10-18 02:59:09 +00005830 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5831 // This instruction is not reachable, just remove it. We insert a store to
5832 // undef so that we know that this code is not reachable, despite the fact
5833 // that we can't modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00005834 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
5835 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner17be6352004-10-18 02:59:09 +00005836 CS.getInstruction());
5837
Devang Patel228ebd02009-10-13 22:56:32 +00005838 // If CS dues not return void then replaceAllUsesWith undef.
5839 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00005840 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00005841 CS.getInstruction()->
5842 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00005843
5844 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5845 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00005846 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner4de84762010-01-04 07:02:48 +00005847 ConstantInt::getTrue(Callee->getContext()), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00005848 }
Chris Lattner17be6352004-10-18 02:59:09 +00005849 return EraseInstFromFunction(*CS.getInstruction());
5850 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005851
Duncan Sandscdb6d922007-09-17 10:26:40 +00005852 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
5853 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
5854 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
5855 return transformCallThroughTrampoline(CS);
5856
Chris Lattner6c266db2003-10-07 22:54:13 +00005857 const PointerType *PTy = cast<PointerType>(Callee->getType());
5858 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5859 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00005860 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00005861 // See if we can optimize any arguments passed through the varargs area of
5862 // the call.
5863 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00005864 E = CS.arg_end(); I != E; ++I, ++ix) {
5865 CastInst *CI = dyn_cast<CastInst>(*I);
5866 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
5867 *I = CI->getOperand(0);
5868 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00005869 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00005870 }
Chris Lattner6c266db2003-10-07 22:54:13 +00005871 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005872
Duncan Sandsf0c33542007-12-19 21:13:37 +00005873 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00005874 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00005875 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00005876 Changed = true;
5877 }
5878
Chris Lattner6c266db2003-10-07 22:54:13 +00005879 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00005880}
5881
Chris Lattner9fe38862003-06-19 17:00:31 +00005882// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5883// attempt to move the cast to the arguments of the call/invoke.
5884//
5885bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5886 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5887 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00005888 if (CE->getOpcode() != Instruction::BitCast ||
5889 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00005890 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00005891 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00005892 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00005893 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00005894
5895 // Okay, this is a cast from a function to a different type. Unless doing so
5896 // would cause a type conversion of one of our arguments, change this call to
5897 // be a direct call with arguments casted to the appropriate types.
5898 //
5899 const FunctionType *FT = Callee->getFunctionType();
5900 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00005901 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00005902
Duncan Sandsf413cdf2008-06-01 07:38:42 +00005903 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00005904 return false; // TODO: Handle multiple return values.
5905
Chris Lattnerf78616b2004-01-14 06:06:08 +00005906 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00005907 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00005908 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00005909 // Conversion is ok if changing from one pointer type to another or from
5910 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005911 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00005912 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005913 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00005914 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00005915 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00005916
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00005917 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00005918 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +00005919 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00005920 return false; // Cannot transform this return value.
5921
Chris Lattner58d74912008-03-12 17:45:29 +00005922 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00005923 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00005924 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00005925 return false; // Attribute not compatible with transformed value.
5926 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005927
Chris Lattnerf78616b2004-01-14 06:06:08 +00005928 // If the callsite is an invoke instruction, and the return value is used by
5929 // a PHI node in a successor, we cannot change the return type of the call
5930 // because there is no place to put the cast instruction (without breaking
5931 // the critical edge). Bail out in this case.
5932 if (!Caller->use_empty())
5933 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5934 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5935 UI != E; ++UI)
5936 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5937 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00005938 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00005939 return false;
5940 }
Chris Lattner9fe38862003-06-19 17:00:31 +00005941
5942 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5943 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005944
Chris Lattner9fe38862003-06-19 17:00:31 +00005945 CallSite::arg_iterator AI = CS.arg_begin();
5946 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5947 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00005948 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00005949
5950 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005951 return false; // Cannot transform this parameter value.
5952
Devang Patel19c87462008-09-26 22:53:05 +00005953 if (CallerPAL.getParamAttributes(i + 1)
5954 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00005955 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00005956
Duncan Sandsf413cdf2008-06-01 07:38:42 +00005957 // Converting from one pointer type to another or between a pointer and an
5958 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00005959 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +00005960 (TD && ((isa<PointerType>(ParamTy) ||
5961 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
5962 (isa<PointerType>(ActTy) ||
5963 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +00005964 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00005965 }
5966
5967 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00005968 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00005969 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00005970
Chris Lattner58d74912008-03-12 17:45:29 +00005971 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
5972 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005973 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00005974 // won't be dropping them. Check that these extra arguments have attributes
5975 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00005976 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
5977 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00005978 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00005979 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00005980 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00005981 return false;
5982 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005983
Chris Lattner9fe38862003-06-19 17:00:31 +00005984 // Okay, we decided that this is a safe thing to do: go ahead and start
5985 // inserting cast instructions as necessary...
5986 std::vector<Value*> Args;
5987 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00005988 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005989 attrVec.reserve(NumCommonArgs);
5990
5991 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00005992 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005993
5994 // If the return value is not being used, the type may not be compatible
5995 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00005996 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00005997
5998 // Add the new return attributes.
5999 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00006000 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00006001
6002 AI = CS.arg_begin();
6003 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6004 const Type *ParamTy = FT->getParamType(i);
6005 if ((*AI)->getType() == ParamTy) {
6006 Args.push_back(*AI);
6007 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00006008 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00006009 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006010 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00006011 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00006012
6013 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00006014 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00006015 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00006016 }
6017
6018 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006019 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +00006020 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00006021 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +00006022
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006023 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006024 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00006025 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00006026 errs() << "WARNING: While resolving call to function '"
6027 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00006028 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006029 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +00006030 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6031 const Type *PTy = getPromotedType((*AI)->getType());
6032 if (PTy != (*AI)->getType()) {
6033 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006034 Instruction::CastOps opcode =
6035 CastInst::getCastOpcode(*AI, false, PTy, false);
6036 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00006037 } else {
6038 Args.push_back(*AI);
6039 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00006040
Duncan Sandse1e520f2008-01-13 08:02:44 +00006041 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00006042 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00006043 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00006044 }
Chris Lattner9fe38862003-06-19 17:00:31 +00006045 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006046 }
Chris Lattner9fe38862003-06-19 17:00:31 +00006047
Devang Patel19c87462008-09-26 22:53:05 +00006048 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
6049 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
6050
Devang Patel9674d152009-10-14 17:29:00 +00006051 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +00006052 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00006053
Eric Christophera66297a2009-07-25 02:45:27 +00006054 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
6055 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00006056
Chris Lattner9fe38862003-06-19 17:00:31 +00006057 Instruction *NC;
6058 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00006059 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00006060 Args.begin(), Args.end(),
6061 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00006062 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00006063 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00006064 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00006065 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
6066 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00006067 CallInst *CI = cast<CallInst>(Caller);
6068 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00006069 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00006070 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00006071 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00006072 }
6073
Chris Lattner6934a042007-02-11 01:23:03 +00006074 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00006075 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00006076 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +00006077 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006078 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00006079 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006080 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00006081
6082 // If this is an invoke instruction, we should insert it after the first
6083 // non-phi, instruction in the normal successor block.
6084 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00006085 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00006086 InsertNewInstBefore(NC, *I);
6087 } else {
6088 // Otherwise, it's a call, just insert cast right after the call instr
6089 InsertNewInstBefore(NC, *Caller);
6090 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +00006091 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00006092 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00006093 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00006094 }
6095 }
6096
Devang Patel1bf5ebc2009-10-13 21:41:20 +00006097
Chris Lattner931f8f32009-08-31 05:17:58 +00006098 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +00006099 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +00006100
6101 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00006102 return true;
6103}
6104
Duncan Sandscdb6d922007-09-17 10:26:40 +00006105// transformCallThroughTrampoline - Turn a call to a function created by the
6106// init_trampoline intrinsic into a direct call to the underlying function.
6107//
6108Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
6109 Value *Callee = CS.getCalledValue();
6110 const PointerType *PTy = cast<PointerType>(Callee->getType());
6111 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00006112 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006113
6114 // If the call already has the 'nest' attribute somewhere then give up -
6115 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00006116 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006117 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00006118
6119 IntrinsicInst *Tramp =
6120 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
6121
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00006122 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00006123 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
6124 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
6125
Devang Patel05988662008-09-25 21:00:45 +00006126 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00006127 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00006128 unsigned NestIdx = 1;
6129 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00006130 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00006131
6132 // Look for a parameter marked with the 'nest' attribute.
6133 for (FunctionType::param_iterator I = NestFTy->param_begin(),
6134 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00006135 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00006136 // Record the parameter type and any other attributes.
6137 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00006138 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006139 break;
6140 }
6141
6142 if (NestTy) {
6143 Instruction *Caller = CS.getInstruction();
6144 std::vector<Value*> NewArgs;
6145 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
6146
Devang Patel05988662008-09-25 21:00:45 +00006147 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00006148 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006149
Duncan Sandscdb6d922007-09-17 10:26:40 +00006150 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006151 // mean appending it. Likewise for attributes.
6152
Devang Patel19c87462008-09-26 22:53:05 +00006153 // Add any result attributes.
6154 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00006155 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006156
Duncan Sandscdb6d922007-09-17 10:26:40 +00006157 {
6158 unsigned Idx = 1;
6159 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
6160 do {
6161 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006162 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00006163 Value *NestVal = Tramp->getOperand(3);
6164 if (NestVal->getType() != NestTy)
6165 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
6166 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00006167 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00006168 }
6169
6170 if (I == E)
6171 break;
6172
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006173 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00006174 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00006175 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006176 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00006177 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00006178
6179 ++Idx, ++I;
6180 } while (1);
6181 }
6182
Devang Patel19c87462008-09-26 22:53:05 +00006183 // Add any function attributes.
6184 if (Attributes Attr = Attrs.getFnAttributes())
6185 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
6186
Duncan Sandscdb6d922007-09-17 10:26:40 +00006187 // The trampoline may have been bitcast to a bogus type (FTy).
6188 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006189 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00006190
Duncan Sandscdb6d922007-09-17 10:26:40 +00006191 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00006192 NewTypes.reserve(FTy->getNumParams()+1);
6193
Duncan Sandscdb6d922007-09-17 10:26:40 +00006194 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006195 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00006196 {
6197 unsigned Idx = 1;
6198 FunctionType::param_iterator I = FTy->param_begin(),
6199 E = FTy->param_end();
6200
6201 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006202 if (Idx == NestIdx)
6203 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00006204 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006205
6206 if (I == E)
6207 break;
6208
Duncan Sandsb0c9b932008-01-14 19:52:09 +00006209 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00006210 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006211
6212 ++Idx, ++I;
6213 } while (1);
6214 }
6215
6216 // Replace the trampoline call with a direct call. Let the generic
6217 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +00006218 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +00006219 FTy->isVarArg());
6220 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +00006221 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +00006222 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +00006223 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +00006224 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
6225 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00006226
6227 Instruction *NewCaller;
6228 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00006229 NewCaller = InvokeInst::Create(NewCallee,
6230 II->getNormalDest(), II->getUnwindDest(),
6231 NewArgs.begin(), NewArgs.end(),
6232 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006233 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00006234 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006235 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00006236 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
6237 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006238 if (cast<CallInst>(Caller)->isTailCall())
6239 cast<CallInst>(NewCaller)->setTailCall();
6240 cast<CallInst>(NewCaller)->
6241 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00006242 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006243 }
Devang Patel9674d152009-10-14 17:29:00 +00006244 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +00006245 Caller->replaceAllUsesWith(NewCaller);
6246 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +00006247 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006248 return 0;
6249 }
6250 }
6251
6252 // Replace the trampoline call with a direct call. Since there is no 'nest'
6253 // parameter, there is no need to adjust the argument list. Let the generic
6254 // code sort out any function type mismatches.
6255 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +00006256 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +00006257 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00006258 CS.setCalledFunction(NewCallee);
6259 return CS.getInstruction();
6260}
6261
Dan Gohman9ad29202009-09-16 16:50:24 +00006262/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
6263/// and if a/b/c and the add's all have a single use, turn this into a phi
Chris Lattner7da52b22006-11-01 04:51:18 +00006264/// and a single binop.
6265Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
6266 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +00006267 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00006268 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00006269 Value *LHSVal = FirstInst->getOperand(0);
6270 Value *RHSVal = FirstInst->getOperand(1);
6271
6272 const Type *LHSType = LHSVal->getType();
6273 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00006274
Dan Gohman9ad29202009-09-16 16:50:24 +00006275 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +00006276 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00006277 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00006278 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00006279 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00006280 // types or GEP's with different index types.
6281 I->getOperand(0)->getType() != LHSType ||
6282 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00006283 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006284
6285 // If they are CmpInst instructions, check their predicates
6286 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
6287 if (cast<CmpInst>(I)->getPredicate() !=
6288 cast<CmpInst>(FirstInst)->getPredicate())
6289 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00006290
6291 // Keep track of which operand needs a phi node.
6292 if (I->getOperand(0) != LHSVal) LHSVal = 0;
6293 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00006294 }
Dan Gohman9ad29202009-09-16 16:50:24 +00006295
6296 // If both LHS and RHS would need a PHI, don't do this transformation,
6297 // because it would increase the number of PHIs entering the block,
6298 // which leads to higher register pressure. This is especially
6299 // bad when the PHIs are in the header of a loop.
6300 if (!LHSVal && !RHSVal)
6301 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00006302
Chris Lattner38b3dcc2008-12-01 03:42:51 +00006303 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +00006304
Chris Lattner7da52b22006-11-01 04:51:18 +00006305 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00006306 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00006307 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00006308 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00006309 NewLHS = PHINode::Create(LHSType,
6310 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00006311 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
6312 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00006313 InsertNewInstBefore(NewLHS, PN);
6314 LHSVal = NewLHS;
6315 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00006316
6317 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00006318 NewRHS = PHINode::Create(RHSType,
6319 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00006320 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
6321 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00006322 InsertNewInstBefore(NewRHS, PN);
6323 RHSVal = NewRHS;
6324 }
6325
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00006326 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +00006327 if (NewLHS || NewRHS) {
6328 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6329 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
6330 if (NewLHS) {
6331 Value *NewInLHS = InInst->getOperand(0);
6332 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
6333 }
6334 if (NewRHS) {
6335 Value *NewInRHS = InInst->getOperand(1);
6336 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
6337 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00006338 }
6339 }
6340
Chris Lattner7da52b22006-11-01 04:51:18 +00006341 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006342 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +00006343 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006344 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +00006345 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +00006346}
6347
Chris Lattner05f18922008-12-01 02:34:36 +00006348Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
6349 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
6350
6351 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
6352 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +00006353 // This is true if all GEP bases are allocas and if all indices into them are
6354 // constants.
6355 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +00006356
6357 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +00006358 // more than one phi, which leads to higher register pressure. This is
6359 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +00006360 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +00006361
Dan Gohman9ad29202009-09-16 16:50:24 +00006362 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +00006363 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
6364 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
6365 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
6366 GEP->getNumOperands() != FirstInst->getNumOperands())
6367 return 0;
6368
Chris Lattner36d3e322009-02-21 00:46:50 +00006369 // Keep track of whether or not all GEPs are of alloca pointers.
6370 if (AllBasePointersAreAllocas &&
6371 (!isa<AllocaInst>(GEP->getOperand(0)) ||
6372 !GEP->hasAllConstantIndices()))
6373 AllBasePointersAreAllocas = false;
6374
Chris Lattner05f18922008-12-01 02:34:36 +00006375 // Compare the operand lists.
6376 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
6377 if (FirstInst->getOperand(op) == GEP->getOperand(op))
6378 continue;
6379
6380 // Don't merge two GEPs when two operands differ (introducing phi nodes)
6381 // if one of the PHIs has a constant for the index. The index may be
6382 // substantially cheaper to compute for the constants, so making it a
6383 // variable index could pessimize the path. This also handles the case
6384 // for struct indices, which must always be constant.
6385 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
6386 isa<ConstantInt>(GEP->getOperand(op)))
6387 return 0;
6388
6389 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
6390 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +00006391
6392 // If we already needed a PHI for an earlier operand, and another operand
6393 // also requires a PHI, we'd be introducing more PHIs than we're
6394 // eliminating, which increases register pressure on entry to the PHI's
6395 // block.
6396 if (NeededPhi)
6397 return 0;
6398
Chris Lattner05f18922008-12-01 02:34:36 +00006399 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +00006400 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +00006401 }
6402 }
6403
Chris Lattner36d3e322009-02-21 00:46:50 +00006404 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +00006405 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +00006406 // offset calculation, but all the predecessors will have to materialize the
6407 // stack address into a register anyway. We'd actually rather *clone* the
6408 // load up into the predecessors so that we have a load of a gep of an alloca,
6409 // which can usually all be folded into the load.
6410 if (AllBasePointersAreAllocas)
6411 return 0;
6412
Chris Lattner05f18922008-12-01 02:34:36 +00006413 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
6414 // that is variable.
6415 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
6416
6417 bool HasAnyPHIs = false;
6418 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
6419 if (FixedOperands[i]) continue; // operand doesn't need a phi.
6420 Value *FirstOp = FirstInst->getOperand(i);
6421 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
6422 FirstOp->getName()+".pn");
6423 InsertNewInstBefore(NewPN, PN);
6424
6425 NewPN->reserveOperandSpace(e);
6426 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
6427 OperandPhis[i] = NewPN;
6428 FixedOperands[i] = NewPN;
6429 HasAnyPHIs = true;
6430 }
6431
6432
6433 // Add all operands to the new PHIs.
6434 if (HasAnyPHIs) {
6435 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6436 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
6437 BasicBlock *InBB = PN.getIncomingBlock(i);
6438
6439 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
6440 if (PHINode *OpPhi = OperandPhis[op])
6441 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
6442 }
6443 }
6444
6445 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +00006446 return cast<GEPOperator>(FirstInst)->isInBounds() ?
6447 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
6448 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006449 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
6450 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +00006451}
6452
6453
Chris Lattner21550882009-02-23 05:56:17 +00006454/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
6455/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +00006456/// obvious the value of the load is not changed from the point of the load to
6457/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00006458///
6459/// Finally, it is safe, but not profitable, to sink a load targetting a
6460/// non-address-taken alloca. Doing so will cause us to not promote the alloca
6461/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +00006462static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +00006463 BasicBlock::iterator BBI = L, E = L->getParent()->end();
6464
6465 for (++BBI; BBI != E; ++BBI)
6466 if (BBI->mayWriteToMemory())
6467 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00006468
6469 // Check for non-address taken alloca. If not address-taken already, it isn't
6470 // profitable to do this xform.
6471 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
6472 bool isAddressTaken = false;
6473 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
6474 UI != E; ++UI) {
6475 if (isa<LoadInst>(UI)) continue;
6476 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
6477 // If storing TO the alloca, then the address isn't taken.
6478 if (SI->getOperand(1) == AI) continue;
6479 }
6480 isAddressTaken = true;
6481 break;
6482 }
6483
Chris Lattner36d3e322009-02-21 00:46:50 +00006484 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +00006485 return false;
6486 }
6487
Chris Lattner36d3e322009-02-21 00:46:50 +00006488 // If this load is a load from a GEP with a constant offset from an alloca,
6489 // then we don't want to sink it. In its present form, it will be
6490 // load [constant stack offset]. Sinking it will cause us to have to
6491 // materialize the stack addresses in each predecessor in a register only to
6492 // do a shared load from register in the successor.
6493 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
6494 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
6495 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
6496 return false;
6497
Chris Lattner76c73142006-11-01 07:13:54 +00006498 return true;
6499}
6500
Chris Lattner751a3622009-11-01 20:04:24 +00006501Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
6502 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
6503
6504 // When processing loads, we need to propagate two bits of information to the
6505 // sunk load: whether it is volatile, and what its alignment is. We currently
6506 // don't sink loads when some have their alignment specified and some don't.
6507 // visitLoadInst will propagate an alignment onto the load when TD is around,
6508 // and if TD isn't around, we can't handle the mixed case.
6509 bool isVolatile = FirstLI->isVolatile();
6510 unsigned LoadAlignment = FirstLI->getAlignment();
6511
6512 // We can't sink the load if the loaded value could be modified between the
6513 // load and the PHI.
6514 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
6515 !isSafeAndProfitableToSinkLoad(FirstLI))
6516 return 0;
6517
6518 // If the PHI is of volatile loads and the load block has multiple
6519 // successors, sinking it would remove a load of the volatile value from
6520 // the path through the other successor.
6521 if (isVolatile &&
6522 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
6523 return 0;
6524
6525 // Check to see if all arguments are the same operation.
6526 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6527 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
6528 if (!LI || !LI->hasOneUse())
6529 return 0;
6530
6531 // We can't sink the load if the loaded value could be modified between
6532 // the load and the PHI.
6533 if (LI->isVolatile() != isVolatile ||
6534 LI->getParent() != PN.getIncomingBlock(i) ||
6535 !isSafeAndProfitableToSinkLoad(LI))
6536 return 0;
6537
6538 // If some of the loads have an alignment specified but not all of them,
6539 // we can't do the transformation.
6540 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
6541 return 0;
6542
Chris Lattnera664bb72009-11-01 20:07:07 +00006543 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +00006544
6545 // If the PHI is of volatile loads and the load block has multiple
6546 // successors, sinking it would remove a load of the volatile value from
6547 // the path through the other successor.
6548 if (isVolatile &&
6549 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
6550 return 0;
6551 }
6552
6553 // Okay, they are all the same operation. Create a new PHI node of the
6554 // correct type, and PHI together all of the LHS's of the instructions.
6555 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
6556 PN.getName()+".in");
6557 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
6558
6559 Value *InVal = FirstLI->getOperand(0);
6560 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
6561
6562 // Add all operands to the new PHI.
6563 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6564 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
6565 if (NewInVal != InVal)
6566 InVal = 0;
6567 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6568 }
6569
6570 Value *PhiVal;
6571 if (InVal) {
6572 // The new PHI unions all of the same values together. This is really
6573 // common, so we handle it intelligently here for compile-time speed.
6574 PhiVal = InVal;
6575 delete NewPN;
6576 } else {
6577 InsertNewInstBefore(NewPN, PN);
6578 PhiVal = NewPN;
6579 }
6580
6581 // If this was a volatile load that we are merging, make sure to loop through
6582 // and mark all the input loads as non-volatile. If we don't do this, we will
6583 // insert a new volatile load and the old ones will not be deletable.
6584 if (isVolatile)
6585 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6586 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
6587
6588 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
6589}
6590
Chris Lattner9fe38862003-06-19 17:00:31 +00006591
Chris Lattnerc22d4d12009-11-10 07:23:37 +00006592
6593/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6594/// operator and they all are only used by the PHI, PHI together their
6595/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00006596Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6597 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6598
Chris Lattner751a3622009-11-01 20:04:24 +00006599 if (isa<GetElementPtrInst>(FirstInst))
6600 return FoldPHIArgGEPIntoPHI(PN);
6601 if (isa<LoadInst>(FirstInst))
6602 return FoldPHIArgLoadIntoPHI(PN);
6603
Chris Lattnerbac32862004-11-14 19:13:23 +00006604 // Scan the instruction, looking for input operations that can be folded away.
6605 // If all input operands to the phi are the same instruction (e.g. a cast from
6606 // the same type or "+42") we can pull the operation through the PHI, reducing
6607 // code size and simplifying code.
6608 Constant *ConstantOp = 0;
6609 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +00006610
Chris Lattnerbac32862004-11-14 19:13:23 +00006611 if (isa<CastInst>(FirstInst)) {
6612 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +00006613
6614 // Be careful about transforming integer PHIs. We don't want to pessimize
6615 // the code by turning an i32 into an i1293.
6616 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattner80f43d32010-01-04 07:53:58 +00006617 if (!ShouldChangeType(PN.getType(), CastSrcTy))
Chris Lattnerbf382b52009-11-08 21:20:06 +00006618 return 0;
6619 }
Reid Spencer832254e2007-02-02 02:16:23 +00006620 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006621 // Can fold binop, compare or shift here if the RHS is a constant,
6622 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00006623 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00006624 if (ConstantOp == 0)
6625 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +00006626 } else {
6627 return 0; // Cannot fold this operation.
6628 }
6629
6630 // Check to see if all arguments are the same operation.
6631 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +00006632 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
6633 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00006634 return 0;
6635 if (CastSrcTy) {
6636 if (I->getOperand(0)->getType() != CastSrcTy)
6637 return 0; // Cast operation must match.
6638 } else if (I->getOperand(1) != ConstantOp) {
6639 return 0;
6640 }
6641 }
6642
6643 // Okay, they are all the same operation. Create a new PHI node of the
6644 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00006645 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
6646 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00006647 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00006648
6649 Value *InVal = FirstInst->getOperand(0);
6650 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00006651
6652 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00006653 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6654 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6655 if (NewInVal != InVal)
6656 InVal = 0;
6657 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6658 }
6659
6660 Value *PhiVal;
6661 if (InVal) {
6662 // The new PHI unions all of the same values together. This is really
6663 // common, so we handle it intelligently here for compile-time speed.
6664 PhiVal = InVal;
6665 delete NewPN;
6666 } else {
6667 InsertNewInstBefore(NewPN, PN);
6668 PhiVal = NewPN;
6669 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006670
Chris Lattnerbac32862004-11-14 19:13:23 +00006671 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +00006672 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006673 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +00006674
Chris Lattner54545ac2008-04-29 17:13:43 +00006675 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006676 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +00006677
Chris Lattner751a3622009-11-01 20:04:24 +00006678 CmpInst *CIOp = cast<CmpInst>(FirstInst);
6679 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
6680 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00006681}
Chris Lattnera1be5662002-05-02 17:06:02 +00006682
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006683/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6684/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00006685static bool DeadPHICycle(PHINode *PN,
6686 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006687 if (PN->use_empty()) return true;
6688 if (!PN->hasOneUse()) return false;
6689
6690 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00006691 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006692 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00006693
6694 // Don't scan crazily complex things.
6695 if (PotentiallyDeadPHIs.size() == 16)
6696 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006697
6698 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6699 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00006700
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006701 return false;
6702}
6703
Chris Lattnercf5008a2007-11-06 21:52:06 +00006704/// PHIsEqualValue - Return true if this phi node is always equal to
6705/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
6706/// z = some value; x = phi (y, z); y = phi (x, z)
6707static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
6708 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
6709 // See if we already saw this PHI node.
6710 if (!ValueEqualPHIs.insert(PN))
6711 return true;
6712
6713 // Don't scan crazily complex things.
6714 if (ValueEqualPHIs.size() == 16)
6715 return false;
6716
6717 // Scan the operands to see if they are either phi nodes or are equal to
6718 // the value.
6719 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6720 Value *Op = PN->getIncomingValue(i);
6721 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
6722 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
6723 return false;
6724 } else if (Op != NonPhiInVal)
6725 return false;
6726 }
6727
6728 return true;
6729}
6730
6731
Chris Lattner9956c052009-11-08 19:23:30 +00006732namespace {
6733struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006734 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +00006735 unsigned Shift; // The amount shifted.
6736 Instruction *Inst; // The trunc instruction.
6737
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006738 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
6739 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +00006740
6741 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006742 if (PHIId < RHS.PHIId) return true;
6743 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +00006744 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006745 if (Shift > RHS.Shift) return false;
6746 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +00006747 RHS.Inst->getType()->getPrimitiveSizeInBits();
6748 }
6749};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006750
6751struct LoweredPHIRecord {
6752 PHINode *PN; // The PHI that was lowered.
6753 unsigned Shift; // The amount shifted.
6754 unsigned Width; // The width extracted.
6755
6756 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
6757 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
6758
6759 // Ctor form used by DenseMap.
6760 LoweredPHIRecord(PHINode *pn, unsigned Sh)
6761 : PN(pn), Shift(Sh), Width(0) {}
6762};
6763}
6764
6765namespace llvm {
6766 template<>
6767 struct DenseMapInfo<LoweredPHIRecord> {
6768 static inline LoweredPHIRecord getEmptyKey() {
6769 return LoweredPHIRecord(0, 0);
6770 }
6771 static inline LoweredPHIRecord getTombstoneKey() {
6772 return LoweredPHIRecord(0, 1);
6773 }
6774 static unsigned getHashValue(const LoweredPHIRecord &Val) {
6775 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
6776 (Val.Width>>3);
6777 }
6778 static bool isEqual(const LoweredPHIRecord &LHS,
6779 const LoweredPHIRecord &RHS) {
6780 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
6781 LHS.Width == RHS.Width;
6782 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006783 };
Chris Lattner4bbf4ee2009-12-15 07:26:43 +00006784 template <>
6785 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner9956c052009-11-08 19:23:30 +00006786}
6787
6788
6789/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
6790/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
6791/// so, we split the PHI into the various pieces being extracted. This sort of
6792/// thing is introduced when SROA promotes an aggregate to large integer values.
6793///
6794/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
6795/// inttoptr. We should produce new PHIs in the right type.
6796///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006797Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
6798 // PHIUsers - Keep track of all of the truncated values extracted from a set
6799 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +00006800 SmallVector<PHIUsageRecord, 16> PHIUsers;
6801
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006802 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
6803 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
6804 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
6805 // check the uses of (to ensure they are all extracts).
6806 SmallVector<PHINode*, 8> PHIsToSlice;
6807 SmallPtrSet<PHINode*, 8> PHIsInspected;
6808
6809 PHIsToSlice.push_back(&FirstPhi);
6810 PHIsInspected.insert(&FirstPhi);
6811
6812 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
6813 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +00006814
Chris Lattner0ebc6ce2009-12-19 07:01:15 +00006815 // Scan the input list of the PHI. If any input is an invoke, and if the
6816 // input is defined in the predecessor, then we won't be split the critical
6817 // edge which is required to insert a truncate. Because of this, we have to
6818 // bail out.
6819 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6820 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
6821 if (II == 0) continue;
6822 if (II->getParent() != PN->getIncomingBlock(i))
6823 continue;
6824
6825 // If we have a phi, and if it's directly in the predecessor, then we have
6826 // a critical edge where we need to put the truncate. Since we can't
6827 // split the edge in instcombine, we have to bail out.
6828 return 0;
6829 }
6830
6831
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006832 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
6833 UI != E; ++UI) {
6834 Instruction *User = cast<Instruction>(*UI);
6835
6836 // If the user is a PHI, inspect its uses recursively.
6837 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
6838 if (PHIsInspected.insert(UserPN))
6839 PHIsToSlice.push_back(UserPN);
6840 continue;
6841 }
6842
6843 // Truncates are always ok.
6844 if (isa<TruncInst>(User)) {
6845 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
6846 continue;
6847 }
6848
6849 // Otherwise it must be a lshr which can only be used by one trunc.
6850 if (User->getOpcode() != Instruction::LShr ||
6851 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
6852 !isa<ConstantInt>(User->getOperand(1)))
6853 return 0;
6854
6855 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
6856 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +00006857 }
Chris Lattner9956c052009-11-08 19:23:30 +00006858 }
6859
6860 // If we have no users, they must be all self uses, just nuke the PHI.
6861 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006862 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +00006863
6864 // If this phi node is transformable, create new PHIs for all the pieces
6865 // extracted out of it. First, sort the users by their offset and size.
6866 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
6867
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006868 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
6869 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
6870 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
6871 );
Chris Lattner9956c052009-11-08 19:23:30 +00006872
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006873 // PredValues - This is a temporary used when rewriting PHI nodes. It is
6874 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +00006875 DenseMap<BasicBlock*, Value*> PredValues;
6876
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006877 // ExtractedVals - Each new PHI we introduce is saved here so we don't
6878 // introduce redundant PHIs.
6879 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
6880
6881 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
6882 unsigned PHIId = PHIUsers[UserI].PHIId;
6883 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +00006884 unsigned Offset = PHIUsers[UserI].Shift;
6885 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +00006886
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006887 PHINode *EltPHI;
6888
6889 // If we've already lowered a user like this, reuse the previously lowered
6890 // value.
6891 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +00006892
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006893 // Otherwise, Create the new PHI node for this user.
6894 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
6895 assert(EltPHI->getType() != PN->getType() &&
6896 "Truncate didn't shrink phi?");
6897
6898 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6899 BasicBlock *Pred = PN->getIncomingBlock(i);
6900 Value *&PredVal = PredValues[Pred];
6901
6902 // If we already have a value for this predecessor, reuse it.
6903 if (PredVal) {
6904 EltPHI->addIncoming(PredVal, Pred);
6905 continue;
6906 }
Chris Lattner9956c052009-11-08 19:23:30 +00006907
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006908 // Handle the PHI self-reuse case.
6909 Value *InVal = PN->getIncomingValue(i);
6910 if (InVal == PN) {
6911 PredVal = EltPHI;
6912 EltPHI->addIncoming(PredVal, Pred);
6913 continue;
Chris Lattner0ebc6ce2009-12-19 07:01:15 +00006914 }
6915
6916 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006917 // If the incoming value was a PHI, and if it was one of the PHIs we
6918 // already rewrote it, just use the lowered value.
6919 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
6920 PredVal = Res;
6921 EltPHI->addIncoming(PredVal, Pred);
6922 continue;
6923 }
6924 }
6925
6926 // Otherwise, do an extract in the predecessor.
6927 Builder->SetInsertPoint(Pred, Pred->getTerminator());
6928 Value *Res = InVal;
6929 if (Offset)
6930 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
6931 Offset), "extract");
6932 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
6933 PredVal = Res;
6934 EltPHI->addIncoming(Res, Pred);
6935
6936 // If the incoming value was a PHI, and if it was one of the PHIs we are
6937 // rewriting, we will ultimately delete the code we inserted. This
6938 // means we need to revisit that PHI to make sure we extract out the
6939 // needed piece.
6940 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
6941 if (PHIsInspected.count(OldInVal)) {
6942 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
6943 OldInVal)-PHIsToSlice.begin();
6944 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
6945 cast<Instruction>(Res)));
6946 ++UserE;
6947 }
Chris Lattner9956c052009-11-08 19:23:30 +00006948 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006949 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +00006950
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006951 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
6952 << *EltPHI << '\n');
6953 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +00006954 }
Chris Lattner9956c052009-11-08 19:23:30 +00006955
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006956 // Replace the use of this piece with the PHI node.
6957 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +00006958 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +00006959
6960 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
6961 // with undefs.
6962 Value *Undef = UndefValue::get(FirstPhi.getType());
6963 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
6964 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
6965 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +00006966}
6967
Chris Lattner473945d2002-05-06 18:06:38 +00006968// PHINode simplification
6969//
Chris Lattner7e708292002-06-25 16:13:24 +00006970Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00006971 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00006972 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00006973
Owen Anderson7e057142006-07-10 22:03:18 +00006974 if (Value *V = PN.hasConstantValue())
6975 return ReplaceInstUsesWith(PN, V);
6976
Owen Anderson7e057142006-07-10 22:03:18 +00006977 // If all PHI operands are the same operation, pull them through the PHI,
6978 // reducing code size.
6979 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +00006980 isa<Instruction>(PN.getIncomingValue(1)) &&
6981 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
6982 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
6983 // FIXME: The hasOneUse check will fail for PHIs that use the value more
6984 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +00006985 PN.getIncomingValue(0)->hasOneUse())
6986 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6987 return Result;
6988
6989 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6990 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6991 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00006992 if (PN.hasOneUse()) {
6993 Instruction *PHIUser = cast<Instruction>(PN.use_back());
6994 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00006995 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00006996 PotentiallyDeadPHIs.insert(&PN);
6997 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00006998 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +00006999 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00007000
7001 // If this phi has a single use, and if that use just computes a value for
7002 // the next iteration of a loop, delete the phi. This occurs with unused
7003 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7004 // common case here is good because the only other things that catch this
7005 // are induction variable analysis (sometimes) and ADCE, which is only run
7006 // late.
7007 if (PHIUser->hasOneUse() &&
7008 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7009 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00007010 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +00007011 }
7012 }
Owen Anderson7e057142006-07-10 22:03:18 +00007013
Chris Lattnercf5008a2007-11-06 21:52:06 +00007014 // We sometimes end up with phi cycles that non-obviously end up being the
7015 // same value, for example:
7016 // z = some value; x = phi (y, z); y = phi (x, z)
7017 // where the phi nodes don't necessarily need to be in the same block. Do a
7018 // quick check to see if the PHI node only contains a single non-phi value, if
7019 // so, scan to see if the phi cycle is actually equal to that value.
7020 {
7021 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
7022 // Scan for the first non-phi operand.
7023 while (InValNo != NumOperandVals &&
7024 isa<PHINode>(PN.getIncomingValue(InValNo)))
7025 ++InValNo;
7026
7027 if (InValNo != NumOperandVals) {
7028 Value *NonPhiInVal = PN.getOperand(InValNo);
7029
7030 // Scan the rest of the operands to see if there are any conflicts, if so
7031 // there is no need to recursively scan other phis.
7032 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
7033 Value *OpVal = PN.getIncomingValue(InValNo);
7034 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
7035 break;
7036 }
7037
7038 // If we scanned over all operands, then we have one unique value plus
7039 // phi values. Scan PHI nodes to see if they all merge in each other or
7040 // the value.
7041 if (InValNo == NumOperandVals) {
7042 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
7043 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
7044 return ReplaceInstUsesWith(PN, NonPhiInVal);
7045 }
7046 }
7047 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +00007048
Dan Gohman5b097012009-10-31 14:22:52 +00007049 // If there are multiple PHIs, sort their operands so that they all list
7050 // the blocks in the same order. This will help identical PHIs be eliminated
7051 // by other passes. Other passes shouldn't depend on this for correctness
7052 // however.
7053 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
7054 if (&PN != FirstPN)
7055 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +00007056 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +00007057 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
7058 if (BBA != BBB) {
7059 Value *VA = PN.getIncomingValue(i);
7060 unsigned j = PN.getBasicBlockIndex(BBB);
7061 Value *VB = PN.getIncomingValue(j);
7062 PN.setIncomingBlock(i, BBB);
7063 PN.setIncomingValue(i, VB);
7064 PN.setIncomingBlock(j, BBA);
7065 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +00007066 // NOTE: Instcombine normally would want us to "return &PN" if we
7067 // modified any of the operands of an instruction. However, since we
7068 // aren't adding or removing uses (just rearranging them) we don't do
7069 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +00007070 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +00007071 }
7072
Chris Lattner9956c052009-11-08 19:23:30 +00007073 // If this is an integer PHI and we know that it has an illegal type, see if
7074 // it is only used by trunc or trunc(lshr) operations. If so, we split the
7075 // PHI into the various pieces being extracted. This sort of thing is
7076 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +00007077 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +00007078 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
7079 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
7080 return Res;
7081
Chris Lattner60921c92003-12-19 05:58:40 +00007082 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00007083}
7084
Chris Lattner7e708292002-06-25 16:13:24 +00007085Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +00007086 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
7087
7088 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
7089 return ReplaceInstUsesWith(GEP, V);
7090
Chris Lattner620ce142004-05-07 22:09:22 +00007091 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007092
Chris Lattnere87597f2004-10-16 18:11:37 +00007093 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00007094 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007095
Chris Lattner28977af2004-04-05 01:30:19 +00007096 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +00007097 if (TD) {
7098 bool MadeChange = false;
7099 unsigned PtrSize = TD->getPointerSizeInBits();
7100
7101 gep_type_iterator GTI = gep_type_begin(GEP);
7102 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
7103 I != E; ++I, ++GTI) {
7104 if (!isa<SequentialType>(*GTI)) continue;
7105
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007106 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +00007107 // to what we need. If narrower, sign-extend it to what we need. This
7108 // explicit cast can make subsequent optimizations more obvious.
7109 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +00007110 if (OpBits == PtrSize)
7111 continue;
7112
Chris Lattner2345d1d2009-08-30 20:01:10 +00007113 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +00007114 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +00007115 }
Chris Lattnerccf4b342009-08-30 04:49:01 +00007116 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00007117 }
Chris Lattner28977af2004-04-05 01:30:19 +00007118
Chris Lattner90ac28c2002-08-02 19:29:35 +00007119 // Combine Indices - If the source pointer to this getelementptr instruction
7120 // is a getelementptr instruction, combine the indices of the two
7121 // getelementptr instructions into a single instruction.
7122 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +00007123 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +00007124 // Note that if our source is a gep chain itself that we wait for that
7125 // chain to be resolved before we perform this transformation. This
7126 // avoids us creating a TON of code in some cases.
7127 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00007128 if (GetElementPtrInst *SrcGEP =
7129 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
7130 if (SrcGEP->getNumOperands() == 2)
7131 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +00007132
Chris Lattner72588fc2007-02-15 22:48:32 +00007133 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00007134
7135 // Find out whether the last index in the source GEP is a sequential idx.
7136 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +00007137 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
7138 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00007139 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00007140
Chris Lattner90ac28c2002-08-02 19:29:35 +00007141 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00007142 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00007143 // Replace: gep (gep %P, long B), long A, ...
7144 // With: T = long A+B; gep %P, T, ...
7145 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00007146 Value *Sum;
7147 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
7148 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +00007149 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00007150 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +00007151 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00007152 Sum = SO1;
7153 } else {
Chris Lattnerab984842009-08-30 05:30:55 +00007154 // If they aren't the same type, then the input hasn't been processed
7155 // by the loop above yet (which canonicalizes sequential index types to
7156 // intptr_t). Just avoid transforming this until the input has been
7157 // normalized.
7158 if (SO1->getType() != GO1->getType())
7159 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007160 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +00007161 }
Chris Lattner620ce142004-05-07 22:09:22 +00007162
Chris Lattnerab984842009-08-30 05:30:55 +00007163 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00007164 if (Src->getNumOperands() == 2) {
7165 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +00007166 GEP.setOperand(1, Sum);
7167 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +00007168 }
Chris Lattnerab984842009-08-30 05:30:55 +00007169 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +00007170 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +00007171 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +00007172 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00007173 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00007174 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00007175 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +00007176 Indices.append(Src->op_begin()+1, Src->op_end());
7177 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00007178 }
7179
Dan Gohmanf8dbee72009-09-07 23:54:19 +00007180 if (!Indices.empty())
7181 return (cast<GEPOperator>(&GEP)->isInBounds() &&
7182 Src->isInBounds()) ?
7183 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
7184 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00007185 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +00007186 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +00007187 }
7188
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00007189 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
7190 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +00007191 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +00007192
Chris Lattner2de23192009-08-30 20:38:21 +00007193 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
7194 // want to change the gep until the bitcasts are eliminated.
7195 if (getBitCastOperand(X)) {
7196 Worklist.AddValue(PtrOp);
7197 return 0;
7198 }
7199
Chris Lattnerc514c1f2009-11-27 00:29:05 +00007200 bool HasZeroPointerIndex = false;
7201 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
7202 HasZeroPointerIndex = C->isZero();
7203
Chris Lattner963f4ba2009-08-30 20:36:46 +00007204 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
7205 // into : GEP [10 x i8]* X, i32 0, ...
7206 //
7207 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
7208 // into : GEP i8* X, ...
7209 //
7210 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +00007211 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +00007212 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7213 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +00007214 if (const ArrayType *CATy =
7215 dyn_cast<ArrayType>(CPTy->getElementType())) {
7216 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
7217 if (CATy->getElementType() == XTy->getElementType()) {
7218 // -> GEP i8* X, ...
7219 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +00007220 return cast<GEPOperator>(&GEP)->isInBounds() ?
7221 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
7222 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +00007223 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
7224 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +00007225 }
7226
7227 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +00007228 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +00007229 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +00007230 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00007231 // At this point, we know that the cast source type is a pointer
7232 // to an array of the same type as the destination pointer
7233 // array. Because the array type is never stepped over (there
7234 // is a leading zero) we can fold the cast into this GEP.
7235 GEP.setOperand(0, X);
7236 return &GEP;
7237 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +00007238 }
7239 }
Chris Lattnereed48272005-09-13 00:40:14 +00007240 } else if (GEP.getNumOperands() == 2) {
7241 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00007242 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
7243 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00007244 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7245 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007246 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +00007247 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7248 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00007249 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00007250 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00007251 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00007252 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
7253 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007254 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00007255 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007256 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007257 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00007258
7259 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00007260 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00007261 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00007262 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00007263
Chris Lattner4de84762010-01-04 07:02:48 +00007264 if (TD && isa<ArrayType>(SrcElTy) &&
7265 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00007266 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +00007267 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00007268
7269 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7270 // allow either a mul, shift, or constant here.
7271 Value *NewIdx = 0;
7272 ConstantInt *Scale = 0;
7273 if (ArrayEltSize == 1) {
7274 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +00007275 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007276 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +00007277 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007278 Scale = CI;
7279 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7280 if (Inst->getOpcode() == Instruction::Shl &&
7281 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007282 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
7283 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +00007284 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +00007285 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007286 NewIdx = Inst->getOperand(0);
7287 } else if (Inst->getOpcode() == Instruction::Mul &&
7288 isa<ConstantInt>(Inst->getOperand(1))) {
7289 Scale = cast<ConstantInt>(Inst->getOperand(1));
7290 NewIdx = Inst->getOperand(0);
7291 }
7292 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00007293
Chris Lattner7835cdd2005-09-13 18:36:04 +00007294 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00007295 // out, perform the transformation. Note, we don't know whether Scale is
7296 // signed or not. We'll use unsigned version of division/modulo
7297 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +00007298 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00007299 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +00007300 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00007301 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00007302 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +00007303 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7304 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007305 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00007306 }
7307
7308 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00007309 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00007310 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00007311 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00007312 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
7313 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
7314 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00007315 // The NewGEP must be pointer typed, so must the old one -> BitCast
7316 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00007317 }
7318 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007319 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00007320 }
Chris Lattner58407792009-01-09 04:53:57 +00007321
Chris Lattner46cd5a12009-01-09 05:44:56 +00007322 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +00007323 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +00007324 /// Y = gep X, <...constant indices...>
7325 /// into a gep of the original struct. This is important for SROA and alias
7326 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +00007327 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007328 if (TD &&
7329 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007330 // Determine how much the GEP moves the pointer. We are guaranteed to get
7331 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00007332 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +00007333 int64_t Offset = OffsetV->getSExtValue();
7334
7335 // If this GEP instruction doesn't move the pointer, just replace the GEP
7336 // with a bitcast of the real input to the dest type.
7337 if (Offset == 0) {
7338 // If the bitcast is of an allocation, and the allocation will be
7339 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00007340 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00007341 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007342 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
7343 if (Instruction *I = visitBitCast(*BCI)) {
7344 if (I != BCI) {
7345 I->takeName(BCI);
7346 BCI->getParent()->getInstList().insert(BCI, I);
7347 ReplaceInstUsesWith(*BCI, I);
7348 }
7349 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00007350 }
Chris Lattner58407792009-01-09 04:53:57 +00007351 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00007352 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00007353 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00007354
7355 // Otherwise, if the offset is non-zero, we need to find out if there is a
7356 // field at Offset in 'A's type. If so, we can pull the cast through the
7357 // GEP.
7358 SmallVector<Value*, 8> NewIndices;
7359 const Type *InTy =
7360 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00007361 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00007362 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
7363 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
7364 NewIndices.end()) :
7365 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
7366 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007367
7368 if (NGEP->getType() == GEP.getType())
7369 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00007370 NGEP->takeName(&GEP);
7371 return new BitCastInst(NGEP, GEP.getType());
7372 }
Chris Lattner58407792009-01-09 04:53:57 +00007373 }
7374 }
7375
Chris Lattner8a2a3112001-12-14 16:52:21 +00007376 return 0;
7377}
7378
Victor Hernandez7b929da2009-10-23 21:09:37 +00007379Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +00007380 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00007381 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00007382 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7383 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +00007384 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +00007385 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +00007386 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007387 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +00007388
Chris Lattner0864acf2002-11-04 16:18:53 +00007389 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +00007390 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +00007391 //
7392 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +00007393 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +00007394
7395 // Now that I is pointing to the first non-allocation-inst in the block,
7396 // insert our getelementptr instruction...
7397 //
Chris Lattner4de84762010-01-04 07:02:48 +00007398 Value *NullIdx =Constant::getNullValue(Type::getInt32Ty(AI.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00007399 Value *Idx[2];
7400 Idx[0] = NullIdx;
7401 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00007402 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
7403 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00007404
7405 // Now make everything use the getelementptr instead of the original
7406 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00007407 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00007408 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +00007409 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00007410 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00007411 }
Chris Lattner7c881df2004-03-19 06:08:10 +00007412
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007413 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +00007414 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +00007415 // Note that we only do this for alloca's, because malloc should allocate
7416 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +00007417 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +00007418 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +00007419
7420 // If the alignment is 0 (unspecified), assign it the preferred alignment.
7421 if (AI.getAlignment() == 0)
7422 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
7423 }
Chris Lattner7c881df2004-03-19 06:08:10 +00007424
Chris Lattner0864acf2002-11-04 16:18:53 +00007425 return 0;
7426}
7427
Victor Hernandez66284e02009-10-24 04:23:03 +00007428Instruction *InstCombiner::visitFree(Instruction &FI) {
7429 Value *Op = FI.getOperand(1);
7430
7431 // free undef -> unreachable.
7432 if (isa<UndefValue>(Op)) {
7433 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00007434 new StoreInst(ConstantInt::getTrue(FI.getContext()),
7435 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +00007436 return EraseInstFromFunction(FI);
7437 }
7438
7439 // If we have 'free null' delete the instruction. This can happen in stl code
7440 // when lots of inlining happens.
7441 if (isa<ConstantPointerNull>(Op))
7442 return EraseInstFromFunction(FI);
7443
Victor Hernandez046e78c2009-10-26 23:43:48 +00007444 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +00007445 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +00007446 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
7447 if (Op->hasOneUse() && CI->hasOneUse()) {
7448 EraseInstFromFunction(FI);
7449 EraseInstFromFunction(*CI);
7450 return EraseInstFromFunction(*cast<Instruction>(Op));
7451 }
7452 } else {
7453 // Op is a call to malloc
7454 if (Op->hasOneUse()) {
7455 EraseInstFromFunction(FI);
7456 return EraseInstFromFunction(*cast<Instruction>(Op));
7457 }
7458 }
Dan Gohman7f712a12009-10-27 00:11:02 +00007459 }
Victor Hernandez66284e02009-10-24 04:23:03 +00007460
7461 return 0;
7462}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00007463
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007464/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00007465static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00007466 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00007467 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00007468 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00007469
Mon P Wang6753f952009-02-07 22:19:29 +00007470 const PointerType *DestTy = cast<PointerType>(CI->getType());
7471 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00007472 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +00007473
7474 // If the address spaces don't match, don't eliminate the cast.
7475 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
7476 return 0;
7477
Chris Lattnerb89e0712004-07-13 01:49:43 +00007478 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00007479
Reid Spencer42230162007-01-22 05:51:25 +00007480 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00007481 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00007482 // If the source is an array, the code below will not succeed. Check to
7483 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7484 // constants.
7485 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7486 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7487 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00007488 Value *Idxs[2];
Chris Lattner4de84762010-01-04 07:02:48 +00007489 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(LI.getContext()));
Chris Lattnere00c43f2009-10-22 06:44:07 +00007490 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +00007491 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00007492 SrcTy = cast<PointerType>(CastOp->getType());
7493 SrcPTy = SrcTy->getElementType();
7494 }
7495
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007496 if (IC.getTargetData() &&
7497 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00007498 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00007499 // Do not allow turning this into a load of an integer, which is then
7500 // casted to a pointer, this pessimizes pointer analysis a lot.
7501 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007502 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
7503 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00007504
Chris Lattnerf9527852005-01-31 04:50:46 +00007505 // Okay, we are casting from one integer or pointer type to another of
7506 // the same size. Instead of casting the pointer before the load, cast
7507 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007508 Value *NewLoad =
7509 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +00007510 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00007511 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00007512 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00007513 }
7514 }
7515 return 0;
7516}
7517
Chris Lattner833b8a42003-06-26 05:06:25 +00007518Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7519 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00007520
Dan Gohman9941f742007-07-20 16:34:21 +00007521 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007522 if (TD) {
7523 unsigned KnownAlign =
7524 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
7525 if (KnownAlign >
7526 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
7527 LI.getAlignment()))
7528 LI.setAlignment(KnownAlign);
7529 }
Dan Gohman9941f742007-07-20 16:34:21 +00007530
Chris Lattner963f4ba2009-08-30 20:36:46 +00007531 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +00007532 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00007533 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00007534 return Res;
7535
7536 // None of the following transforms are legal for volatile loads.
7537 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00007538
Dan Gohman2276a7b2008-10-15 23:19:35 +00007539 // Do really simple store-to-load forwarding and load CSE, to catch cases
7540 // where there are several consequtive memory accesses to the same location,
7541 // separated by a few arithmetic operations.
7542 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +00007543 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
7544 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +00007545
Chris Lattner878e4942009-10-22 06:25:11 +00007546 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +00007547 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
7548 const Value *GEPI0 = GEPI->getOperand(0);
7549 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +00007550 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +00007551 // Insert a new store to null instruction before the load to indicate
7552 // that this code is not reachable. We do this instead of inserting
7553 // an unreachable instruction directly because we cannot modify the
7554 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00007555 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +00007556 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00007557 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +00007558 }
Christopher Lambb15147e2007-12-29 07:56:53 +00007559 }
Chris Lattner37366c12005-05-01 04:24:53 +00007560
Chris Lattner878e4942009-10-22 06:25:11 +00007561 // load null/undef -> unreachable
7562 // TODO: Consider a target hook for valid address spaces for this xform.
7563 if (isa<UndefValue>(Op) ||
7564 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
7565 // Insert a new store to null instruction before the load to indicate that
7566 // this code is not reachable. We do this instead of inserting an
7567 // unreachable instruction directly because we cannot modify the CFG.
7568 new StoreInst(UndefValue::get(LI.getType()),
7569 Constant::getNullValue(Op->getType()), &LI);
7570 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007571 }
Chris Lattner878e4942009-10-22 06:25:11 +00007572
7573 // Instcombine load (constantexpr_cast global) -> cast (load global)
7574 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7575 if (CE->isCast())
7576 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
7577 return Res;
7578
Chris Lattner37366c12005-05-01 04:24:53 +00007579 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00007580 // Change select and PHI nodes to select values instead of addresses: this
7581 // helps alias analysis out a lot, allows many others simplifications, and
7582 // exposes redundancy in the code.
7583 //
7584 // Note that we cannot do the transformation unless we know that the
7585 // introduced loads cannot trap! Something like this is valid as long as
7586 // the condition is always false: load (select bool %C, int* null, int* %G),
7587 // but it would not be valid if we transformed it to load from null
7588 // unconditionally.
7589 //
7590 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7591 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00007592 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7593 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007594 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
7595 SI->getOperand(1)->getName()+".val");
7596 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
7597 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +00007598 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +00007599 }
7600
Chris Lattner684fe212004-09-23 15:46:00 +00007601 // load (select (cond, null, P)) -> load P
7602 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7603 if (C->isNullValue()) {
7604 LI.setOperand(0, SI->getOperand(2));
7605 return &LI;
7606 }
7607
7608 // load (select (cond, P, null)) -> load P
7609 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7610 if (C->isNullValue()) {
7611 LI.setOperand(0, SI->getOperand(1));
7612 return &LI;
7613 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00007614 }
7615 }
Chris Lattner833b8a42003-06-26 05:06:25 +00007616 return 0;
7617}
7618
Reid Spencer55af2b52007-01-19 21:20:31 +00007619/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +00007620/// when possible. This makes it generally easy to do alias analysis and/or
7621/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007622static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7623 User *CI = cast<User>(SI.getOperand(1));
7624 Value *CastOp = CI->getOperand(0);
7625
7626 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +00007627 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
7628 if (SrcTy == 0) return 0;
7629
7630 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007631
Chris Lattner1b8eaf52009-01-16 20:08:59 +00007632 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
7633 return 0;
7634
Chris Lattner3914f722009-01-24 01:00:13 +00007635 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
7636 /// to its first element. This allows us to handle things like:
7637 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
7638 /// on 32-bit hosts.
7639 SmallVector<Value*, 4> NewGEPIndices;
7640
Chris Lattner1b8eaf52009-01-16 20:08:59 +00007641 // If the source is an array, the code below will not succeed. Check to
7642 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7643 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +00007644 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
7645 // Index through pointer.
Chris Lattner4de84762010-01-04 07:02:48 +00007646 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +00007647 NewGEPIndices.push_back(Zero);
7648
7649 while (1) {
7650 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +00007651 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +00007652 break;
Chris Lattner3914f722009-01-24 01:00:13 +00007653 NewGEPIndices.push_back(Zero);
7654 SrcPTy = STy->getElementType(0);
7655 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
7656 NewGEPIndices.push_back(Zero);
7657 SrcPTy = ATy->getElementType();
7658 } else {
7659 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007660 }
Chris Lattner3914f722009-01-24 01:00:13 +00007661 }
7662
Owen Andersondebcb012009-07-29 22:17:13 +00007663 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +00007664 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +00007665
7666 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
7667 return 0;
7668
Chris Lattner71759c42009-01-16 20:12:52 +00007669 // If the pointers point into different address spaces or if they point to
7670 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007671 if (!IC.getTargetData() ||
7672 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +00007673 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007674 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
7675 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +00007676 return 0;
7677
7678 // Okay, we are casting from one integer or pointer type to another of
7679 // the same size. Instead of casting the pointer before
7680 // the store, cast the value to be stored.
7681 Value *NewCast;
7682 Value *SIOp0 = SI.getOperand(0);
7683 Instruction::CastOps opcode = Instruction::BitCast;
7684 const Type* CastSrcTy = SIOp0->getType();
7685 const Type* CastDstTy = SrcPTy;
7686 if (isa<PointerType>(CastDstTy)) {
7687 if (CastSrcTy->isInteger())
7688 opcode = Instruction::IntToPtr;
7689 } else if (isa<IntegerType>(CastDstTy)) {
7690 if (isa<PointerType>(SIOp0->getType()))
7691 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007692 }
Chris Lattner3914f722009-01-24 01:00:13 +00007693
7694 // SIOp0 is a pointer to aggregate and this is a store to the first field,
7695 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00007696 if (!NewGEPIndices.empty())
7697 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
7698 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +00007699
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007700 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
7701 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +00007702 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007703}
7704
Chris Lattner4aebaee2008-11-27 08:56:30 +00007705/// equivalentAddressValues - Test if A and B will obviously have the same
7706/// value. This includes recognizing that %t0 and %t1 will have the same
7707/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +00007708/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +00007709/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +00007710/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +00007711/// %t2 = load i32* %t1
7712///
7713static bool equivalentAddressValues(Value *A, Value *B) {
7714 // Test if the values are trivially equivalent.
7715 if (A == B) return true;
7716
7717 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +00007718 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
7719 // its only used to compare two uses within the same basic block, which
7720 // means that they'll always either have the same value or one of them
7721 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +00007722 if (isa<BinaryOperator>(A) ||
7723 isa<CastInst>(A) ||
7724 isa<PHINode>(A) ||
7725 isa<GetElementPtrInst>(A))
7726 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +00007727 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +00007728 return true;
7729
7730 // Otherwise they may not be equivalent.
7731 return false;
7732}
7733
Dale Johannesen4945c652009-03-03 21:26:39 +00007734// If this instruction has two uses, one of which is a llvm.dbg.declare,
7735// return the llvm.dbg.declare.
7736DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
7737 if (!V->hasNUses(2))
7738 return 0;
7739 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
7740 UI != E; ++UI) {
7741 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
7742 return DI;
7743 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
7744 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
7745 return DI;
7746 }
7747 }
7748 return 0;
7749}
7750
Chris Lattner2f503e62005-01-31 05:36:43 +00007751Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7752 Value *Val = SI.getOperand(0);
7753 Value *Ptr = SI.getOperand(1);
7754
Chris Lattner836692d2007-01-15 06:51:56 +00007755 // If the RHS is an alloca with a single use, zapify the store, making the
7756 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +00007757 // If the RHS is an alloca with a two uses, the other one being a
7758 // llvm.dbg.declare, zapify the store and the declare, making the
7759 // alloca dead. We must do this to prevent declare's from affecting
7760 // codegen.
7761 if (!SI.isVolatile()) {
7762 if (Ptr->hasOneUse()) {
7763 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +00007764 EraseInstFromFunction(SI);
7765 ++NumCombined;
7766 return 0;
7767 }
Dale Johannesen4945c652009-03-03 21:26:39 +00007768 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
7769 if (isa<AllocaInst>(GEP->getOperand(0))) {
7770 if (GEP->getOperand(0)->hasOneUse()) {
7771 EraseInstFromFunction(SI);
7772 ++NumCombined;
7773 return 0;
7774 }
7775 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
7776 EraseInstFromFunction(*DI);
7777 EraseInstFromFunction(SI);
7778 ++NumCombined;
7779 return 0;
7780 }
7781 }
7782 }
7783 }
7784 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
7785 EraseInstFromFunction(*DI);
7786 EraseInstFromFunction(SI);
7787 ++NumCombined;
7788 return 0;
7789 }
Chris Lattner836692d2007-01-15 06:51:56 +00007790 }
Chris Lattner2f503e62005-01-31 05:36:43 +00007791
Dan Gohman9941f742007-07-20 16:34:21 +00007792 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007793 if (TD) {
7794 unsigned KnownAlign =
7795 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
7796 if (KnownAlign >
7797 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
7798 SI.getAlignment()))
7799 SI.setAlignment(KnownAlign);
7800 }
Dan Gohman9941f742007-07-20 16:34:21 +00007801
Dale Johannesenacb51a32009-03-03 01:43:03 +00007802 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +00007803 // stores to the same location, separated by a few arithmetic operations. This
7804 // situation often occurs with bitfield accesses.
7805 BasicBlock::iterator BBI = &SI;
7806 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7807 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +00007808 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +00007809 // Don't count debug info directives, lest they affect codegen,
7810 // and we skip pointer-to-pointer bitcasts, which are NOPs.
7811 // It is necessary for correctness to skip those that feed into a
7812 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +00007813 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +00007814 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +00007815 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +00007816 continue;
7817 }
Chris Lattner9ca96412006-02-08 03:25:32 +00007818
7819 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7820 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +00007821 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
7822 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +00007823 ++NumDeadStore;
7824 ++BBI;
7825 EraseInstFromFunction(*PrevSI);
7826 continue;
7827 }
7828 break;
7829 }
7830
Chris Lattnerb4db97f2006-05-26 19:19:20 +00007831 // If this is a load, we have to stop. However, if the loaded value is from
7832 // the pointer we're loading and is producing the pointer we're storing,
7833 // then *this* store is dead (X = load P; store X -> P).
7834 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +00007835 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
7836 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +00007837 EraseInstFromFunction(SI);
7838 ++NumCombined;
7839 return 0;
7840 }
7841 // Otherwise, this is a load from some other location. Stores before it
7842 // may not be dead.
7843 break;
7844 }
7845
Chris Lattner9ca96412006-02-08 03:25:32 +00007846 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +00007847 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00007848 break;
7849 }
7850
7851
7852 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00007853
7854 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +00007855 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +00007856 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00007857 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +00007858 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +00007859 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00007860 ++NumCombined;
7861 }
7862 return 0; // Do not modify these!
7863 }
7864
7865 // store undef, Ptr -> noop
7866 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00007867 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00007868 ++NumCombined;
7869 return 0;
7870 }
7871
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007872 // If the pointer destination is a cast, see if we can fold the cast into the
7873 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00007874 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007875 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7876 return Res;
7877 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00007878 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007879 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7880 return Res;
7881
Chris Lattner408902b2005-09-12 23:23:25 +00007882
Dale Johannesen4084c4e2009-03-05 02:06:48 +00007883 // If this store is the last instruction in the basic block (possibly
7884 // excepting debug info instructions and the pointer bitcasts that feed
7885 // into them), and if the block ends with an unconditional branch, try
7886 // to move it to the successor block.
7887 BBI = &SI;
7888 do {
7889 ++BBI;
7890 } while (isa<DbgInfoIntrinsic>(BBI) ||
7891 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +00007892 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +00007893 if (BI->isUnconditional())
7894 if (SimplifyStoreAtEndOfBlock(SI))
7895 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +00007896
Chris Lattner2f503e62005-01-31 05:36:43 +00007897 return 0;
7898}
7899
Chris Lattner3284d1f2007-04-15 00:07:55 +00007900/// SimplifyStoreAtEndOfBlock - Turn things like:
7901/// if () { *P = v1; } else { *P = v2 }
7902/// into a phi node with a store in the successor.
7903///
Chris Lattner31755a02007-04-15 01:02:18 +00007904/// Simplify things like:
7905/// *P = v1; if () { *P = v2; }
7906/// into a phi node with a store in the successor.
7907///
Chris Lattner3284d1f2007-04-15 00:07:55 +00007908bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
7909 BasicBlock *StoreBB = SI.getParent();
7910
7911 // Check to see if the successor block has exactly two incoming edges. If
7912 // so, see if the other predecessor contains a store to the same location.
7913 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +00007914 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +00007915
7916 // Determine whether Dest has exactly two predecessors and, if so, compute
7917 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +00007918 pred_iterator PI = pred_begin(DestBB);
7919 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +00007920 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +00007921 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00007922 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +00007923 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00007924 return false;
7925
7926 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +00007927 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +00007928 return false;
Chris Lattner31755a02007-04-15 01:02:18 +00007929 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00007930 }
Chris Lattner31755a02007-04-15 01:02:18 +00007931 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00007932 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +00007933
7934 // Bail out if all the relevant blocks aren't distinct (this can happen,
7935 // for example, if SI is in an infinite loop)
7936 if (StoreBB == DestBB || OtherBB == DestBB)
7937 return false;
7938
Chris Lattner31755a02007-04-15 01:02:18 +00007939 // Verify that the other block ends in a branch and is not otherwise empty.
7940 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +00007941 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +00007942 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +00007943 return false;
7944
Chris Lattner31755a02007-04-15 01:02:18 +00007945 // If the other block ends in an unconditional branch, check for the 'if then
7946 // else' case. there is an instruction before the branch.
7947 StoreInst *OtherStore = 0;
7948 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +00007949 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +00007950 // Skip over debugging info.
7951 while (isa<DbgInfoIntrinsic>(BBI) ||
7952 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
7953 if (BBI==OtherBB->begin())
7954 return false;
7955 --BBI;
7956 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +00007957 // If this isn't a store, isn't a store to the same location, or if the
7958 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +00007959 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +00007960 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
7961 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +00007962 return false;
7963 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +00007964 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +00007965 // destinations is StoreBB, then we have the if/then case.
7966 if (OtherBr->getSuccessor(0) != StoreBB &&
7967 OtherBr->getSuccessor(1) != StoreBB)
7968 return false;
7969
7970 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +00007971 // if/then triangle. See if there is a store to the same ptr as SI that
7972 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +00007973 for (;; --BBI) {
7974 // Check to see if we find the matching store.
7975 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +00007976 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
7977 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +00007978 return false;
7979 break;
7980 }
Eli Friedman6903a242008-06-13 22:02:12 +00007981 // If we find something that may be using or overwriting the stored
7982 // value, or if we run out of instructions, we can't do the xform.
7983 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +00007984 BBI == OtherBB->begin())
7985 return false;
7986 }
7987
7988 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +00007989 // make sure nothing reads or overwrites the stored value in
7990 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +00007991 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
7992 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +00007993 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +00007994 return false;
7995 }
7996 }
Chris Lattner3284d1f2007-04-15 00:07:55 +00007997
Chris Lattner31755a02007-04-15 01:02:18 +00007998 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +00007999 Value *MergedVal = OtherStore->getOperand(0);
8000 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +00008001 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +00008002 PN->reserveOperandSpace(2);
8003 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +00008004 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
8005 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +00008006 }
8007
8008 // Advance to a place where it is safe to insert the new store and
8009 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +00008010 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +00008011 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +00008012 OtherStore->isVolatile(),
8013 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +00008014
8015 // Nuke the old stores.
8016 EraseInstFromFunction(SI);
8017 EraseInstFromFunction(*OtherStore);
8018 ++NumCombined;
8019 return true;
8020}
8021
Chris Lattner2f503e62005-01-31 05:36:43 +00008022
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00008023Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8024 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00008025 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00008026 BasicBlock *TrueDest;
8027 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00008028 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00008029 !isa<Constant>(X)) {
8030 // Swap Destinations and condition...
8031 BI.setCondition(X);
8032 BI.setSuccessor(0, FalseDest);
8033 BI.setSuccessor(1, TrueDest);
8034 return &BI;
8035 }
8036
Reid Spencere4d87aa2006-12-23 06:05:41 +00008037 // Cannonicalize fcmp_one -> fcmp_oeq
8038 FCmpInst::Predicate FPred; Value *Y;
8039 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00008040 TrueDest, FalseDest)) &&
8041 BI.getCondition()->hasOneUse())
8042 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8043 FPred == FCmpInst::FCMP_OGE) {
8044 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
8045 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
8046
8047 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008048 BI.setSuccessor(0, FalseDest);
8049 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00008050 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008051 return &BI;
8052 }
8053
8054 // Cannonicalize icmp_ne -> icmp_eq
8055 ICmpInst::Predicate IPred;
8056 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00008057 TrueDest, FalseDest)) &&
8058 BI.getCondition()->hasOneUse())
8059 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8060 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8061 IPred == ICmpInst::ICMP_SGE) {
8062 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
8063 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
8064 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00008065 BI.setSuccessor(0, FalseDest);
8066 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00008067 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00008068 return &BI;
8069 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008070
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00008071 return 0;
8072}
Chris Lattner0864acf2002-11-04 16:18:53 +00008073
Chris Lattner46238a62004-07-03 00:26:11 +00008074Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8075 Value *Cond = SI.getCondition();
8076 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8077 if (I->getOpcode() == Instruction::Add)
8078 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8079 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8080 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00008081 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008082 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00008083 AddRHS));
8084 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00008085 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00008086 return &SI;
8087 }
8088 }
8089 return 0;
8090}
8091
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00008092Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00008093 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00008094
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00008095 if (!EV.hasIndices())
8096 return ReplaceInstUsesWith(EV, Agg);
8097
8098 if (Constant *C = dyn_cast<Constant>(Agg)) {
8099 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008100 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00008101
8102 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00008103 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00008104
8105 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
8106 // Extract the element indexed by the first index out of the constant
8107 Value *V = C->getOperand(*EV.idx_begin());
8108 if (EV.getNumIndices() > 1)
8109 // Extract the remaining indices out of the constant indexed by the
8110 // first index
8111 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
8112 else
8113 return ReplaceInstUsesWith(EV, V);
8114 }
8115 return 0; // Can't handle other constants
8116 }
8117 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
8118 // We're extracting from an insertvalue instruction, compare the indices
8119 const unsigned *exti, *exte, *insi, *inse;
8120 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
8121 exte = EV.idx_end(), inse = IV->idx_end();
8122 exti != exte && insi != inse;
8123 ++exti, ++insi) {
8124 if (*insi != *exti)
8125 // The insert and extract both reference distinctly different elements.
8126 // This means the extract is not influenced by the insert, and we can
8127 // replace the aggregate operand of the extract with the aggregate
8128 // operand of the insert. i.e., replace
8129 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
8130 // %E = extractvalue { i32, { i32 } } %I, 0
8131 // with
8132 // %E = extractvalue { i32, { i32 } } %A, 0
8133 return ExtractValueInst::Create(IV->getAggregateOperand(),
8134 EV.idx_begin(), EV.idx_end());
8135 }
8136 if (exti == exte && insi == inse)
8137 // Both iterators are at the end: Index lists are identical. Replace
8138 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
8139 // %C = extractvalue { i32, { i32 } } %B, 1, 0
8140 // with "i32 42"
8141 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
8142 if (exti == exte) {
8143 // The extract list is a prefix of the insert list. i.e. replace
8144 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
8145 // %E = extractvalue { i32, { i32 } } %I, 1
8146 // with
8147 // %X = extractvalue { i32, { i32 } } %A, 1
8148 // %E = insertvalue { i32 } %X, i32 42, 0
8149 // by switching the order of the insert and extract (though the
8150 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008151 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
8152 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00008153 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
8154 insi, inse);
8155 }
8156 if (insi == inse)
8157 // The insert list is a prefix of the extract list
8158 // We can simply remove the common indices from the extract and make it
8159 // operate on the inserted value instead of the insertvalue result.
8160 // i.e., replace
8161 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
8162 // %E = extractvalue { i32, { i32 } } %I, 1, 0
8163 // with
8164 // %E extractvalue { i32 } { i32 42 }, 0
8165 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
8166 exti, exte);
8167 }
Chris Lattner7e606e22009-11-09 07:07:56 +00008168 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
8169 // We're extracting from an intrinsic, see if we're the only user, which
8170 // allows us to simplify multiple result intrinsics to simpler things that
8171 // just get one value..
8172 if (II->hasOneUse()) {
8173 // Check if we're grabbing the overflow bit or the result of a 'with
8174 // overflow' intrinsic. If it's the latter we can remove the intrinsic
8175 // and replace it with a traditional binary instruction.
8176 switch (II->getIntrinsicID()) {
8177 case Intrinsic::uadd_with_overflow:
8178 case Intrinsic::sadd_with_overflow:
8179 if (*EV.idx_begin() == 0) { // Normal result.
8180 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
8181 II->replaceAllUsesWith(UndefValue::get(II->getType()));
8182 EraseInstFromFunction(*II);
8183 return BinaryOperator::CreateAdd(LHS, RHS);
8184 }
8185 break;
8186 case Intrinsic::usub_with_overflow:
8187 case Intrinsic::ssub_with_overflow:
8188 if (*EV.idx_begin() == 0) { // Normal result.
8189 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
8190 II->replaceAllUsesWith(UndefValue::get(II->getType()));
8191 EraseInstFromFunction(*II);
8192 return BinaryOperator::CreateSub(LHS, RHS);
8193 }
8194 break;
8195 case Intrinsic::umul_with_overflow:
8196 case Intrinsic::smul_with_overflow:
8197 if (*EV.idx_begin() == 0) { // Normal result.
8198 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
8199 II->replaceAllUsesWith(UndefValue::get(II->getType()));
8200 EraseInstFromFunction(*II);
8201 return BinaryOperator::CreateMul(LHS, RHS);
8202 }
8203 break;
8204 default:
8205 break;
8206 }
8207 }
8208 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00008209 // Can't simplify extracts from other values. Note that nested extracts are
8210 // already simplified implicitely by the above (extract ( extract (insert) )
8211 // will be translated into extract ( insert ( extract ) ) first and then just
8212 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00008213 return 0;
8214}
8215
Chris Lattner220b0cf2006-03-05 00:22:33 +00008216/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8217/// is to leave as a vector operation.
8218static bool CheapToScalarize(Value *V, bool isConstant) {
8219 if (isa<ConstantAggregateZero>(V))
8220 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +00008221 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00008222 if (isConstant) return true;
8223 // If all elts are the same, we can extract.
8224 Constant *Op0 = C->getOperand(0);
8225 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8226 if (C->getOperand(i) != Op0)
8227 return false;
8228 return true;
8229 }
8230 Instruction *I = dyn_cast<Instruction>(V);
8231 if (!I) return false;
8232
8233 // Insert element gets simplified to the inserted element or is deleted if
8234 // this is constant idx extract element and its a constant idx insertelt.
8235 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8236 isa<ConstantInt>(I->getOperand(2)))
8237 return true;
8238 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8239 return true;
8240 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8241 if (BO->hasOneUse() &&
8242 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8243 CheapToScalarize(BO->getOperand(1), isConstant)))
8244 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008245 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8246 if (CI->hasOneUse() &&
8247 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8248 CheapToScalarize(CI->getOperand(1), isConstant)))
8249 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +00008250
8251 return false;
8252}
8253
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008254/// Read and decode a shufflevector mask.
8255///
8256/// It turns undef elements into values that are larger than the number of
8257/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +00008258static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8259 unsigned NElts = SVI->getType()->getNumElements();
8260 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8261 return std::vector<unsigned>(NElts, 0);
8262 if (isa<UndefValue>(SVI->getOperand(2)))
8263 return std::vector<unsigned>(NElts, 2*NElts);
8264
8265 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +00008266 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +00008267 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
8268 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +00008269 Result.push_back(NElts*2); // undef -> 8
8270 else
Gabor Greif177dd3f2008-06-12 21:37:33 +00008271 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00008272 return Result;
8273}
8274
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008275/// FindScalarElement - Given a vector and an element number, see if the scalar
8276/// value is already around as a register, for example if it were inserted then
8277/// extracted from the vector.
Chris Lattner4de84762010-01-04 07:02:48 +00008278static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00008279 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8280 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00008281 unsigned Width = PTy->getNumElements();
8282 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008283 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008284
8285 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008286 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008287 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +00008288 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +00008289 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008290 return CP->getOperand(EltNo);
8291 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8292 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00008293 if (!isa<ConstantInt>(III->getOperand(2)))
8294 return 0;
8295 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008296
8297 // If this is an insert to the element we are looking for, return the
8298 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00008299 if (EltNo == IIElt)
8300 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008301
8302 // Otherwise, the insertelement doesn't modify the value, recurse on its
8303 // vector input.
Chris Lattner4de84762010-01-04 07:02:48 +00008304 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00008305 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00008306 unsigned LHSWidth =
8307 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +00008308 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +00008309 if (InEl < LHSWidth)
Chris Lattner4de84762010-01-04 07:02:48 +00008310 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +00008311 else if (InEl < LHSWidth*2)
Chris Lattner4de84762010-01-04 07:02:48 +00008312 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +00008313 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008314 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008315 }
8316
8317 // Otherwise, we don't know.
8318 return 0;
8319}
8320
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008321Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +00008322 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +00008323 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008324 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +00008325
Dan Gohman07a96762007-07-16 14:29:03 +00008326 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +00008327 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +00008328 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +00008329
Reid Spencer9d6565a2007-02-15 02:26:10 +00008330 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +00008331 // If vector val is constant with all elements the same, replace EI with
8332 // that element. When the elements are not identical, we cannot replace yet
8333 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +00008334 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +00008335 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00008336 if (C->getOperand(i) != op0) {
8337 op0 = 0;
8338 break;
8339 }
8340 if (op0)
8341 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008342 }
Eli Friedman76e7ba82009-07-18 19:04:16 +00008343
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008344 // If extracting a specified index from the vector, see if we can recursively
8345 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00008346 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +00008347 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +00008348 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +00008349
8350 // If this is extracting an invalid index, turn this into undef, to avoid
8351 // crashing the code below.
8352 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008353 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +00008354
Chris Lattner867b99f2006-10-05 06:55:50 +00008355 // This instruction only demands the single element from the input vector.
8356 // If the input vector has a single use, simplify it based on this use
8357 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +00008358 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +00008359 APInt UndefElts(VectorWidth, 0);
8360 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +00008361 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +00008362 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +00008363 EI.setOperand(0, V);
8364 return &EI;
8365 }
8366 }
8367
Chris Lattner4de84762010-01-04 07:02:48 +00008368 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008369 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +00008370
8371 // If the this extractelement is directly using a bitcast from a vector of
8372 // the same number of elements, see if we can find the source element from
8373 // it. In this case, we will end up needing to bitcast the scalars.
8374 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
8375 if (const VectorType *VT =
8376 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
8377 if (VT->getNumElements() == VectorWidth)
Chris Lattner4de84762010-01-04 07:02:48 +00008378 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
Chris Lattnerb7300fa2007-04-14 23:02:14 +00008379 return new BitCastInst(Elt, EI.getType());
8380 }
Chris Lattner389a6f52006-04-10 23:06:36 +00008381 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008382
Chris Lattner73fa49d2006-05-25 22:53:38 +00008383 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +00008384 // Push extractelement into predecessor operation if legal and
8385 // profitable to do so
8386 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8387 if (I->hasOneUse() &&
8388 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
8389 Value *newEI0 =
8390 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
8391 EI.getName()+".lhs");
8392 Value *newEI1 =
8393 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
8394 EI.getName()+".rhs");
8395 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +00008396 }
Chris Lattner275a6d62009-09-08 18:48:01 +00008397 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +00008398 // Extracting the inserted element?
8399 if (IE->getOperand(2) == EI.getOperand(1))
8400 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8401 // If the inserted and extracted elements are constants, they must not
8402 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +00008403 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00008404 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +00008405 EI.setOperand(0, IE->getOperand(0));
8406 return &EI;
8407 }
8408 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8409 // If this is extracting an element from a shufflevector, figure out where
8410 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +00008411 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8412 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +00008413 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +00008414 unsigned LHSWidth =
8415 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
8416
8417 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +00008418 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +00008419 else if (SrcIdx < LHSWidth*2) {
8420 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +00008421 Src = SVI->getOperand(1);
8422 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008423 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00008424 }
Eric Christophera3500da2009-07-25 02:28:41 +00008425 return ExtractElementInst::Create(Src,
Chris Lattner4de84762010-01-04 07:02:48 +00008426 ConstantInt::get(Type::getInt32Ty(EI.getContext()),
8427 SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008428 }
8429 }
Eli Friedman2451a642009-07-18 23:06:53 +00008430 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +00008431 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008432 return 0;
8433}
8434
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008435/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8436/// elements from either LHS or RHS, return the shuffle mask and true.
8437/// Otherwise, return false.
8438static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner4de84762010-01-04 07:02:48 +00008439 std::vector<Constant*> &Mask) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008440 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8441 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +00008442 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008443
8444 if (isa<UndefValue>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +00008445 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008446 return true;
Chris Lattner4de84762010-01-04 07:02:48 +00008447 }
8448
8449 if (V == LHS) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008450 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +00008451 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008452 return true;
Chris Lattner4de84762010-01-04 07:02:48 +00008453 }
8454
8455 if (V == RHS) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008456 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +00008457 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
8458 i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008459 return true;
Chris Lattner4de84762010-01-04 07:02:48 +00008460 }
8461
8462 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008463 // If this is an insert of an extract from some other vector, include it.
8464 Value *VecOp = IEI->getOperand(0);
8465 Value *ScalarOp = IEI->getOperand(1);
8466 Value *IdxOp = IEI->getOperand(2);
8467
Chris Lattnerd929f062006-04-27 21:14:21 +00008468 if (!isa<ConstantInt>(IdxOp))
8469 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +00008470 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +00008471
8472 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8473 // Okay, we can handle this if the vector we are insertinting into is
8474 // transitively ok.
Chris Lattner4de84762010-01-04 07:02:48 +00008475 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerd929f062006-04-27 21:14:21 +00008476 // If so, update the mask to reflect the inserted undef.
Chris Lattner4de84762010-01-04 07:02:48 +00008477 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
Chris Lattnerd929f062006-04-27 21:14:21 +00008478 return true;
8479 }
8480 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8481 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008482 EI->getOperand(0)->getType() == V->getType()) {
8483 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00008484 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008485
8486 // This must be extracting from either LHS or RHS.
8487 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8488 // Okay, we can handle this if the vector we are insertinting into is
8489 // transitively ok.
Chris Lattner4de84762010-01-04 07:02:48 +00008490 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008491 // If so, update the mask to reflect the inserted value.
8492 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +00008493 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +00008494 ConstantInt::get(Type::getInt32Ty(V->getContext()),
8495 ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008496 } else {
8497 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +00008498 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +00008499 ConstantInt::get(Type::getInt32Ty(V->getContext()),
8500 ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008501
8502 }
8503 return true;
8504 }
8505 }
8506 }
8507 }
8508 }
8509 // TODO: Handle shufflevector here!
8510
8511 return false;
8512}
8513
8514/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8515/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8516/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00008517static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner4de84762010-01-04 07:02:48 +00008518 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00008519 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008520 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00008521 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00008522 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +00008523
8524 if (isa<UndefValue>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +00008525 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Chris Lattnerefb47352006-04-15 01:39:45 +00008526 return V;
8527 } else if (isa<ConstantAggregateZero>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +00008528 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Chris Lattnerefb47352006-04-15 01:39:45 +00008529 return V;
8530 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8531 // If this is an insert of an extract from some other vector, include it.
8532 Value *VecOp = IEI->getOperand(0);
8533 Value *ScalarOp = IEI->getOperand(1);
8534 Value *IdxOp = IEI->getOperand(2);
8535
8536 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8537 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8538 EI->getOperand(0)->getType() == V->getType()) {
8539 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00008540 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8541 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00008542
8543 // Either the extracted from or inserted into vector must be RHSVec,
8544 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008545 if (EI->getOperand(0) == RHS || RHS == 0) {
8546 RHS = EI->getOperand(0);
Chris Lattner4de84762010-01-04 07:02:48 +00008547 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +00008548 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +00008549 ConstantInt::get(Type::getInt32Ty(V->getContext()),
8550 NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00008551 return V;
8552 }
8553
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008554 if (VecOp == RHS) {
Chris Lattner4de84762010-01-04 07:02:48 +00008555 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00008556 // Everything but the extracted element is replaced with the RHS.
8557 for (unsigned i = 0; i != NumElts; ++i) {
8558 if (i != InsertedIdx)
Chris Lattner4de84762010-01-04 07:02:48 +00008559 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()),
8560 NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +00008561 }
8562 return V;
8563 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008564
8565 // If this insertelement is a chain that comes from exactly these two
8566 // vectors, return the vector and the effective shuffle.
Chris Lattner4de84762010-01-04 07:02:48 +00008567 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008568 return EI->getOperand(0);
Chris Lattnerefb47352006-04-15 01:39:45 +00008569 }
8570 }
8571 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008572 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00008573
8574 // Otherwise, can't do anything fancy. Return an identity vector.
8575 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +00008576 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Chris Lattnerefb47352006-04-15 01:39:45 +00008577 return V;
8578}
8579
8580Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8581 Value *VecOp = IE.getOperand(0);
8582 Value *ScalarOp = IE.getOperand(1);
8583 Value *IdxOp = IE.getOperand(2);
8584
Chris Lattner599ded12007-04-09 01:11:16 +00008585 // Inserting an undef or into an undefined place, remove this.
8586 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
8587 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +00008588
Chris Lattnerefb47352006-04-15 01:39:45 +00008589 // If the inserted element was extracted from some other vector, and if the
8590 // indexes are constant, try to turn this into a shufflevector operation.
8591 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8592 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8593 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +00008594 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +00008595 unsigned ExtractedIdx =
8596 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +00008597 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00008598
8599 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8600 return ReplaceInstUsesWith(IE, VecOp);
8601
8602 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008603 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +00008604
8605 // If we are extracting a value from a vector, then inserting it right
8606 // back into the same place, just use the input vector.
8607 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8608 return ReplaceInstUsesWith(IE, VecOp);
8609
Chris Lattnerefb47352006-04-15 01:39:45 +00008610 // If this insertelement isn't used by some other insertelement, turn it
8611 // (and any insertelements it points to), into one big shuffle.
8612 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8613 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008614 Value *RHS = 0;
Chris Lattner4de84762010-01-04 07:02:48 +00008615 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008616 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008617 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +00008618 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +00008619 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00008620 }
8621 }
8622 }
8623
Eli Friedmanb9a4cac2009-06-06 20:08:03 +00008624 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
8625 APInt UndefElts(VWidth, 0);
8626 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
8627 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
8628 return &IE;
8629
Chris Lattnerefb47352006-04-15 01:39:45 +00008630 return 0;
8631}
8632
8633
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008634Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8635 Value *LHS = SVI.getOperand(0);
8636 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00008637 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008638
8639 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00008640
Chris Lattner867b99f2006-10-05 06:55:50 +00008641 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +00008642 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008643 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +00008644
Dan Gohman488fbfc2008-09-09 18:11:14 +00008645 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00008646
8647 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
8648 return 0;
8649
Evan Cheng388df622009-02-03 10:05:09 +00008650 APInt UndefElts(VWidth, 0);
8651 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
8652 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +00008653 LHS = SVI.getOperand(0);
8654 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00008655 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +00008656 }
Chris Lattnerefb47352006-04-15 01:39:45 +00008657
Chris Lattner863bcff2006-05-25 23:48:38 +00008658 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8659 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8660 if (LHS == RHS || isa<UndefValue>(LHS)) {
8661 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008662 // shuffle(undef,undef,mask) -> undef.
8663 return ReplaceInstUsesWith(SVI, LHS);
8664 }
8665
Chris Lattner863bcff2006-05-25 23:48:38 +00008666 // Remap any references to RHS to use LHS.
8667 std::vector<Constant*> Elts;
8668 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00008669 if (Mask[i] >= 2*e)
Chris Lattner4de84762010-01-04 07:02:48 +00008670 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008671 else {
8672 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +00008673 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00008674 Mask[i] = 2*e; // Turn into undef.
Chris Lattner4de84762010-01-04 07:02:48 +00008675 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Dan Gohman4ce96272008-08-06 18:17:32 +00008676 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +00008677 Mask[i] = Mask[i] % e; // Force to LHS.
Chris Lattner4de84762010-01-04 07:02:48 +00008678 Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
8679 Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +00008680 }
Chris Lattner7b2e27922006-05-26 00:29:06 +00008681 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008682 }
Chris Lattner863bcff2006-05-25 23:48:38 +00008683 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008684 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +00008685 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008686 LHS = SVI.getOperand(0);
8687 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008688 MadeChange = true;
8689 }
8690
Chris Lattner7b2e27922006-05-26 00:29:06 +00008691 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00008692 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00008693
Chris Lattner863bcff2006-05-25 23:48:38 +00008694 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8695 if (Mask[i] >= e*2) continue; // Ignore undef values.
8696 // Is this an identity shuffle of the LHS value?
8697 isLHSID &= (Mask[i] == i);
8698
8699 // Is this an identity shuffle of the RHS value?
8700 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00008701 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008702
Chris Lattner863bcff2006-05-25 23:48:38 +00008703 // Eliminate identity shuffles.
8704 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8705 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008706
Chris Lattner7b2e27922006-05-26 00:29:06 +00008707 // If the LHS is a shufflevector itself, see if we can combine it with this
8708 // one without producing an unusual shuffle. Here we are really conservative:
8709 // we are absolutely afraid of producing a shuffle mask not in the input
8710 // program, because the code gen may not be smart enough to turn a merged
8711 // shuffle into two specific shuffles: it may produce worse code. As such,
8712 // we only merge two shuffles if the result is one of the two input shuffle
8713 // masks. In this case, merging the shuffles just removes one instruction,
8714 // which we know is safe. This is good for things like turning:
8715 // (splat(splat)) -> splat.
8716 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8717 if (isa<UndefValue>(RHS)) {
8718 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8719
David Greenef941d292009-11-16 21:52:23 +00008720 if (LHSMask.size() == Mask.size()) {
8721 std::vector<unsigned> NewMask;
8722 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sands76700ba2009-11-20 13:19:51 +00008723 if (Mask[i] >= e)
David Greenef941d292009-11-16 21:52:23 +00008724 NewMask.push_back(2*e);
8725 else
8726 NewMask.push_back(LHSMask[Mask[i]]);
Chris Lattner7b2e27922006-05-26 00:29:06 +00008727
David Greenef941d292009-11-16 21:52:23 +00008728 // If the result mask is equal to the src shuffle or this
8729 // shuffle mask, do the replacement.
8730 if (NewMask == LHSMask || NewMask == Mask) {
8731 unsigned LHSInNElts =
8732 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
8733 getNumElements();
8734 std::vector<Constant*> Elts;
8735 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8736 if (NewMask[i] >= LHSInNElts*2) {
Chris Lattner4de84762010-01-04 07:02:48 +00008737 Elts.push_back(UndefValue::get(
8738 Type::getInt32Ty(SVI.getContext())));
David Greenef941d292009-11-16 21:52:23 +00008739 } else {
Chris Lattner4de84762010-01-04 07:02:48 +00008740 Elts.push_back(ConstantInt::get(
8741 Type::getInt32Ty(SVI.getContext()),
David Greenef941d292009-11-16 21:52:23 +00008742 NewMask[i]));
8743 }
Chris Lattner7b2e27922006-05-26 00:29:06 +00008744 }
David Greenef941d292009-11-16 21:52:23 +00008745 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8746 LHSSVI->getOperand(1),
8747 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008748 }
Chris Lattner7b2e27922006-05-26 00:29:06 +00008749 }
8750 }
8751 }
Chris Lattnerc5eff442007-01-30 22:32:46 +00008752
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008753 return MadeChange ? &SVI : 0;
8754}
8755
8756
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008757
Chris Lattnerea1c4542004-12-08 23:43:58 +00008758
8759/// TryToSinkInstruction - Try to move the specified instruction from its
8760/// current block into the beginning of DestBlock, which can only happen if it's
8761/// safe to move the instruction past all of the instructions between it and the
8762/// end of its block.
8763static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8764 assert(I->hasOneUse() && "Invariants didn't hold!");
8765
Chris Lattner108e9022005-10-27 17:13:11 +00008766 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00008767 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00008768 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00008769
Chris Lattnerea1c4542004-12-08 23:43:58 +00008770 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00008771 if (isa<AllocaInst>(I) && I->getParent() ==
8772 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00008773 return false;
8774
Chris Lattner96a52a62004-12-09 07:14:34 +00008775 // We can only sink load instructions if there is nothing between the load and
8776 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00008777 if (I->mayReadFromMemory()) {
8778 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00008779 Scan != E; ++Scan)
8780 if (Scan->mayWriteToMemory())
8781 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00008782 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00008783
Dan Gohman02dea8b2008-05-23 21:05:58 +00008784 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00008785
Dale Johannesenbd8e6502009-03-03 01:09:07 +00008786 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +00008787 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00008788 ++NumSunkInst;
8789 return true;
8790}
8791
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008792
8793/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8794/// all reachable code to the worklist.
8795///
8796/// This has a couple of tricks to make the code faster and more powerful. In
8797/// particular, we constant fold and DCE instructions as we go, to avoid adding
8798/// them to the worklist (this significantly speeds up instcombine on code where
8799/// many instructions are dead or constant). Additionally, if we find a branch
8800/// whose condition is a known constant, we only visit the reachable successors.
8801///
Chris Lattner2ee743b2009-10-15 04:59:28 +00008802static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00008803 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00008804 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008805 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00008806 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00008807 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00008808 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +00008809
8810 std::vector<Instruction*> InstrsForInstCombineWorklist;
8811 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008812
Chris Lattner2ee743b2009-10-15 04:59:28 +00008813 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
8814
Chris Lattner2c7718a2007-03-23 19:17:18 +00008815 while (!Worklist.empty()) {
8816 BB = Worklist.back();
8817 Worklist.pop_back();
8818
8819 // We have now visited this block! If we've already been here, ignore it.
8820 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00008821
Chris Lattner2c7718a2007-03-23 19:17:18 +00008822 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8823 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008824
Chris Lattner2c7718a2007-03-23 19:17:18 +00008825 // DCE instruction if trivially dead.
8826 if (isInstructionTriviallyDead(Inst)) {
8827 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00008828 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00008829 Inst->eraseFromParent();
8830 continue;
8831 }
8832
8833 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00008834 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00008835 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00008836 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
8837 << *Inst << '\n');
8838 Inst->replaceAllUsesWith(C);
8839 ++NumConstProp;
8840 Inst->eraseFromParent();
8841 continue;
8842 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00008843
8844
8845
8846 if (TD) {
8847 // See if we can constant fold its operands.
8848 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
8849 i != e; ++i) {
8850 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
8851 if (CE == 0) continue;
8852
8853 // If we already folded this constant, don't try again.
8854 if (!FoldedConstants.insert(CE))
8855 continue;
8856
Chris Lattner7b550cc2009-11-06 04:27:31 +00008857 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00008858 if (NewC && NewC != CE) {
8859 *i = NewC;
8860 MadeIRChange = true;
8861 }
8862 }
8863 }
8864
Devang Patel7fe1dec2008-11-19 18:56:50 +00008865
Chris Lattner67f7d542009-10-12 03:58:40 +00008866 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008867 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00008868
8869 // Recursively visit successors. If this is a branch or switch on a
8870 // constant, only visit the reachable successor.
8871 TerminatorInst *TI = BB->getTerminator();
8872 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8873 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
8874 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00008875 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00008876 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00008877 continue;
8878 }
8879 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8880 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8881 // See if this is an explicit destination.
8882 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8883 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00008884 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00008885 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00008886 continue;
8887 }
8888
8889 // Otherwise it is the default destination.
8890 Worklist.push_back(SI->getSuccessor(0));
8891 continue;
8892 }
8893 }
8894
8895 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
8896 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008897 }
Chris Lattner67f7d542009-10-12 03:58:40 +00008898
8899 // Once we've found all of the instructions to add to instcombine's worklist,
8900 // add them in reverse order. This way instcombine will visit from the top
8901 // of the function down. This jives well with the way that it adds all uses
8902 // of instructions to the worklist after doing a transformation, thus avoiding
8903 // some N^2 behavior in pathological cases.
8904 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
8905 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00008906
8907 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008908}
8909
Chris Lattnerec9c3582007-03-03 02:04:50 +00008910bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00008911 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00008912
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00008913 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
8914 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00008915
Chris Lattnerb3d59702005-07-07 20:40:38 +00008916 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008917 // Do a depth-first traversal of the function, populate the worklist with
8918 // the reachable instructions. Ignore blocks that are not reachable. Keep
8919 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00008920 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00008921 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00008922
Chris Lattnerb3d59702005-07-07 20:40:38 +00008923 // Do a quick scan over the function. If we find any blocks that are
8924 // unreachable, remove any instructions inside of them. This prevents
8925 // the instcombine code from having to deal with some bad special cases.
8926 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8927 if (!Visited.count(BB)) {
8928 Instruction *Term = BB->getTerminator();
8929 while (Term != BB->begin()) { // Remove instrs bottom-up
8930 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00008931
Chris Lattnerbdff5482009-08-23 04:37:46 +00008932 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00008933 // A debug intrinsic shouldn't force another iteration if we weren't
8934 // going to do one without it.
8935 if (!isa<DbgInfoIntrinsic>(I)) {
8936 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00008937 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00008938 }
Devang Patel228ebd02009-10-13 22:56:32 +00008939
Devang Patel228ebd02009-10-13 22:56:32 +00008940 // If I is not void type then replaceAllUsesWith undef.
8941 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00008942 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00008943 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00008944 I->eraseFromParent();
8945 }
8946 }
8947 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00008948
Chris Lattner873ff012009-08-30 05:55:36 +00008949 while (!Worklist.isEmpty()) {
8950 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008951 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00008952
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008953 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00008954 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008955 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00008956 EraseInstFromFunction(*I);
8957 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00008958 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00008959 continue;
8960 }
Chris Lattner62b14df2002-09-02 04:59:56 +00008961
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008962 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00008963 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00008964 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00008965 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00008966
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00008967 // Add operands to the worklist.
8968 ReplaceInstUsesWith(*I, C);
8969 ++NumConstProp;
8970 EraseInstFromFunction(*I);
8971 MadeIRChange = true;
8972 continue;
8973 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00008974
Chris Lattnerea1c4542004-12-08 23:43:58 +00008975 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00008976 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00008977 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00008978 Instruction *UserInst = cast<Instruction>(I->use_back());
8979 BasicBlock *UserParent;
8980
8981 // Get the block the use occurs in.
8982 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
8983 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
8984 else
8985 UserParent = UserInst->getParent();
8986
Chris Lattnerea1c4542004-12-08 23:43:58 +00008987 if (UserParent != BB) {
8988 bool UserIsSuccessor = false;
8989 // See if the user is one of our successors.
8990 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8991 if (*SI == UserParent) {
8992 UserIsSuccessor = true;
8993 break;
8994 }
8995
8996 // If the user is one of our immediate successors, and if that successor
8997 // only has us as a predecessors (we'd have to split the critical edge
8998 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00008999 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00009000 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00009001 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00009002 }
9003 }
9004
Chris Lattner74381062009-08-30 07:44:24 +00009005 // Now that we have an instruction, try combining it to simplify it.
9006 Builder->SetInsertPoint(I->getParent(), I);
9007
Reid Spencera9b81012007-03-26 17:44:01 +00009008#ifndef NDEBUG
9009 std::string OrigI;
9010#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00009011 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00009012 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
9013
Chris Lattner90ac28c2002-08-02 19:29:35 +00009014 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00009015 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009016 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00009017 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00009018 DEBUG(errs() << "IC: Old = " << *I << '\n'
9019 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00009020
Chris Lattnerf523d062004-06-09 05:08:07 +00009021 // Everything uses the new instruction now.
9022 I->replaceAllUsesWith(Result);
9023
9024 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00009025 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00009026 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009027
Chris Lattner6934a042007-02-11 01:23:03 +00009028 // Move the name to the new instruction first.
9029 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009030
9031 // Insert the new instruction into the basic block...
9032 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00009033 BasicBlock::iterator InsertPos = I;
9034
9035 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9036 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9037 ++InsertPos;
9038
9039 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00009040
Chris Lattner7a1e9242009-08-30 06:13:40 +00009041 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00009042 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00009043#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00009044 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
9045 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00009046#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00009047
Chris Lattner90ac28c2002-08-02 19:29:35 +00009048 // If the instruction was modified, it's possible that it is now dead.
9049 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00009050 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00009051 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00009052 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00009053 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00009054 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00009055 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00009056 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00009057 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009058 }
9059 }
9060
Chris Lattner873ff012009-08-30 05:55:36 +00009061 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00009062 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00009063}
9064
Chris Lattnerec9c3582007-03-03 02:04:50 +00009065
9066bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00009067 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00009068 TD = getAnalysisIfAvailable<TargetData>();
9069
Chris Lattner74381062009-08-30 07:44:24 +00009070
9071 /// Builder - This is an IRBuilder that automatically inserts new
9072 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00009073 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00009074 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00009075 InstCombineIRInserter(Worklist));
9076 Builder = &TheBuilder;
9077
Chris Lattnerec9c3582007-03-03 02:04:50 +00009078 bool EverMadeChange = false;
9079
9080 // Iterate while there is work to do.
9081 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00009082 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00009083 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00009084
9085 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00009086 return EverMadeChange;
9087}
9088
Brian Gaeke96d4bf72004-07-27 17:43:21 +00009089FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009090 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00009091}