blob: 82cc9ebac184dca4d7c119248a96f8727c84e7ac [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"
Nick Lewycky5be29202008-02-03 16:33:09 +000051#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000052#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000053#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000054#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000055#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056#include "llvm/Support/PatternMatch.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000060#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000061#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000062using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000063using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000070
Chris Lattnerdd841ae2002-04-18 17:39:14 +000071
Dan Gohman844731a2008-05-13 00:00:25 +000072char InstCombiner::ID = 0;
73static RegisterPass<InstCombiner>
74X("instcombine", "Combine redundant instructions");
75
Chris Lattnere0b4b722010-01-04 07:17:19 +000076void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.addPreservedID(LCSSAID);
78 AU.setPreservesCFG();
79}
80
81
Chris Lattner4f98c562003-03-10 21:43:22 +000082// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +000083// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +000084static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +000085 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +000086 if (BinaryOperator::isNeg(V) ||
87 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +000088 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +000089 return 3;
90 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +000091 }
Chris Lattnere87597f2004-10-16 18:11:37 +000092 if (isa<Argument>(V)) return 3;
93 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +000094}
Chris Lattnerdd841ae2002-04-18 17:39:14 +000095
Chris Lattnerc8802d22003-03-11 00:12:48 +000096// isOnlyUse - Return true if this instruction will be deleted if we stop using
97// it.
98static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +000099 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000100}
101
Chris Lattner4cb170c2004-02-23 06:38:22 +0000102// getPromotedType - Return the specified type promoted as it would be to pass
103// though a va_arg area...
104static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000105 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
106 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000107 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000108 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000109 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000110}
111
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000112/// ShouldChangeType - Return true if it is desirable to convert a computation
113/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
114/// type for example, or from a smaller to a larger illegal type.
115static bool ShouldChangeType(const Type *From, const Type *To,
116 const TargetData *TD) {
117 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
118
119 // If we don't have TD, we don't know if the source/dest are legal.
120 if (!TD) return false;
121
122 unsigned FromWidth = From->getPrimitiveSizeInBits();
123 unsigned ToWidth = To->getPrimitiveSizeInBits();
124 bool FromLegal = TD->isLegalInteger(FromWidth);
125 bool ToLegal = TD->isLegalInteger(ToWidth);
126
127 // If this is a legal integer from type, and the result would be an illegal
128 // type, don't do the transformation.
129 if (FromLegal && !ToLegal)
130 return false;
131
132 // Otherwise, if both are illegal, do not increase the size of the result. We
133 // do allow things like i160 -> i64, but not i64 -> i160.
134 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
135 return false;
136
137 return true;
138}
139
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000140/// getBitCastOperand - If the specified operand is a CastInst, a constant
141/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
142/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000143static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000144 if (Operator *O = dyn_cast<Operator>(V)) {
145 if (O->getOpcode() == Instruction::BitCast)
146 return O->getOperand(0);
147 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
148 if (GEP->hasAllZeroIndices())
149 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000150 }
Chris Lattnereed48272005-09-13 00:40:14 +0000151 return 0;
152}
153
Reid Spencer3da59db2006-11-27 01:05:10 +0000154/// This function is a wrapper around CastInst::isEliminableCastPair. It
155/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000156static Instruction::CastOps
157isEliminableCastPair(
158 const CastInst *CI, ///< The first cast instruction
159 unsigned opcode, ///< The opcode of the second cast instruction
160 const Type *DstTy, ///< The target type for the second cast instruction
161 TargetData *TD ///< The target data for pointer size
162) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000163
Reid Spencer3da59db2006-11-27 01:05:10 +0000164 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
165 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000166
Reid Spencer3da59db2006-11-27 01:05:10 +0000167 // Get the opcodes of the two Cast instructions
168 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
169 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000170
Chris Lattnera0e69692009-03-24 18:35:40 +0000171 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000172 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000173 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000174
175 // We don't want to form an inttoptr or ptrtoint that converts to an integer
176 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000177 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000178 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000179 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000180 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000181 Res = 0;
182
183 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000184}
185
186/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
187/// in any code being generated. It does not require codegen if V is simple
188/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000189static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
190 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000191 if (V->getType() == Ty || isa<Constant>(V)) return false;
192
Chris Lattner01575b72006-05-25 23:24:33 +0000193 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000194 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000195 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000196 return false;
197 return true;
198}
199
Chris Lattner4f98c562003-03-10 21:43:22 +0000200// SimplifyCommutative - This performs a few simplifications for commutative
201// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000202//
Chris Lattner4f98c562003-03-10 21:43:22 +0000203// 1. Order operands such that they are listed from right (least complex) to
204// left (most complex). This puts constants before unary operators before
205// binary operators.
206//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000207// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
208// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000209//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000210bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000211 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000212 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000213 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000214
Chris Lattner4f98c562003-03-10 21:43:22 +0000215 if (!I.isAssociative()) return Changed;
216 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000217 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
218 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
219 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000220 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000221 cast<Constant>(I.getOperand(1)),
222 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000223 I.setOperand(0, Op->getOperand(0));
224 I.setOperand(1, Folded);
225 return true;
226 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
227 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
228 isOnlyUse(Op) && isOnlyUse(Op1)) {
229 Constant *C1 = cast<Constant>(Op->getOperand(1));
230 Constant *C2 = cast<Constant>(Op1->getOperand(1));
231
232 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000233 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000234 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000235 Op1->getOperand(0),
236 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000237 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000238 I.setOperand(0, New);
239 I.setOperand(1, Folded);
240 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000241 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000242 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000243 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000244}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000245
Chris Lattner8d969642003-03-10 23:06:50 +0000246// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
247// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000248//
Dan Gohman186a6362009-08-12 16:04:34 +0000249static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000250 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000251 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000252
Chris Lattner0ce85802004-12-14 20:08:06 +0000253 // Constants can be considered to be negated values if they can be folded.
254 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000255 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000256
257 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
258 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000259 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000260
Chris Lattner8d969642003-03-10 23:06:50 +0000261 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000262}
263
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000264// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
265// instruction if the LHS is a constant negative zero (which is the 'negate'
266// form).
267//
Dan Gohman186a6362009-08-12 16:04:34 +0000268static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000269 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000270 return BinaryOperator::getFNegArgument(V);
271
272 // Constants can be considered to be negated values if they can be folded.
273 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000274 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000275
276 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
277 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000278 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000279
280 return 0;
281}
282
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000283/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
284/// returning the kind and providing the out parameter results if we
285/// successfully match.
286static SelectPatternFlavor
287MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
288 SelectInst *SI = dyn_cast<SelectInst>(V);
289 if (SI == 0) return SPF_UNKNOWN;
290
291 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
292 if (ICI == 0) return SPF_UNKNOWN;
293
294 LHS = ICI->getOperand(0);
295 RHS = ICI->getOperand(1);
296
297 // (icmp X, Y) ? X : Y
298 if (SI->getTrueValue() == ICI->getOperand(0) &&
299 SI->getFalseValue() == ICI->getOperand(1)) {
300 switch (ICI->getPredicate()) {
301 default: return SPF_UNKNOWN; // Equality.
302 case ICmpInst::ICMP_UGT:
303 case ICmpInst::ICMP_UGE: return SPF_UMAX;
304 case ICmpInst::ICMP_SGT:
305 case ICmpInst::ICMP_SGE: return SPF_SMAX;
306 case ICmpInst::ICMP_ULT:
307 case ICmpInst::ICMP_ULE: return SPF_UMIN;
308 case ICmpInst::ICMP_SLT:
309 case ICmpInst::ICMP_SLE: return SPF_SMIN;
310 }
311 }
312
313 // (icmp X, Y) ? Y : X
314 if (SI->getTrueValue() == ICI->getOperand(1) &&
315 SI->getFalseValue() == ICI->getOperand(0)) {
316 switch (ICI->getPredicate()) {
317 default: return SPF_UNKNOWN; // Equality.
318 case ICmpInst::ICMP_UGT:
319 case ICmpInst::ICMP_UGE: return SPF_UMIN;
320 case ICmpInst::ICMP_SGT:
321 case ICmpInst::ICMP_SGE: return SPF_SMIN;
322 case ICmpInst::ICMP_ULT:
323 case ICmpInst::ICMP_ULE: return SPF_UMAX;
324 case ICmpInst::ICMP_SLT:
325 case ICmpInst::ICMP_SLE: return SPF_SMAX;
326 }
327 }
328
329 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
330
331 return SPF_UNKNOWN;
332}
333
Chris Lattner48b59ec2009-10-26 15:40:07 +0000334/// isFreeToInvert - Return true if the specified value is free to invert (apply
335/// ~ to). This happens in cases where the ~ can be eliminated.
336static inline bool isFreeToInvert(Value *V) {
337 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000338 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000339 return true;
340
341 // Constants can be considered to be not'ed values.
342 if (isa<ConstantInt>(V))
343 return true;
344
345 // Compares can be inverted if they have a single use.
346 if (CmpInst *CI = dyn_cast<CmpInst>(V))
347 return CI->hasOneUse();
348
349 return false;
350}
351
352static inline Value *dyn_castNotVal(Value *V) {
353 // If this is not(not(x)) don't return that this is a not: we want the two
354 // not's to be folded first.
355 if (BinaryOperator::isNot(V)) {
356 Value *Operand = BinaryOperator::getNotArgument(V);
357 if (!isFreeToInvert(Operand))
358 return Operand;
359 }
Chris Lattner8d969642003-03-10 23:06:50 +0000360
361 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000362 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000363 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000364 return 0;
365}
366
Chris Lattner48b59ec2009-10-26 15:40:07 +0000367
368
Chris Lattnerc8802d22003-03-11 00:12:48 +0000369// dyn_castFoldableMul - If this value is a multiply that can be folded into
370// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000371// non-constant operand of the multiply, and set CST to point to the multiplier.
372// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000373//
Dan Gohman186a6362009-08-12 16:04:34 +0000374static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000375 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000376 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000377 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000378 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000379 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000380 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000381 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000382 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000383 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000384 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000385 CST = ConstantInt::get(V->getType()->getContext(),
386 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000387 return I->getOperand(0);
388 }
389 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000390 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000391}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000392
Reid Spencer7177c3a2007-03-25 05:33:51 +0000393/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000394static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000395 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000396 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000397}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000398/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000399static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000400 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000401 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000402}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000403/// MultiplyOverflows - True if the multiply can not be expressed in an int
404/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000405static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000406 uint32_t W = C1->getBitWidth();
407 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
408 if (sign) {
409 LHSExt.sext(W * 2);
410 RHSExt.sext(W * 2);
411 } else {
412 LHSExt.zext(W * 2);
413 RHSExt.zext(W * 2);
414 }
415
416 APInt MulExt = LHSExt * RHSExt;
417
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000418 if (!sign)
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000419 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000420
421 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
422 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
423 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000424}
Chris Lattner955f3312004-09-28 21:48:02 +0000425
Reid Spencere7816b52007-03-08 01:52:58 +0000426
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000427// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
428// set of known zero and one bits, compute the maximum and minimum values that
429// could have the specified known zero and known one bits, returning them in
430// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000431static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000432 const APInt& KnownOne,
433 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000434 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
435 KnownZero.getBitWidth() == Min.getBitWidth() &&
436 KnownZero.getBitWidth() == Max.getBitWidth() &&
437 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000438 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000439
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000440 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
441 // bit if it is unknown.
442 Min = KnownOne;
443 Max = KnownOne|UnknownBits;
444
Dan Gohman1c8491e2009-04-25 17:12:48 +0000445 if (UnknownBits.isNegative()) { // Sign bit is unknown
446 Min.set(Min.getBitWidth()-1);
447 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000448 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000449}
450
451// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
452// a set of known zero and one bits, compute the maximum and minimum values that
453// could have the specified known zero and known one bits, returning them in
454// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000455static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000456 const APInt &KnownOne,
457 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000458 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
459 KnownZero.getBitWidth() == Min.getBitWidth() &&
460 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000461 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000462 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000463
464 // The minimum value is when the unknown bits are all zeros.
465 Min = KnownOne;
466 // The maximum value is when the unknown bits are all ones.
467 Max = KnownOne|UnknownBits;
468}
Chris Lattner255d8912006-02-11 09:31:47 +0000469
Dan Gohman45b4e482008-05-19 22:14:15 +0000470
Chris Lattner564a7272003-08-13 19:01:45 +0000471/// AssociativeOpt - Perform an optimization on an associative operator. This
472/// function is designed to check a chain of associative operators for a
473/// potential to apply a certain optimization. Since the optimization may be
474/// applicable if the expression was reassociated, this checks the chain, then
475/// reassociates the expression as necessary to expose the optimization
476/// opportunity. This makes use of a special Functor, which must define
477/// 'shouldApply' and 'apply' methods.
478///
479template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +0000480static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +0000481 unsigned Opcode = Root.getOpcode();
482 Value *LHS = Root.getOperand(0);
483
484 // Quick check, see if the immediate LHS matches...
485 if (F.shouldApply(LHS))
486 return F.apply(Root);
487
488 // Otherwise, if the LHS is not of the same opcode as the root, return.
489 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000490 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000491 // Should we apply this transform to the RHS?
492 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
493
494 // If not to the RHS, check to see if we should apply to the LHS...
495 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
496 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
497 ShouldApply = true;
498 }
499
500 // If the functor wants to apply the optimization to the RHS of LHSI,
501 // reassociate the expression from ((? op A) op B) to (? op (A op B))
502 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +0000503 // Now all of the instructions are in the current basic block, go ahead
504 // and perform the reassociation.
505 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
506
507 // First move the selected RHS to the LHS of the root...
508 Root.setOperand(0, LHSI->getOperand(1));
509
510 // Make what used to be the LHS of the root be the user of the root...
511 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000512 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000513 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000514 return 0;
515 }
Chris Lattner65725312004-04-16 18:08:07 +0000516 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000517 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000518 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +0000519 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +0000520 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000521
522 // Now propagate the ExtraOperand down the chain of instructions until we
523 // get to LHSI.
524 while (TmpLHSI != LHSI) {
525 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000526 // Move the instruction to immediately before the chain we are
527 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +0000528 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +0000529 ARI = NextLHSI;
530
Chris Lattner564a7272003-08-13 19:01:45 +0000531 Value *NextOp = NextLHSI->getOperand(1);
532 NextLHSI->setOperand(1, ExtraOperand);
533 TmpLHSI = NextLHSI;
534 ExtraOperand = NextOp;
535 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000536
Chris Lattner564a7272003-08-13 19:01:45 +0000537 // Now that the instructions are reassociated, have the functor perform
538 // the transformation...
539 return F.apply(Root);
540 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000541
Chris Lattner564a7272003-08-13 19:01:45 +0000542 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
543 }
544 return 0;
545}
546
Dan Gohman844731a2008-05-13 00:00:25 +0000547namespace {
Chris Lattner564a7272003-08-13 19:01:45 +0000548
Nick Lewycky02d639f2008-05-23 04:34:58 +0000549// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +0000550struct AddRHS {
551 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +0000552 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +0000553 bool shouldApply(Value *LHS) const { return LHS == RHS; }
554 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +0000555 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +0000556 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +0000557 }
558};
559
560// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
561// iff C1&C2 == 0
562struct AddMaskingAnd {
563 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +0000564 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +0000565 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000566 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +0000567 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000568 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000569 }
570 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000571 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000572 }
573};
574
Dan Gohman844731a2008-05-13 00:00:25 +0000575}
576
Chris Lattner6e7ba452005-01-01 16:22:27 +0000577static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000578 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000579 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000580 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000581
Chris Lattner2eefe512004-04-09 19:05:30 +0000582 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000583 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
584 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000585
Chris Lattner2eefe512004-04-09 19:05:30 +0000586 if (Constant *SOC = dyn_cast<Constant>(SO)) {
587 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000588 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
589 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000590 }
591
592 Value *Op0 = SO, *Op1 = ConstOperand;
593 if (!ConstIsRHS)
594 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000595
Chris Lattner6e7ba452005-01-01 16:22:27 +0000596 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000597 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
598 SO->getName()+".op");
599 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
600 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
601 SO->getName()+".cmp");
602 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
603 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
604 SO->getName()+".cmp");
605 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000606}
607
608// FoldOpIntoSelect - Given an instruction with a select as one operand and a
609// constant as the other operand, try to fold the binary operator into the
610// select arguments. This also works for Cast instructions, which obviously do
611// not have a second operand.
612static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
613 InstCombiner *IC) {
614 // Don't modify shared select instructions
615 if (!SI->hasOneUse()) return 0;
616 Value *TV = SI->getOperand(1);
617 Value *FV = SI->getOperand(2);
618
619 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000620 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +0000621 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000622
Chris Lattner6e7ba452005-01-01 16:22:27 +0000623 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
624 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
625
Gabor Greif051a9502008-04-06 20:25:17 +0000626 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
627 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000628 }
629 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000630}
631
Chris Lattner4e998b22004-09-29 05:07:12 +0000632
Chris Lattner5d1704d2009-09-27 19:57:57 +0000633/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
634/// has a PHI node as operand #0, see if we can fold the instruction into the
635/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000636///
637/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
638/// that would normally be unprofitable because they strongly encourage jump
639/// threading.
640Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
641 bool AllowAggressive) {
642 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000643 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000644 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000645 if (NumPHIValues == 0 ||
646 // We normally only transform phis with a single use, unless we're trying
647 // hard to make jump threading happen.
648 (!PN->hasOneUse() && !AllowAggressive))
649 return 0;
650
651
Chris Lattner5d1704d2009-09-27 19:57:57 +0000652 // Check to see if all of the operands of the PHI are simple constants
653 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000654 // remember the BB it is in. If there is more than one or if *it* is a PHI,
655 // bail out. We don't do arbitrary constant expressions here because moving
656 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000657 BasicBlock *NonConstBB = 0;
658 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000659 if (!isa<Constant>(PN->getIncomingValue(i)) ||
660 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000661 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000662 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000663 NonConstBB = PN->getIncomingBlock(i);
664
665 // If the incoming non-constant value is in I's block, we have an infinite
666 // loop.
667 if (NonConstBB == I.getParent())
668 return 0;
669 }
670
671 // If there is exactly one non-constant value, we can insert a copy of the
672 // operation in that block. However, if this is a critical edge, we would be
673 // inserting the computation one some other paths (e.g. inside a loop). Only
674 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000675 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000676 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
677 if (!BI || !BI->isUnconditional()) return 0;
678 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000679
680 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000681 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000682 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000683 InsertNewInstBefore(NewPN, *PN);
684 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000685
686 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000687 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
688 // We only currently try to fold the condition of a select when it is a phi,
689 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000690 Value *TrueV = SI->getTrueValue();
691 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000692 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000693 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000694 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000695 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
696 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000697 Value *InV = 0;
698 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000699 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000700 } else {
701 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000702 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
703 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000704 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000705 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000706 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000707 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000708 }
709 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000710 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000711 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000712 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000713 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000714 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000715 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000716 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000717 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000718 } else {
719 assert(PN->getIncomingBlock(i) == NonConstBB);
720 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000721 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000722 PN->getIncomingValue(i), C, "phitmp",
723 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000724 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000725 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000726 CI->getPredicate(),
727 PN->getIncomingValue(i), C, "phitmp",
728 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000729 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000730 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000731
732 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000733 }
734 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000735 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000736 } else {
737 CastInst *CI = cast<CastInst>(&I);
738 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000739 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000740 Value *InV;
741 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000742 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000743 } else {
744 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000745 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000746 I.getType(), "phitmp",
747 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000748 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000749 }
750 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000751 }
752 }
753 return ReplaceInstUsesWith(I, NewPN);
754}
755
Chris Lattner2454a2e2008-01-29 06:52:45 +0000756
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000757/// WillNotOverflowSignedAdd - Return true if we can prove that:
758/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
759/// This basically requires proving that the add in the original type would not
760/// overflow to change the sign bit or have a carry out.
761bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
762 // There are different heuristics we can use for this. Here are some simple
763 // ones.
764
765 // Add has the property that adding any two 2's complement numbers can only
766 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000767 // have at least two sign bits, we know that the addition of the two values
768 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000769 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
770 return true;
771
772
773 // If one of the operands only has one non-zero bit, and if the other operand
774 // has a known-zero bit in a more significant place than it (not including the
775 // sign bit) the ripple may go up to and fill the zero, but won't change the
776 // sign. For example, (X & ~4) + 1.
777
778 // TODO: Implement.
779
780 return false;
781}
782
Chris Lattner2454a2e2008-01-29 06:52:45 +0000783
Chris Lattner7e708292002-06-25 16:13:24 +0000784Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000785 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000786 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000787
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000788 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
789 I.hasNoUnsignedWrap(), TD))
790 return ReplaceInstUsesWith(I, V);
791
792
Chris Lattner66331a42004-04-10 22:01:55 +0000793 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +0000794 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000795 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000796 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +0000797 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +0000798 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000799 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000800
801 // See if SimplifyDemandedBits can simplify this. This handles stuff like
802 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +0000803 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000804 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +0000805
Eli Friedman709b33d2009-07-13 22:27:52 +0000806 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +0000807 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Chris Lattner4de84762010-01-04 07:02:48 +0000808 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +0000809 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +0000810 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000811
812 if (isa<PHINode>(LHS))
813 if (Instruction *NV = FoldOpIntoPhi(I))
814 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +0000815
Chris Lattner4f637d42006-01-06 17:59:59 +0000816 ConstantInt *XorRHS = 0;
817 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +0000818 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000819 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000820 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000821 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +0000822
Zhou Sheng4351c642007-04-02 08:20:41 +0000823 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000824 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
825 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +0000826 do {
827 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +0000828 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
829 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000830 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
831 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +0000832 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +0000833 if (!MaskedValueIsZero(XorLHS,
834 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +0000835 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000836 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000837 }
838 }
839 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000840 C0080Val = APIntOps::lshr(C0080Val, Size);
841 CFF80Val = APIntOps::ashr(CFF80Val, Size);
842 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +0000843
Reid Spencer35c38852007-03-28 01:36:16 +0000844 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000845 // with funny bit widths then this switch statement should be removed. It
846 // is just here to get the size of the "middle" type back up to something
847 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +0000848 const Type *MiddleType = 0;
849 switch (Size) {
850 default: break;
Chris Lattner4de84762010-01-04 07:02:48 +0000851 case 32:
852 case 16:
853 case 8: MiddleType = IntegerType::get(I.getContext(), Size); break;
Reid Spencer35c38852007-03-28 01:36:16 +0000854 }
855 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +0000856 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +0000857 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +0000858 }
859 }
Chris Lattner66331a42004-04-10 22:01:55 +0000860 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000861
Chris Lattner4de84762010-01-04 07:02:48 +0000862 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000863 return BinaryOperator::CreateXor(LHS, RHS);
864
Nick Lewycky7d26bd82008-05-23 04:39:38 +0000865 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000866 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +0000867 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +0000868 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +0000869
870 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
871 if (RHSI->getOpcode() == Instruction::Sub)
872 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
873 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
874 }
875 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
876 if (LHSI->getOpcode() == Instruction::Sub)
877 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
878 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
879 }
Robert Bocchino71698282004-07-27 21:02:21 +0000880 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000881
Chris Lattner5c4afb92002-05-08 22:46:53 +0000882 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +0000883 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000884 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +0000885 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +0000886 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +0000887 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +0000888 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +0000889 }
Chris Lattnerdd12f962008-02-17 21:03:36 +0000890 }
891
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000892 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +0000893 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000894
895 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000896 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000897 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000898 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000899
Misha Brukmanfd939082005-04-21 23:48:37 +0000900
Chris Lattner50af16a2004-11-13 19:50:12 +0000901 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +0000902 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000903 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000904 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000905
906 // X*C1 + X*C2 --> X * (C1+C2)
907 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +0000908 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000909 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000910 }
911
912 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000913 if (dyn_castFoldableMul(RHS, C2) == LHS)
914 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000915
Chris Lattnere617c9e2007-01-05 02:17:46 +0000916 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +0000917 if (dyn_castNotVal(LHS) == RHS ||
918 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +0000919 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +0000920
Chris Lattnerad3448c2003-02-18 19:57:07 +0000921
Chris Lattner564a7272003-08-13 19:01:45 +0000922 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +0000923 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
924 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +0000925 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +0000926
927 // A+B --> A|B iff A and B have no bits set in common.
928 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
929 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
930 APInt LHSKnownOne(IT->getBitWidth(), 0);
931 APInt LHSKnownZero(IT->getBitWidth(), 0);
932 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
933 if (LHSKnownZero != 0) {
934 APInt RHSKnownOne(IT->getBitWidth(), 0);
935 APInt RHSKnownZero(IT->getBitWidth(), 0);
936 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
937
938 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +0000939 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +0000940 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +0000941 }
942 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000943
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000944 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +0000945 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000946 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +0000947 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
948 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000949 if (W != Y) {
950 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000951 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000952 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000953 std::swap(W, X);
954 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000955 std::swap(Y, Z);
956 std::swap(W, X);
957 }
958 }
959
960 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +0000961 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000962 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000963 }
964 }
965 }
966
Chris Lattner6b032052003-10-02 15:11:26 +0000967 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +0000968 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +0000969 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +0000970 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000971
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000972 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +0000973 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000974 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000975 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000976 if (Anded == CRHS) {
977 // See if all bits from the first bit set in the Add RHS up are included
978 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000979 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000980
981 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000982 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000983
984 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000985 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +0000986
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000987 if (AddRHSHighBits == AddRHSHighBitsAnd) {
988 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +0000989 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000990 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000991 }
992 }
993 }
994
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000995 // Try to fold constant add into select arguments.
996 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000997 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000998 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000999 }
1000
Chris Lattner42790482007-12-20 01:56:58 +00001001 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00001002 {
1003 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00001004 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00001005 if (!SI) {
1006 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00001007 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00001008 }
Chris Lattner42790482007-12-20 01:56:58 +00001009 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00001010 Value *TV = SI->getTrueValue();
1011 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00001012 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00001013
1014 // Can we fold the add into the argument of the select?
1015 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00001016 if (match(FV, m_Zero()) &&
1017 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00001018 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00001019 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00001020 if (match(TV, m_Zero()) &&
1021 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00001022 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00001023 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00001024 }
1025 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00001026
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001027 // Check for (add (sext x), y), see if we can merge this into an
1028 // integer add followed by a sext.
1029 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1030 // (add (sext x), cst) --> (sext (add x, cst'))
1031 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
1032 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001033 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001034 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001035 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001036 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1037 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00001038 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1039 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001040 return new SExtInst(NewAdd, I.getType());
1041 }
1042 }
1043
1044 // (add (sext x), (sext y)) --> (sext (add int x, y))
1045 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1046 // Only do this if x/y have the same type, if at last one of them has a
1047 // single use (so we don't increase the number of sexts), and if the
1048 // integer add will not overflow.
1049 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1050 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1051 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1052 RHSConv->getOperand(0))) {
1053 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00001054 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1055 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001056 return new SExtInst(NewAdd, I.getType());
1057 }
1058 }
1059 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001060
1061 return Changed ? &I : 0;
1062}
1063
1064Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
1065 bool Changed = SimplifyCommutative(I);
1066 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1067
1068 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1069 // X + 0 --> X
1070 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001071 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001072 (I.getType())->getValueAPF()))
1073 return ReplaceInstUsesWith(I, LHS);
1074 }
1075
1076 if (isa<PHINode>(LHS))
1077 if (Instruction *NV = FoldOpIntoPhi(I))
1078 return NV;
1079 }
1080
1081 // -A + B --> B - A
1082 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00001083 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001084 return BinaryOperator::CreateFSub(RHS, LHSV);
1085
1086 // A + -B --> A - B
1087 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00001088 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001089 return BinaryOperator::CreateFSub(LHS, V);
1090
1091 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
1092 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
1093 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
1094 return ReplaceInstUsesWith(I, LHS);
1095
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001096 // Check for (add double (sitofp x), y), see if we can merge this into an
1097 // integer add followed by a promotion.
1098 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1099 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1100 // ... if the constant fits in the integer value. This is useful for things
1101 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1102 // requires a constant pool load, and generally allows the add to be better
1103 // instcombined.
1104 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
1105 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001106 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001107 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001108 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001109 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1110 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00001111 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1112 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001113 return new SIToFPInst(NewAdd, I.getType());
1114 }
1115 }
1116
1117 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1118 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1119 // Only do this if x/y have the same type, if at last one of them has a
1120 // single use (so we don't increase the number of int->fp conversions),
1121 // and if the integer add will not overflow.
1122 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1123 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1124 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1125 RHSConv->getOperand(0))) {
1126 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00001127 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00001128 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001129 return new SIToFPInst(NewAdd, I.getType());
1130 }
1131 }
1132 }
1133
Chris Lattner7e708292002-06-25 16:13:24 +00001134 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001135}
1136
Chris Lattner092543c2009-11-04 08:05:20 +00001137
1138/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
1139/// code necessary to compute the offset from the base pointer (without adding
1140/// in the base pointer). Return the result as a signed integer of intptr size.
1141static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
1142 TargetData &TD = *IC.getTargetData();
1143 gep_type_iterator GTI = gep_type_begin(GEP);
1144 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
1145 Value *Result = Constant::getNullValue(IntPtrTy);
1146
1147 // Build a mask for high order bits.
1148 unsigned IntPtrWidth = TD.getPointerSizeInBits();
1149 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
1150
1151 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
1152 ++i, ++GTI) {
1153 Value *Op = *i;
1154 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
1155 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
1156 if (OpC->isZero()) continue;
1157
1158 // Handle a struct index, which adds its field offset to the pointer.
1159 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1160 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1161
1162 Result = IC.Builder->CreateAdd(Result,
1163 ConstantInt::get(IntPtrTy, Size),
1164 GEP->getName()+".offs");
1165 continue;
1166 }
1167
1168 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
1169 Constant *OC =
1170 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
1171 Scale = ConstantExpr::getMul(OC, Scale);
1172 // Emit an add instruction.
1173 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
1174 continue;
1175 }
1176 // Convert to correct type.
1177 if (Op->getType() != IntPtrTy)
1178 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
1179 if (Size != 1) {
1180 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
1181 // We'll let instcombine(mul) convert this to a shl if possible.
1182 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
1183 }
1184
1185 // Emit an add instruction.
1186 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
1187 }
1188 return Result;
1189}
1190
1191
1192/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
1193/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
1194/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
1195/// be complex, and scales are involved. The above expression would also be
1196/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
1197/// This later form is less amenable to optimization though, and we are allowed
1198/// to generate the first by knowing that pointer arithmetic doesn't overflow.
1199///
1200/// If we can't emit an optimized form for this expression, this returns null.
1201///
1202static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
1203 InstCombiner &IC) {
1204 TargetData &TD = *IC.getTargetData();
1205 gep_type_iterator GTI = gep_type_begin(GEP);
1206
1207 // Check to see if this gep only has a single variable index. If so, and if
1208 // any constant indices are a multiple of its scale, then we can compute this
1209 // in terms of the scale of the variable index. For example, if the GEP
1210 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
1211 // because the expression will cross zero at the same point.
1212 unsigned i, e = GEP->getNumOperands();
1213 int64_t Offset = 0;
1214 for (i = 1; i != e; ++i, ++GTI) {
1215 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1216 // Compute the aggregate offset of constant indices.
1217 if (CI->isZero()) continue;
1218
1219 // Handle a struct index, which adds its field offset to the pointer.
1220 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1221 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
1222 } else {
1223 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1224 Offset += Size*CI->getSExtValue();
1225 }
1226 } else {
1227 // Found our variable index.
1228 break;
1229 }
1230 }
1231
1232 // If there are no variable indices, we must have a constant offset, just
1233 // evaluate it the general way.
1234 if (i == e) return 0;
1235
1236 Value *VariableIdx = GEP->getOperand(i);
1237 // Determine the scale factor of the variable element. For example, this is
1238 // 4 if the variable index is into an array of i32.
1239 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
1240
1241 // Verify that there are no other variable indices. If so, emit the hard way.
1242 for (++i, ++GTI; i != e; ++i, ++GTI) {
1243 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
1244 if (!CI) return 0;
1245
1246 // Compute the aggregate offset of constant indices.
1247 if (CI->isZero()) continue;
1248
1249 // Handle a struct index, which adds its field offset to the pointer.
1250 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1251 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
1252 } else {
1253 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1254 Offset += Size*CI->getSExtValue();
1255 }
1256 }
1257
1258 // Okay, we know we have a single variable index, which must be a
1259 // pointer/array/vector index. If there is no offset, life is simple, return
1260 // the index.
1261 unsigned IntPtrWidth = TD.getPointerSizeInBits();
1262 if (Offset == 0) {
1263 // Cast to intptrty in case a truncation occurs. If an extension is needed,
1264 // we don't need to bother extending: the extension won't affect where the
1265 // computation crosses zero.
1266 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
1267 VariableIdx = new TruncInst(VariableIdx,
1268 TD.getIntPtrType(VariableIdx->getContext()),
1269 VariableIdx->getName(), &I);
1270 return VariableIdx;
1271 }
1272
1273 // Otherwise, there is an index. The computation we will do will be modulo
1274 // the pointer size, so get it.
1275 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
1276
1277 Offset &= PtrSizeMask;
1278 VariableScale &= PtrSizeMask;
1279
1280 // To do this transformation, any constant index must be a multiple of the
1281 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
1282 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
1283 // multiple of the variable scale.
1284 int64_t NewOffs = Offset / (int64_t)VariableScale;
1285 if (Offset != NewOffs*(int64_t)VariableScale)
1286 return 0;
1287
1288 // Okay, we can do this evaluation. Start by converting the index to intptr.
1289 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
1290 if (VariableIdx->getType() != IntPtrTy)
1291 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
1292 true /*SExt*/,
1293 VariableIdx->getName(), &I);
1294 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
1295 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
1296}
1297
1298
1299/// Optimize pointer differences into the same array into a size. Consider:
1300/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1301/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1302///
1303Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1304 const Type *Ty) {
1305 assert(TD && "Must have target data info for this");
1306
1307 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1308 // this.
1309 bool Swapped;
Chris Lattner85c1c962010-01-01 22:42:29 +00001310 GetElementPtrInst *GEP = 0;
1311 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +00001312
Chris Lattner85c1c962010-01-01 22:42:29 +00001313 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
1314 // For now we require one side to be the base pointer "A" or a constant
1315 // expression derived from it.
1316 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
1317 // (gep X, ...) - X
1318 if (LHSGEP->getOperand(0) == RHS) {
1319 GEP = LHSGEP;
1320 Swapped = false;
1321 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
1322 // (gep X, ...) - (ce_gep X, ...)
1323 if (CE->getOpcode() == Instruction::GetElementPtr &&
1324 LHSGEP->getOperand(0) == CE->getOperand(0)) {
1325 CstGEP = CE;
1326 GEP = LHSGEP;
1327 Swapped = false;
1328 }
1329 }
1330 }
1331
1332 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
1333 // X - (gep X, ...)
1334 if (RHSGEP->getOperand(0) == LHS) {
1335 GEP = RHSGEP;
1336 Swapped = true;
1337 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
1338 // (ce_gep X, ...) - (gep X, ...)
1339 if (CE->getOpcode() == Instruction::GetElementPtr &&
1340 RHSGEP->getOperand(0) == CE->getOperand(0)) {
1341 CstGEP = CE;
1342 GEP = RHSGEP;
1343 Swapped = true;
1344 }
1345 }
1346 }
1347
1348 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00001349 return 0;
1350
Chris Lattner092543c2009-11-04 08:05:20 +00001351 // Emit the offset of the GEP and an intptr_t.
1352 Value *Result = EmitGEPOffset(GEP, *this);
Chris Lattner85c1c962010-01-01 22:42:29 +00001353
1354 // If we had a constant expression GEP on the other side offsetting the
1355 // pointer, subtract it from the offset we have.
1356 if (CstGEP) {
1357 Value *CstOffset = EmitGEPOffset(CstGEP, *this);
1358 Result = Builder->CreateSub(Result, CstOffset);
1359 }
1360
Chris Lattner092543c2009-11-04 08:05:20 +00001361
1362 // If we have p - gep(p, ...) then we have to negate the result.
1363 if (Swapped)
1364 Result = Builder->CreateNeg(Result, "diff.neg");
1365
1366 return Builder->CreateIntCast(Result, Ty, true);
1367}
1368
1369
Chris Lattner7e708292002-06-25 16:13:24 +00001370Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001371 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001372
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001373 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001374 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001375
Chris Lattner3bf68152009-12-21 04:04:05 +00001376 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
1377 if (Value *V = dyn_castNegVal(Op1)) {
1378 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1379 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1380 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1381 return Res;
1382 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001383
Chris Lattnere87597f2004-10-16 18:11:37 +00001384 if (isa<UndefValue>(Op0))
1385 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1386 if (isa<UndefValue>(Op1))
1387 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner4de84762010-01-04 07:02:48 +00001388 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner092543c2009-11-04 08:05:20 +00001389 return BinaryOperator::CreateXor(Op0, Op1);
1390
Chris Lattnerd65460f2003-11-05 01:06:05 +00001391 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00001392 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00001393 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00001394 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001395
Chris Lattnerd65460f2003-11-05 01:06:05 +00001396 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001397 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001398 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00001399 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00001400
Chris Lattner76b7a062007-01-15 07:02:54 +00001401 // -(X >>u 31) -> (X >>s 31)
1402 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00001403 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001404 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001405 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001406 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00001407 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001408 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00001409 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001410 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001411 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00001412 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00001413 }
1414 }
Chris Lattner092543c2009-11-04 08:05:20 +00001415 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001416 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1417 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001418 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00001419 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00001420 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001421 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001422 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00001423 }
1424 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001425 }
1426 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001427 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001428
1429 // Try to fold constant sub into select arguments.
1430 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001431 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001432 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00001433
1434 // C - zext(bool) -> bool ? C - 1 : C
1435 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattner4de84762010-01-04 07:02:48 +00001436 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +00001437 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00001438 }
1439
Chris Lattner43d84d62005-04-07 16:15:25 +00001440 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001441 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00001442 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001443 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001444 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001445 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001446 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001447 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001448 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1449 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1450 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00001451 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00001452 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00001453 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001454 }
1455
Chris Lattnerfd059242003-10-15 16:48:29 +00001456 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001457 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1458 // is not used by anyone else...
1459 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001460 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00001461 // Swap the two operands of the subexpr...
1462 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1463 Op1I->setOperand(0, IIOp1);
1464 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001465
Chris Lattnera2881962003-02-18 19:28:33 +00001466 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001467 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001468 }
1469
1470 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1471 //
1472 if (Op1I->getOpcode() == Instruction::And &&
1473 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1474 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1475
Chris Lattner74381062009-08-30 07:44:24 +00001476 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001477 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001478 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001479
Reid Spencerac5209e2006-10-16 23:08:08 +00001480 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00001481 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00001482 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00001483 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00001484 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001485 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001486 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00001487
Chris Lattnerad3448c2003-02-18 19:57:07 +00001488 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001489 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00001490 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001491 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001492 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00001493 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001494 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001495 }
Chris Lattner40371712002-05-09 01:29:19 +00001496 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001497 }
Chris Lattnera2881962003-02-18 19:28:33 +00001498
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001499 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1500 if (Op0I->getOpcode() == Instruction::Add) {
1501 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1502 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1503 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1504 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1505 } else if (Op0I->getOpcode() == Instruction::Sub) {
1506 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001507 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001508 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001509 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001510 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001511
Chris Lattner50af16a2004-11-13 19:50:12 +00001512 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00001513 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00001514 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00001515 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001516
Chris Lattner50af16a2004-11-13 19:50:12 +00001517 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00001518 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001519 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00001520 }
Chris Lattner092543c2009-11-04 08:05:20 +00001521
1522 // Optimize pointer differences into the same array into a size. Consider:
1523 // &A[10] - &A[0]: we should compile this to "10".
1524 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00001525 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001526 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1527 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00001528 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1529 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001530
1531 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001532 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1533 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1534 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1535 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001536 }
1537
Chris Lattner3f5b8772002-05-06 16:14:14 +00001538 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001539}
1540
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001541Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1542 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1543
1544 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00001545 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001546 return BinaryOperator::CreateFAdd(Op0, V);
1547
1548 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1549 if (Op1I->getOpcode() == Instruction::FAdd) {
1550 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001551 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001552 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001553 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001554 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001555 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001556 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001557 }
1558
1559 return 0;
1560}
1561
Chris Lattnera0141b92007-07-15 20:42:37 +00001562/// isSignBitCheck - Given an exploded icmp instruction, return true if the
1563/// comparison only checks the sign bit. If it only checks the sign bit, set
1564/// TrueIfSigned if the result of the comparison is true when the input value is
1565/// signed.
1566static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
1567 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001568 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00001569 case ICmpInst::ICMP_SLT: // True if LHS s< 0
1570 TrueIfSigned = true;
1571 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00001572 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
1573 TrueIfSigned = true;
1574 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00001575 case ICmpInst::ICMP_SGT: // True if LHS s> -1
1576 TrueIfSigned = false;
1577 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00001578 case ICmpInst::ICMP_UGT:
1579 // True if LHS u> RHS and RHS == high-bit-mask - 1
1580 TrueIfSigned = true;
1581 return RHS->getValue() ==
1582 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
1583 case ICmpInst::ICMP_UGE:
1584 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
1585 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00001586 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00001587 default:
1588 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00001589 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00001590}
1591
Chris Lattner7e708292002-06-25 16:13:24 +00001592Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001593 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00001594 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001595
Chris Lattnera2498472009-10-11 21:36:10 +00001596 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001597 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00001598
Chris Lattner8af304a2009-10-11 07:53:15 +00001599 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00001600 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1601 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001602
1603 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00001604 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00001605 if (SI->getOpcode() == Instruction::Shl)
1606 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001607 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001608 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001609
Zhou Sheng843f07672007-04-19 05:39:12 +00001610 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00001611 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00001612 if (CI->equalsInt(1)) // X * 1 == X
1613 return ReplaceInstUsesWith(I, Op0);
1614 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00001615 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001616
Zhou Sheng97b52c22007-03-29 01:57:21 +00001617 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00001618 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001619 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00001620 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001621 }
Chris Lattnera2498472009-10-11 21:36:10 +00001622 } else if (isa<VectorType>(Op1C->getType())) {
1623 if (Op1C->isNullValue())
1624 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00001625
Chris Lattnera2498472009-10-11 21:36:10 +00001626 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00001627 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00001628 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00001629
1630 // As above, vector X*splat(1.0) -> X in all defined cases.
1631 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00001632 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
1633 if (CI->equalsInt(1))
1634 return ReplaceInstUsesWith(I, Op0);
1635 }
1636 }
Chris Lattnera2881962003-02-18 19:28:33 +00001637 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001638
1639 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1640 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00001641 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001642 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00001643 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
1644 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001645 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001646
1647 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001648
1649 // Try to fold constant mul into select arguments.
1650 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001651 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001652 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001653
1654 if (isa<PHINode>(Op0))
1655 if (Instruction *NV = FoldOpIntoPhi(I))
1656 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001657 }
1658
Dan Gohman186a6362009-08-12 16:04:34 +00001659 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00001660 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001661 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001662
Nick Lewycky0c730792008-11-21 07:33:58 +00001663 // (X / Y) * Y = X - (X % Y)
1664 // (X / Y) * -Y = (X % Y) - X
1665 {
Chris Lattnera2498472009-10-11 21:36:10 +00001666 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00001667 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
1668 if (!BO ||
1669 (BO->getOpcode() != Instruction::UDiv &&
1670 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00001671 Op1C = Op0;
1672 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00001673 }
Chris Lattnera2498472009-10-11 21:36:10 +00001674 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00001675 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00001676 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00001677 (BO->getOpcode() == Instruction::UDiv ||
1678 BO->getOpcode() == Instruction::SDiv)) {
1679 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
1680
Dan Gohmanfa94b942009-08-12 16:33:09 +00001681 // If the division is exact, X % Y is zero.
1682 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
1683 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00001684 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00001685 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00001686 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00001687 }
1688
Chris Lattner74381062009-08-30 07:44:24 +00001689 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00001690 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00001691 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00001692 else
Chris Lattner74381062009-08-30 07:44:24 +00001693 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00001694 Rem->takeName(BO);
1695
Chris Lattnera2498472009-10-11 21:36:10 +00001696 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00001697 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00001698 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00001699 }
1700 }
1701
Chris Lattner8af304a2009-10-11 07:53:15 +00001702 /// i1 mul -> i1 and.
Chris Lattner4de84762010-01-04 07:02:48 +00001703 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattnera2498472009-10-11 21:36:10 +00001704 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001705
Chris Lattner8af304a2009-10-11 07:53:15 +00001706 // X*(1 << Y) --> X << Y
1707 // (1 << Y)*X --> X << Y
1708 {
1709 Value *Y;
1710 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00001711 return BinaryOperator::CreateShl(Op1, Y);
1712 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00001713 return BinaryOperator::CreateShl(Op0, Y);
1714 }
1715
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001716 // If one of the operands of the multiply is a cast from a boolean value, then
1717 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00001718 // X * Y (where Y is 0 or 1) -> X & (0-Y)
1719 if (!isa<VectorType>(I.getType())) {
1720 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00001721 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00001722
Chris Lattnerd2c58362009-10-11 21:29:45 +00001723 Value *BoolCast = 0, *OtherOp = 0;
1724 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00001725 BoolCast = Op0, OtherOp = Op1;
1726 else if (MaskedValueIsZero(Op1, Negative2))
1727 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00001728
Chris Lattner0036e3a2009-10-11 21:22:21 +00001729 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00001730 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
1731 BoolCast, "tmp");
1732 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001733 }
1734 }
1735
Chris Lattner7e708292002-06-25 16:13:24 +00001736 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001737}
1738
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001739Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
1740 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00001741 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001742
1743 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00001744 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1745 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001746 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1747 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1748 if (Op1F->isExactlyValue(1.0))
1749 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00001750 } else if (isa<VectorType>(Op1C->getType())) {
1751 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001752 // As above, vector X*splat(1.0) -> X in all defined cases.
1753 if (Constant *Splat = Op1V->getSplatValue()) {
1754 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
1755 if (F->isExactlyValue(1.0))
1756 return ReplaceInstUsesWith(I, Op0);
1757 }
1758 }
1759 }
1760
1761 // Try to fold constant mul into select arguments.
1762 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1763 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1764 return R;
1765
1766 if (isa<PHINode>(Op0))
1767 if (Instruction *NV = FoldOpIntoPhi(I))
1768 return NV;
1769 }
1770
Dan Gohman186a6362009-08-12 16:04:34 +00001771 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00001772 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001773 return BinaryOperator::CreateFMul(Op0v, Op1v);
1774
1775 return Changed ? &I : 0;
1776}
1777
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001778/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
1779/// instruction.
1780bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
1781 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
1782
1783 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
1784 int NonNullOperand = -1;
1785 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
1786 if (ST->isNullValue())
1787 NonNullOperand = 2;
1788 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
1789 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
1790 if (ST->isNullValue())
1791 NonNullOperand = 1;
1792
1793 if (NonNullOperand == -1)
1794 return false;
1795
1796 Value *SelectCond = SI->getOperand(0);
1797
1798 // Change the div/rem to use 'Y' instead of the select.
1799 I.setOperand(1, SI->getOperand(NonNullOperand));
1800
1801 // Okay, we know we replace the operand of the div/rem with 'Y' with no
1802 // problem. However, the select, or the condition of the select may have
1803 // multiple uses. Based on our knowledge that the operand must be non-zero,
1804 // propagate the known value for the select into other uses of it, and
1805 // propagate a known value of the condition into its other users.
1806
1807 // If the select and condition only have a single use, don't bother with this,
1808 // early exit.
1809 if (SI->use_empty() && SelectCond->hasOneUse())
1810 return true;
1811
1812 // Scan the current block backward, looking for other uses of SI.
1813 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
1814
1815 while (BBI != BBFront) {
1816 --BBI;
1817 // If we found a call to a function, we can't assume it will return, so
1818 // information from below it cannot be propagated above it.
1819 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
1820 break;
1821
1822 // Replace uses of the select or its condition with the known values.
1823 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
1824 I != E; ++I) {
1825 if (*I == SI) {
1826 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001827 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001828 } else if (*I == SelectCond) {
Chris Lattner4de84762010-01-04 07:02:48 +00001829 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
1830 ConstantInt::getFalse(BBI->getContext());
Chris Lattner7a1e9242009-08-30 06:13:40 +00001831 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001832 }
1833 }
1834
1835 // If we past the instruction, quit looking for it.
1836 if (&*BBI == SI)
1837 SI = 0;
1838 if (&*BBI == SelectCond)
1839 SelectCond = 0;
1840
1841 // If we ran out of things to eliminate, break out of the loop.
1842 if (SelectCond == 0 && SI == 0)
1843 break;
1844
1845 }
1846 return true;
1847}
1848
1849
Reid Spencer1628cec2006-10-26 06:15:43 +00001850/// This function implements the transforms on div instructions that work
1851/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
1852/// used by the visitors to those instructions.
1853/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00001854Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001855 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001856
Chris Lattner50b2ca42008-02-19 06:12:18 +00001857 // undef / X -> 0 for integer.
1858 // undef / X -> undef for FP (the undef could be a snan).
1859 if (isa<UndefValue>(Op0)) {
1860 if (Op0->getType()->isFPOrFPVector())
1861 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00001862 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00001863 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001864
1865 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00001866 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00001867 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001868
Reid Spencer1628cec2006-10-26 06:15:43 +00001869 return 0;
1870}
Misha Brukmanfd939082005-04-21 23:48:37 +00001871
Reid Spencer1628cec2006-10-26 06:15:43 +00001872/// This function implements the transforms common to both integer division
1873/// instructions (udiv and sdiv). It is called by the visitors to those integer
1874/// division instructions.
1875/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00001876Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001877 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1878
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00001879 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001880 if (Op0 == Op1) {
1881 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001882 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001883 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001884 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001885 }
1886
Owen Andersoneed707b2009-07-24 23:12:02 +00001887 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00001888 return ReplaceInstUsesWith(I, CI);
1889 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00001890
Reid Spencer1628cec2006-10-26 06:15:43 +00001891 if (Instruction *Common = commonDivTransforms(I))
1892 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00001893
1894 // Handle cases involving: [su]div X, (select Cond, Y, Z)
1895 // This does not apply for fdiv.
1896 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1897 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00001898
1899 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1900 // div X, 1 == X
1901 if (RHS->equalsInt(1))
1902 return ReplaceInstUsesWith(I, Op0);
1903
1904 // (X / C1) / C2 -> X / (C1*C2)
1905 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1906 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
1907 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001908 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00001909 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00001910 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00001911 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001912 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001913 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00001914 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001915
Reid Spencerbca0e382007-03-23 20:05:17 +00001916 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00001917 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1918 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1919 return R;
1920 if (isa<PHINode>(Op0))
1921 if (Instruction *NV = FoldOpIntoPhi(I))
1922 return NV;
1923 }
Chris Lattner8e49e082006-09-09 20:26:32 +00001924 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001925
Chris Lattnera2881962003-02-18 19:28:33 +00001926 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001927 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001928 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00001929 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00001930
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001931 // It can't be division by zero, hence it must be division by one.
Chris Lattner4de84762010-01-04 07:02:48 +00001932 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001933 return ReplaceInstUsesWith(I, Op0);
1934
Nick Lewycky895f0852008-11-27 20:21:08 +00001935 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
1936 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
1937 // div X, 1 == X
1938 if (X->isOne())
1939 return ReplaceInstUsesWith(I, Op0);
1940 }
1941
Reid Spencer1628cec2006-10-26 06:15:43 +00001942 return 0;
1943}
1944
1945Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1946 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1947
1948 // Handle the integer div common cases
1949 if (Instruction *Common = commonIDivTransforms(I))
1950 return Common;
1951
Reid Spencer1628cec2006-10-26 06:15:43 +00001952 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00001953 // X udiv C^2 -> X >> C
1954 // Check to see if this is an unsigned division with an exact power of 2,
1955 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00001956 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001957 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00001958 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00001959
1960 // X udiv C, where C >= signbit
1961 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00001962 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00001963 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00001964 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00001965 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001966 }
1967
1968 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00001969 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001970 if (RHSI->getOpcode() == Instruction::Shl &&
1971 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001972 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00001973 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001974 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00001975 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00001976 if (uint32_t C2 = C1.logBase2())
1977 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001978 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001979 }
1980 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001981 }
1982
Reid Spencer1628cec2006-10-26 06:15:43 +00001983 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
1984 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001985 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00001986 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001987 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001988 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00001989 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001990 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00001991 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001992 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00001993 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00001994 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00001995
1996 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00001997 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00001998 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00001999
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002000 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002001 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002002 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002003 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002004 return 0;
2005}
2006
Reid Spencer1628cec2006-10-26 06:15:43 +00002007Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2008 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2009
2010 // Handle the integer div common cases
2011 if (Instruction *Common = commonIDivTransforms(I))
2012 return Common;
2013
2014 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2015 // sdiv X, -1 == -X
2016 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002017 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00002018
Dan Gohmanfa94b942009-08-12 16:33:09 +00002019 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00002020 if (cast<SDivOperator>(&I)->isExact() &&
2021 RHS->getValue().isNonNegative() &&
2022 RHS->getValue().isPowerOf2()) {
2023 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
2024 RHS->getValue().exactLogBase2());
2025 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
2026 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00002027
2028 // -X/C --> X/-C provided the negation doesn't overflow.
2029 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
2030 if (isa<Constant>(Sub->getOperand(0)) &&
2031 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00002032 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00002033 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
2034 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00002035 }
2036
2037 // If the sign bits of both operands are zero (i.e. we can prove they are
2038 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002039 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002040 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00002041 if (MaskedValueIsZero(Op0, Mask)) {
2042 if (MaskedValueIsZero(Op1, Mask)) {
2043 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2044 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2045 }
2046 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00002047 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00002048 ShiftedInt->getValue().isPowerOf2()) {
2049 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
2050 // Safe because the only negative value (1 << Y) can take on is
2051 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
2052 // the sign bit set.
2053 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2054 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002055 }
Eli Friedman8be17392009-07-18 09:53:21 +00002056 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002057
2058 return 0;
2059}
2060
2061Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2062 return commonDivTransforms(I);
2063}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002064
Reid Spencer0a783f72006-11-02 01:53:59 +00002065/// This function implements the transforms on rem instructions that work
2066/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2067/// is used by the visitors to those instructions.
2068/// @brief Transforms common to all three rem instructions
2069Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002070 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002071
Chris Lattner50b2ca42008-02-19 06:12:18 +00002072 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2073 if (I.getType()->isFPOrFPVector())
2074 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00002075 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002076 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002077 if (isa<UndefValue>(Op1))
2078 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002079
2080 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002081 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2082 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00002083
Reid Spencer0a783f72006-11-02 01:53:59 +00002084 return 0;
2085}
2086
2087/// This function implements the transforms common to both integer remainder
2088/// instructions (urem and srem). It is called by the visitors to those integer
2089/// remainder instructions.
2090/// @brief Common integer remainder transforms
2091Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2092 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2093
2094 if (Instruction *common = commonRemTransforms(I))
2095 return common;
2096
Dale Johannesened6af242009-01-21 00:35:19 +00002097 // 0 % X == 0 for integer, we don't need to preserve faults!
2098 if (Constant *LHS = dyn_cast<Constant>(Op0))
2099 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00002100 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00002101
Chris Lattner857e8cd2004-12-12 21:48:58 +00002102 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002103 // X % 0 == undef, we don't need to preserve faults!
2104 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002105 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002106
Chris Lattnera2881962003-02-18 19:28:33 +00002107 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002108 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002109
Chris Lattner97943922006-02-28 05:49:21 +00002110 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2111 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2112 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2113 return R;
2114 } else if (isa<PHINode>(Op0I)) {
2115 if (Instruction *NV = FoldOpIntoPhi(I))
2116 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002117 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002118
2119 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00002120 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002121 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002122 }
Chris Lattnera2881962003-02-18 19:28:33 +00002123 }
2124
Reid Spencer0a783f72006-11-02 01:53:59 +00002125 return 0;
2126}
2127
2128Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2129 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2130
2131 if (Instruction *common = commonIRemTransforms(I))
2132 return common;
2133
2134 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2135 // X urem C^2 -> X and C
2136 // Check to see if this is an unsigned remainder with an exact power of 2,
2137 // if so, convert to a bitwise and.
2138 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002139 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00002140 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00002141 }
2142
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002143 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002144 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2145 if (RHSI->getOpcode() == Instruction::Shl &&
2146 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002147 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002148 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00002149 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002150 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002151 }
2152 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002153 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002154
Reid Spencer0a783f72006-11-02 01:53:59 +00002155 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2156 // where C1&C2 are powers of two.
2157 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2158 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2159 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2160 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002161 if ((STO->getValue().isPowerOf2()) &&
2162 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00002163 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
2164 SI->getName()+".t");
2165 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
2166 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00002167 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00002168 }
2169 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002170 }
2171
Chris Lattner3f5b8772002-05-06 16:14:14 +00002172 return 0;
2173}
2174
Reid Spencer0a783f72006-11-02 01:53:59 +00002175Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2176 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2177
Dan Gohmancff55092007-11-05 23:16:33 +00002178 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00002179 if (Instruction *Common = commonIRemTransforms(I))
2180 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00002181
Dan Gohman186a6362009-08-12 16:04:34 +00002182 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00002183 if (!isa<Constant>(RHSNeg) ||
2184 (isa<ConstantInt>(RHSNeg) &&
2185 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002186 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00002187 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00002188 I.setOperand(1, RHSNeg);
2189 return &I;
2190 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00002191
Dan Gohmancff55092007-11-05 23:16:33 +00002192 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002193 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002194 if (I.getType()->isInteger()) {
2195 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2196 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2197 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002198 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00002199 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002200 }
2201
Nick Lewycky2a8f6592008-12-18 06:31:11 +00002202 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00002203 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
2204 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00002205
Nick Lewycky9dce8732008-12-20 16:48:00 +00002206 bool hasNegative = false;
2207 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
2208 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
2209 if (RHS->getValue().isNegative())
2210 hasNegative = true;
2211
2212 if (hasNegative) {
2213 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00002214 for (unsigned i = 0; i != VWidth; ++i) {
2215 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
2216 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002217 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00002218 else
2219 Elts[i] = RHS;
2220 }
2221 }
2222
Owen Andersonaf7ec972009-07-28 21:19:26 +00002223 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00002224 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00002225 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00002226 I.setOperand(1, NewRHSV);
2227 return &I;
2228 }
2229 }
2230 }
2231
Reid Spencer0a783f72006-11-02 01:53:59 +00002232 return 0;
2233}
2234
2235Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002236 return commonRemTransforms(I);
2237}
2238
Chris Lattner457dd822004-06-09 07:59:58 +00002239// isOneBitSet - Return true if there is exactly one bit set in the specified
2240// constant.
2241static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002242 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002243}
2244
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002245// isHighOnes - Return true if the constant is of the form 1+0+.
2246// This is the same as lowones(~X).
2247static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002248 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002249}
2250
Reid Spencere4d87aa2006-12-23 06:05:41 +00002251/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002252/// are carefully arranged to allow folding of expressions such as:
2253///
2254/// (A < B) | (A > B) --> (A != B)
2255///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002256/// Note that this is only valid if the first and second predicates have the
2257/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002258///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002259/// Three bits are used to represent the condition, as follows:
2260/// 0 A > B
2261/// 1 A == B
2262/// 2 A < B
2263///
2264/// <=> Value Definition
2265/// 000 0 Always false
2266/// 001 1 A > B
2267/// 010 2 A == B
2268/// 011 3 A >= B
2269/// 100 4 A < B
2270/// 101 5 A != B
2271/// 110 6 A <= B
2272/// 111 7 Always true
2273///
2274static unsigned getICmpCode(const ICmpInst *ICI) {
2275 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002276 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002277 case ICmpInst::ICMP_UGT: return 1; // 001
2278 case ICmpInst::ICMP_SGT: return 1; // 001
2279 case ICmpInst::ICMP_EQ: return 2; // 010
2280 case ICmpInst::ICMP_UGE: return 3; // 011
2281 case ICmpInst::ICMP_SGE: return 3; // 011
2282 case ICmpInst::ICMP_ULT: return 4; // 100
2283 case ICmpInst::ICMP_SLT: return 4; // 100
2284 case ICmpInst::ICMP_NE: return 5; // 101
2285 case ICmpInst::ICMP_ULE: return 6; // 110
2286 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002287 // True -> 7
2288 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00002289 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002290 return 0;
2291 }
2292}
2293
Evan Cheng8db90722008-10-14 17:15:11 +00002294/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
2295/// predicate into a three bit mask. It also returns whether it is an ordered
2296/// predicate by reference.
2297static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
2298 isOrdered = false;
2299 switch (CC) {
2300 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
2301 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00002302 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
2303 case FCmpInst::FCMP_UGT: return 1; // 001
2304 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
2305 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00002306 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
2307 case FCmpInst::FCMP_UGE: return 3; // 011
2308 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
2309 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00002310 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
2311 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00002312 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
2313 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00002314 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00002315 default:
2316 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00002317 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00002318 return 0;
2319 }
2320}
2321
Reid Spencere4d87aa2006-12-23 06:05:41 +00002322/// getICmpValue - This is the complement of getICmpCode, which turns an
2323/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00002324/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00002325/// of predicate to use in the new icmp instruction.
Chris Lattner4de84762010-01-04 07:02:48 +00002326static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002327 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002328 default: llvm_unreachable("Illegal ICmp code!");
Chris Lattner4de84762010-01-04 07:02:48 +00002329 case 0: return ConstantInt::getFalse(LHS->getContext());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002330 case 1:
2331 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002332 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002333 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002334 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2335 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002336 case 3:
2337 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002338 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002339 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002340 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002341 case 4:
2342 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002343 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002344 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002345 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2346 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002347 case 6:
2348 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002349 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002350 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002351 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00002352 case 7: return ConstantInt::getTrue(LHS->getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002353 }
2354}
2355
Evan Cheng8db90722008-10-14 17:15:11 +00002356/// getFCmpValue - This is the complement of getFCmpCode, which turns an
2357/// opcode and two operands into either a FCmp instruction. isordered is passed
2358/// in to determine which kind of predicate to use in the new fcmp instruction.
2359static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner4de84762010-01-04 07:02:48 +00002360 Value *LHS, Value *RHS) {
Evan Cheng8db90722008-10-14 17:15:11 +00002361 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002362 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00002363 case 0:
2364 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002365 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002366 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002367 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002368 case 1:
2369 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002370 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002371 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002372 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002373 case 2:
2374 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002375 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002376 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002377 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002378 case 3:
2379 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002380 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002381 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002382 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002383 case 4:
2384 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002385 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002386 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002387 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002388 case 5:
2389 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002390 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002391 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002392 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00002393 case 6:
2394 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002395 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00002396 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002397 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00002398 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng8db90722008-10-14 17:15:11 +00002399 }
2400}
2401
Chris Lattnerb9553d62008-11-16 04:55:20 +00002402/// PredicatesFoldable - Return true if both predicates match sign or if at
2403/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00002404static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00002405 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
2406 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
2407 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002408}
2409
2410namespace {
2411// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2412struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002413 InstCombiner &IC;
2414 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002415 ICmpInst::Predicate pred;
2416 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2417 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2418 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002419 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002420 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2421 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002422 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
2423 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002424 return false;
2425 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00002426 Instruction *apply(Instruction &Log) const {
2427 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2428 if (ICI->getOperand(0) != LHS) {
2429 assert(ICI->getOperand(1) == LHS);
2430 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002431 }
2432
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002433 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002434 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00002435 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002436 unsigned Code;
2437 switch (Log.getOpcode()) {
2438 case Instruction::And: Code = LHSCode & RHSCode; break;
2439 case Instruction::Or: Code = LHSCode | RHSCode; break;
2440 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00002441 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002442 }
2443
Nick Lewycky4a134af2009-10-25 05:20:17 +00002444 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Chris Lattner4de84762010-01-04 07:02:48 +00002445 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002446 if (Instruction *I = dyn_cast<Instruction>(RV))
2447 return I;
2448 // Otherwise, it's a constant boolean value...
2449 return IC.ReplaceInstUsesWith(Log, RV);
2450 }
2451};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00002452} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002453
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002454// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2455// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00002456// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002457Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002458 ConstantInt *OpRHS,
2459 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002460 BinaryOperator &TheAnd) {
2461 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002462 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00002463 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002464 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002465
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002466 switch (Op->getOpcode()) {
2467 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002468 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002469 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00002470 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002471 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002472 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002473 }
2474 break;
2475 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002476 if (Together == AndRHS) // (X | C) & C --> C
2477 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002478
Chris Lattner6e7ba452005-01-01 16:22:27 +00002479 if (Op->hasOneUse() && Together != OpRHS) {
2480 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00002481 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00002482 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002483 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002484 }
2485 break;
2486 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002487 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002488 // Adding a one to a single bit bit-field should be turned into an XOR
2489 // of the bit. First thing to check is to see if this AND is with a
2490 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002491 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002492
2493 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002494 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002495 // Ok, at this point, we know that we are masking the result of the
2496 // ADD down to exactly one bit. If the constant we are adding has
2497 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002498 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002499
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002500 // Check to see if any bits below the one bit set in AndRHSV are set.
2501 if ((AddRHS & (AndRHSV-1)) == 0) {
2502 // If not, the only thing that can effect the output of the AND is
2503 // the bit specified by AndRHSV. If that bit is set, the effect of
2504 // the XOR is to toggle the bit. If it is clear, then the ADD has
2505 // no effect.
2506 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2507 TheAnd.setOperand(0, X);
2508 return &TheAnd;
2509 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002510 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00002511 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002512 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002513 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002514 }
2515 }
2516 }
2517 }
2518 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002519
2520 case Instruction::Shl: {
2521 // We know that the AND will not produce any of the bits shifted in, so if
2522 // the anded constant includes them, clear them now!
2523 //
Zhou Sheng290bec52007-03-29 08:15:12 +00002524 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002525 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00002526 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00002527 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
2528 AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002529
Zhou Sheng290bec52007-03-29 08:15:12 +00002530 if (CI->getValue() == ShlMask) {
2531 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00002532 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2533 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002534 TheAnd.setOperand(1, CI);
2535 return &TheAnd;
2536 }
2537 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002538 }
Chris Lattner4de84762010-01-04 07:02:48 +00002539 case Instruction::LShr: {
Chris Lattner62a355c2003-09-19 19:05:02 +00002540 // We know that the AND will not produce any of the bits shifted in, so if
2541 // the anded constant includes them, clear them now! This only applies to
2542 // unsigned shifts, because a signed shr may bring in set bits!
2543 //
Zhou Sheng290bec52007-03-29 08:15:12 +00002544 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002545 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00002546 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00002547 ConstantInt *CI = ConstantInt::get(Op->getContext(),
2548 AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00002549
Zhou Sheng290bec52007-03-29 08:15:12 +00002550 if (CI->getValue() == ShrMask) {
2551 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00002552 return ReplaceInstUsesWith(TheAnd, Op);
2553 } else if (CI != AndRHS) {
2554 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2555 return &TheAnd;
2556 }
2557 break;
2558 }
2559 case Instruction::AShr:
2560 // Signed shr.
2561 // See if this is shifting in some sign extension, then masking it out
2562 // with an and.
2563 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00002564 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002565 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00002566 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00002567 Constant *C = ConstantInt::get(Op->getContext(),
2568 AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00002569 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00002570 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00002571 // Make the argument unsigned.
2572 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00002573 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002574 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00002575 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002576 }
2577 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002578 }
2579 return 0;
2580}
2581
Chris Lattner8b170942002-08-09 23:47:40 +00002582
Chris Lattnera96879a2004-09-29 17:40:11 +00002583/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2584/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00002585/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2586/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00002587/// insert new instructions.
2588Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002589 bool isSigned, bool Inside,
2590 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002591 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00002592 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00002593 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002594
Chris Lattnera96879a2004-09-29 17:40:11 +00002595 if (Inside) {
2596 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002597 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00002598
Reid Spencere4d87aa2006-12-23 06:05:41 +00002599 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002600 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00002601 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00002602 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002603 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002604 }
2605
2606 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00002607 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00002608 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002609 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002610 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00002611 }
2612
2613 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002614 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00002615
Reid Spencere4e40032007-03-21 23:19:50 +00002616 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00002617 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002618 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002619 ICmpInst::Predicate pred = (isSigned ?
2620 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002621 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002622 }
Reid Spencerb83eb642006-10-20 07:07:24 +00002623
Reid Spencere4e40032007-03-21 23:19:50 +00002624 // Emit V-Lo >u Hi-1-Lo
2625 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00002626 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00002627 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002628 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002629 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00002630}
2631
Chris Lattner7203e152005-09-18 07:22:02 +00002632// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2633// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2634// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2635// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00002636static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002637 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00002638 uint32_t BitWidth = Val->getType()->getBitWidth();
2639 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00002640
2641 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00002642 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00002643 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00002644 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00002645 return true;
2646}
2647
Chris Lattner7203e152005-09-18 07:22:02 +00002648/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2649/// where isSub determines whether the operator is a sub. If we can fold one of
2650/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00002651///
2652/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2653/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2654/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2655///
2656/// return (A +/- B).
2657///
2658Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002659 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00002660 Instruction &I) {
2661 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2662 if (!LHSI || LHSI->getNumOperands() != 2 ||
2663 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2664
2665 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2666
2667 switch (LHSI->getOpcode()) {
2668 default: return 0;
2669 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00002670 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00002671 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00002672 if ((Mask->getValue().countLeadingZeros() +
2673 Mask->getValue().countPopulation()) ==
2674 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00002675 break;
2676
2677 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2678 // part, we don't need any explicit masks to take them out of A. If that
2679 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00002680 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00002681 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00002682 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00002683 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00002684 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00002685 break;
2686 }
2687 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002688 return 0;
2689 case Instruction::Or:
2690 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00002691 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00002692 if ((Mask->getValue().countLeadingZeros() +
2693 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00002694 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00002695 break;
2696 return 0;
2697 }
2698
Chris Lattnerc8e77562005-09-18 04:24:45 +00002699 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00002700 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
2701 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00002702}
2703
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002704/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
2705Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
2706 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00002707 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002708 ConstantInt *LHSCst, *RHSCst;
2709 ICmpInst::Predicate LHSCC, RHSCC;
2710
Chris Lattnerea065fb2008-11-16 05:10:52 +00002711 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002712 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00002713 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002714 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00002715 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002716 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00002717
Chris Lattner3f40e232009-11-29 00:51:17 +00002718 if (LHSCst == RHSCst && LHSCC == RHSCC) {
2719 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
2720 // where C is a power of 2
2721 if (LHSCC == ICmpInst::ICMP_ULT &&
2722 LHSCst->getValue().isPowerOf2()) {
2723 Value *NewOr = Builder->CreateOr(Val, Val2);
2724 return new ICmpInst(LHSCC, NewOr, LHSCst);
2725 }
2726
2727 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
2728 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
2729 Value *NewOr = Builder->CreateOr(Val, Val2);
2730 return new ICmpInst(LHSCC, NewOr, LHSCst);
2731 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00002732 }
2733
2734 // From here on, we only handle:
2735 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
2736 if (Val != Val2) return 0;
2737
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002738 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
2739 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
2740 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
2741 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
2742 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
2743 return 0;
2744
2745 // We can't fold (ugt x, C) & (sgt x, C2).
2746 if (!PredicatesFoldable(LHSCC, RHSCC))
2747 return 0;
2748
2749 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00002750 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00002751 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002752 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00002753 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00002754 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002755 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00002756 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
2757
2758 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002759 std::swap(LHS, RHS);
2760 std::swap(LHSCst, RHSCst);
2761 std::swap(LHSCC, RHSCC);
2762 }
2763
2764 // At this point, we know we have have two icmp instructions
2765 // comparing a value against two constants and and'ing the result
2766 // together. Because of the above check, we know that we only have
2767 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
2768 // (from the FoldICmpLogical check above), that the two constants
2769 // are not equal and that the larger constant is on the RHS
2770 assert(LHSCst != RHSCst && "Compares not folded above?");
2771
2772 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002773 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002774 case ICmpInst::ICMP_EQ:
2775 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002776 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002777 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
2778 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
2779 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00002780 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002781 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
2782 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
2783 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
2784 return ReplaceInstUsesWith(I, LHS);
2785 }
2786 case ICmpInst::ICMP_NE:
2787 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002788 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002789 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00002790 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002791 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002792 break; // (X != 13 & X u< 15) -> no change
2793 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00002794 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002795 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002796 break; // (X != 13 & X s< 15) -> no change
2797 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
2798 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
2799 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
2800 return ReplaceInstUsesWith(I, RHS);
2801 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00002802 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00002803 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00002804 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002805 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00002806 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002807 }
2808 break; // (X != 13 & X != 15) -> no change
2809 }
2810 break;
2811 case ICmpInst::ICMP_ULT:
2812 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002813 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002814 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
2815 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00002816 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002817 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
2818 break;
2819 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
2820 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
2821 return ReplaceInstUsesWith(I, LHS);
2822 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
2823 break;
2824 }
2825 break;
2826 case ICmpInst::ICMP_SLT:
2827 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002828 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002829 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
2830 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00002831 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002832 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
2833 break;
2834 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
2835 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
2836 return ReplaceInstUsesWith(I, LHS);
2837 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
2838 break;
2839 }
2840 break;
2841 case ICmpInst::ICMP_UGT:
2842 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002843 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002844 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
2845 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
2846 return ReplaceInstUsesWith(I, RHS);
2847 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
2848 break;
2849 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00002850 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002851 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002852 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00002853 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00002854 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002855 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002856 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
2857 break;
2858 }
2859 break;
2860 case ICmpInst::ICMP_SGT:
2861 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002862 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002863 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
2864 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
2865 return ReplaceInstUsesWith(I, RHS);
2866 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
2867 break;
2868 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00002869 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002870 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002871 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00002872 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00002873 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002874 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002875 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
2876 break;
2877 }
2878 break;
2879 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002880
2881 return 0;
2882}
2883
Chris Lattner42d1be02009-07-23 05:14:02 +00002884Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
2885 FCmpInst *RHS) {
2886
2887 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
2888 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
2889 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
2890 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2891 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2892 // If either of the constants are nans, then the whole thing returns
2893 // false.
2894 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00002895 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002896 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00002897 LHS->getOperand(0), RHS->getOperand(0));
2898 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00002899
2900 // Handle vector zeros. This occurs because the canonical form of
2901 // "fcmp ord x,x" is "fcmp ord x, 0".
2902 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2903 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002904 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00002905 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00002906 return 0;
2907 }
2908
2909 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2910 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2911 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2912
2913
2914 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2915 // Swap RHS operands to match LHS.
2916 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2917 std::swap(Op1LHS, Op1RHS);
2918 }
2919
2920 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2921 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
2922 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002923 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00002924
2925 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner4de84762010-01-04 07:02:48 +00002926 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00002927 if (Op0CC == FCmpInst::FCMP_TRUE)
2928 return ReplaceInstUsesWith(I, RHS);
2929 if (Op1CC == FCmpInst::FCMP_TRUE)
2930 return ReplaceInstUsesWith(I, LHS);
2931
2932 bool Op0Ordered;
2933 bool Op1Ordered;
2934 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2935 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2936 if (Op1Pred == 0) {
2937 std::swap(LHS, RHS);
2938 std::swap(Op0Pred, Op1Pred);
2939 std::swap(Op0Ordered, Op1Ordered);
2940 }
2941 if (Op0Pred == 0) {
2942 // uno && ueq -> uno && (uno || eq) -> ueq
2943 // ord && olt -> ord && (ord && lt) -> olt
2944 if (Op0Ordered == Op1Ordered)
2945 return ReplaceInstUsesWith(I, RHS);
2946
2947 // uno && oeq -> uno && (ord && eq) -> false
2948 // uno && ord -> false
2949 if (!Op0Ordered)
Chris Lattner4de84762010-01-04 07:02:48 +00002950 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00002951 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner4de84762010-01-04 07:02:48 +00002952 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner42d1be02009-07-23 05:14:02 +00002953 }
2954 }
2955
2956 return 0;
2957}
2958
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002959
Chris Lattner7e708292002-06-25 16:13:24 +00002960Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002961 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002962 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002963
Chris Lattnerd06094f2009-11-10 00:55:12 +00002964 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
2965 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002966
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002967 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00002968 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002969 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00002970 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00002971
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002972 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002973 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002974 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002975
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002976 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002977 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002978 Value *Op0LHS = Op0I->getOperand(0);
2979 Value *Op0RHS = Op0I->getOperand(1);
2980 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002981 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002982 case Instruction::Xor:
2983 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00002984 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002985 if (!Op0I->hasOneUse()) break;
2986
2987 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2988 // Not masking anything out for the LHS, move to RHS.
2989 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
2990 Op0RHS->getName()+".masked");
2991 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
2992 }
2993 if (!isa<Constant>(Op0RHS) &&
2994 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2995 // Not masking anything out for the RHS, move to LHS.
2996 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
2997 Op0LHS->getName()+".masked");
2998 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00002999 }
3000
Chris Lattner6e7ba452005-01-01 16:22:27 +00003001 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003002 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003003 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3004 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3005 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3006 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003007 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003008 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003009 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003010 break;
3011
3012 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003013 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3014 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3015 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3016 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003017 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003018
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003019 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3020 // has 1's for all bits that the subtraction with A might affect.
3021 if (Op0I->hasOneUse()) {
3022 uint32_t BitWidth = AndRHSMask.getBitWidth();
3023 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3024 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3025
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003026 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003027 if (!(A && A->isZero()) && // avoid infinite recursion.
3028 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00003029 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003030 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3031 }
3032 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003033 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003034
3035 case Instruction::Shl:
3036 case Instruction::LShr:
3037 // (1 << x) & 1 --> zext(x == 0)
3038 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003039 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00003040 Value *NewICmp =
3041 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003042 return new ZExtInst(NewICmp, I.getType());
3043 }
3044 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003045 }
3046
Chris Lattner58403262003-07-23 19:25:52 +00003047 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003048 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003049 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003050 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003051 // If this is an integer truncation or change from signed-to-unsigned, and
3052 // if the source is an and/or with immediate, transform it. This
3053 // frequently occurs for bitfield accesses.
3054 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003055 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003056 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00003057 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00003058 if (CastOp->getOpcode() == Instruction::And) {
3059 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003060 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3061 // This will fold the two constants together, which may allow
3062 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00003063 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003064 CastOp->getOperand(0), I.getType(),
3065 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00003066 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00003067 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00003068 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003069 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003070 } else if (CastOp->getOpcode() == Instruction::Or) {
3071 // Change: and (cast (or X, C1) to T), C2
3072 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00003073 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00003074 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00003075 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00003076 return ReplaceInstUsesWith(I, AndRHS);
3077 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003078 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003079 }
Chris Lattner06782f82003-07-23 19:36:21 +00003080 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003081
3082 // Try to fold constant and into select arguments.
3083 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003084 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003085 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003086 if (isa<PHINode>(Op0))
3087 if (Instruction *NV = FoldOpIntoPhi(I))
3088 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003089 }
3090
Chris Lattner5b62aa72004-06-18 06:07:51 +00003091
Misha Brukmancb6267b2004-07-30 12:50:08 +00003092 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00003093 if (Value *Op0NotVal = dyn_castNotVal(Op0))
3094 if (Value *Op1NotVal = dyn_castNotVal(Op1))
3095 if (Op0->hasOneUse() && Op1->hasOneUse()) {
3096 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
3097 I.getName()+".demorgan");
3098 return BinaryOperator::CreateNot(Or);
3099 }
3100
Chris Lattner2082ad92006-02-13 23:07:23 +00003101 {
Chris Lattner003b6202007-06-15 05:58:24 +00003102 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00003103 // (A|B) & ~(A&B) -> A^B
3104 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
3105 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
3106 ((A == C && B == D) || (A == D && B == C)))
3107 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003108
Chris Lattnerd06094f2009-11-10 00:55:12 +00003109 // ~(A&B) & (A|B) -> A^B
3110 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
3111 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
3112 ((A == C && B == D) || (A == D && B == C)))
3113 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00003114
3115 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003116 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00003117 if (A == Op1) { // (A^B)&A -> A&(A^B)
3118 I.swapOperands(); // Simplify below
3119 std::swap(Op0, Op1);
3120 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3121 cast<BinaryOperator>(Op0)->swapOperands();
3122 I.swapOperands(); // Simplify below
3123 std::swap(Op0, Op1);
3124 }
3125 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00003126
Chris Lattner64daab52006-04-01 08:03:55 +00003127 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003128 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00003129 if (B == Op0) { // B&(A^B) -> B&(B^A)
3130 cast<BinaryOperator>(Op1)->swapOperands();
3131 std::swap(A, B);
3132 }
Chris Lattner74381062009-08-30 07:44:24 +00003133 if (A == Op0) // A&(A^B) -> A & ~B
3134 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00003135 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00003136
3137 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00003138 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
3139 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00003140 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00003141 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
3142 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00003143 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00003144 }
3145
Reid Spencere4d87aa2006-12-23 06:05:41 +00003146 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3147 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00003148 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003149 return R;
3150
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003151 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
3152 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
3153 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00003154 }
3155
Chris Lattner6fc205f2006-05-05 06:39:07 +00003156 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003157 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3158 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3159 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3160 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00003161 if (SrcTy == Op1C->getOperand(0)->getType() &&
3162 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003163 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003164 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3165 I.getType(), TD) &&
3166 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3167 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00003168 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
3169 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003170 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003171 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003172 }
Chris Lattnere511b742006-11-14 07:46:50 +00003173
3174 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003175 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3176 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3177 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003178 SI0->getOperand(1) == SI1->getOperand(1) &&
3179 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00003180 Value *NewOp =
3181 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
3182 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003183 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003184 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003185 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003186 }
3187
Evan Cheng8db90722008-10-14 17:15:11 +00003188 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00003189 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00003190 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
3191 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
3192 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00003193 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003194
Chris Lattner7e708292002-06-25 16:13:24 +00003195 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003196}
3197
Chris Lattner8c34cd22008-10-05 02:13:19 +00003198/// CollectBSwapParts - Analyze the specified subexpression and see if it is
3199/// capable of providing pieces of a bswap. The subexpression provides pieces
3200/// of a bswap if it is proven that each of the non-zero bytes in the output of
3201/// the expression came from the corresponding "byte swapped" byte in some other
3202/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
3203/// we know that the expression deposits the low byte of %X into the high byte
3204/// of the bswap result and that all other bytes are zero. This expression is
3205/// accepted, the high byte of ByteValues is set to X to indicate a correct
3206/// match.
3207///
3208/// This function returns true if the match was unsuccessful and false if so.
3209/// On entry to the function the "OverallLeftShift" is a signed integer value
3210/// indicating the number of bytes that the subexpression is later shifted. For
3211/// example, if the expression is later right shifted by 16 bits, the
3212/// OverallLeftShift value would be -2 on entry. This is used to specify which
3213/// byte of ByteValues is actually being set.
3214///
3215/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
3216/// byte is masked to zero by a user. For example, in (X & 255), X will be
3217/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
3218/// this function to working on up to 32-byte (256 bit) values. ByteMask is
3219/// always in the local (OverallLeftShift) coordinate space.
3220///
3221static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
3222 SmallVector<Value*, 8> &ByteValues) {
3223 if (Instruction *I = dyn_cast<Instruction>(V)) {
3224 // If this is an or instruction, it may be an inner node of the bswap.
3225 if (I->getOpcode() == Instruction::Or) {
3226 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3227 ByteValues) ||
3228 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
3229 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003230 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00003231
3232 // If this is a logical shift by a constant multiple of 8, recurse with
3233 // OverallLeftShift and ByteMask adjusted.
3234 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
3235 unsigned ShAmt =
3236 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
3237 // Ensure the shift amount is defined and of a byte value.
3238 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
3239 return true;
3240
3241 unsigned ByteShift = ShAmt >> 3;
3242 if (I->getOpcode() == Instruction::Shl) {
3243 // X << 2 -> collect(X, +2)
3244 OverallLeftShift += ByteShift;
3245 ByteMask >>= ByteShift;
3246 } else {
3247 // X >>u 2 -> collect(X, -2)
3248 OverallLeftShift -= ByteShift;
3249 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00003250 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00003251 }
3252
3253 if (OverallLeftShift >= (int)ByteValues.size()) return true;
3254 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
3255
3256 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3257 ByteValues);
3258 }
3259
3260 // If this is a logical 'and' with a mask that clears bytes, clear the
3261 // corresponding bytes in ByteMask.
3262 if (I->getOpcode() == Instruction::And &&
3263 isa<ConstantInt>(I->getOperand(1))) {
3264 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
3265 unsigned NumBytes = ByteValues.size();
3266 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
3267 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
3268
3269 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
3270 // If this byte is masked out by a later operation, we don't care what
3271 // the and mask is.
3272 if ((ByteMask & (1 << i)) == 0)
3273 continue;
3274
3275 // If the AndMask is all zeros for this byte, clear the bit.
3276 APInt MaskB = AndMask & Byte;
3277 if (MaskB == 0) {
3278 ByteMask &= ~(1U << i);
3279 continue;
3280 }
3281
3282 // If the AndMask is not all ones for this byte, it's not a bytezap.
3283 if (MaskB != Byte)
3284 return true;
3285
3286 // Otherwise, this byte is kept.
3287 }
3288
3289 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
3290 ByteValues);
3291 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00003292 }
3293
Chris Lattner8c34cd22008-10-05 02:13:19 +00003294 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
3295 // the input value to the bswap. Some observations: 1) if more than one byte
3296 // is demanded from this input, then it could not be successfully assembled
3297 // into a byteswap. At least one of the two bytes would not be aligned with
3298 // their ultimate destination.
3299 if (!isPowerOf2_32(ByteMask)) return true;
3300 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003301
Chris Lattner8c34cd22008-10-05 02:13:19 +00003302 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
3303 // is demanded, it needs to go into byte 0 of the result. This means that the
3304 // byte needs to be shifted until it lands in the right byte bucket. The
3305 // shift amount depends on the position: if the byte is coming from the high
3306 // part of the value (e.g. byte 3) then it must be shifted right. If from the
3307 // low part, it must be shifted left.
3308 unsigned DestByteNo = InputByteNo + OverallLeftShift;
3309 if (InputByteNo < ByteValues.size()/2) {
3310 if (ByteValues.size()-1-DestByteNo != InputByteNo)
3311 return true;
3312 } else {
3313 if (ByteValues.size()-1-DestByteNo != InputByteNo)
3314 return true;
3315 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00003316
3317 // If the destination byte value is already defined, the values are or'd
3318 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00003319 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003320 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00003321 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003322 return false;
3323}
3324
3325/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3326/// If so, insert the new bswap intrinsic and return it.
3327Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003328 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00003329 if (!ITy || ITy->getBitWidth() % 16 ||
3330 // ByteMask only allows up to 32-byte values.
3331 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00003332 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003333
3334 /// ByteValues - For each byte of the result, we keep track of which value
3335 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003336 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003337 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003338
3339 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00003340 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
3341 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00003342 return 0;
3343
3344 // Check to see if all of the bytes come from the same value.
3345 Value *V = ByteValues[0];
3346 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3347
3348 // Check to make sure that all of the bytes come from the same value.
3349 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3350 if (ByteValues[i] != V)
3351 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003352 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003353 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003354 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00003355 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003356}
3357
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003358/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
3359/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
3360/// we can simplify this expression to "cond ? C : D or B".
3361static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner4de84762010-01-04 07:02:48 +00003362 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00003363 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00003364 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00003365 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003366 return 0;
3367
Chris Lattnera6a474d2008-11-16 04:26:55 +00003368 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00003369 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003370 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00003371 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003372 return SelectInst::Create(Cond, C, B);
3373 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00003374 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003375 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00003376 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00003377 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003378 return 0;
3379}
Chris Lattnerafe91a52006-06-15 19:07:26 +00003380
Chris Lattner69d4ced2008-11-16 05:20:07 +00003381/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
3382Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
3383 ICmpInst *LHS, ICmpInst *RHS) {
3384 Value *Val, *Val2;
3385 ConstantInt *LHSCst, *RHSCst;
3386 ICmpInst::Predicate LHSCC, RHSCC;
3387
3388 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00003389 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3390 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00003391 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00003392
3393
3394 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
3395 if (LHSCst == RHSCst && LHSCC == RHSCC &&
3396 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
3397 Value *NewOr = Builder->CreateOr(Val, Val2);
3398 return new ICmpInst(LHSCC, NewOr, LHSCst);
3399 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00003400
3401 // From here on, we only handle:
3402 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
3403 if (Val != Val2) return 0;
3404
3405 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3406 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3407 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3408 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3409 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3410 return 0;
3411
3412 // We can't fold (ugt x, C) | (sgt x, C2).
3413 if (!PredicatesFoldable(LHSCC, RHSCC))
3414 return 0;
3415
3416 // Ensure that the larger constant is on the RHS.
3417 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00003418 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00003419 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00003420 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00003421 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3422 else
3423 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3424
3425 if (ShouldSwap) {
3426 std::swap(LHS, RHS);
3427 std::swap(LHSCst, RHSCst);
3428 std::swap(LHSCC, RHSCC);
3429 }
3430
3431 // At this point, we know we have have two icmp instructions
3432 // comparing a value against two constants and or'ing the result
3433 // together. Because of the above check, we know that we only have
3434 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3435 // FoldICmpLogical check above), that the two constants are not
3436 // equal.
3437 assert(LHSCst != RHSCst && "Compares not folded above?");
3438
3439 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003440 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003441 case ICmpInst::ICMP_EQ:
3442 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003443 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003444 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00003445 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003446 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00003447 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003448 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00003449 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003450 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00003451 }
3452 break; // (X == 13 | X == 15) -> no change
3453 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3454 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
3455 break;
3456 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3457 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3458 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
3459 return ReplaceInstUsesWith(I, RHS);
3460 }
3461 break;
3462 case ICmpInst::ICMP_NE:
3463 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003464 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003465 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3466 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3467 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
3468 return ReplaceInstUsesWith(I, LHS);
3469 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3470 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3471 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00003472 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00003473 }
3474 break;
3475 case ICmpInst::ICMP_ULT:
3476 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003477 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003478 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
3479 break;
3480 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
3481 // If RHSCst is [us]MAXINT, it is always false. Not handling
3482 // this can cause overflow.
3483 if (RHSCst->isMaxValue(false))
3484 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00003485 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003486 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00003487 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3488 break;
3489 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3490 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
3491 return ReplaceInstUsesWith(I, RHS);
3492 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3493 break;
3494 }
3495 break;
3496 case ICmpInst::ICMP_SLT:
3497 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003498 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003499 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3500 break;
3501 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
3502 // If RHSCst is [us]MAXINT, it is always false. Not handling
3503 // this can cause overflow.
3504 if (RHSCst->isMaxValue(true))
3505 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00003506 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003507 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00003508 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3509 break;
3510 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3511 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3512 return ReplaceInstUsesWith(I, RHS);
3513 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3514 break;
3515 }
3516 break;
3517 case ICmpInst::ICMP_UGT:
3518 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003519 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003520 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3521 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3522 return ReplaceInstUsesWith(I, LHS);
3523 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3524 break;
3525 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3526 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00003527 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00003528 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3529 break;
3530 }
3531 break;
3532 case ICmpInst::ICMP_SGT:
3533 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003534 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00003535 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3536 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3537 return ReplaceInstUsesWith(I, LHS);
3538 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3539 break;
3540 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3541 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00003542 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00003543 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3544 break;
3545 }
3546 break;
3547 }
3548 return 0;
3549}
3550
Chris Lattner5414cc52009-07-23 05:46:22 +00003551Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
3552 FCmpInst *RHS) {
3553 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
3554 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
3555 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
3556 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3557 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3558 // If either of the constants are nans, then the whole thing returns
3559 // true.
3560 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00003561 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00003562
3563 // Otherwise, no need to compare the two constants, compare the
3564 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003565 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00003566 LHS->getOperand(0), RHS->getOperand(0));
3567 }
3568
3569 // Handle vector zeros. This occurs because the canonical form of
3570 // "fcmp uno x,x" is "fcmp uno x, 0".
3571 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3572 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003573 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00003574 LHS->getOperand(0), RHS->getOperand(0));
3575
3576 return 0;
3577 }
3578
3579 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3580 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3581 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3582
3583 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3584 // Swap RHS operands to match LHS.
3585 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3586 std::swap(Op1LHS, Op1RHS);
3587 }
3588 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3589 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
3590 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003591 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00003592 Op0LHS, Op0RHS);
3593 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner4de84762010-01-04 07:02:48 +00003594 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00003595 if (Op0CC == FCmpInst::FCMP_FALSE)
3596 return ReplaceInstUsesWith(I, RHS);
3597 if (Op1CC == FCmpInst::FCMP_FALSE)
3598 return ReplaceInstUsesWith(I, LHS);
3599 bool Op0Ordered;
3600 bool Op1Ordered;
3601 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3602 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3603 if (Op0Ordered == Op1Ordered) {
3604 // If both are ordered or unordered, return a new fcmp with
3605 // or'ed predicates.
Chris Lattner4de84762010-01-04 07:02:48 +00003606 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +00003607 if (Instruction *I = dyn_cast<Instruction>(RV))
3608 return I;
3609 // Otherwise, it's a constant boolean value...
3610 return ReplaceInstUsesWith(I, RV);
3611 }
3612 }
3613 return 0;
3614}
3615
Bill Wendlinga698a472008-12-01 08:23:25 +00003616/// FoldOrWithConstants - This helper function folds:
3617///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00003618/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00003619///
3620/// into:
3621///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00003622/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00003623///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00003624/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00003625Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00003626 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00003627 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
3628 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00003629
Bill Wendling286a0542008-12-02 06:24:20 +00003630 Value *V1 = 0;
3631 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00003632 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00003633
Bill Wendling29976b92008-12-02 06:18:11 +00003634 APInt Xor = CI1->getValue() ^ CI2->getValue();
3635 if (!Xor.isAllOnesValue()) return 0;
3636
Bill Wendling286a0542008-12-02 06:24:20 +00003637 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00003638 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00003639 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00003640 }
3641
3642 return 0;
3643}
3644
Chris Lattner7e708292002-06-25 16:13:24 +00003645Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003646 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003647 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003648
Chris Lattnerd06094f2009-11-10 00:55:12 +00003649 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
3650 return ReplaceInstUsesWith(I, V);
3651
3652
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003653 // See if we can simplify any instructions used by the instruction whose sole
3654 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003655 if (SimplifyDemandedInstructionBits(I))
3656 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003657
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003658 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003659 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003660 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00003661 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003662 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00003663 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003664 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003665 return BinaryOperator::CreateAnd(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00003666 ConstantInt::get(I.getContext(),
3667 RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003668 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003669
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003670 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00003671 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003672 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00003673 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003674 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003675 return BinaryOperator::CreateXor(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00003676 ConstantInt::get(I.getContext(),
3677 C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003678 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003679
3680 // Try to fold constant and into select arguments.
3681 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003682 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003683 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003684 if (isa<PHINode>(Op0))
3685 if (Instruction *NV = FoldOpIntoPhi(I))
3686 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003687 }
3688
Chris Lattner4f637d42006-01-06 17:59:59 +00003689 Value *A = 0, *B = 0;
3690 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003691
Chris Lattner6423d4c2006-07-10 20:25:24 +00003692 // (A | B) | C and A | (B | C) -> bswap if possible.
3693 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00003694 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3695 match(Op1, m_Or(m_Value(), m_Value())) ||
3696 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3697 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003698 if (Instruction *BSwap = MatchBSwap(I))
3699 return BSwap;
3700 }
3701
Chris Lattner6e4c6492005-05-09 04:58:36 +00003702 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003703 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003704 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003705 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00003706 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00003707 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003708 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003709 }
3710
3711 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003712 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003713 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003714 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00003715 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00003716 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003717 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003718 }
3719
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003720 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00003721 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00003722 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3723 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003724 Value *V1 = 0, *V2 = 0, *V3 = 0;
3725 C1 = dyn_cast<ConstantInt>(C);
3726 C2 = dyn_cast<ConstantInt>(D);
3727 if (C1 && C2) { // (A & C1)|(B & C2)
3728 // If we have: ((V + N) & C1) | (V & C2)
3729 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3730 // replace with V+N.
3731 if (C1->getValue() == ~C2->getValue()) {
3732 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00003733 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003734 // Add commutes, try both ways.
3735 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3736 return ReplaceInstUsesWith(I, A);
3737 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3738 return ReplaceInstUsesWith(I, A);
3739 }
3740 // Or commutes, try both ways.
3741 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003742 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003743 // Add commutes, try both ways.
3744 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3745 return ReplaceInstUsesWith(I, B);
3746 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3747 return ReplaceInstUsesWith(I, B);
3748 }
3749 }
Chris Lattnere4412c12010-01-04 06:03:59 +00003750
3751 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
3752 // iff (C1&C2) == 0 and (N&~C1) == 0
3753 if ((C1->getValue() & C2->getValue()) == 0) {
3754 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
3755 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
3756 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
3757 return BinaryOperator::CreateAnd(A,
3758 ConstantInt::get(A->getContext(),
3759 C1->getValue()|C2->getValue()));
3760 // Or commutes, try both ways.
3761 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
3762 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
3763 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
3764 return BinaryOperator::CreateAnd(B,
3765 ConstantInt::get(B->getContext(),
3766 C1->getValue()|C2->getValue()));
3767 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00003768 }
3769
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003770 // Check to see if we have any common things being and'ed. If so, find the
3771 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003772 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
Chris Lattnere4412c12010-01-04 06:03:59 +00003773 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003774 if (A == B) // (A & C)|(A & D) == A & (C|D)
3775 V1 = A, V2 = C, V3 = D;
3776 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3777 V1 = A, V2 = B, V3 = C;
3778 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3779 V1 = C, V2 = A, V3 = D;
3780 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3781 V1 = C, V2 = A, V3 = B;
3782
3783 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00003784 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003785 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003786 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003787 }
Dan Gohmanb493b272008-10-28 22:38:57 +00003788
Dan Gohman1975d032008-10-30 20:40:10 +00003789 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner4de84762010-01-04 07:02:48 +00003790 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003791 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00003792 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003793 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00003794 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003795 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00003796 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00003797 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00003798
Bill Wendlingb01865c2008-11-30 13:52:49 +00003799 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003800 if ((match(C, m_Not(m_Specific(D))) &&
3801 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003802 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00003803 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003804 if ((match(A, m_Not(m_Specific(D))) &&
3805 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003806 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00003807 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003808 if ((match(C, m_Not(m_Specific(B))) &&
3809 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003810 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00003811 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00003812 if ((match(A, m_Not(m_Specific(B))) &&
3813 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00003814 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003815 }
Chris Lattnere511b742006-11-14 07:46:50 +00003816
3817 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003818 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3819 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3820 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003821 SI0->getOperand(1) == SI1->getOperand(1) &&
3822 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00003823 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
3824 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003825 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003826 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003827 }
3828 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003829
Bill Wendlingb3833d12008-12-01 01:07:11 +00003830 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00003831 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
3832 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00003833 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00003834 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00003835 }
3836 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00003837 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
3838 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00003839 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00003840 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00003841 }
3842
Chris Lattnerd06094f2009-11-10 00:55:12 +00003843 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3844 if (Value *Op0NotVal = dyn_castNotVal(Op0))
3845 if (Value *Op1NotVal = dyn_castNotVal(Op1))
3846 if (Op0->hasOneUse() && Op1->hasOneUse()) {
3847 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
3848 I.getName()+".demorgan");
3849 return BinaryOperator::CreateNot(And);
3850 }
Chris Lattnera2881962003-02-18 19:28:33 +00003851
Reid Spencere4d87aa2006-12-23 06:05:41 +00003852 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3853 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00003854 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003855 return R;
3856
Chris Lattner69d4ced2008-11-16 05:20:07 +00003857 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
3858 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
3859 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003860 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003861
3862 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00003863 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003864 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003865 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00003866 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
3867 !isa<ICmpInst>(Op1C->getOperand(0))) {
3868 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00003869 if (SrcTy == Op1C->getOperand(0)->getType() &&
3870 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00003871 // Only do this if the casts both really cause code to be
3872 // generated.
3873 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3874 I.getType(), TD) &&
3875 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3876 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00003877 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
3878 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003879 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00003880 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003881 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003882 }
Chris Lattner99c65742007-10-24 05:38:08 +00003883 }
3884
3885
3886 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
3887 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00003888 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
3889 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
3890 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00003891 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003892
Chris Lattner7e708292002-06-25 16:13:24 +00003893 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003894}
3895
Dan Gohman844731a2008-05-13 00:00:25 +00003896namespace {
3897
Chris Lattnerc317d392004-02-16 01:20:27 +00003898// XorSelf - Implements: X ^ X --> 0
3899struct XorSelf {
3900 Value *RHS;
3901 XorSelf(Value *rhs) : RHS(rhs) {}
3902 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3903 Instruction *apply(BinaryOperator &Xor) const {
3904 return &Xor;
3905 }
3906};
Chris Lattner3f5b8772002-05-06 16:14:14 +00003907
Dan Gohman844731a2008-05-13 00:00:25 +00003908}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003909
Chris Lattner7e708292002-06-25 16:13:24 +00003910Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003911 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003912 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003913
Evan Chengd34af782008-03-25 20:07:13 +00003914 if (isa<UndefValue>(Op1)) {
3915 if (isa<UndefValue>(Op0))
3916 // Handle undef ^ undef -> 0 special case. This is a common
3917 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00003918 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003919 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00003920 }
Chris Lattnere87597f2004-10-16 18:11:37 +00003921
Chris Lattnerc317d392004-02-16 01:20:27 +00003922 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00003923 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00003924 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00003925 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00003926 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003927
3928 // See if we can simplify any instructions used by the instruction whose sole
3929 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003930 if (SimplifyDemandedInstructionBits(I))
3931 return &I;
3932 if (isa<VectorType>(I.getType()))
3933 if (isa<ConstantAggregateZero>(Op1))
3934 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00003935
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003936 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00003937 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003938 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
3939 if (Op0I->getOpcode() == Instruction::And ||
3940 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00003941 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
3942 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
3943 if (dyn_castNotVal(Op0I->getOperand(1)))
3944 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00003945 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00003946 Value *NotY =
3947 Builder->CreateNot(Op0I->getOperand(1),
3948 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003949 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003950 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00003951 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003952 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00003953
3954 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
3955 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
3956 if (isFreeToInvert(Op0I->getOperand(0)) &&
3957 isFreeToInvert(Op0I->getOperand(1))) {
3958 Value *NotX =
3959 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
3960 Value *NotY =
3961 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
3962 if (Op0I->getOpcode() == Instruction::And)
3963 return BinaryOperator::CreateOr(NotX, NotY);
3964 return BinaryOperator::CreateAnd(NotX, NotY);
3965 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003966 }
3967 }
3968 }
3969
3970
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003971 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00003972 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00003973 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003974 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003975 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00003976 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00003977
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003978 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003979 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00003980 FCI->getOperand(0), FCI->getOperand(1));
3981 }
3982
Nick Lewycky517e1f52008-05-31 19:01:33 +00003983 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
3984 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3985 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
3986 if (CI->hasOneUse() && Op0C->hasOneUse()) {
3987 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00003988 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
3989 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner4de84762010-01-04 07:02:48 +00003990 ConstantInt::getTrue(I.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +00003991 Op0C->getDestTy()))) {
3992 CI->setPredicate(CI->getInversePredicate());
3993 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00003994 }
3995 }
3996 }
3997 }
3998
Reid Spencere4d87aa2006-12-23 06:05:41 +00003999 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004000 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004001 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4002 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004003 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4004 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00004005 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004006 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004007 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004008
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004009 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004010 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004011 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004012 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004013 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004014 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00004015 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00004016 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00004017 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004018 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004019 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner4de84762010-01-04 07:02:48 +00004020 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00004021 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004022 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004023
Chris Lattner7c4049c2004-01-12 19:35:11 +00004024 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004025 } else if (Op0I->getOpcode() == Instruction::Or) {
4026 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004027 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004028 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004029 // Anything in both C1 and C2 is known to be zero, remove it from
4030 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00004031 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4032 NewRHS = ConstantExpr::getAnd(NewRHS,
4033 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00004034 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004035 I.setOperand(0, Op0I->getOperand(0));
4036 I.setOperand(1, NewRHS);
4037 return &I;
4038 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004039 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004040 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004041 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004042
4043 // Try to fold constant and into select arguments.
4044 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004045 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004046 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004047 if (isa<PHINode>(Op0))
4048 if (Instruction *NV = FoldOpIntoPhi(I))
4049 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004050 }
4051
Dan Gohman186a6362009-08-12 16:04:34 +00004052 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004053 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00004054 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004055
Dan Gohman186a6362009-08-12 16:04:34 +00004056 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004057 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00004058 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004059
Chris Lattner318bf792007-03-18 22:51:34 +00004060
4061 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4062 if (Op1I) {
4063 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00004064 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00004065 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004066 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004067 I.swapOperands();
4068 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004069 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004070 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004071 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004072 }
Dan Gohman4ae51262009-08-12 16:23:25 +00004073 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00004074 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00004075 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00004076 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00004077 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004078 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004079 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004080 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004081 std::swap(A, B);
4082 }
Chris Lattner318bf792007-03-18 22:51:34 +00004083 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004084 I.swapOperands(); // Simplified below.
4085 std::swap(Op0, Op1);
4086 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004087 }
Chris Lattner318bf792007-03-18 22:51:34 +00004088 }
4089
4090 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4091 if (Op0I) {
4092 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00004093 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004094 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00004095 if (A == Op1) // (B|A)^B == (A|B)^B
4096 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00004097 if (B == Op1) // (A|B)^B == A & ~B
4098 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00004099 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00004100 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00004101 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00004102 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00004103 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004104 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00004105 if (A == Op1) // (A&B)^A -> (B&A)^A
4106 std::swap(A, B);
4107 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004108 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00004109 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004110 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004111 }
Chris Lattner318bf792007-03-18 22:51:34 +00004112 }
4113
4114 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4115 if (Op0I && Op1I && Op0I->isShift() &&
4116 Op0I->getOpcode() == Op1I->getOpcode() &&
4117 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4118 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004119 Value *NewOp =
4120 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
4121 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004122 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004123 Op1I->getOperand(1));
4124 }
4125
4126 if (Op0I && Op1I) {
4127 Value *A, *B, *C, *D;
4128 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00004129 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4130 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00004131 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004132 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004133 }
4134 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00004135 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4136 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00004137 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004138 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004139 }
4140
4141 // (A & B)^(C & D)
4142 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004143 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4144 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00004145 // (X & Y)^(X & Y) -> (Y^Z) & X
4146 Value *X = 0, *Y = 0, *Z = 0;
4147 if (A == C)
4148 X = A, Y = B, Z = D;
4149 else if (A == D)
4150 X = A, Y = B, Z = C;
4151 else if (B == C)
4152 X = B, Y = A, Z = D;
4153 else if (B == D)
4154 X = B, Y = A, Z = C;
4155
4156 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00004157 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004158 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004159 }
4160 }
4161 }
4162
Reid Spencere4d87aa2006-12-23 06:05:41 +00004163 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4164 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00004165 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004166 return R;
4167
Chris Lattner6fc205f2006-05-05 06:39:07 +00004168 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004169 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004170 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004171 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4172 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004173 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004174 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004175 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4176 I.getType(), TD) &&
4177 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4178 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004179 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
4180 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004181 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004182 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004183 }
Chris Lattner99c65742007-10-24 05:38:08 +00004184 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00004185
Chris Lattner7e708292002-06-25 16:13:24 +00004186 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004187}
4188
Chris Lattner4de84762010-01-04 07:02:48 +00004189static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004190 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00004191}
Chris Lattnera96879a2004-09-29 17:40:11 +00004192
Dan Gohman6de29f82009-06-15 22:12:54 +00004193static bool HasAddOverflow(ConstantInt *Result,
4194 ConstantInt *In1, ConstantInt *In2,
4195 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00004196 if (IsSigned)
4197 if (In2->getValue().isNegative())
4198 return Result->getValue().sgt(In1->getValue());
4199 else
4200 return Result->getValue().slt(In1->getValue());
4201 else
4202 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004203}
4204
Dan Gohman6de29f82009-06-15 22:12:54 +00004205/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00004206/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00004207static bool AddWithOverflow(Constant *&Result, Constant *In1,
Chris Lattner4de84762010-01-04 07:02:48 +00004208 Constant *In2, bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004209 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00004210
Dan Gohman6de29f82009-06-15 22:12:54 +00004211 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
4212 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Chris Lattner4de84762010-01-04 07:02:48 +00004213 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
4214 if (HasAddOverflow(ExtractElement(Result, Idx),
4215 ExtractElement(In1, Idx),
4216 ExtractElement(In2, Idx),
Dan Gohman6de29f82009-06-15 22:12:54 +00004217 IsSigned))
4218 return true;
4219 }
4220 return false;
4221 }
4222
4223 return HasAddOverflow(cast<ConstantInt>(Result),
4224 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
4225 IsSigned);
4226}
4227
4228static bool HasSubOverflow(ConstantInt *Result,
4229 ConstantInt *In1, ConstantInt *In2,
4230 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00004231 if (IsSigned)
4232 if (In2->getValue().isNegative())
4233 return Result->getValue().slt(In1->getValue());
4234 else
4235 return Result->getValue().sgt(In1->getValue());
4236 else
4237 return Result->getValue().ugt(In1->getValue());
4238}
4239
Dan Gohman6de29f82009-06-15 22:12:54 +00004240/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
4241/// overflowed for this type.
4242static bool SubWithOverflow(Constant *&Result, Constant *In1,
Chris Lattner4de84762010-01-04 07:02:48 +00004243 Constant *In2, bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004244 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00004245
4246 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
4247 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Chris Lattner4de84762010-01-04 07:02:48 +00004248 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
4249 if (HasSubOverflow(ExtractElement(Result, Idx),
4250 ExtractElement(In1, Idx),
4251 ExtractElement(In2, Idx),
Dan Gohman6de29f82009-06-15 22:12:54 +00004252 IsSigned))
4253 return true;
4254 }
4255 return false;
4256 }
4257
4258 return HasSubOverflow(cast<ConstantInt>(Result),
4259 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
4260 IsSigned);
4261}
4262
Chris Lattner10c0d912008-04-22 02:53:33 +00004263
Reid Spencere4d87aa2006-12-23 06:05:41 +00004264/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004265/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00004266Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004267 ICmpInst::Predicate Cond,
4268 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00004269 // Look through bitcasts.
4270 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4271 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004272
Chris Lattner574da9b2005-01-13 20:14:25 +00004273 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00004274 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004275 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00004276 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00004277 // know pointers can't overflow since the gep is inbounds. See if we can
4278 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00004279 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4280
4281 // If not, synthesize the offset the hard way.
4282 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00004283 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004284 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00004285 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00004286 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004287 // If the base pointers are different, but the indices are the same, just
4288 // compare the base pointer.
4289 if (PtrBase != GEPRHS->getOperand(0)) {
4290 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004291 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004292 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004293 if (IndicesTheSame)
4294 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4295 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4296 IndicesTheSame = false;
4297 break;
4298 }
4299
4300 // If all indices are the same, just compare the base pointers.
4301 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004302 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00004303 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004304
4305 // Otherwise, the base pointers are different and the indices are
4306 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004307 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004308 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004309
Chris Lattnere9d782b2005-01-13 22:25:21 +00004310 // If one of the GEPs has all zero indices, recurse.
4311 bool AllZeros = true;
4312 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4313 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4314 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4315 AllZeros = false;
4316 break;
4317 }
4318 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004319 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4320 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004321
4322 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004323 AllZeros = true;
4324 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4325 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4326 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4327 AllZeros = false;
4328 break;
4329 }
4330 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004331 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004332
Chris Lattner4401c9c2005-01-14 00:20:05 +00004333 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4334 // If the GEPs only differ by one index, compare it.
4335 unsigned NumDifferences = 0; // Keep track of # differences.
4336 unsigned DiffOperand = 0; // The operand that differs.
4337 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4338 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004339 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4340 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004341 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004342 NumDifferences = 2;
4343 break;
4344 } else {
4345 if (NumDifferences++) break;
4346 DiffOperand = i;
4347 }
4348 }
4349
4350 if (NumDifferences == 0) // SAME GEP?
4351 return ReplaceInstUsesWith(I, // No comparison is needed here.
Chris Lattner4de84762010-01-04 07:02:48 +00004352 ConstantInt::get(Type::getInt1Ty(I.getContext()),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00004353 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00004354
Chris Lattner4401c9c2005-01-14 00:20:05 +00004355 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004356 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4357 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004358 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004359 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004360 }
4361 }
4362
Reid Spencere4d87aa2006-12-23 06:05:41 +00004363 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004364 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004365 if (TD &&
4366 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00004367 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4368 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00004369 Value *L = EmitGEPOffset(GEPLHS, *this);
4370 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004371 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004372 }
4373 }
4374 return 0;
4375}
4376
Chris Lattnera5406232008-05-19 20:18:56 +00004377/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4378///
4379Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4380 Instruction *LHSI,
4381 Constant *RHSC) {
4382 if (!isa<ConstantFP>(RHSC)) return 0;
4383 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4384
4385 // Get the width of the mantissa. We don't want to hack on conversions that
4386 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00004387 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00004388 if (MantissaWidth == -1) return 0; // Unknown.
4389
4390 // Check to see that the input is converted from an integer type that is small
4391 // enough that preserves all bits. TODO: check here for "known" sign bits.
4392 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00004393 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00004394
4395 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00004396 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
4397 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00004398 ++InputSize;
4399
4400 // If the conversion would lose info, don't hack on this.
4401 if ((int)InputSize > MantissaWidth)
4402 return 0;
4403
4404 // Otherwise, we can potentially simplify the comparison. We know that it
4405 // will always come through as an integer value and we know the constant is
4406 // not a NAN (it would have been previously simplified).
4407 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4408
4409 ICmpInst::Predicate Pred;
4410 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004411 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00004412 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00004413 case FCmpInst::FCMP_OEQ:
4414 Pred = ICmpInst::ICMP_EQ;
4415 break;
Chris Lattnera5406232008-05-19 20:18:56 +00004416 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00004417 case FCmpInst::FCMP_OGT:
4418 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4419 break;
Chris Lattnera5406232008-05-19 20:18:56 +00004420 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00004421 case FCmpInst::FCMP_OGE:
4422 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4423 break;
Chris Lattnera5406232008-05-19 20:18:56 +00004424 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00004425 case FCmpInst::FCMP_OLT:
4426 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4427 break;
Chris Lattnera5406232008-05-19 20:18:56 +00004428 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00004429 case FCmpInst::FCMP_OLE:
4430 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4431 break;
Chris Lattnera5406232008-05-19 20:18:56 +00004432 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00004433 case FCmpInst::FCMP_ONE:
4434 Pred = ICmpInst::ICMP_NE;
4435 break;
Chris Lattnera5406232008-05-19 20:18:56 +00004436 case FCmpInst::FCMP_ORD:
Chris Lattner4de84762010-01-04 07:02:48 +00004437 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattnera5406232008-05-19 20:18:56 +00004438 case FCmpInst::FCMP_UNO:
Chris Lattner4de84762010-01-04 07:02:48 +00004439 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattnera5406232008-05-19 20:18:56 +00004440 }
4441
4442 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4443
4444 // Now we know that the APFloat is a normal number, zero or inf.
4445
Chris Lattner85162782008-05-20 03:50:52 +00004446 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00004447 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00004448 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00004449
Bill Wendlingc143bcf2008-11-09 04:26:50 +00004450 if (!LHSUnsigned) {
4451 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4452 // and large values.
4453 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4454 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4455 APFloat::rmNearestTiesToEven);
4456 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4457 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4458 Pred == ICmpInst::ICMP_SLE)
Chris Lattner4de84762010-01-04 07:02:48 +00004459 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
4460 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00004461 }
4462 } else {
4463 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4464 // +INF and large values.
4465 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
4466 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4467 APFloat::rmNearestTiesToEven);
4468 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4469 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4470 Pred == ICmpInst::ICMP_ULE)
Chris Lattner4de84762010-01-04 07:02:48 +00004471 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
4472 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00004473 }
Chris Lattnera5406232008-05-19 20:18:56 +00004474 }
4475
Bill Wendlingc143bcf2008-11-09 04:26:50 +00004476 if (!LHSUnsigned) {
4477 // See if the RHS value is < SignedMin.
4478 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4479 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4480 APFloat::rmNearestTiesToEven);
4481 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4482 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4483 Pred == ICmpInst::ICMP_SGE)
Chris Lattner4de84762010-01-04 07:02:48 +00004484 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
4485 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00004486 }
Chris Lattnera5406232008-05-19 20:18:56 +00004487 }
4488
Bill Wendlingc143bcf2008-11-09 04:26:50 +00004489 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4490 // [0, UMAX], but it may still be fractional. See if it is fractional by
4491 // casting the FP value to the integer value and back, checking for equality.
4492 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00004493 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00004494 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4495 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00004496 if (!RHS.isZero()) {
4497 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00004498 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4499 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00004500 if (!Equal) {
4501 // If we had a comparison against a fractional value, we have to adjust
4502 // the compare predicate and sometimes the value. RHSC is rounded towards
4503 // zero at this point.
4504 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004505 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00004506 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Chris Lattner4de84762010-01-04 07:02:48 +00004507 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00004508 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Chris Lattner4de84762010-01-04 07:02:48 +00004509 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00004510 case ICmpInst::ICMP_ULE:
4511 // (float)int <= 4.4 --> int <= 4
4512 // (float)int <= -4.4 --> false
4513 if (RHS.isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00004514 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00004515 break;
4516 case ICmpInst::ICMP_SLE:
4517 // (float)int <= 4.4 --> int <= 4
4518 // (float)int <= -4.4 --> int < -4
4519 if (RHS.isNegative())
4520 Pred = ICmpInst::ICMP_SLT;
4521 break;
4522 case ICmpInst::ICMP_ULT:
4523 // (float)int < -4.4 --> false
4524 // (float)int < 4.4 --> int <= 4
4525 if (RHS.isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00004526 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00004527 Pred = ICmpInst::ICMP_ULE;
4528 break;
4529 case ICmpInst::ICMP_SLT:
4530 // (float)int < -4.4 --> int < -4
4531 // (float)int < 4.4 --> int <= 4
4532 if (!RHS.isNegative())
4533 Pred = ICmpInst::ICMP_SLE;
4534 break;
4535 case ICmpInst::ICMP_UGT:
4536 // (float)int > 4.4 --> int > 4
4537 // (float)int > -4.4 --> true
4538 if (RHS.isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00004539 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00004540 break;
4541 case ICmpInst::ICMP_SGT:
4542 // (float)int > 4.4 --> int > 4
4543 // (float)int > -4.4 --> int >= -4
4544 if (RHS.isNegative())
4545 Pred = ICmpInst::ICMP_SGE;
4546 break;
4547 case ICmpInst::ICMP_UGE:
4548 // (float)int >= -4.4 --> true
4549 // (float)int >= 4.4 --> int > 4
4550 if (!RHS.isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00004551 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00004552 Pred = ICmpInst::ICMP_UGT;
4553 break;
4554 case ICmpInst::ICMP_SGE:
4555 // (float)int >= -4.4 --> int >= -4
4556 // (float)int >= 4.4 --> int > 4
4557 if (!RHS.isNegative())
4558 Pred = ICmpInst::ICMP_SGT;
4559 break;
4560 }
Chris Lattnera5406232008-05-19 20:18:56 +00004561 }
4562 }
4563
4564 // Lower this FP comparison into an appropriate integer version of the
4565 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004566 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00004567}
4568
Chris Lattner1f12e442010-01-02 08:12:04 +00004569/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
4570/// cmp pred (load (gep GV, ...)), cmpcst
4571/// where GV is a global variable with a constant initializer. Try to simplify
Chris Lattner82602bc2010-01-02 20:20:33 +00004572/// this into some simple computation that does not need the load. For example
4573/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00004574///
4575/// If AndCst is non-null, then the loaded value is masked with that constant
4576/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Chris Lattner1f12e442010-01-02 08:12:04 +00004577Instruction *InstCombiner::
4578FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00004579 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattner56ba7a72010-01-03 03:03:27 +00004580 ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
4581 if (Init == 0 || Init->getNumOperands() > 1024) return 0;
Chris Lattner1f12e442010-01-02 08:12:04 +00004582
4583 // There are many forms of this optimization we can handle, for now, just do
4584 // the simple index into a single-dimensional array.
4585 //
Chris Lattner56ba7a72010-01-03 03:03:27 +00004586 // Require: GEP GV, 0, i {{, constant indices}}
4587 if (GEP->getNumOperands() < 3 ||
Chris Lattner1f12e442010-01-02 08:12:04 +00004588 !isa<ConstantInt>(GEP->getOperand(1)) ||
Chris Lattner56ba7a72010-01-03 03:03:27 +00004589 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
4590 isa<Constant>(GEP->getOperand(2)))
Chris Lattner1f12e442010-01-02 08:12:04 +00004591 return 0;
Chris Lattner56ba7a72010-01-03 03:03:27 +00004592
4593 // Check that indices after the variable are constants and in-range for the
4594 // type they index. Collect the indices. This is typically for arrays of
4595 // structs.
4596 SmallVector<unsigned, 4> LaterIndices;
Chris Lattner1f12e442010-01-02 08:12:04 +00004597
Chris Lattner56ba7a72010-01-03 03:03:27 +00004598 const Type *EltTy = cast<ArrayType>(Init->getType())->getElementType();
4599 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
4600 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
4601 if (Idx == 0) return 0; // Variable index.
4602
4603 uint64_t IdxVal = Idx->getZExtValue();
4604 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
4605
4606 if (const StructType *STy = dyn_cast<StructType>(EltTy))
4607 EltTy = STy->getElementType(IdxVal);
4608 else if (const ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
4609 if (IdxVal >= ATy->getNumElements()) return 0;
4610 EltTy = ATy->getElementType();
4611 } else {
4612 return 0; // Unknown type.
4613 }
4614
4615 LaterIndices.push_back(IdxVal);
4616 }
Chris Lattner1f12e442010-01-02 08:12:04 +00004617
Chris Lattner82602bc2010-01-02 20:20:33 +00004618 enum { Overdefined = -3, Undefined = -2 };
4619
Chris Lattner1f12e442010-01-02 08:12:04 +00004620 // Variables for our state machines.
4621
Chris Lattnerbef37372010-01-02 09:35:17 +00004622 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
4623 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
Chris Lattner82602bc2010-01-02 20:20:33 +00004624 // and 87 is the second (and last) index. FirstTrueElement is -2 when
Chris Lattnerbef37372010-01-02 09:35:17 +00004625 // undefined, otherwise set to the first true element. SecondTrueElement is
Chris Lattner82602bc2010-01-02 20:20:33 +00004626 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
4627 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
Chris Lattner1f12e442010-01-02 08:12:04 +00004628
Chris Lattnerbef37372010-01-02 09:35:17 +00004629 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
4630 // form "i != 47 & i != 87". Same state transitions as for true elements.
Chris Lattner82602bc2010-01-02 20:20:33 +00004631 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Chris Lattner1f12e442010-01-02 08:12:04 +00004632
Chris Lattnerb4f82b42010-01-02 21:50:18 +00004633 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
4634 /// define a state machine that triggers for ranges of values that the index
4635 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
4636 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
4637 /// index in the range (inclusive). We use -2 for undefined here because we
4638 /// use relative comparisons and don't want 0-1 to match -1.
4639 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
4640
Chris Lattner10d514e2010-01-02 08:56:52 +00004641 // MagicBitvector - This is a magic bitvector where we set a bit if the
4642 // comparison is true for element 'i'. If there are 64 elements or less in
4643 // the array, this will fully represent all the comparison results.
4644 uint64_t MagicBitvector = 0;
4645
4646
Chris Lattner1f12e442010-01-02 08:12:04 +00004647 // Scan the array and see if one of our patterns matches.
4648 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
4649 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00004650 Constant *Elt = Init->getOperand(i);
4651
Chris Lattner56ba7a72010-01-03 03:03:27 +00004652 // If this is indexing an array of structures, get the structure element.
4653 if (!LaterIndices.empty())
4654 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices.data(),
4655 LaterIndices.size());
4656
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00004657 // If the element is masked, handle it.
4658 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
4659
Chris Lattner1f12e442010-01-02 08:12:04 +00004660 // Find out if the comparison would be true or false for the i'th element.
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00004661 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Chris Lattner1f12e442010-01-02 08:12:04 +00004662 CompareRHS, TD);
4663 // If the result is undef for this element, ignore it.
Chris Lattnerb4f82b42010-01-02 21:50:18 +00004664 if (isa<UndefValue>(C)) {
4665 // Extend range state machines to cover this element in case there is an
4666 // undef in the middle of the range.
4667 if (TrueRangeEnd == (int)i-1)
4668 TrueRangeEnd = i;
4669 if (FalseRangeEnd == (int)i-1)
4670 FalseRangeEnd = i;
4671 continue;
4672 }
Chris Lattner1f12e442010-01-02 08:12:04 +00004673
4674 // If we can't compute the result for any of the elements, we have to give
4675 // up evaluating the entire conditional.
4676 if (!isa<ConstantInt>(C)) return 0;
4677
4678 // Otherwise, we know if the comparison is true or false for this element,
4679 // update our state machines.
4680 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
4681
Chris Lattnerb4f82b42010-01-02 21:50:18 +00004682 // State machine for single/double/range index comparison.
Chris Lattner1f12e442010-01-02 08:12:04 +00004683 if (IsTrueForElt) {
Chris Lattnerbef37372010-01-02 09:35:17 +00004684 // Update the TrueElement state machine.
Chris Lattner82602bc2010-01-02 20:20:33 +00004685 if (FirstTrueElement == Undefined)
Chris Lattnerb4f82b42010-01-02 21:50:18 +00004686 FirstTrueElement = TrueRangeEnd = i; // First true element.
4687 else {
4688 // Update double-compare state machine.
4689 if (SecondTrueElement == Undefined)
4690 SecondTrueElement = i;
4691 else
4692 SecondTrueElement = Overdefined;
4693
4694 // Update range state machine.
4695 if (TrueRangeEnd == (int)i-1)
4696 TrueRangeEnd = i;
4697 else
4698 TrueRangeEnd = Overdefined;
4699 }
Chris Lattner1f12e442010-01-02 08:12:04 +00004700 } else {
Chris Lattnerbef37372010-01-02 09:35:17 +00004701 // Update the FalseElement state machine.
Chris Lattner82602bc2010-01-02 20:20:33 +00004702 if (FirstFalseElement == Undefined)
Chris Lattnerb4f82b42010-01-02 21:50:18 +00004703 FirstFalseElement = FalseRangeEnd = i; // First false element.
4704 else {
4705 // Update double-compare state machine.
4706 if (SecondFalseElement == Undefined)
4707 SecondFalseElement = i;
4708 else
4709 SecondFalseElement = Overdefined;
4710
4711 // Update range state machine.
4712 if (FalseRangeEnd == (int)i-1)
4713 FalseRangeEnd = i;
4714 else
4715 FalseRangeEnd = Overdefined;
4716 }
Chris Lattner1f12e442010-01-02 08:12:04 +00004717 }
4718
Chris Lattnerb4f82b42010-01-02 21:50:18 +00004719
Chris Lattner10d514e2010-01-02 08:56:52 +00004720 // If this element is in range, update our magic bitvector.
4721 if (i < 64 && IsTrueForElt)
Chris Lattner33a1ec72010-01-02 09:22:13 +00004722 MagicBitvector |= 1ULL << i;
Chris Lattner10d514e2010-01-02 08:56:52 +00004723
Chris Lattnerb4f82b42010-01-02 21:50:18 +00004724 // If all of our states become overdefined, bail out early. Since the
4725 // predicate is expensive, only check it every 8 elements. This is only
4726 // really useful for really huge arrays.
4727 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
4728 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
4729 FalseRangeEnd == Overdefined)
Chris Lattner1f12e442010-01-02 08:12:04 +00004730 return 0;
4731 }
4732
4733 // Now that we've scanned the entire array, emit our new comparison(s). We
4734 // order the state machines in complexity of the generated code.
Chris Lattnerbef37372010-01-02 09:35:17 +00004735 Value *Idx = GEP->getOperand(2);
4736
Chris Lattnerb4f82b42010-01-02 21:50:18 +00004737
Chris Lattnerbef37372010-01-02 09:35:17 +00004738 // If the comparison is only true for one or two elements, emit direct
4739 // comparisons.
Chris Lattner82602bc2010-01-02 20:20:33 +00004740 if (SecondTrueElement != Overdefined) {
Chris Lattner1f12e442010-01-02 08:12:04 +00004741 // None true -> false.
Chris Lattner82602bc2010-01-02 20:20:33 +00004742 if (FirstTrueElement == Undefined)
Chris Lattner4de84762010-01-04 07:02:48 +00004743 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext()));
Chris Lattner1f12e442010-01-02 08:12:04 +00004744
Chris Lattnerbef37372010-01-02 09:35:17 +00004745 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
4746
Chris Lattner1f12e442010-01-02 08:12:04 +00004747 // True for one element -> 'i == 47'.
Chris Lattner82602bc2010-01-02 20:20:33 +00004748 if (SecondTrueElement == Undefined)
Chris Lattnerbef37372010-01-02 09:35:17 +00004749 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
4750
4751 // True for two elements -> 'i == 47 | i == 72'.
4752 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
4753 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
4754 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
4755 return BinaryOperator::CreateOr(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00004756 }
4757
Chris Lattnerbef37372010-01-02 09:35:17 +00004758 // If the comparison is only false for one or two elements, emit direct
4759 // comparisons.
Chris Lattner82602bc2010-01-02 20:20:33 +00004760 if (SecondFalseElement != Overdefined) {
Chris Lattner1f12e442010-01-02 08:12:04 +00004761 // None false -> true.
Chris Lattner82602bc2010-01-02 20:20:33 +00004762 if (FirstFalseElement == Undefined)
Chris Lattner4de84762010-01-04 07:02:48 +00004763 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext()));
Chris Lattner1f12e442010-01-02 08:12:04 +00004764
Chris Lattnerbef37372010-01-02 09:35:17 +00004765 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
4766
4767 // False for one element -> 'i != 47'.
Chris Lattner82602bc2010-01-02 20:20:33 +00004768 if (SecondFalseElement == Undefined)
Chris Lattnerbef37372010-01-02 09:35:17 +00004769 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
4770
4771 // False for two elements -> 'i != 47 & i != 72'.
4772 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
4773 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
4774 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
4775 return BinaryOperator::CreateAnd(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00004776 }
4777
Chris Lattnerb4f82b42010-01-02 21:50:18 +00004778 // If the comparison can be replaced with a range comparison for the elements
4779 // where it is true, emit the range check.
4780 if (TrueRangeEnd != Overdefined) {
4781 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
4782
4783 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
4784 if (FirstTrueElement) {
4785 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
4786 Idx = Builder->CreateAdd(Idx, Offs);
4787 }
4788
4789 Value *End = ConstantInt::get(Idx->getType(),
4790 TrueRangeEnd-FirstTrueElement+1);
4791 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
4792 }
4793
4794 // False range check.
4795 if (FalseRangeEnd != Overdefined) {
4796 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
4797 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
4798 if (FirstFalseElement) {
4799 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
4800 Idx = Builder->CreateAdd(Idx, Offs);
4801 }
4802
4803 Value *End = ConstantInt::get(Idx->getType(),
4804 FalseRangeEnd-FirstFalseElement);
4805 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
4806 }
4807
4808
Chris Lattner10d514e2010-01-02 08:56:52 +00004809 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
4810 // of this load, replace it with computation that does:
4811 // ((magic_cst >> i) & 1) != 0
4812 if (Init->getNumOperands() <= 32 ||
4813 (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
4814 const Type *Ty;
4815 if (Init->getNumOperands() <= 32)
4816 Ty = Type::getInt32Ty(Init->getContext());
4817 else
4818 Ty = Type::getInt64Ty(Init->getContext());
Chris Lattnerbef37372010-01-02 09:35:17 +00004819 Value *V = Builder->CreateIntCast(Idx, Ty, false);
Chris Lattner10d514e2010-01-02 08:56:52 +00004820 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
4821 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
4822 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
4823 }
Chris Lattner1f12e442010-01-02 08:12:04 +00004824
Chris Lattner1f12e442010-01-02 08:12:04 +00004825 return 0;
4826}
4827
4828
Reid Spencere4d87aa2006-12-23 06:05:41 +00004829Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00004830 bool Changed = false;
4831
4832 /// Orders the operands of the compare so that they are listed from most
4833 /// complex to least complex. This puts constants before unary operators,
4834 /// before binary operators.
4835 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4836 I.swapOperands();
4837 Changed = true;
4838 }
4839
Chris Lattner8b170942002-08-09 23:47:40 +00004840 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00004841
Chris Lattner210c5d42009-11-09 23:55:12 +00004842 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
4843 return ReplaceInstUsesWith(I, V);
4844
Chris Lattner58e97462007-01-14 19:42:17 +00004845 // Simplify 'fcmp pred X, X'
4846 if (Op0 == Op1) {
4847 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004848 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00004849 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4850 case FCmpInst::FCMP_ULT: // True if unordered or less than
4851 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4852 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4853 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4854 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00004855 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00004856 return &I;
4857
4858 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4859 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4860 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4861 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4862 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4863 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00004864 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00004865 return &I;
4866 }
4867 }
4868
Reid Spencere4d87aa2006-12-23 06:05:41 +00004869 // Handle fcmp with constant RHS
4870 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4871 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4872 switch (LHSI->getOpcode()) {
4873 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00004874 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4875 // block. If in the same block, we're encouraging jump threading. If
4876 // not, we are just pessimizing the code by making an i1 phi.
4877 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00004878 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00004879 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004880 break;
Chris Lattnera5406232008-05-19 20:18:56 +00004881 case Instruction::SIToFP:
4882 case Instruction::UIToFP:
4883 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
4884 return NV;
4885 break;
Chris Lattner34e0c762010-01-02 08:20:51 +00004886 case Instruction::Select: {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004887 // If either operand of the select is a constant, we can fold the
4888 // comparison into the select arms, which will cause one to be
4889 // constant folded and the select turned into a bitwise or.
4890 Value *Op1 = 0, *Op2 = 0;
4891 if (LHSI->hasOneUse()) {
4892 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4893 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00004894 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004895 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00004896 Op2 = Builder->CreateFCmp(I.getPredicate(),
4897 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004898 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4899 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00004900 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004901 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00004902 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
4903 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004904 }
4905 }
4906
4907 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00004908 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004909 break;
4910 }
Chris Lattner34e0c762010-01-02 08:20:51 +00004911 case Instruction::Load:
4912 if (GetElementPtrInst *GEP =
4913 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4914 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4915 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Chris Lattnera0085af2010-01-03 06:58:48 +00004916 !cast<LoadInst>(LHSI)->isVolatile())
Chris Lattner34e0c762010-01-02 08:20:51 +00004917 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
4918 return Res;
Chris Lattner34e0c762010-01-02 08:20:51 +00004919 }
4920 break;
4921 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004922 }
4923
4924 return Changed ? &I : 0;
4925}
4926
4927Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00004928 bool Changed = false;
4929
4930 /// Orders the operands of the compare so that they are listed from most
4931 /// complex to least complex. This puts constants before unary operators,
4932 /// before binary operators.
4933 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4934 I.swapOperands();
4935 Changed = true;
4936 }
4937
Reid Spencere4d87aa2006-12-23 06:05:41 +00004938 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00004939
Chris Lattner210c5d42009-11-09 23:55:12 +00004940 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
4941 return ReplaceInstUsesWith(I, V);
4942
4943 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00004944
Reid Spencere4d87aa2006-12-23 06:05:41 +00004945 // icmp's with boolean values can always be turned into bitwise operations
Chris Lattner4de84762010-01-04 07:02:48 +00004946 if (Ty == Type::getInt1Ty(I.getContext())) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004947 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004948 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00004949 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00004950 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00004951 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004952 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00004953 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004954 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004955
Reid Spencere4d87aa2006-12-23 06:05:41 +00004956 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00004957 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00004958 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00004959 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00004960 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004961 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00004962 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00004963 case ICmpInst::ICMP_SGT:
4964 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00004965 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00004966 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00004967 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00004968 return BinaryOperator::CreateAnd(Not, Op0);
4969 }
4970 case ICmpInst::ICMP_UGE:
4971 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
4972 // FALL THROUGH
4973 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00004974 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004975 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00004976 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00004977 case ICmpInst::ICMP_SGE:
4978 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
4979 // FALL THROUGH
4980 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00004981 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00004982 return BinaryOperator::CreateOr(Not, Op0);
4983 }
Chris Lattner5dbef222004-08-11 00:50:51 +00004984 }
Chris Lattner8b170942002-08-09 23:47:40 +00004985 }
4986
Dan Gohman1c8491e2009-04-25 17:12:48 +00004987 unsigned BitWidth = 0;
4988 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00004989 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
4990 else if (Ty->isIntOrIntVector())
4991 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00004992
4993 bool isSignBit = false;
4994
Dan Gohman81b28ce2008-09-16 18:46:06 +00004995 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00004996 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00004997 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00004998
Chris Lattnerb6566012008-01-05 01:18:20 +00004999 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
Chris Lattner1f12e442010-01-02 08:12:04 +00005000 if (I.isEquality() && CI->isZero() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005001 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00005002 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005003 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005004 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005005
Dan Gohman81b28ce2008-09-16 18:46:06 +00005006 // If we have an icmp le or icmp ge instruction, turn it into the
5007 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00005008 // them being folded in the code below. The SimplifyICmpInst code has
5009 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00005010 switch (I.getPredicate()) {
5011 default: break;
5012 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00005013 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005014 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005015 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005016 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00005017 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005018 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005019 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005020 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00005021 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005022 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005023 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005024 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00005025 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005026 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005027 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005028 }
5029
Chris Lattner183661e2008-07-11 05:40:05 +00005030 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005031 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005032 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00005033 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5034 }
5035
5036 // See if we can fold the comparison based on range information we can get
5037 // by checking whether bits are known to be zero or one in the input.
5038 if (BitWidth != 0) {
5039 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5040 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
5041
5042 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00005043 isSignBit ? APInt::getSignBit(BitWidth)
5044 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00005045 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005046 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00005047 if (SimplifyDemandedBits(I.getOperandUse(1),
5048 APInt::getAllOnesValue(BitWidth),
5049 Op1KnownZero, Op1KnownOne, 0))
5050 return &I;
5051
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005052 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005053 // in. Compute the Min, Max and RHS values based on the known bits. For the
5054 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00005055 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
5056 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00005057 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00005058 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
5059 Op0Min, Op0Max);
5060 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
5061 Op1Min, Op1Max);
5062 } else {
5063 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
5064 Op0Min, Op0Max);
5065 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
5066 Op1Min, Op1Max);
5067 }
5068
Chris Lattner183661e2008-07-11 05:40:05 +00005069 // If Min and Max are known to be the same, then SimplifyDemandedBits
5070 // figured out that the LHS is a constant. Just constant fold this now so
5071 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00005072 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005073 return new ICmpInst(I.getPredicate(),
Chris Lattner4de84762010-01-04 07:02:48 +00005074 ConstantInt::get(I.getContext(), Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00005075 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005076 return new ICmpInst(I.getPredicate(), Op0,
Chris Lattner4de84762010-01-04 07:02:48 +00005077 ConstantInt::get(I.getContext(), Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005078
Chris Lattner183661e2008-07-11 05:40:05 +00005079 // Based on the range information we know about the LHS, see if we can
5080 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00005081 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005082 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00005083 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005084 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner4de84762010-01-04 07:02:48 +00005085 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner84dff672008-07-11 05:08:55 +00005086 break;
5087 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005088 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner4de84762010-01-04 07:02:48 +00005089 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner84dff672008-07-11 05:08:55 +00005090 break;
5091 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005092 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005093 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005094 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005095 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005096 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005097 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00005098 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5099 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005100 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005101 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005102
5103 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5104 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005105 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00005106 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005107 }
Chris Lattner84dff672008-07-11 05:08:55 +00005108 break;
5109 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005110 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005111 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005112 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005113 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005114
5115 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005116 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00005117 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5118 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005119 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005120 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005121
5122 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5123 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005124 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00005125 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005126 }
Chris Lattner84dff672008-07-11 05:08:55 +00005127 break;
5128 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00005129 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Chris Lattner4de84762010-01-04 07:02:48 +00005130 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005131 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Chris Lattner4de84762010-01-04 07:02:48 +00005132 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005133 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005134 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00005135 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5136 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005137 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005138 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005139 }
Chris Lattner84dff672008-07-11 05:08:55 +00005140 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00005141 case ICmpInst::ICMP_SGT:
5142 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005143 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005144 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005145 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005146
5147 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005148 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00005149 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5150 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005151 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005152 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005153 }
5154 break;
5155 case ICmpInst::ICMP_SGE:
5156 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
5157 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005158 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005159 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005160 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005161 break;
5162 case ICmpInst::ICMP_SLE:
5163 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
5164 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005165 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005166 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005167 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005168 break;
5169 case ICmpInst::ICMP_UGE:
5170 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
5171 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005172 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005173 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005174 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005175 break;
5176 case ICmpInst::ICMP_ULE:
5177 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
5178 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005179 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00005180 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00005181 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner84dff672008-07-11 05:08:55 +00005182 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005183 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00005184
5185 // Turn a signed comparison into an unsigned one if both operands
5186 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00005187 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00005188 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
5189 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005190 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00005191 }
5192
5193 // Test if the ICmpInst instruction is used exclusively by a select as
5194 // part of a minimum or maximum operation. If so, refrain from doing
5195 // any other folding. This helps out other analyses which understand
5196 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5197 // and CodeGen. And in this case, at least one of the comparison
5198 // operands has at least one user besides the compare (the select),
5199 // which would often largely negate the benefit of folding anyway.
5200 if (I.hasOneUse())
5201 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5202 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5203 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5204 return 0;
5205
5206 // See if we are doing a comparison between a constant and an instruction that
5207 // can be folded into the comparison.
5208 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005209 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005210 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005211 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005212 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005213 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5214 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005215 }
5216
Chris Lattner01deb9d2007-04-03 17:43:25 +00005217 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005218 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5219 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5220 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005221 case Instruction::GetElementPtr:
Reid Spencere4d87aa2006-12-23 06:05:41 +00005222 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnerec12d052010-01-01 23:09:08 +00005223 if (RHSC->isNullValue() &&
5224 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
5225 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5226 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00005227 break;
Chris Lattner6970b662005-04-23 15:31:55 +00005228 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00005229 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005230 // block. If in the same block, we're encouraging jump threading. If
5231 // not, we are just pessimizing the code by making an i1 phi.
5232 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005233 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005234 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005235 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005236 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005237 // If either operand of the select is a constant, we can fold the
5238 // comparison into the select arms, which will cause one to be
5239 // constant folded and the select turned into a bitwise or.
5240 Value *Op1 = 0, *Op2 = 0;
Eli Friedman97b087c2009-12-18 08:22:35 +00005241 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
5242 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5243 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
5244 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5245
5246 // We only want to perform this transformation if it will not lead to
5247 // additional code. This is true if either both sides of the select
5248 // fold to a constant (in which case the icmp is replaced with a select
5249 // which will usually simplify) or this is the only user of the
5250 // select (in which case we are trading a select+icmp for a simpler
5251 // select+icmp).
5252 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
5253 if (!Op1)
Chris Lattner74381062009-08-30 07:44:24 +00005254 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
5255 RHSC, I.getName());
Eli Friedman97b087c2009-12-18 08:22:35 +00005256 if (!Op2)
5257 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
5258 RHSC, I.getName());
Gabor Greif051a9502008-04-06 20:25:17 +00005259 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman97b087c2009-12-18 08:22:35 +00005260 }
Chris Lattner6970b662005-04-23 15:31:55 +00005261 break;
5262 }
Victor Hernandez83d63912009-09-18 22:35:49 +00005263 case Instruction::Call:
5264 // If we have (malloc != null), and if the malloc has a single use, we
5265 // can assume it is successful and remove the malloc.
5266 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
5267 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00005268 // Need to explicitly erase malloc call here, instead of adding it to
5269 // Worklist, because it won't get DCE'd from the Worklist since
5270 // isInstructionTriviallyDead() returns false for function calls.
5271 // It is OK to replace LHSI/MallocCall with Undef because the
5272 // instruction that uses it will be erased via Worklist.
5273 if (extractMallocCall(LHSI)) {
5274 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
5275 EraseInstFromFunction(*LHSI);
5276 return ReplaceInstUsesWith(I,
Chris Lattner4de84762010-01-04 07:02:48 +00005277 ConstantInt::get(Type::getInt1Ty(I.getContext()),
Victor Hernandez83d63912009-09-18 22:35:49 +00005278 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00005279 }
5280 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
5281 if (MallocCall->hasOneUse()) {
5282 MallocCall->replaceAllUsesWith(
5283 UndefValue::get(MallocCall->getType()));
5284 EraseInstFromFunction(*MallocCall);
5285 Worklist.Add(LHSI); // The malloc's bitcast use.
5286 return ReplaceInstUsesWith(I,
Chris Lattner4de84762010-01-04 07:02:48 +00005287 ConstantInt::get(Type::getInt1Ty(I.getContext()),
Victor Hernandez68afa542009-10-21 19:11:40 +00005288 !I.isTrueWhenEqual()));
5289 }
Victor Hernandez83d63912009-09-18 22:35:49 +00005290 }
5291 break;
Chris Lattnerec12d052010-01-01 23:09:08 +00005292 case Instruction::IntToPtr:
5293 // icmp pred inttoptr(X), null -> icmp pred X, 0
5294 if (RHSC->isNullValue() && TD &&
5295 TD->getIntPtrType(RHSC->getContext()) ==
5296 LHSI->getOperand(0)->getType())
5297 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5298 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5299 break;
Chris Lattner1f12e442010-01-02 08:12:04 +00005300
5301 case Instruction::Load:
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00005302 // Try to optimize things like "A[i] > 4" to index computations.
Chris Lattner1f12e442010-01-02 08:12:04 +00005303 if (GetElementPtrInst *GEP =
Chris Lattner34e0c762010-01-02 08:20:51 +00005304 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
Chris Lattner1f12e442010-01-02 08:12:04 +00005305 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
5306 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Chris Lattnera0085af2010-01-03 06:58:48 +00005307 !cast<LoadInst>(LHSI)->isVolatile())
Chris Lattner1f12e442010-01-02 08:12:04 +00005308 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
5309 return Res;
Chris Lattner34e0c762010-01-02 08:20:51 +00005310 }
Chris Lattner1f12e442010-01-02 08:12:04 +00005311 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005312 }
Chris Lattner6970b662005-04-23 15:31:55 +00005313 }
5314
Reid Spencere4d87aa2006-12-23 06:05:41 +00005315 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005316 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005317 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005318 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005319 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005320 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5321 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005322 return NI;
5323
Reid Spencere4d87aa2006-12-23 06:05:41 +00005324 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005325 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5326 // now.
5327 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5328 if (isa<PointerType>(Op0->getType()) &&
5329 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005330 // We keep moving the cast from the left operand over to the right
5331 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005332 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005333
Chris Lattner57d86372007-01-06 01:45:59 +00005334 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5335 // so eliminate it as well.
5336 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5337 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005338
Chris Lattnerde90b762003-11-03 04:25:02 +00005339 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005340 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005341 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005342 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005343 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005344 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00005345 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005346 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005347 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005348 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005349 }
Chris Lattner57d86372007-01-06 01:45:59 +00005350 }
5351
5352 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005353 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005354 // This comes up when you have code like
5355 // int X = A < B;
5356 // if (X) ...
5357 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005358 // with a constant or another cast from the same type.
Eli Friedman8e4b1972009-12-17 21:27:47 +00005359 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005360 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005361 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005362 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005363
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005364 // See if it's the same type of instruction on the left and right.
5365 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5366 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00005367 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00005368 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00005369 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005370 default: break;
5371 case Instruction::Add:
5372 case Instruction::Sub:
5373 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00005374 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005375 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00005376 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00005377 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
5378 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5379 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00005380 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00005381 ? I.getUnsignedPredicate()
5382 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005383 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00005384 Op1I->getOperand(0));
5385 }
5386
5387 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00005388 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00005389 ? I.getUnsignedPredicate()
5390 : I.getSignedPredicate();
5391 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005392 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00005393 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00005394 }
5395 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005396 break;
5397 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00005398 if (!I.isEquality())
5399 break;
5400
Nick Lewycky5d52c452008-08-21 05:56:10 +00005401 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5402 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5403 // Mask = -1 >> count-trailing-zeros(Cst).
5404 if (!CI->isZero() && !CI->isOne()) {
5405 const APInt &AP = CI->getValue();
Chris Lattner4de84762010-01-04 07:02:48 +00005406 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Nick Lewycky5d52c452008-08-21 05:56:10 +00005407 APInt::getLowBitsSet(AP.getBitWidth(),
5408 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005409 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00005410 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
5411 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005412 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005413 }
5414 }
5415 break;
5416 }
5417 }
5418 }
5419 }
5420
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005421 // ~x < ~y --> y < x
5422 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005423 if (match(Op0, m_Not(m_Value(A))) &&
5424 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005425 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005426 }
5427
Chris Lattner65b72ba2006-09-18 04:22:48 +00005428 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005429 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005430
5431 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00005432 if (match(Op0, m_Neg(m_Value(A))) &&
5433 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005434 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005435
Dan Gohman4ae51262009-08-12 16:23:25 +00005436 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005437 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5438 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005439 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00005440 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005441 }
5442
Dan Gohman4ae51262009-08-12 16:23:25 +00005443 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005444 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00005445 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00005446 if (match(B, m_ConstantInt(C1)) &&
5447 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Chris Lattner4de84762010-01-04 07:02:48 +00005448 Constant *NC = ConstantInt::get(I.getContext(),
5449 C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00005450 Value *Xor = Builder->CreateXor(C, NC, "tmp");
5451 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00005452 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005453
5454 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005455 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5456 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5457 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5458 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005459 }
5460 }
5461
Dan Gohman4ae51262009-08-12 16:23:25 +00005462 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005463 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005464 // A == (A^B) -> B == 0
5465 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005466 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00005467 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005468 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005469
5470 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00005471 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005472 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00005473 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00005474
5475 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00005476 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005477 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00005478 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00005479
Chris Lattner9c2328e2006-11-14 06:06:06 +00005480 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5481 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005482 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5483 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00005484 Value *X = 0, *Y = 0, *Z = 0;
5485
5486 if (A == C) {
5487 X = B; Y = D; Z = A;
5488 } else if (A == D) {
5489 X = B; Y = C; Z = A;
5490 } else if (B == C) {
5491 X = A; Y = D; Z = B;
5492 } else if (B == D) {
5493 X = A; Y = C; Z = B;
5494 }
5495
5496 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00005497 Op1 = Builder->CreateXor(X, Y, "tmp");
5498 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00005499 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00005500 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00005501 return &I;
5502 }
5503 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005504 }
Chris Lattner2799baf2009-12-21 03:19:28 +00005505
5506 {
5507 Value *X; ConstantInt *Cst;
Chris Lattner3bf68152009-12-21 04:04:05 +00005508 // icmp X+Cst, X
Chris Lattner2799baf2009-12-21 03:19:28 +00005509 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00005510 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
5511
Chris Lattner2799baf2009-12-21 03:19:28 +00005512 // icmp X, X+Cst
5513 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00005514 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
Chris Lattner2799baf2009-12-21 03:19:28 +00005515 }
Chris Lattner7e708292002-06-25 16:13:24 +00005516 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005517}
5518
Chris Lattner2799baf2009-12-21 03:19:28 +00005519/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
5520Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
5521 Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +00005522 ICmpInst::Predicate Pred,
5523 Value *TheAdd) {
Chris Lattner2799baf2009-12-21 03:19:28 +00005524 // If we have X+0, exit early (simplifying logic below) and let it get folded
5525 // elsewhere. icmp X+0, X -> icmp X, X
5526 if (CI->isZero()) {
5527 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
5528 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
5529 }
5530
5531 // (X+4) == X -> false.
5532 if (Pred == ICmpInst::ICMP_EQ)
5533 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
5534
5535 // (X+4) != X -> true.
5536 if (Pred == ICmpInst::ICMP_NE)
5537 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner3bf68152009-12-21 04:04:05 +00005538
5539 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
5540 bool isNUW = false, isNSW = false;
5541 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
5542 isNUW = Add->hasNoUnsignedWrap();
5543 isNSW = Add->hasNoSignedWrap();
5544 }
Chris Lattner2799baf2009-12-21 03:19:28 +00005545
5546 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
5547 // so the values can never be equal. Similiarly for all other "or equals"
5548 // operators.
5549
5550 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
5551 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
5552 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
5553 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattner3bf68152009-12-21 04:04:05 +00005554 // If this is an NUW add, then this is always false.
5555 if (isNUW)
5556 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
5557
Chris Lattner2799baf2009-12-21 03:19:28 +00005558 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
5559 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
5560 }
5561
5562 // (X+1) >u X --> X <u (0-1) --> X != 255
5563 // (X+2) >u X --> X <u (0-2) --> X <u 254
5564 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Chris Lattner3bf68152009-12-21 04:04:05 +00005565 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
5566 // If this is an NUW add, then this is always true.
5567 if (isNUW)
5568 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner2799baf2009-12-21 03:19:28 +00005569 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00005570 }
Chris Lattner2799baf2009-12-21 03:19:28 +00005571
5572 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
5573 ConstantInt *SMax = ConstantInt::get(X->getContext(),
5574 APInt::getSignedMaxValue(BitWidth));
5575
5576 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
5577 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
5578 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
5579 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
5580 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
5581 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Chris Lattner3bf68152009-12-21 04:04:05 +00005582 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
5583 // If this is an NSW add, then we have two cases: if the constant is
5584 // positive, then this is always false, if negative, this is always true.
5585 if (isNSW) {
5586 bool isTrue = CI->getValue().isNegative();
5587 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
5588 }
5589
Chris Lattner2799baf2009-12-21 03:19:28 +00005590 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00005591 }
Chris Lattner2799baf2009-12-21 03:19:28 +00005592
5593 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
5594 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
5595 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
5596 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
5597 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
5598 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Chris Lattner3bf68152009-12-21 04:04:05 +00005599
5600 // If this is an NSW add, then we have two cases: if the constant is
5601 // positive, then this is always true, if negative, this is always false.
5602 if (isNSW) {
5603 bool isTrue = !CI->getValue().isNegative();
5604 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
5605 }
5606
Chris Lattner2799baf2009-12-21 03:19:28 +00005607 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
5608 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
5609 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
5610}
Chris Lattner562ef782007-06-20 23:46:26 +00005611
5612/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5613/// and CmpRHS are both known to be integer constants.
5614Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5615 ConstantInt *DivRHS) {
5616 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5617 const APInt &CmpRHSV = CmpRHS->getValue();
5618
5619 // FIXME: If the operand types don't match the type of the divide
5620 // then don't attempt this transform. The code below doesn't have the
5621 // logic to deal with a signed divide and an unsigned compare (and
5622 // vice versa). This is because (x /s C1) <s C2 produces different
5623 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5624 // (x /u C1) <u C2. Simply casting the operands and result won't
5625 // work. :( The if statement below tests that condition and bails
5626 // if it finds it.
5627 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00005628 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00005629 return 0;
5630 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005631 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00005632 if (DivIsSigned && DivRHS->isAllOnesValue())
5633 return 0; // The overflow computation also screws up here
5634 if (DivRHS->isOne())
5635 return 0; // Not worth bothering, and eliminates some funny cases
5636 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00005637
5638 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5639 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5640 // C2 (CI). By solving for X we can turn this into a range check
5641 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005642 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00005643
5644 // Determine if the product overflows by seeing if the product is
5645 // not equal to the divide. Make sure we do the same kind of divide
5646 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005647 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5648 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00005649
5650 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005651 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005652
Chris Lattner1dbfd482007-06-21 18:11:19 +00005653 // Figure out the interval that is being checked. For example, a comparison
5654 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5655 // Compute this interval based on the constants involved and the signedness of
5656 // the compare/divide. This computes a half-open interval, keeping track of
5657 // whether either value in the interval overflows. After analysis each
5658 // overflow variable is set to 0 if it's corresponding bound variable is valid
5659 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5660 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00005661 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005662
Chris Lattner562ef782007-06-20 23:46:26 +00005663 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005664 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005665 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005666 HiOverflow = LoOverflow = ProdOV;
5667 if (!HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00005668 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005669 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005670 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005671 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00005672 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00005673 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005674 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005675 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5676 HiOverflow = LoOverflow = ProdOV;
5677 if (!HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00005678 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005679 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005680 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00005681 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00005682 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
5683 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005684 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005685 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner4de84762010-01-04 07:02:48 +00005686 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattnera6321b42008-10-11 22:55:00 +00005687 }
Chris Lattner562ef782007-06-20 23:46:26 +00005688 }
Dan Gohman76491272008-02-13 22:09:18 +00005689 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005690 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005691 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00005692 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00005693 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005694 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5695 HiOverflow = 1; // [INTMIN+1, overflow)
5696 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5697 }
Dan Gohman76491272008-02-13 22:09:18 +00005698 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005699 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00005700 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005701 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005702 if (!LoOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00005703 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005704 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00005705 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
5706 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00005707 if (!HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00005708 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005709 }
5710
Chris Lattner1dbfd482007-06-21 18:11:19 +00005711 // Dividing by a negative swaps the condition. LT <-> GT
5712 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005713 }
5714
5715 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005716 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005717 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00005718 case ICmpInst::ICMP_EQ:
5719 if (LoOverflow && HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00005720 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattner562ef782007-06-20 23:46:26 +00005721 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005722 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005723 ICmpInst::ICMP_UGE, X, LoBound);
5724 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005725 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005726 ICmpInst::ICMP_ULT, X, HiBound);
5727 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005728 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005729 case ICmpInst::ICMP_NE:
5730 if (LoOverflow && HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00005731 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattner562ef782007-06-20 23:46:26 +00005732 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005733 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005734 ICmpInst::ICMP_ULT, X, LoBound);
5735 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005736 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005737 ICmpInst::ICMP_UGE, X, HiBound);
5738 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005739 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005740 case ICmpInst::ICMP_ULT:
5741 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005742 if (LoOverflow == +1) // Low bound is greater than input range.
Chris Lattner4de84762010-01-04 07:02:48 +00005743 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005744 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner4de84762010-01-04 07:02:48 +00005745 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005746 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005747 case ICmpInst::ICMP_UGT:
5748 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005749 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner4de84762010-01-04 07:02:48 +00005750 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005751 else if (HiOverflow == -1) // High bound less than input range.
Chris Lattner4de84762010-01-04 07:02:48 +00005752 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005753 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005754 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005755 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005756 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005757 }
5758}
5759
5760
Chris Lattner01deb9d2007-04-03 17:43:25 +00005761/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5762///
5763Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5764 Instruction *LHSI,
5765 ConstantInt *RHS) {
5766 const APInt &RHSV = RHS->getValue();
5767
5768 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00005769 case Instruction::Trunc:
5770 if (ICI.isEquality() && LHSI->hasOneUse()) {
5771 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
5772 // of the high bits truncated out of x are known.
5773 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
5774 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5775 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
5776 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
5777 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
5778
5779 // If all the high bits are known, we can do this xform.
5780 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
5781 // Pull in the high bits from known-ones set.
5782 APInt NewRHS(RHS->getValue());
5783 NewRHS.zext(SrcBits);
5784 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005785 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00005786 ConstantInt::get(ICI.getContext(), NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00005787 }
5788 }
5789 break;
5790
Duncan Sands0091bf22007-04-04 06:42:45 +00005791 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005792 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5793 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5794 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005795 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5796 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005797 Value *CompareVal = LHSI->getOperand(0);
5798
5799 // If the sign bit of the XorCST is not set, there is no change to
5800 // the operation, just stop using the Xor.
5801 if (!XorCST->getValue().isNegative()) {
5802 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00005803 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00005804 return &ICI;
5805 }
5806
5807 // Was the old condition true if the operand is positive?
5808 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5809
5810 // If so, the new one isn't.
5811 isTrueIfPositive ^= true;
5812
5813 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005814 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00005815 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005816 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005817 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00005818 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005819 }
Nick Lewycky4333f492009-01-31 21:30:05 +00005820
5821 if (LHSI->hasOneUse()) {
5822 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
5823 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
5824 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00005825 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00005826 ? ICI.getUnsignedPredicate()
5827 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005828 return new ICmpInst(Pred, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00005829 ConstantInt::get(ICI.getContext(),
5830 RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00005831 }
5832
5833 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00005834 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00005835 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00005836 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00005837 ? ICI.getUnsignedPredicate()
5838 : ICI.getSignedPredicate();
5839 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005840 return new ICmpInst(Pred, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00005841 ConstantInt::get(ICI.getContext(),
5842 RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00005843 }
5844 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005845 }
5846 break;
5847 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5848 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5849 LHSI->getOperand(0)->hasOneUse()) {
5850 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5851
5852 // If the LHS is an AND of a truncating cast, we can widen the
5853 // and/compare to be the input width without changing the value
5854 // produced, eliminating a cast.
5855 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5856 // We can do this transformation if either the AND constant does not
5857 // have its sign bit set or if it is an equality comparison.
5858 // Extending a relational comparison when we're checking the sign
5859 // bit would not work.
5860 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005861 (ICI.isEquality() ||
5862 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005863 uint32_t BitWidth =
5864 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5865 APInt NewCST = AndCST->getValue();
5866 NewCST.zext(BitWidth);
5867 APInt NewCI = RHSV;
5868 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00005869 Value *NewAnd =
5870 Builder->CreateAnd(Cast->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00005871 ConstantInt::get(ICI.getContext(), NewCST),
5872 LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005873 return new ICmpInst(ICI.getPredicate(), NewAnd,
Chris Lattner4de84762010-01-04 07:02:48 +00005874 ConstantInt::get(ICI.getContext(), NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005875 }
5876 }
5877
5878 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5879 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5880 // happens a LOT in code produced by the C front-end, for bitfield
5881 // access.
5882 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5883 if (Shift && !Shift->isShift())
5884 Shift = 0;
5885
5886 ConstantInt *ShAmt;
5887 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5888 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5889 const Type *AndTy = AndCST->getType(); // Type of the and.
5890
5891 // We can fold this as long as we can't shift unknown bits
5892 // into the mask. This can only happen with signed shift
5893 // rights, as they sign-extend.
5894 if (ShAmt) {
5895 bool CanFold = Shift->isLogicalShift();
5896 if (!CanFold) {
5897 // To test for the bad case of the signed shr, see if any
5898 // of the bits shifted in could be tested after the mask.
5899 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5900 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5901
5902 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5903 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5904 AndCST->getValue()) == 0)
5905 CanFold = true;
5906 }
5907
5908 if (CanFold) {
5909 Constant *NewCst;
5910 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00005911 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00005912 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00005913 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00005914
5915 // Check to see if we are shifting out any of the bits being
5916 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005917 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00005918 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005919 // If we shifted bits out, the fold is not going to work out.
5920 // As a special case, check to see if this means that the
5921 // result is always true or false now.
5922 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Chris Lattner4de84762010-01-04 07:02:48 +00005923 return ReplaceInstUsesWith(ICI,
5924 ConstantInt::getFalse(ICI.getContext()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005925 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner4de84762010-01-04 07:02:48 +00005926 return ReplaceInstUsesWith(ICI,
5927 ConstantInt::getTrue(ICI.getContext()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005928 } else {
5929 ICI.setOperand(1, NewCst);
5930 Constant *NewAndCST;
5931 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00005932 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00005933 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00005934 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00005935 LHSI->setOperand(1, NewAndCST);
5936 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005937 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005938 return &ICI;
5939 }
5940 }
5941 }
5942
5943 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5944 // preferable because it allows the C<<Y expression to be hoisted out
5945 // of a loop if Y is invariant and X is not.
5946 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00005947 ICI.isEquality() && !Shift->isArithmeticShift() &&
5948 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005949 // Compute C << Y.
5950 Value *NS;
5951 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00005952 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00005953 } else {
5954 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00005955 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00005956 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005957
5958 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00005959 Value *NewAnd =
5960 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00005961
5962 ICI.setOperand(0, NewAnd);
5963 return &ICI;
5964 }
5965 }
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00005966
5967 // Try to optimize things like "A[i]&42 == 0" to index computations.
5968 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
5969 if (GetElementPtrInst *GEP =
5970 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
5971 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
5972 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
5973 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
5974 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
5975 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
5976 return Res;
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00005977 }
5978 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005979 break;
Nick Lewycky546d6312010-01-02 15:25:44 +00005980
5981 case Instruction::Or: {
5982 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
5983 break;
5984 Value *P, *Q;
5985 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
5986 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
5987 // -> and (icmp eq P, null), (icmp eq Q, null).
5988
5989 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
5990 Constant::getNullValue(P->getType()));
5991 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
5992 Constant::getNullValue(Q->getType()));
Nick Lewyckyf994bf02010-01-02 16:14:56 +00005993 Instruction *Op;
5994 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky11ed0312010-01-03 00:55:31 +00005995 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
Nick Lewyckyf994bf02010-01-02 16:14:56 +00005996 else
Nick Lewycky11ed0312010-01-03 00:55:31 +00005997 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
Nick Lewyckyf994bf02010-01-02 16:14:56 +00005998 return Op;
Nick Lewycky546d6312010-01-02 15:25:44 +00005999 }
6000 break;
6001 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006002
Chris Lattnera0141b92007-07-15 20:42:37 +00006003 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6004 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6005 if (!ShAmt) break;
6006
6007 uint32_t TypeBits = RHSV.getBitWidth();
6008
6009 // Check that the shift amount is in range. If not, don't perform
6010 // undefined shifts. When the shift is visited it will be
6011 // simplified.
6012 if (ShAmt->uge(TypeBits))
6013 break;
6014
6015 if (ICI.isEquality()) {
6016 // If we are comparing against bits always shifted out, the
6017 // comparison cannot succeed.
6018 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006019 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006020 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006021 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6022 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner4de84762010-01-04 07:02:48 +00006023 Constant *Cst =
6024 ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006025 return ReplaceInstUsesWith(ICI, Cst);
6026 }
6027
6028 if (LHSI->hasOneUse()) {
6029 // Otherwise strength reduce the shift into an and.
6030 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6031 Constant *Mask =
Chris Lattner4de84762010-01-04 07:02:48 +00006032 ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006033 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006034
Chris Lattner74381062009-08-30 07:44:24 +00006035 Value *And =
6036 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006037 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner4de84762010-01-04 07:02:48 +00006038 ConstantInt::get(ICI.getContext(),
6039 RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006040 }
6041 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006042
6043 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6044 bool TrueIfSigned = false;
6045 if (LHSI->hasOneUse() &&
6046 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6047 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner4de84762010-01-04 07:02:48 +00006048 Constant *Mask = ConstantInt::get(ICI.getContext(), APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006049 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006050 Value *And =
6051 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006052 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006053 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006054 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006055 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006056 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006057
6058 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006059 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006060 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006061 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006062 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006063
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006064 // Check that the shift amount is in range. If not, don't perform
6065 // undefined shifts. When the shift is visited it will be
6066 // simplified.
6067 uint32_t TypeBits = RHSV.getBitWidth();
6068 if (ShAmt->uge(TypeBits))
6069 break;
6070
6071 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006072
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006073 // If we are comparing against bits always shifted out, the
6074 // comparison cannot succeed.
6075 APInt Comp = RHSV << ShAmtVal;
6076 if (LHSI->getOpcode() == Instruction::LShr)
6077 Comp = Comp.lshr(ShAmtVal);
6078 else
6079 Comp = Comp.ashr(ShAmtVal);
6080
6081 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6082 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner4de84762010-01-04 07:02:48 +00006083 Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
6084 IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006085 return ReplaceInstUsesWith(ICI, Cst);
6086 }
6087
6088 // Otherwise, check to see if the bits shifted out are known to be zero.
6089 // If so, we can compare against the unshifted value:
6090 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006091 if (LHSI->hasOneUse() &&
6092 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006093 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006094 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006095 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006096 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006097
Evan Chengf30752c2008-04-23 00:38:06 +00006098 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006099 // Otherwise strength reduce the shift into an and.
6100 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Chris Lattner4de84762010-01-04 07:02:48 +00006101 Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006102
Chris Lattner74381062009-08-30 07:44:24 +00006103 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6104 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006105 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006106 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006107 }
6108 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006109 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006110
6111 case Instruction::SDiv:
6112 case Instruction::UDiv:
6113 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6114 // Fold this div into the comparison, producing a range check.
6115 // Determine, based on the divide type, what the range is being
6116 // checked. If there is an overflow on the low or high side, remember
6117 // it, otherwise compute the range [low, hi) bounding the new value.
6118 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006119 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6120 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6121 DivRHS))
6122 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006123 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006124
6125 case Instruction::Add:
Chris Lattner2799baf2009-12-21 03:19:28 +00006126 // Fold: icmp pred (add X, C1), C2
Nick Lewycky5be29202008-02-03 16:33:09 +00006127 if (!ICI.isEquality()) {
6128 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6129 if (!LHSC) break;
6130 const APInt &LHSV = LHSC->getValue();
6131
6132 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6133 .subtract(LHSV);
6134
Nick Lewycky4a134af2009-10-25 05:20:17 +00006135 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00006136 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006137 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00006138 ConstantInt::get(ICI.getContext(),CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006139 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006140 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00006141 ConstantInt::get(ICI.getContext(),CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006142 }
6143 } else {
6144 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006145 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00006146 ConstantInt::get(ICI.getContext(),CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006147 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006148 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00006149 ConstantInt::get(ICI.getContext(),CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006150 }
6151 }
6152 }
6153 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006154 }
6155
6156 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6157 if (ICI.isEquality()) {
6158 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6159
6160 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6161 // the second operand is a constant, simplify a bit.
6162 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6163 switch (BO->getOpcode()) {
6164 case Instruction::SRem:
6165 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6166 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6167 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6168 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00006169 Value *NewRem =
6170 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6171 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006172 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00006173 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006174 }
6175 }
6176 break;
6177 case Instruction::Add:
6178 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6179 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6180 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006181 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006182 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006183 } else if (RHSV == 0) {
6184 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6185 // efficiently invertible, or if the add has just this one use.
6186 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6187
Dan Gohman186a6362009-08-12 16:04:34 +00006188 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006189 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00006190 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006191 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006192 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00006193 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006194 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006195 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006196 }
6197 }
6198 break;
6199 case Instruction::Xor:
6200 // For the xor case, we can xor two constants together, eliminating
6201 // the explicit xor.
6202 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006203 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006204 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006205
6206 // FALLTHROUGH
6207 case Instruction::Sub:
6208 // Replace (([sub|xor] A, B) != 0) with (A != B)
6209 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006210 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006211 BO->getOperand(1));
6212 break;
6213
6214 case Instruction::Or:
6215 // If bits are being or'd in that are not present in the constant we
6216 // are comparing against, then the comparison could never succeed!
6217 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006218 Constant *NotCI = ConstantExpr::getNot(RHS);
6219 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00006220 return ReplaceInstUsesWith(ICI,
Chris Lattner4de84762010-01-04 07:02:48 +00006221 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
Owen Andersond672ecb2009-07-03 00:17:18 +00006222 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006223 }
6224 break;
6225
6226 case Instruction::And:
6227 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6228 // If bits are being compared against that are and'd out, then the
6229 // comparison can never succeed!
6230 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00006231 return ReplaceInstUsesWith(ICI,
Chris Lattner4de84762010-01-04 07:02:48 +00006232 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
Owen Andersond672ecb2009-07-03 00:17:18 +00006233 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006234
6235 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6236 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006237 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00006238 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00006239 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006240
6241 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006242 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006243 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00006244 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006245 ICmpInst::Predicate pred = isICMP_NE ?
6246 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006247 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006248 }
6249
6250 // ((X & ~7) == 0) --> X < 8
6251 if (RHSV == 0 && isHighOnes(BOC)) {
6252 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006253 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006254 ICmpInst::Predicate pred = isICMP_NE ?
6255 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006256 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006257 }
6258 }
6259 default: break;
6260 }
6261 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6262 // Handle icmp {eq|ne} <intrinsic>, intcst.
6263 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006264 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006265 ICI.setOperand(0, II->getOperand(1));
Chris Lattner4de84762010-01-04 07:02:48 +00006266 ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006267 return &ICI;
6268 }
6269 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006270 }
6271 return 0;
6272}
6273
6274/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6275/// We only handle extending casts so far.
6276///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006277Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6278 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006279 Value *LHSCIOp = LHSCI->getOperand(0);
6280 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006281 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006282 Value *RHSCIOp;
6283
Chris Lattner8c756c12007-05-05 22:41:33 +00006284 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6285 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00006286 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
6287 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00006288 cast<IntegerType>(DestTy)->getBitWidth()) {
6289 Value *RHSOp = 0;
6290 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006291 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006292 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6293 RHSOp = RHSC->getOperand(0);
6294 // If the pointer types don't match, insert a bitcast.
6295 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00006296 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00006297 }
6298
6299 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006300 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00006301 }
6302
6303 // The code below only handles extension cast instructions, so far.
6304 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006305 if (LHSCI->getOpcode() != Instruction::ZExt &&
6306 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006307 return 0;
6308
Reid Spencere4d87aa2006-12-23 06:05:41 +00006309 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006310 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006311
Reid Spencere4d87aa2006-12-23 06:05:41 +00006312 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006313 // Not an extension from the same type?
6314 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006315 if (RHSCIOp->getType() != LHSCIOp->getType())
6316 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006317
Nick Lewycky4189a532008-01-28 03:48:02 +00006318 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006319 // and the other is a zext), then we can't handle this.
6320 if (CI->getOpcode() != LHSCI->getOpcode())
6321 return 0;
6322
Nick Lewycky4189a532008-01-28 03:48:02 +00006323 // Deal with equality cases early.
6324 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006325 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00006326
6327 // A signed comparison of sign extended values simplifies into a
6328 // signed comparison.
6329 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006330 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00006331
6332 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006333 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006334 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006335
Reid Spencere4d87aa2006-12-23 06:05:41 +00006336 // If we aren't dealing with a constant on the RHS, exit early
6337 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6338 if (!CI)
6339 return 0;
6340
6341 // Compute the constant that would happen if we truncated to SrcTy then
6342 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006343 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6344 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006345 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006346
6347 // If the re-extended constant didn't change...
6348 if (Res2 == CI) {
Eli Friedmanb17cb062009-12-17 22:42:29 +00006349 // Deal with equality cases early.
6350 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006351 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedmanb17cb062009-12-17 22:42:29 +00006352
6353 // A signed comparison of sign extended values simplifies into a
6354 // signed comparison.
6355 if (isSignedExt && isSignedCmp)
6356 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6357
6358 // The other three cases all fold into an unsigned comparison.
6359 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006360 }
6361
6362 // The re-extended constant changed so the constant cannot be represented
6363 // in the shorter type. Consequently, we cannot emit a simple comparison.
6364
6365 // First, handle some easy cases. We know the result cannot be equal at this
6366 // point so handle the ICI.isEquality() cases
6367 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Chris Lattner4de84762010-01-04 07:02:48 +00006368 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00006369 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner4de84762010-01-04 07:02:48 +00006370 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00006371
6372 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6373 // should have been folded away previously and not enter in here.
6374 Value *Result;
6375 if (isSignedCmp) {
6376 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006377 if (cast<ConstantInt>(CI)->getValue().isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00006378 Result = ConstantInt::getFalse(ICI.getContext()); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006379 else
Chris Lattner4de84762010-01-04 07:02:48 +00006380 Result = ConstantInt::getTrue(ICI.getContext()); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006381 } else {
6382 // We're performing an unsigned comparison.
6383 if (isSignedExt) {
6384 // We're performing an unsigned comp with a sign extended value.
6385 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00006386 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00006387 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006388 } else {
6389 // Unsigned extend & unsigned compare -> always true.
Chris Lattner4de84762010-01-04 07:02:48 +00006390 Result = ConstantInt::getTrue(ICI.getContext());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006391 }
6392 }
6393
6394 // Finally, return the value computed.
6395 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00006396 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006397 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00006398
6399 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6400 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6401 "ICmp should be folded!");
6402 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00006403 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00006404 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00006405}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006406
Reid Spencer832254e2007-02-02 02:16:23 +00006407Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6408 return commonShiftTransforms(I);
6409}
6410
6411Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6412 return commonShiftTransforms(I);
6413}
6414
6415Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006416 if (Instruction *R = commonShiftTransforms(I))
6417 return R;
6418
6419 Value *Op0 = I.getOperand(0);
6420
6421 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6422 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6423 if (CSI->isAllOnesValue())
6424 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00006425
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006426 // See if we can turn a signed shr into an unsigned shr.
6427 if (MaskedValueIsZero(Op0,
6428 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
6429 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6430
6431 // Arithmetic shifting an all-sign-bit value is a no-op.
6432 unsigned NumSignBits = ComputeNumSignBits(Op0);
6433 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
6434 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00006435
Chris Lattner348f6652007-12-06 01:59:46 +00006436 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006437}
6438
6439Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6440 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006441 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006442
6443 // shl X, 0 == X and shr X, 0 == X
6444 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00006445 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6446 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00006447 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006448
Reid Spencere4d87aa2006-12-23 06:05:41 +00006449 if (isa<UndefValue>(Op0)) {
6450 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006451 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006452 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00006453 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006454 }
6455 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006456 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6457 return ReplaceInstUsesWith(I, Op0);
6458 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00006459 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006460 }
6461
Dan Gohman9004c8a2009-05-21 02:28:33 +00006462 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00006463 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00006464 return &I;
6465
Chris Lattner2eefe512004-04-09 19:05:30 +00006466 // Try to fold constant and into select arguments.
6467 if (isa<Constant>(Op0))
6468 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006469 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006470 return R;
6471
Reid Spencerb83eb642006-10-20 07:07:24 +00006472 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006473 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6474 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006475 return 0;
6476}
6477
Reid Spencerb83eb642006-10-20 07:07:24 +00006478Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006479 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00006480 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006481
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006482 // See if we can simplify any instructions used by the instruction whose sole
6483 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006484 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006485
Dan Gohmana119de82009-06-14 23:30:43 +00006486 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
6487 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00006488 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006489 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006490 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00006491 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006492 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00006493 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006494 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006495 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006496 }
6497
6498 // ((X*C1) << C2) == (X * (C1 << C2))
6499 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6500 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6501 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006502 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006503 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006504
6505 // Try to fold constant and into select arguments.
6506 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6507 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6508 return R;
6509 if (isa<PHINode>(Op0))
6510 if (Instruction *NV = FoldOpIntoPhi(I))
6511 return NV;
6512
Chris Lattner8999dd32007-12-22 09:07:47 +00006513 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6514 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6515 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6516 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6517 // place. Don't try to do this transformation in this case. Also, we
6518 // require that the input operand is a shift-by-constant so that we have
6519 // confidence that the shifts will get folded together. We could do this
6520 // xform in more cases, but it is unlikely to be profitable.
6521 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6522 isa<ConstantInt>(TrOp->getOperand(1))) {
6523 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006524 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00006525 // (shift2 (shift1 & 0x00FF), c2)
6526 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00006527
6528 // For logical shifts, the truncation has the effect of making the high
6529 // part of the register be zeros. Emulate this by inserting an AND to
6530 // clear the top bits as needed. This 'and' will usually be zapped by
6531 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006532 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
6533 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00006534 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6535
6536 // The mask we constructed says what the trunc would do if occurring
6537 // between the shifts. We want to know the effect *after* the second
6538 // shift. We know that it is a logical shift by a constant, so adjust the
6539 // mask as appropriate.
6540 if (I.getOpcode() == Instruction::Shl)
6541 MaskV <<= Op1->getZExtValue();
6542 else {
6543 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6544 MaskV = MaskV.lshr(Op1->getZExtValue());
6545 }
6546
Chris Lattner74381062009-08-30 07:44:24 +00006547 // shift1 & 0x00FF
Chris Lattner4de84762010-01-04 07:02:48 +00006548 Value *And = Builder->CreateAnd(NSh,
6549 ConstantInt::get(I.getContext(), MaskV),
Chris Lattner74381062009-08-30 07:44:24 +00006550 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00006551
6552 // Return the value truncated to the interesting size.
6553 return new TruncInst(And, I.getType());
6554 }
6555 }
6556
Chris Lattner4d5542c2006-01-06 07:12:35 +00006557 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006558 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6559 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6560 Value *V1, *V2;
6561 ConstantInt *CC;
6562 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006563 default: break;
6564 case Instruction::Add:
6565 case Instruction::And:
6566 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006567 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006568 // These operators commute.
6569 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006570 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006571 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006572 m_Specific(Op1)))) {
6573 Value *YS = // (Y << C)
6574 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
6575 // (X + (Y << C))
6576 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
6577 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00006578 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00006579 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00006580 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006581 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006582
Chris Lattner150f12a2005-09-18 06:30:59 +00006583 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006584 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006585 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006586 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00006587 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00006588 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00006589 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006590 Value *YS = // (Y << C)
6591 Builder->CreateShl(Op0BO->getOperand(0), Op1,
6592 Op0BO->getName());
6593 // X & (CC << C)
6594 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6595 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006596 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006597 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006598 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006599
Reid Spencera07cb7d2007-02-02 14:41:37 +00006600 // FALL THROUGH.
6601 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006602 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006603 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006604 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00006605 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006606 Value *YS = // (Y << C)
6607 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
6608 // (X + (Y << C))
6609 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
6610 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00006611 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00006612 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00006613 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006614 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006615
Chris Lattner13d4ab42006-05-31 21:14:00 +00006616 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006617 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6618 match(Op0BO->getOperand(0),
6619 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00006620 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006621 cast<BinaryOperator>(Op0BO->getOperand(0))
6622 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006623 Value *YS = // (Y << C)
6624 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
6625 // X & (CC << C)
6626 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6627 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00006628
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006629 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006630 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006631
Chris Lattner11021cb2005-09-18 05:12:10 +00006632 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006633 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006634 }
6635
6636
6637 // If the operand is an bitwise operator with a constant RHS, and the
6638 // shift is the only use, we can pull it out of the shift.
6639 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6640 bool isValid = true; // Valid only for And, Or, Xor
6641 bool highBitSet = false; // Transform if high bit of constant set?
6642
6643 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006644 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006645 case Instruction::Add:
6646 isValid = isLeftShift;
6647 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006648 case Instruction::Or:
6649 case Instruction::Xor:
6650 highBitSet = false;
6651 break;
6652 case Instruction::And:
6653 highBitSet = true;
6654 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006655 }
6656
6657 // If this is a signed shift right, and the high bit is modified
6658 // by the logical operation, do not perform the transformation.
6659 // The highBitSet boolean indicates the value of the high bit of
6660 // the constant which would cause it to be modified for this
6661 // operation.
6662 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006663 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006664 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006665
6666 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006667 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006668
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006669 Value *NewShift =
6670 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00006671 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006672
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006673 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006674 NewRHS);
6675 }
6676 }
6677 }
6678 }
6679
Chris Lattnerad0124c2006-01-06 07:52:12 +00006680 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006681 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6682 if (ShiftOp && !ShiftOp->isShift())
6683 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006684
Reid Spencerb83eb642006-10-20 07:07:24 +00006685 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006686 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006687 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6688 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006689 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6690 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6691 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006692
Zhou Sheng4351c642007-04-02 08:20:41 +00006693 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00006694
6695 const IntegerType *Ty = cast<IntegerType>(I.getType());
6696
6697 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006698 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00006699 // If this is oversized composite shift, then unsigned shifts get 0, ashr
6700 // saturates.
6701 if (AmtSum >= TypeBits) {
6702 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00006703 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00006704 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
6705 }
6706
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006707 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00006708 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006709 }
6710
6711 if (ShiftOp->getOpcode() == Instruction::LShr &&
6712 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00006713 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00006714 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00006715
Chris Lattnerb87056f2007-02-05 00:57:54 +00006716 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00006717 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006718 }
6719
6720 if (ShiftOp->getOpcode() == Instruction::AShr &&
6721 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006722 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00006723 if (AmtSum >= TypeBits)
6724 AmtSum = TypeBits-1;
6725
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006726 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006727
Zhou Shenge9e03f62007-03-28 15:02:20 +00006728 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner4de84762010-01-04 07:02:48 +00006729 return BinaryOperator::CreateAnd(Shift,
6730 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006731 }
6732
Chris Lattnerb87056f2007-02-05 00:57:54 +00006733 // Okay, if we get here, one shift must be left, and the other shift must be
6734 // right. See if the amounts are equal.
6735 if (ShiftAmt1 == ShiftAmt2) {
6736 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6737 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006738 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00006739 return BinaryOperator::CreateAnd(X,
6740 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006741 }
6742 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6743 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006744 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00006745 return BinaryOperator::CreateAnd(X,
6746 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006747 }
6748 // We can simplify ((X << C) >>s C) into a trunc + sext.
6749 // NOTE: we could do this for any C, but that would make 'unusual' integer
6750 // types. For now, just stick to ones well-supported by the code
6751 // generators.
6752 const Type *SExtType = 0;
6753 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006754 case 1 :
6755 case 8 :
6756 case 16 :
6757 case 32 :
6758 case 64 :
6759 case 128:
Chris Lattner4de84762010-01-04 07:02:48 +00006760 SExtType = IntegerType::get(I.getContext(),
6761 Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00006762 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006763 default: break;
6764 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006765 if (SExtType)
6766 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006767 // Otherwise, we can't handle it yet.
6768 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006769 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006770
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006771 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006772 if (I.getOpcode() == Instruction::Shl) {
6773 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6774 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006775 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006776
Reid Spencer55702aa2007-03-25 21:11:44 +00006777 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00006778 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00006779 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006780 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006781
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006782 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006783 if (I.getOpcode() == Instruction::LShr) {
6784 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006785 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006786
Reid Spencerd5e30f02007-03-26 17:18:58 +00006787 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00006788 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00006789 ConstantInt::get(I.getContext(),Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006790 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006791
6792 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6793 } else {
6794 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006795 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006796
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006797 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006798 if (I.getOpcode() == Instruction::Shl) {
6799 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6800 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006801 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
6802 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006803
Reid Spencer55702aa2007-03-25 21:11:44 +00006804 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00006805 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00006806 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006807 }
6808
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006809 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006810 if (I.getOpcode() == Instruction::LShr) {
6811 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006812 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006813
Reid Spencer68d27cf2007-03-26 23:45:51 +00006814 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00006815 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00006816 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006817 }
6818
6819 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006820 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006821 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006822 return 0;
6823}
6824
Chris Lattnera1be5662002-05-02 17:06:02 +00006825
Chris Lattnercfd65102005-10-29 04:36:15 +00006826/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6827/// expression. If so, decompose it, returning some value X, such that Val is
6828/// X*Scale+Offset.
6829///
6830static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Chris Lattner4de84762010-01-04 07:02:48 +00006831 int &Offset) {
6832 assert(Val->getType() == Type::getInt32Ty(Val->getContext()) &&
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006833 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006834 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006835 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006836 Scale = 0;
Chris Lattner4de84762010-01-04 07:02:48 +00006837 return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006838 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6839 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6840 if (I->getOpcode() == Instruction::Shl) {
6841 // This is a value scaled by '1 << the shift amt'.
6842 Scale = 1U << RHS->getZExtValue();
6843 Offset = 0;
6844 return I->getOperand(0);
6845 } else if (I->getOpcode() == Instruction::Mul) {
6846 // This value is scaled by 'RHS'.
6847 Scale = RHS->getZExtValue();
6848 Offset = 0;
6849 return I->getOperand(0);
6850 } else if (I->getOpcode() == Instruction::Add) {
6851 // We have X+C. Check to see if we really have (X*C2)+C1,
6852 // where C1 is divisible by C2.
6853 unsigned SubScale;
6854 Value *SubVal =
Chris Lattner4de84762010-01-04 07:02:48 +00006855 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
Chris Lattner6a94de22007-10-12 05:30:59 +00006856 Offset += RHS->getZExtValue();
6857 Scale = SubScale;
6858 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006859 }
6860 }
6861 }
6862
6863 // Otherwise, we can't look past this.
6864 Scale = 1;
6865 Offset = 0;
6866 return Val;
6867}
6868
6869
Chris Lattnerb3f83972005-10-24 06:03:58 +00006870/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6871/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006872Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00006873 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006874 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006875
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006876 BuilderTy AllocaBuilder(*Builder);
6877 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
6878
Chris Lattnerb53c2382005-10-24 06:22:12 +00006879 // Remove any uses of AI that are dead.
6880 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006881
Chris Lattnerb53c2382005-10-24 06:22:12 +00006882 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6883 Instruction *User = cast<Instruction>(*UI++);
6884 if (isInstructionTriviallyDead(User)) {
6885 while (UI != E && *UI == User)
6886 ++UI; // If this instruction uses AI more than once, don't break UI.
6887
Chris Lattnerb53c2382005-10-24 06:22:12 +00006888 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00006889 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006890 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006891 }
6892 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00006893
6894 // This requires TargetData to get the alloca alignment and size information.
6895 if (!TD) return 0;
6896
Chris Lattnerb3f83972005-10-24 06:03:58 +00006897 // Get the type really allocated and the type casted to.
6898 const Type *AllocElTy = AI.getAllocatedType();
6899 const Type *CastElTy = PTy->getElementType();
6900 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006901
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006902 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6903 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006904 if (CastElTyAlign < AllocElTyAlign) return 0;
6905
Chris Lattner39387a52005-10-24 06:35:18 +00006906 // If the allocation has multiple uses, only promote it if we are strictly
6907 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00006908 // same, we open the door to infinite loops of various kinds. (A reference
6909 // from a dbg.declare doesn't count as a use for this purpose.)
6910 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
6911 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00006912
Duncan Sands777d2302009-05-09 07:06:46 +00006913 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
6914 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006915 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006916
Chris Lattner455fcc82005-10-29 03:19:53 +00006917 // See if we can satisfy the modulus by pulling a scale out of the array
6918 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006919 unsigned ArraySizeScale;
6920 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006921 Value *NumElements = // See if the array size is a decomposable linear expr.
Chris Lattner4de84762010-01-04 07:02:48 +00006922 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
Chris Lattnercfd65102005-10-29 04:36:15 +00006923
Chris Lattner455fcc82005-10-29 03:19:53 +00006924 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6925 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006926 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6927 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006928
Chris Lattner455fcc82005-10-29 03:19:53 +00006929 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6930 Value *Amt = 0;
6931 if (Scale == 1) {
6932 Amt = NumElements;
6933 } else {
Chris Lattner4de84762010-01-04 07:02:48 +00006934 Amt = ConstantInt::get(Type::getInt32Ty(CI.getContext()), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006935 // Insert before the alloca, not before the cast.
6936 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006937 }
6938
Jeff Cohen86796be2007-04-04 16:58:57 +00006939 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Chris Lattner4de84762010-01-04 07:02:48 +00006940 Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
6941 Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006942 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00006943 }
6944
Victor Hernandez7b929da2009-10-23 21:09:37 +00006945 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006946 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00006947 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006948
Dale Johannesena0a66372009-03-05 00:39:02 +00006949 // If the allocation has one real use plus a dbg.declare, just remove the
6950 // declare.
6951 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
6952 EraseInstFromFunction(*DI);
6953 }
6954 // If the allocation has multiple real uses, insert a cast and change all
6955 // things that used it to use the new cast. This will also hack on CI, but it
6956 // will die soon.
6957 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006958 // New is the allocation instruction, pointer typed. AI is the original
6959 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00006960 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006961 AI.replaceAllUsesWith(NewCast);
6962 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006963 return ReplaceInstUsesWith(CI, New);
6964}
6965
Chris Lattner70074e02006-05-13 02:06:03 +00006966/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006967/// and return it as type Ty without inserting any new casts and without
6968/// changing the computed value. This is used by code that tries to decide
6969/// whether promoting or shrinking integer operations to wider or smaller types
6970/// will allow us to eliminate a truncate or extend.
6971///
6972/// This is a truncation operation if Ty is smaller than V->getType(), or an
6973/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00006974///
6975/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
6976/// should return true if trunc(V) can be computed by computing V in the smaller
6977/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
6978/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6979/// efficiently truncated.
6980///
6981/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6982/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6983/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00006984bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00006985 unsigned CastOpc,
6986 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00006987 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00006988 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00006989 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006990
6991 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006992 if (!I) return false;
6993
Dan Gohman6de29f82009-06-15 22:12:54 +00006994 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00006995
Chris Lattner951626b2007-08-02 06:11:14 +00006996 // If this is an extension or truncate, we can often eliminate it.
6997 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6998 // If this is a cast from the destination type, we can trivially eliminate
6999 // it, and this will remove a cast overall.
7000 if (I->getOperand(0)->getType() == Ty) {
7001 // If the first operand is itself a cast, and is eliminable, do not count
7002 // this as an eliminable cast. We would prefer to eliminate those two
7003 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007004 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007005 ++NumCastsRemoved;
7006 return true;
7007 }
7008 }
7009
7010 // We can't extend or shrink something that has multiple uses: doing so would
7011 // require duplicating the instruction in general, which isn't profitable.
7012 if (!I->hasOneUse()) return false;
7013
Evan Chengf35fd542009-01-15 17:01:23 +00007014 unsigned Opc = I->getOpcode();
7015 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007016 case Instruction::Add:
7017 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007018 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007019 case Instruction::And:
7020 case Instruction::Or:
7021 case Instruction::Xor:
7022 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007023 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007024 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007025 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007026 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007027
Eli Friedman070a9812009-07-13 22:46:01 +00007028 case Instruction::UDiv:
7029 case Instruction::URem: {
7030 // UDiv and URem can be truncated if all the truncated bits are zero.
7031 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7032 uint32_t BitWidth = Ty->getScalarSizeInBits();
7033 if (BitWidth < OrigBitWidth) {
7034 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7035 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7036 MaskedValueIsZero(I->getOperand(1), Mask)) {
7037 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7038 NumCastsRemoved) &&
7039 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7040 NumCastsRemoved);
7041 }
7042 }
7043 break;
7044 }
Chris Lattner46b96052006-11-29 07:18:39 +00007045 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007046 // If we are truncating the result of this SHL, and if it's a shift of a
7047 // constant amount, we can always perform a SHL in a smaller type.
7048 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007049 uint32_t BitWidth = Ty->getScalarSizeInBits();
7050 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007051 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007052 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007053 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007054 }
7055 break;
7056 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007057 // If this is a truncate of a logical shr, we can truncate it to a smaller
7058 // lshr iff we know that the bits we would otherwise be shifting in are
7059 // already zeros.
7060 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007061 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7062 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007063 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007064 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007065 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7066 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007067 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007068 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007069 }
7070 }
Chris Lattner46b96052006-11-29 07:18:39 +00007071 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007072 case Instruction::ZExt:
7073 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007074 case Instruction::Trunc:
7075 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007076 // can safely replace it. Note that replacing it does not reduce the number
7077 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007078 if (Opc == CastOpc)
7079 return true;
7080
7081 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007082 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007083 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007084 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007085 case Instruction::Select: {
7086 SelectInst *SI = cast<SelectInst>(I);
7087 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007088 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007089 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007090 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007091 }
Chris Lattner8114b712008-06-18 04:00:49 +00007092 case Instruction::PHI: {
7093 // We can change a phi if we can change all operands.
7094 PHINode *PN = cast<PHINode>(I);
7095 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7096 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007097 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007098 return false;
7099 return true;
7100 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007101 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007102 // TODO: Can handle more cases here.
7103 break;
7104 }
7105
7106 return false;
7107}
7108
7109/// EvaluateInDifferentType - Given an expression that
7110/// CanEvaluateInDifferentType returns true for, actually insert the code to
7111/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007112Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007113 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007114 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00007115 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007116
7117 // Otherwise, it must be an instruction.
7118 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007119 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007120 unsigned Opc = I->getOpcode();
7121 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007122 case Instruction::Add:
7123 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007124 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007125 case Instruction::And:
7126 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007127 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007128 case Instruction::AShr:
7129 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00007130 case Instruction::Shl:
7131 case Instruction::UDiv:
7132 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007133 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007134 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007135 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007136 break;
7137 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007138 case Instruction::Trunc:
7139 case Instruction::ZExt:
7140 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007141 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007142 // just return the source. There's no need to insert it because it is not
7143 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007144 if (I->getOperand(0)->getType() == Ty)
7145 return I->getOperand(0);
7146
Chris Lattner8114b712008-06-18 04:00:49 +00007147 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00007148 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007149 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007150 case Instruction::Select: {
7151 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7152 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7153 Res = SelectInst::Create(I->getOperand(0), True, False);
7154 break;
7155 }
Chris Lattner8114b712008-06-18 04:00:49 +00007156 case Instruction::PHI: {
7157 PHINode *OPN = cast<PHINode>(I);
7158 PHINode *NPN = PHINode::Create(Ty);
7159 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7160 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7161 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7162 }
7163 Res = NPN;
7164 break;
7165 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007166 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007167 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00007168 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00007169 break;
7170 }
7171
Chris Lattner8114b712008-06-18 04:00:49 +00007172 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007173 return InsertNewInstBefore(Res, *I);
7174}
7175
Reid Spencer3da59db2006-11-27 01:05:10 +00007176/// @brief Implement the transforms common to all CastInst visitors.
7177Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007178 Value *Src = CI.getOperand(0);
7179
Dan Gohman23d9d272007-05-11 21:10:54 +00007180 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007181 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007182 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007183 if (Instruction::CastOps opc =
7184 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7185 // The first cast (CSrc) is eliminable so we need to fix up or replace
7186 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007187 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007188 }
7189 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007190
Reid Spencer3da59db2006-11-27 01:05:10 +00007191 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007192 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7193 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7194 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007195
7196 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00007197 if (isa<PHINode>(Src)) {
7198 // We don't do this if this would create a PHI node with an illegal type if
7199 // it is currently legal.
7200 if (!isa<IntegerType>(Src->getType()) ||
7201 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerc22d4d12009-11-10 07:23:37 +00007202 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner9956c052009-11-08 19:23:30 +00007203 if (Instruction *NV = FoldOpIntoPhi(CI))
7204 return NV;
Chris Lattner9956c052009-11-08 19:23:30 +00007205 }
Chris Lattner9fb92132006-04-12 18:09:35 +00007206
Reid Spencer3da59db2006-11-27 01:05:10 +00007207 return 0;
7208}
7209
Chris Lattner46cd5a12009-01-09 05:44:56 +00007210/// FindElementAtOffset - Given a type and a constant offset, determine whether
7211/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007212/// the specified offset. If so, fill them into NewIndices and return the
7213/// resultant element type, otherwise return null.
7214static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7215 SmallVectorImpl<Value*> &NewIndices,
Chris Lattner4de84762010-01-04 07:02:48 +00007216 const TargetData *TD) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007217 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00007218 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007219
7220 // Start with the index over the outer type. Note that the type size
7221 // might be zero (even if the offset isn't zero) if the indexed type
7222 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +00007223 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +00007224 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00007225 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007226 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00007227 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007228
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007229 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00007230 if (Offset < 0) {
7231 --FirstIdx;
7232 Offset += TySize;
7233 assert(Offset >= 0);
7234 }
7235 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7236 }
7237
Owen Andersoneed707b2009-07-24 23:12:02 +00007238 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00007239
7240 // Index into the types. If we fail, set OrigBase to null.
7241 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007242 // Indexing into tail padding between struct/array elements.
7243 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00007244 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007245
Chris Lattner46cd5a12009-01-09 05:44:56 +00007246 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7247 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007248 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7249 "Offset must stay within the indexed type");
7250
Chris Lattner46cd5a12009-01-09 05:44:56 +00007251 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +00007252 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
7253 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00007254
7255 Offset -= SL->getElementOffset(Elt);
7256 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00007257 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00007258 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007259 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00007260 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007261 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00007262 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007263 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007264 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00007265 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007266 }
7267 }
7268
Chris Lattner3914f722009-01-24 01:00:13 +00007269 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007270}
7271
Chris Lattnerd3e28342007-04-27 17:44:50 +00007272/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7273Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7274 Value *Src = CI.getOperand(0);
7275
Chris Lattnerd3e28342007-04-27 17:44:50 +00007276 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007277 // If casting the result of a getelementptr instruction with no offset, turn
7278 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007279 if (GEP->hasAllZeroIndices()) {
7280 // Changing the cast operand is usually not a good idea but it is safe
7281 // here because the pointer operand is being replaced with another
7282 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00007283 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007284 CI.setOperand(0, GEP->getOperand(0));
7285 return &CI;
7286 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007287
7288 // If the GEP has a single use, and the base pointer is a bitcast, and the
7289 // GEP computes a constant offset, see if we can convert these three
7290 // instructions into fewer. This typically happens with unions and other
7291 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007292 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007293 if (GEP->hasAllConstantIndices()) {
7294 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00007295 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00007296 int64_t Offset = OffsetV->getSExtValue();
7297
7298 // Get the base pointer input of the bitcast, and the type it points to.
7299 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7300 const Type *GEPIdxTy =
7301 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007302 SmallVector<Value*, 8> NewIndices;
Chris Lattner4de84762010-01-04 07:02:48 +00007303 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007304 // If we were able to index down into an element, create the GEP
7305 // and bitcast the result. This eliminates one bitcast, potentially
7306 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00007307 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
7308 Builder->CreateInBoundsGEP(OrigBase,
7309 NewIndices.begin(), NewIndices.end()) :
7310 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00007311 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00007312
Chris Lattner46cd5a12009-01-09 05:44:56 +00007313 if (isa<BitCastInst>(CI))
7314 return new BitCastInst(NGEP, CI.getType());
7315 assert(isa<PtrToIntInst>(CI));
7316 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00007317 }
7318 }
7319 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007320 }
7321
7322 return commonCastTransforms(CI);
7323}
7324
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00007325/// commonIntCastTransforms - This function implements the common transforms
7326/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00007327Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7328 if (Instruction *Result = commonCastTransforms(CI))
7329 return Result;
7330
7331 Value *Src = CI.getOperand(0);
7332 const Type *SrcTy = Src->getType();
7333 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00007334 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
7335 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007336
Reid Spencer3da59db2006-11-27 01:05:10 +00007337 // See if we can simplify any instructions used by the LHS whose sole
7338 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00007339 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00007340 return &CI;
7341
7342 // If the source isn't an instruction or has more than one use then we
7343 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007344 Instruction *SrcI = dyn_cast<Instruction>(Src);
7345 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007346 return 0;
7347
Chris Lattnerc739cd62007-03-03 05:27:34 +00007348 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007349 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00007350 // Only do this if the dest type is a simple type, don't convert the
7351 // expression tree to something weird like i93 unless the source is also
7352 // strange.
Chris Lattner6b583912009-11-10 17:00:47 +00007353 if ((isa<VectorType>(DestTy) ||
7354 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
7355 CanEvaluateInDifferentType(SrcI, DestTy,
7356 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007357 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007358 // eliminates the cast, so it is always a win. If this is a zero-extension,
7359 // we need to do an AND to maintain the clear top-part of the computation,
7360 // so we require that the input have eliminated at least one cast. If this
7361 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007362 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00007363 bool DoXForm = false;
7364 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007365 switch (CI.getOpcode()) {
7366 default:
7367 // All the others use floating point so we shouldn't actually
7368 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00007369 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00007370 case Instruction::Trunc:
7371 DoXForm = true;
7372 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007373 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007374 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00007375
Chris Lattner39c27ed2009-01-31 19:05:27 +00007376 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00007377 // If it's unnecessary to issue an AND to clear the high bits, it's
7378 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00007379 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007380 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7381 if (MaskedValueIsZero(TryRes, Mask))
7382 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00007383
7384 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00007385 if (TryI->use_empty())
7386 EraseInstFromFunction(*TryI);
7387 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007388 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007389 }
Evan Chengf35fd542009-01-15 17:01:23 +00007390 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007391 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00007392 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00007393 // If we do not have to emit the truncate + sext pair, then it's always
7394 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00007395 //
7396 // It's not safe to eliminate the trunc + sext pair if one of the
7397 // eliminated cast is a truncate. e.g.
7398 // t2 = trunc i32 t1 to i16
7399 // t3 = sext i16 t2 to i32
7400 // !=
7401 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00007402 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007403 unsigned NumSignBits = ComputeNumSignBits(TryRes);
7404 if (NumSignBits > (DestBitSize - SrcBitSize))
7405 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00007406
7407 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00007408 if (TryI->use_empty())
7409 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00007410 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007411 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007412 }
Evan Chengf35fd542009-01-15 17:01:23 +00007413 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007414
7415 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00007416 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
7417 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00007418 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7419 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007420 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00007421 // Just replace this cast with the result.
7422 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007423
Reid Spencer3da59db2006-11-27 01:05:10 +00007424 assert(Res->getType() == DestTy);
7425 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00007426 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00007427 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00007428 // Just replace this cast with the result.
7429 return ReplaceInstUsesWith(CI, Res);
7430 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00007431 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00007432
7433 // If the high bits are already zero, just replace this cast with the
7434 // result.
7435 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7436 if (MaskedValueIsZero(Res, Mask))
7437 return ReplaceInstUsesWith(CI, Res);
7438
7439 // We need to emit an AND to clear the high bits.
Chris Lattner4de84762010-01-04 07:02:48 +00007440 Constant *C = ConstantInt::get(CI.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00007441 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007442 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007443 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00007444 case Instruction::SExt: {
7445 // If the high bits are already filled with sign bit, just replace this
7446 // cast with the result.
7447 unsigned NumSignBits = ComputeNumSignBits(Res);
7448 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00007449 return ReplaceInstUsesWith(CI, Res);
7450
Reid Spencer3da59db2006-11-27 01:05:10 +00007451 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00007452 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007453 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00007454 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007455 }
7456 }
7457
7458 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7459 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7460
7461 switch (SrcI->getOpcode()) {
7462 case Instruction::Add:
7463 case Instruction::Mul:
7464 case Instruction::And:
7465 case Instruction::Or:
7466 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007467 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00007468 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
7469 // Don't insert two casts unless at least one can be eliminated.
7470 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007471 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00007472 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
7473 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007474 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007475 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007476 }
7477 }
7478
7479 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7480 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7481 SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner4de84762010-01-04 07:02:48 +00007482 Op1 == ConstantInt::getTrue(CI.getContext()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007483 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00007484 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00007485 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00007486 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007487 }
7488 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007489
Eli Friedman65445c52009-07-13 21:45:57 +00007490 case Instruction::Shl: {
7491 // Canonicalize trunc inside shl, if we can.
7492 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
7493 if (CI && DestBitSize < SrcBitSize &&
7494 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00007495 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
7496 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007497 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007498 }
7499 break;
Eli Friedman65445c52009-07-13 21:45:57 +00007500 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007501 }
7502 return 0;
7503}
7504
Chris Lattner8a9f5712007-04-11 06:57:46 +00007505Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007506 if (Instruction *Result = commonIntCastTransforms(CI))
7507 return Result;
7508
7509 Value *Src = CI.getOperand(0);
7510 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00007511 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
7512 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00007513
7514 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00007515 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00007516 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007517 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00007518 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007519 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00007520 }
Dan Gohman6de29f82009-06-15 22:12:54 +00007521
Chris Lattner4f9797d2009-03-24 18:15:30 +00007522 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
7523 ConstantInt *ShAmtV = 0;
7524 Value *ShiftOp = 0;
7525 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00007526 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00007527 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7528
7529 // Get a mask for the bits shifting in.
7530 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7531 if (MaskedValueIsZero(ShiftOp, Mask)) {
7532 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00007533 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00007534
7535 // Okay, we can shrink this. Truncate the input, then return a new
7536 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00007537 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00007538 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00007539 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007540 }
7541 }
Chris Lattner9956c052009-11-08 19:23:30 +00007542
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007543 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007544}
7545
Evan Chengb98a10e2008-03-24 00:21:34 +00007546/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7547/// in order to eliminate the icmp.
7548Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7549 bool DoXform) {
7550 // If we are just checking for a icmp eq of a single bit and zext'ing it
7551 // to an integer, then shift the bit to the appropriate place and then
7552 // cast to integer to avoid the comparison.
7553 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7554 const APInt &Op1CV = Op1C->getValue();
7555
7556 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7557 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7558 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7559 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7560 if (!DoXform) return ICI;
7561
7562 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00007563 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00007564 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007565 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00007566 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007567 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007568
7569 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00007570 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007571 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00007572 }
7573
7574 return ReplaceInstUsesWith(CI, In);
7575 }
7576
7577
7578
7579 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7580 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7581 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7582 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7583 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7584 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7585 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7586 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7587 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7588 // This only works for EQ and NE
7589 ICI->isEquality()) {
7590 // If Op1C some other power of two, convert:
7591 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7592 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7593 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7594 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7595
7596 APInt KnownZeroMask(~KnownZero);
7597 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7598 if (!DoXform) return ICI;
7599
7600 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7601 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7602 // (X&4) == 2 --> false
7603 // (X&4) != 2 --> true
Chris Lattner4de84762010-01-04 07:02:48 +00007604 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
7605 isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007606 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00007607 return ReplaceInstUsesWith(CI, Res);
7608 }
7609
7610 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7611 Value *In = ICI->getOperand(0);
7612 if (ShiftAmt) {
7613 // Perform a logical shr by shiftamt.
7614 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007615 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
7616 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00007617 }
7618
7619 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00007620 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007621 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007622 }
7623
7624 if (CI.getType() == In->getType())
7625 return ReplaceInstUsesWith(CI, In);
7626 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007627 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007628 }
7629 }
7630 }
7631
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00007632 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
7633 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
7634 // may lead to additional simplifications.
7635 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
7636 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
7637 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky83e8ec72009-12-05 05:00:00 +00007638 Value *LHS = ICI->getOperand(0);
7639 Value *RHS = ICI->getOperand(1);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00007640
Nick Lewycky83e8ec72009-12-05 05:00:00 +00007641 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
7642 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
7643 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7644 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
7645 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00007646
Nick Lewycky83e8ec72009-12-05 05:00:00 +00007647 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
7648 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
7649 APInt UnknownBit = ~KnownBits;
7650 if (UnknownBit.countPopulation() == 1) {
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00007651 if (!DoXform) return ICI;
7652
Nick Lewycky83e8ec72009-12-05 05:00:00 +00007653 Value *Result = Builder->CreateXor(LHS, RHS);
7654
7655 // Mask off any bits that are set and won't be shifted away.
7656 if (KnownOneLHS.uge(UnknownBit))
7657 Result = Builder->CreateAnd(Result,
7658 ConstantInt::get(ITy, UnknownBit));
7659
7660 // Shift the bit we're testing down to the lsb.
7661 Result = Builder->CreateLShr(
7662 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
7663
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00007664 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky83e8ec72009-12-05 05:00:00 +00007665 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
7666 Result->takeName(ICI);
7667 return ReplaceInstUsesWith(CI, Result);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00007668 }
7669 }
7670 }
7671 }
7672
Evan Chengb98a10e2008-03-24 00:21:34 +00007673 return 0;
7674}
7675
Chris Lattner8a9f5712007-04-11 06:57:46 +00007676Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Chris Lattnerdffbef02010-01-04 06:23:24 +00007677 // If one of the common conversion will work, do it.
Reid Spencer3da59db2006-11-27 01:05:10 +00007678 if (Instruction *Result = commonIntCastTransforms(CI))
7679 return Result;
7680
7681 Value *Src = CI.getOperand(0);
7682
Chris Lattnera84f47c2009-02-17 20:47:23 +00007683 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7684 // types and if the sizes are just right we can convert this into a logical
7685 // 'and' which will be much cheaper than the pair of casts.
7686 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
7687 // Get the sizes of the types involved. We know that the intermediate type
7688 // will be smaller than A or C, but don't know the relation between A and C.
7689 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00007690 unsigned SrcSize = A->getType()->getScalarSizeInBits();
7691 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
7692 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00007693 // If we're actually extending zero bits, then if
7694 // SrcSize < DstSize: zext(a & mask)
7695 // SrcSize == DstSize: a & mask
7696 // SrcSize > DstSize: trunc(a) & mask
7697 if (SrcSize < DstSize) {
7698 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00007699 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007700 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00007701 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007702 }
7703
7704 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00007705 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00007706 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00007707 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007708 }
7709 if (SrcSize > DstSize) {
7710 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00007711 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00007712 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00007713 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00007714 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00007715 }
7716 }
7717
Evan Chengb98a10e2008-03-24 00:21:34 +00007718 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7719 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007720
Evan Chengb98a10e2008-03-24 00:21:34 +00007721 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7722 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7723 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7724 // of the (zext icmp) will be transformed.
7725 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7726 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7727 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7728 (transformZExtICmp(LHS, CI, false) ||
7729 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00007730 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
7731 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007732 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007733 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007734 }
7735
Dan Gohmanfd3daa72009-06-18 16:30:21 +00007736 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00007737 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
7738 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
7739 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
7740 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00007741 if (TI0->getType() == CI.getType())
7742 return
7743 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007744 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00007745 }
7746
Dan Gohmanfd3daa72009-06-18 16:30:21 +00007747 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
7748 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
7749 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
7750 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
7751 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
7752 And->getOperand(1) == C)
7753 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
7754 Value *TI0 = TI->getOperand(0);
7755 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007756 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007757 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00007758 return BinaryOperator::CreateXor(NewAnd, ZC);
7759 }
7760 }
7761
Reid Spencer3da59db2006-11-27 01:05:10 +00007762 return 0;
7763}
7764
Chris Lattner8a9f5712007-04-11 06:57:46 +00007765Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007766 if (Instruction *I = commonIntCastTransforms(CI))
7767 return I;
7768
Chris Lattner8a9f5712007-04-11 06:57:46 +00007769 Value *Src = CI.getOperand(0);
7770
Dan Gohman1975d032008-10-30 20:40:10 +00007771 // Canonicalize sign-extend from i1 to a select.
Chris Lattner4de84762010-01-04 07:02:48 +00007772 if (Src->getType() == Type::getInt1Ty(CI.getContext()))
Dan Gohman1975d032008-10-30 20:40:10 +00007773 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00007774 Constant::getAllOnesValue(CI.getType()),
7775 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00007776
7777 // See if the value being truncated is already sign extended. If so, just
7778 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00007779 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00007780 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00007781 unsigned OpBits = Op->getType()->getScalarSizeInBits();
7782 unsigned MidBits = Src->getType()->getScalarSizeInBits();
7783 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00007784 unsigned NumSignBits = ComputeNumSignBits(Op);
7785
7786 if (OpBits == DestBits) {
7787 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7788 // bits, it is already ready.
7789 if (NumSignBits > DestBits-MidBits)
7790 return ReplaceInstUsesWith(CI, Op);
7791 } else if (OpBits < DestBits) {
7792 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7793 // bits, just sext from i32.
7794 if (NumSignBits > OpBits-MidBits)
7795 return new SExtInst(Op, CI.getType(), "tmp");
7796 } else {
7797 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7798 // bits, just truncate to i32.
7799 if (NumSignBits > OpBits-MidBits)
7800 return new TruncInst(Op, CI.getType(), "tmp");
7801 }
7802 }
Chris Lattner46bbad22008-08-06 07:35:52 +00007803
7804 // If the input is a shl/ashr pair of a same constant, then this is a sign
7805 // extension from a smaller value. If we could trust arbitrary bitwidth
7806 // integers, we could turn this into a truncate to the smaller bit and then
7807 // use a sext for the whole extension. Since we don't, look deeper and check
7808 // for a truncate. If the source and dest are the same type, eliminate the
7809 // trunc and extend and just do shifts. For example, turn:
7810 // %a = trunc i32 %i to i8
7811 // %b = shl i8 %a, 6
7812 // %c = ashr i8 %b, 6
7813 // %d = sext i8 %c to i32
7814 // into:
7815 // %a = shl i32 %i, 30
7816 // %d = ashr i32 %a, 30
7817 Value *A = 0;
7818 ConstantInt *BA = 0, *CA = 0;
7819 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007820 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00007821 BA == CA && isa<TruncInst>(A)) {
7822 Value *I = cast<TruncInst>(A)->getOperand(0);
7823 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007824 unsigned MidSize = Src->getType()->getScalarSizeInBits();
7825 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00007826 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00007827 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007828 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00007829 return BinaryOperator::CreateAShr(I, ShAmtV);
7830 }
7831 }
7832
Chris Lattnerba417832007-04-11 06:12:58 +00007833 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007834}
7835
Chris Lattnerb7530652008-01-27 05:29:54 +00007836/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7837/// in the specified FP type without changing its value.
Chris Lattner4de84762010-01-04 07:02:48 +00007838static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00007839 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00007840 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00007841 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
7842 if (!losesInfo)
Chris Lattner4de84762010-01-04 07:02:48 +00007843 return ConstantFP::get(CFP->getContext(), F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007844 return 0;
7845}
7846
7847/// LookThroughFPExtensions - If this is an fp extension instruction, look
7848/// through it until we get the source value.
Chris Lattner4de84762010-01-04 07:02:48 +00007849static Value *LookThroughFPExtensions(Value *V) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007850 if (Instruction *I = dyn_cast<Instruction>(V))
7851 if (I->getOpcode() == Instruction::FPExt)
Chris Lattner4de84762010-01-04 07:02:48 +00007852 return LookThroughFPExtensions(I->getOperand(0));
Chris Lattnerb7530652008-01-27 05:29:54 +00007853
7854 // If this value is a constant, return the constant in the smallest FP type
7855 // that can accurately represent it. This allows us to turn
7856 // (float)((double)X+2.0) into x+2.0f.
7857 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +00007858 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
Chris Lattnerb7530652008-01-27 05:29:54 +00007859 return V; // No constant folding of this.
7860 // See if the value can be truncated to float and then reextended.
Chris Lattner4de84762010-01-04 07:02:48 +00007861 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007862 return V;
Chris Lattner4de84762010-01-04 07:02:48 +00007863 if (CFP->getType() == Type::getDoubleTy(V->getContext()))
Chris Lattnerb7530652008-01-27 05:29:54 +00007864 return V; // Won't shrink.
Chris Lattner4de84762010-01-04 07:02:48 +00007865 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007866 return V;
7867 // Don't try to shrink to various long double types.
7868 }
7869
7870 return V;
7871}
7872
7873Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7874 if (Instruction *I = commonCastTransforms(CI))
7875 return I;
7876
Dan Gohmanae3a0be2009-06-04 22:49:04 +00007877 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00007878 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00007879 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00007880 // many builtins (sqrt, etc).
7881 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7882 if (OpI && OpI->hasOneUse()) {
7883 switch (OpI->getOpcode()) {
7884 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00007885 case Instruction::FAdd:
7886 case Instruction::FSub:
7887 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00007888 case Instruction::FDiv:
7889 case Instruction::FRem:
7890 const Type *SrcTy = OpI->getType();
Chris Lattner4de84762010-01-04 07:02:48 +00007891 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7892 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
Chris Lattnerb7530652008-01-27 05:29:54 +00007893 if (LHSTrunc->getType() != SrcTy &&
7894 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007895 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00007896 // If the source types were both smaller than the destination type of
7897 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00007898 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
7899 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00007900 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
7901 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007902 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007903 }
7904 }
7905 break;
7906 }
7907 }
7908 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007909}
7910
7911Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7912 return commonCastTransforms(CI);
7913}
7914
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007915Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00007916 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7917 if (OpI == 0)
7918 return commonCastTransforms(FI);
7919
7920 // fptoui(uitofp(X)) --> X
7921 // fptoui(sitofp(X)) --> X
7922 // This is safe if the intermediate type has enough bits in its mantissa to
7923 // accurately represent all values of X. For example, do not do this with
7924 // i64->float->i64. This is also safe for sitofp case, because any negative
7925 // 'X' value would cause an undefined result for the fptoui.
7926 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7927 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00007928 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00007929 OpI->getType()->getFPMantissaWidth())
7930 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007931
7932 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007933}
7934
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007935Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00007936 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7937 if (OpI == 0)
7938 return commonCastTransforms(FI);
7939
7940 // fptosi(sitofp(X)) --> X
7941 // fptosi(uitofp(X)) --> X
7942 // This is safe if the intermediate type has enough bits in its mantissa to
7943 // accurately represent all values of X. For example, do not do this with
7944 // i64->float->i64. This is also safe for sitofp case, because any negative
7945 // 'X' value would cause an undefined result for the fptoui.
7946 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7947 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00007948 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00007949 OpI->getType()->getFPMantissaWidth())
7950 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007951
7952 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007953}
7954
7955Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7956 return commonCastTransforms(CI);
7957}
7958
7959Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7960 return commonCastTransforms(CI);
7961}
7962
Chris Lattnera0e69692009-03-24 18:35:40 +00007963Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
7964 // If the destination integer type is smaller than the intptr_t type for
7965 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
7966 // trunc to be exposed to other transforms. Don't do this for extending
7967 // ptrtoint's, because we don't know if the target sign or zero extends its
7968 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007969 if (TD &&
7970 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007971 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
7972 TD->getIntPtrType(CI.getContext()),
7973 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00007974 return new TruncInst(P, CI.getType());
7975 }
7976
Chris Lattnerd3e28342007-04-27 17:44:50 +00007977 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007978}
7979
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007980Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00007981 // If the source integer type is larger than the intptr_t type for
7982 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
7983 // allows the trunc to be exposed to other transforms. Don't do this for
7984 // extending inttoptr's, because we don't know if the target sign or zero
7985 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007986 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00007987 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007988 Value *P = Builder->CreateTrunc(CI.getOperand(0),
7989 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00007990 return new IntToPtrInst(P, CI.getType());
7991 }
7992
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007993 if (Instruction *I = commonCastTransforms(CI))
7994 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007995
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007996 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007997}
7998
Chris Lattnerd3e28342007-04-27 17:44:50 +00007999Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008000 // If the operands are integer typed then apply the integer transforms,
8001 // otherwise just apply the common ones.
8002 Value *Src = CI.getOperand(0);
8003 const Type *SrcTy = Src->getType();
8004 const Type *DestTy = CI.getType();
8005
Eli Friedman7e25d452009-07-13 20:53:00 +00008006 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008007 if (Instruction *I = commonPointerCastTransforms(CI))
8008 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008009 } else {
8010 if (Instruction *Result = commonCastTransforms(CI))
8011 return Result;
8012 }
8013
8014
8015 // Get rid of casts from one type to the same type. These are useless and can
8016 // be replaced by the operand.
8017 if (DestTy == Src->getType())
8018 return ReplaceInstUsesWith(CI, Src);
8019
Reid Spencer3da59db2006-11-27 01:05:10 +00008020 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008021 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8022 const Type *DstElTy = DstPTy->getElementType();
8023 const Type *SrcElTy = SrcPTy->getElementType();
8024
Nate Begeman83ad90a2008-03-31 00:22:16 +00008025 // If the address spaces don't match, don't eliminate the bitcast, which is
8026 // required for changing types.
8027 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8028 return 0;
8029
Victor Hernandez83d63912009-09-18 22:35:49 +00008030 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008031 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008032 // There is no need to modify malloc calls because it is their bitcast that
8033 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00008034 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00008035 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8036 return V;
8037
Chris Lattnerd717c182007-05-05 22:32:24 +00008038 // If the source and destination are pointers, and this cast is equivalent
8039 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008040 // This can enhance SROA and other transforms that want type-safe pointers.
Chris Lattner4de84762010-01-04 07:02:48 +00008041 Constant *ZeroUInt =
8042 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008043 unsigned NumZeros = 0;
8044 while (SrcElTy != DstElTy &&
8045 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8046 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8047 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8048 ++NumZeros;
8049 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008050
Chris Lattnerd3e28342007-04-27 17:44:50 +00008051 // If we found a path from the src to dest, create the getelementptr now.
8052 if (SrcElTy == DstElTy) {
8053 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chris Lattner4de84762010-01-04 07:02:48 +00008054 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008055 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008056 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008057 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008058
Eli Friedman2451a642009-07-18 23:06:53 +00008059 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8060 if (DestVTy->getNumElements() == 1) {
8061 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008062 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008063 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner4de84762010-01-04 07:02:48 +00008064 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Eli Friedman2451a642009-07-18 23:06:53 +00008065 }
8066 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8067 }
8068 }
8069
8070 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8071 if (SrcVTy->getNumElements() == 1) {
8072 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008073 Value *Elem =
8074 Builder->CreateExtractElement(Src,
Chris Lattner4de84762010-01-04 07:02:48 +00008075 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Eli Friedman2451a642009-07-18 23:06:53 +00008076 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8077 }
8078 }
8079 }
8080
Reid Spencer3da59db2006-11-27 01:05:10 +00008081 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8082 if (SVI->hasOneUse()) {
8083 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8084 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008085 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008086 cast<VectorType>(DestTy)->getNumElements() ==
8087 SVI->getType()->getNumElements() &&
8088 SVI->getType()->getNumElements() ==
8089 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008090 CastInst *Tmp;
8091 // If either of the operands is a cast from CI.getType(), then
8092 // evaluating the shuffle in the casted destination's type will allow
8093 // us to eliminate at least one cast.
8094 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8095 Tmp->getOperand(0)->getType() == DestTy) ||
8096 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8097 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008098 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8099 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008100 // Return a new shuffle vector. Use the same element ID's, as we
8101 // know the vector types match #elts.
8102 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008103 }
8104 }
8105 }
8106 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008107 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008108}
8109
Chris Lattnere576b912004-04-09 23:46:01 +00008110/// GetSelectFoldableOperands - We want to turn code that looks like this:
8111/// %C = or %A, %B
8112/// %D = select %cond, %C, %A
8113/// into:
8114/// %C = select %cond, %B, 0
8115/// %D = or %A, %C
8116///
8117/// Assuming that the specified instruction is an operand to the select, return
8118/// a bitmask indicating which operands of this instruction are foldable if they
8119/// equal the other incoming value of the select.
8120///
8121static unsigned GetSelectFoldableOperands(Instruction *I) {
8122 switch (I->getOpcode()) {
8123 case Instruction::Add:
8124 case Instruction::Mul:
8125 case Instruction::And:
8126 case Instruction::Or:
8127 case Instruction::Xor:
8128 return 3; // Can fold through either operand.
8129 case Instruction::Sub: // Can only fold on the amount subtracted.
8130 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008131 case Instruction::LShr:
8132 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008133 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008134 default:
8135 return 0; // Cannot fold
8136 }
8137}
8138
8139/// GetSelectFoldableConstant - For the same transformation as the previous
8140/// function, return the identity constant that goes into the select.
Chris Lattner4de84762010-01-04 07:02:48 +00008141static Constant *GetSelectFoldableConstant(Instruction *I) {
Chris Lattnere576b912004-04-09 23:46:01 +00008142 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008143 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008144 case Instruction::Add:
8145 case Instruction::Sub:
8146 case Instruction::Or:
8147 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008148 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008149 case Instruction::LShr:
8150 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008151 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008152 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008153 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008154 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008155 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008156 }
8157}
8158
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008159/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8160/// have the same opcode and only one use each. Try to simplify this.
8161Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8162 Instruction *FI) {
8163 if (TI->getNumOperands() == 1) {
8164 // If this is a non-volatile load or a cast from the same type,
8165 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008166 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008167 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8168 return 0;
8169 } else {
8170 return 0; // unknown unary op.
8171 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008172
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008173 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008174 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00008175 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008176 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008177 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008178 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008179 }
8180
Reid Spencer832254e2007-02-02 02:16:23 +00008181 // Only handle binary operators here.
8182 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008183 return 0;
8184
8185 // Figure out if the operations have any operands in common.
8186 Value *MatchOp, *OtherOpT, *OtherOpF;
8187 bool MatchIsOpZero;
8188 if (TI->getOperand(0) == FI->getOperand(0)) {
8189 MatchOp = TI->getOperand(0);
8190 OtherOpT = TI->getOperand(1);
8191 OtherOpF = FI->getOperand(1);
8192 MatchIsOpZero = true;
8193 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8194 MatchOp = TI->getOperand(1);
8195 OtherOpT = TI->getOperand(0);
8196 OtherOpF = FI->getOperand(0);
8197 MatchIsOpZero = false;
8198 } else if (!TI->isCommutative()) {
8199 return 0;
8200 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8201 MatchOp = TI->getOperand(0);
8202 OtherOpT = TI->getOperand(1);
8203 OtherOpF = FI->getOperand(0);
8204 MatchIsOpZero = true;
8205 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8206 MatchOp = TI->getOperand(1);
8207 OtherOpT = TI->getOperand(0);
8208 OtherOpF = FI->getOperand(1);
8209 MatchIsOpZero = true;
8210 } else {
8211 return 0;
8212 }
8213
8214 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008215 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8216 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008217 InsertNewInstBefore(NewSI, SI);
8218
8219 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8220 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008221 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008222 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008223 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008224 }
Torok Edwinc23197a2009-07-14 16:55:14 +00008225 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00008226 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008227}
8228
Evan Chengde621922009-03-31 20:42:45 +00008229static bool isSelect01(Constant *C1, Constant *C2) {
8230 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8231 if (!C1I)
8232 return false;
8233 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8234 if (!C2I)
8235 return false;
8236 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8237}
8238
8239/// FoldSelectIntoOp - Try fold the select into one of the operands to
8240/// facilitate further optimization.
8241Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8242 Value *FalseVal) {
8243 // See the comment above GetSelectFoldableOperands for a description of the
8244 // transformation we are doing here.
8245 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
8246 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8247 !isa<Constant>(FalseVal)) {
8248 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8249 unsigned OpToFold = 0;
8250 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8251 OpToFold = 1;
8252 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8253 OpToFold = 2;
8254 }
8255
8256 if (OpToFold) {
Chris Lattner4de84762010-01-04 07:02:48 +00008257 Constant *C = GetSelectFoldableConstant(TVI);
Evan Chengde621922009-03-31 20:42:45 +00008258 Value *OOp = TVI->getOperand(2-OpToFold);
8259 // Avoid creating select between 2 constants unless it's selecting
8260 // between 0 and 1.
8261 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
8262 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
8263 InsertNewInstBefore(NewSel, SI);
8264 NewSel->takeName(TVI);
8265 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8266 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00008267 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00008268 }
8269 }
8270 }
8271 }
8272 }
8273
8274 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
8275 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8276 !isa<Constant>(TrueVal)) {
8277 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8278 unsigned OpToFold = 0;
8279 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8280 OpToFold = 1;
8281 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8282 OpToFold = 2;
8283 }
8284
8285 if (OpToFold) {
Chris Lattner4de84762010-01-04 07:02:48 +00008286 Constant *C = GetSelectFoldableConstant(FVI);
Evan Chengde621922009-03-31 20:42:45 +00008287 Value *OOp = FVI->getOperand(2-OpToFold);
8288 // Avoid creating select between 2 constants unless it's selecting
8289 // between 0 and 1.
8290 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
8291 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
8292 InsertNewInstBefore(NewSel, SI);
8293 NewSel->takeName(FVI);
8294 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8295 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00008296 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00008297 }
8298 }
8299 }
8300 }
8301 }
8302
8303 return 0;
8304}
8305
Dan Gohman81b28ce2008-09-16 18:46:06 +00008306/// visitSelectInstWithICmp - Visit a SelectInst that has an
8307/// ICmpInst as its first operand.
8308///
8309Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8310 ICmpInst *ICI) {
8311 bool Changed = false;
8312 ICmpInst::Predicate Pred = ICI->getPredicate();
8313 Value *CmpLHS = ICI->getOperand(0);
8314 Value *CmpRHS = ICI->getOperand(1);
8315 Value *TrueVal = SI.getTrueValue();
8316 Value *FalseVal = SI.getFalseValue();
8317
8318 // Check cases where the comparison is with a constant that
8319 // can be adjusted to fit the min/max idiom. We may edit ICI in
8320 // place here, so make sure the select is the only user.
8321 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00008322 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00008323 switch (Pred) {
8324 default: break;
8325 case ICmpInst::ICMP_ULT:
8326 case ICmpInst::ICMP_SLT: {
8327 // X < MIN ? T : F --> F
8328 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8329 return ReplaceInstUsesWith(SI, FalseVal);
8330 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00008331 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00008332 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8333 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8334 Pred = ICmpInst::getSwappedPredicate(Pred);
8335 CmpRHS = AdjustedRHS;
8336 std::swap(FalseVal, TrueVal);
8337 ICI->setPredicate(Pred);
8338 ICI->setOperand(1, CmpRHS);
8339 SI.setOperand(1, TrueVal);
8340 SI.setOperand(2, FalseVal);
8341 Changed = true;
8342 }
8343 break;
8344 }
8345 case ICmpInst::ICMP_UGT:
8346 case ICmpInst::ICMP_SGT: {
8347 // X > MAX ? T : F --> F
8348 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8349 return ReplaceInstUsesWith(SI, FalseVal);
8350 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00008351 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00008352 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8353 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8354 Pred = ICmpInst::getSwappedPredicate(Pred);
8355 CmpRHS = AdjustedRHS;
8356 std::swap(FalseVal, TrueVal);
8357 ICI->setPredicate(Pred);
8358 ICI->setOperand(1, CmpRHS);
8359 SI.setOperand(1, TrueVal);
8360 SI.setOperand(2, FalseVal);
8361 Changed = true;
8362 }
8363 break;
8364 }
8365 }
8366
Dan Gohman1975d032008-10-30 20:40:10 +00008367 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8368 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00008369 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00008370 if (match(TrueVal, m_ConstantInt<-1>()) &&
8371 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008372 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00008373 else if (match(TrueVal, m_ConstantInt<0>()) &&
8374 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008375 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8376
Dan Gohman1975d032008-10-30 20:40:10 +00008377 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8378 // If we are just checking for a icmp eq of a single bit and zext'ing it
8379 // to an integer, then shift the bit to the appropriate place and then
8380 // cast to integer to avoid the comparison.
8381 const APInt &Op1CV = CI->getValue();
8382
8383 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8384 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8385 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00008386 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00008387 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008388 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008389 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00008390 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00008391 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00008392 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00008393 if (In->getType() != SI.getType())
8394 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00008395 true/*SExt*/, "tmp", ICI);
8396
8397 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00008398 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00008399 In->getName()+".not"), *ICI);
8400
8401 return ReplaceInstUsesWith(SI, In);
8402 }
8403 }
8404 }
8405
Dan Gohman81b28ce2008-09-16 18:46:06 +00008406 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8407 // Transform (X == Y) ? X : Y -> Y
8408 if (Pred == ICmpInst::ICMP_EQ)
8409 return ReplaceInstUsesWith(SI, FalseVal);
8410 // Transform (X != Y) ? X : Y -> X
8411 if (Pred == ICmpInst::ICMP_NE)
8412 return ReplaceInstUsesWith(SI, TrueVal);
8413 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8414
8415 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8416 // Transform (X == Y) ? Y : X -> X
8417 if (Pred == ICmpInst::ICMP_EQ)
8418 return ReplaceInstUsesWith(SI, FalseVal);
8419 // Transform (X != Y) ? Y : X -> Y
8420 if (Pred == ICmpInst::ICMP_NE)
8421 return ReplaceInstUsesWith(SI, TrueVal);
8422 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8423 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00008424 return Changed ? &SI : 0;
8425}
8426
Chris Lattnerc6df8f42009-09-27 20:18:49 +00008427
Chris Lattner7f239582009-10-22 00:17:26 +00008428/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
8429/// PHI node (but the two may be in different blocks). See if the true/false
8430/// values (V) are live in all of the predecessor blocks of the PHI. For
8431/// example, cases like this cannot be mapped:
8432///
8433/// X = phi [ C1, BB1], [C2, BB2]
8434/// Y = add
8435/// Z = select X, Y, 0
8436///
8437/// because Y is not live in BB1/BB2.
8438///
8439static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
8440 const SelectInst &SI) {
8441 // If the value is a non-instruction value like a constant or argument, it
8442 // can always be mapped.
8443 const Instruction *I = dyn_cast<Instruction>(V);
8444 if (I == 0) return true;
8445
8446 // If V is a PHI node defined in the same block as the condition PHI, we can
8447 // map the arguments.
8448 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
8449
8450 if (const PHINode *VP = dyn_cast<PHINode>(I))
8451 if (VP->getParent() == CondPHI->getParent())
8452 return true;
8453
8454 // Otherwise, if the PHI and select are defined in the same block and if V is
8455 // defined in a different block, then we can transform it.
8456 if (SI.getParent() == CondPHI->getParent() &&
8457 I->getParent() != CondPHI->getParent())
8458 return true;
8459
8460 // Otherwise we have a 'hard' case and we can't tell without doing more
8461 // detailed dominator based analysis, punt.
8462 return false;
8463}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00008464
Chris Lattnerb109b5c2009-12-21 06:03:05 +00008465/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
8466/// SPF2(SPF1(A, B), C)
8467Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
8468 SelectPatternFlavor SPF1,
8469 Value *A, Value *B,
8470 Instruction &Outer,
8471 SelectPatternFlavor SPF2, Value *C) {
8472 if (C == A || C == B) {
8473 // MAX(MAX(A, B), B) -> MAX(A, B)
8474 // MIN(MIN(a, b), a) -> MIN(a, b)
8475 if (SPF1 == SPF2)
8476 return ReplaceInstUsesWith(Outer, Inner);
8477
8478 // MAX(MIN(a, b), a) -> a
8479 // MIN(MAX(a, b), a) -> a
Daniel Dunbareddfaaf2009-12-21 23:27:57 +00008480 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
8481 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
8482 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
8483 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattnerb109b5c2009-12-21 06:03:05 +00008484 return ReplaceInstUsesWith(Outer, C);
8485 }
8486
8487 // TODO: MIN(MIN(A, 23), 97)
8488 return 0;
8489}
8490
8491
8492
8493
Chris Lattner3d69f462004-03-12 05:52:32 +00008494Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008495 Value *CondVal = SI.getCondition();
8496 Value *TrueVal = SI.getTrueValue();
8497 Value *FalseVal = SI.getFalseValue();
8498
8499 // select true, X, Y -> X
8500 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008501 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008502 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008503
8504 // select C, X, X -> X
8505 if (TrueVal == FalseVal)
8506 return ReplaceInstUsesWith(SI, TrueVal);
8507
Chris Lattnere87597f2004-10-16 18:11:37 +00008508 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8509 return ReplaceInstUsesWith(SI, FalseVal);
8510 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8511 return ReplaceInstUsesWith(SI, TrueVal);
8512 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8513 if (isa<Constant>(TrueVal))
8514 return ReplaceInstUsesWith(SI, TrueVal);
8515 else
8516 return ReplaceInstUsesWith(SI, FalseVal);
8517 }
8518
Chris Lattner4de84762010-01-04 07:02:48 +00008519 if (SI.getType() == Type::getInt1Ty(SI.getContext())) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008520 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008521 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008522 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008523 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008524 } else {
8525 // Change: A = select B, false, C --> A = and !B, C
8526 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00008527 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008528 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008529 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008530 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008531 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008532 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008533 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008534 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008535 } else {
8536 // Change: A = select B, C, true --> A = or !B, C
8537 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00008538 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008539 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008540 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008541 }
8542 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008543
8544 // select a, b, a -> a&b
8545 // select a, a, b -> a|b
8546 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008547 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008548 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008549 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008550 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008551
Chris Lattner2eefe512004-04-09 19:05:30 +00008552 // Selecting between two integer constants?
8553 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8554 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008555 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008556 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008557 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008558 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008559 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008560 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00008561 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008562 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008563 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008564 }
Chris Lattner457dd822004-06-09 07:59:58 +00008565
Reid Spencere4d87aa2006-12-23 06:05:41 +00008566 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008567 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008568 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008569 // non-constant value, eliminate this whole mess. This corresponds to
8570 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008571 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008572 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008573 cast<Constant>(IC->getOperand(1))->isNullValue())
8574 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8575 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008576 isa<ConstantInt>(ICA->getOperand(1)) &&
8577 (ICA->getOperand(1) == TrueValC ||
8578 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008579 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8580 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008581 // know whether we have a icmp_ne or icmp_eq and whether the
8582 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008583 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008584 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008585 Value *V = ICA;
8586 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008587 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008588 Instruction::Xor, V, ICA->getOperand(1)), SI);
8589 return ReplaceInstUsesWith(SI, V);
8590 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008591 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008592 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008593
8594 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008595 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8596 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008597 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008598 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8599 // This is not safe in general for floating point:
8600 // consider X== -0, Y== +0.
8601 // It becomes safe if either operand is a nonzero constant.
8602 ConstantFP *CFPt, *CFPf;
8603 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8604 !CFPt->getValueAPF().isZero()) ||
8605 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8606 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008607 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008608 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008609 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008610 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008611 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00008612 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00008613
Reid Spencere4d87aa2006-12-23 06:05:41 +00008614 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008615 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008616 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8617 // This is not safe in general for floating point:
8618 // consider X== -0, Y== +0.
8619 // It becomes safe if either operand is a nonzero constant.
8620 ConstantFP *CFPt, *CFPf;
8621 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8622 !CFPt->getValueAPF().isZero()) ||
8623 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8624 !CFPf->getValueAPF().isZero()))
8625 return ReplaceInstUsesWith(SI, FalseVal);
8626 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008627 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008628 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8629 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00008630 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00008631 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00008632 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00008633 }
8634
8635 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00008636 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8637 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8638 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00008639
Chris Lattner87875da2005-01-13 22:52:24 +00008640 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8641 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8642 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008643 Instruction *AddOp = 0, *SubOp = 0;
8644
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008645 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8646 if (TI->getOpcode() == FI->getOpcode())
8647 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8648 return IV;
8649
8650 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8651 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008652 if ((TI->getOpcode() == Instruction::Sub &&
8653 FI->getOpcode() == Instruction::Add) ||
8654 (TI->getOpcode() == Instruction::FSub &&
8655 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00008656 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008657 } else if ((FI->getOpcode() == Instruction::Sub &&
8658 TI->getOpcode() == Instruction::Add) ||
8659 (FI->getOpcode() == Instruction::FSub &&
8660 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00008661 AddOp = TI; SubOp = FI;
8662 }
8663
8664 if (AddOp) {
8665 Value *OtherAddOp = 0;
8666 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8667 OtherAddOp = AddOp->getOperand(1);
8668 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8669 OtherAddOp = AddOp->getOperand(0);
8670 }
8671
8672 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008673 // So at this point we know we have (Y -> OtherAddOp):
8674 // select C, (add X, Y), (sub X, Z)
8675 Value *NegVal; // Compute -Z
8676 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008677 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00008678 } else {
8679 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00008680 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00008681 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008682 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008683
8684 Value *NewTrueOp = OtherAddOp;
8685 Value *NewFalseOp = NegVal;
8686 if (AddOp != TI)
8687 std::swap(NewTrueOp, NewFalseOp);
8688 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008689 SelectInst::Create(CondVal, NewTrueOp,
8690 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008691
8692 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008693 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008694 }
8695 }
8696 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008697
Chris Lattnere576b912004-04-09 23:46:01 +00008698 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008699 if (SI.getType()->isInteger()) {
Chris Lattnerb109b5c2009-12-21 06:03:05 +00008700 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Chengde621922009-03-31 20:42:45 +00008701 return FoldI;
Chris Lattnerb109b5c2009-12-21 06:03:05 +00008702
8703 // MAX(MAX(a, b), a) -> MAX(a, b)
8704 // MIN(MIN(a, b), a) -> MIN(a, b)
8705 // MAX(MIN(a, b), a) -> a
8706 // MIN(MAX(a, b), a) -> a
8707 Value *LHS, *RHS, *LHS2, *RHS2;
8708 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
8709 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
8710 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
8711 SI, SPF, RHS))
8712 return R;
8713 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
8714 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
8715 SI, SPF, LHS))
8716 return R;
8717 }
8718
8719 // TODO.
8720 // ABS(-X) -> ABS(X)
8721 // ABS(ABS(X)) -> ABS(X)
Chris Lattnere576b912004-04-09 23:46:01 +00008722 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008723
Chris Lattner7f239582009-10-22 00:17:26 +00008724 // See if we can fold the select into a phi node if the condition is a select.
8725 if (isa<PHINode>(SI.getCondition()))
8726 // The true/false values have to be live in the PHI predecessor's blocks.
8727 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
8728 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
8729 if (Instruction *NV = FoldOpIntoPhi(SI))
8730 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00008731
Chris Lattnera1df33c2005-04-24 07:30:14 +00008732 if (BinaryOperator::isNot(CondVal)) {
8733 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8734 SI.setOperand(1, FalseVal);
8735 SI.setOperand(2, TrueVal);
8736 return &SI;
8737 }
8738
Chris Lattner3d69f462004-03-12 05:52:32 +00008739 return 0;
8740}
8741
Dan Gohmaneee962e2008-04-10 18:43:06 +00008742/// EnforceKnownAlignment - If the specified pointer points to an object that
8743/// we control, modify the object's alignment to PrefAlign. This isn't
8744/// often possible though. If alignment is important, a more reliable approach
8745/// is to simply align all global variables and allocation instructions to
8746/// their preferred alignment from the beginning.
8747///
8748static unsigned EnforceKnownAlignment(Value *V,
8749 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008750
Dan Gohmaneee962e2008-04-10 18:43:06 +00008751 User *U = dyn_cast<User>(V);
8752 if (!U) return Align;
8753
Dan Gohmanca178902009-07-17 20:47:02 +00008754 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008755 default: break;
8756 case Instruction::BitCast:
8757 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8758 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008759 // If all indexes are zero, it is just the alignment of the base pointer.
8760 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00008761 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00008762 if (!isa<Constant>(*i) ||
8763 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008764 AllZeroOperands = false;
8765 break;
8766 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008767
8768 if (AllZeroOperands) {
8769 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008770 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008771 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008772 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008773 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008774 }
8775
8776 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8777 // If there is a large requested alignment and we can, bump up the alignment
8778 // of the global.
8779 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00008780 if (GV->getAlignment() >= PrefAlign)
8781 Align = GV->getAlignment();
8782 else {
8783 GV->setAlignment(PrefAlign);
8784 Align = PrefAlign;
8785 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008786 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00008787 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
8788 // If there is a requested alignment and if this is an alloca, round up.
8789 if (AI->getAlignment() >= PrefAlign)
8790 Align = AI->getAlignment();
8791 else {
8792 AI->setAlignment(PrefAlign);
8793 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008794 }
8795 }
8796
8797 return Align;
8798}
8799
8800/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8801/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8802/// and it is more than the alignment of the ultimate object, see if we can
8803/// increase the alignment of the ultimate object, making this check succeed.
8804unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8805 unsigned PrefAlign) {
8806 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8807 sizeof(PrefAlign) * CHAR_BIT;
8808 APInt Mask = APInt::getAllOnesValue(BitWidth);
8809 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8810 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8811 unsigned TrailZ = KnownZero.countTrailingOnes();
8812 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8813
8814 if (PrefAlign > Align)
8815 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8816
8817 // We don't need to make any adjustment.
8818 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008819}
8820
Chris Lattnerf497b022008-01-13 23:50:23 +00008821Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008822 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00008823 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008824 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00008825 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00008826
8827 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008828 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00008829 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00008830 return MI;
8831 }
8832
8833 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8834 // load/store.
8835 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8836 if (MemOpLength == 0) return 0;
8837
Chris Lattner37ac6082008-01-14 00:28:35 +00008838 // Source and destination pointer types are always "i8*" for intrinsic. See
8839 // if the size is something we can handle with a single primitive load/store.
8840 // A single load+store correctly handles overlapping memory in the memmove
8841 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008842 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008843 if (Size == 0) return MI; // Delete this mem transfer.
8844
8845 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008846 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008847
Chris Lattner37ac6082008-01-14 00:28:35 +00008848 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00008849 Type *NewPtrTy =
Chris Lattner4de84762010-01-04 07:02:48 +00008850 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008851
8852 // Memcpy forces the use of i8* for the source and destination. That means
8853 // that if you're using memcpy to move one double around, you'll get a cast
8854 // from double* to i8*. We'd much rather use a double load+store rather than
8855 // an i64 load+store, here because this improves the odds that the source or
8856 // dest address will be promotable. See if we can find a better type than the
8857 // integer datatype.
8858 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8859 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008860 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00008861 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8862 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00008863 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00008864 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8865 if (STy->getNumElements() == 1)
8866 SrcETy = STy->getElementType(0);
8867 else
8868 break;
8869 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8870 if (ATy->getNumElements() == 1)
8871 SrcETy = ATy->getElementType();
8872 else
8873 break;
8874 } else
8875 break;
8876 }
8877
Dan Gohman8f8e2692008-05-23 01:52:21 +00008878 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00008879 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00008880 }
8881 }
8882
8883
Chris Lattnerf497b022008-01-13 23:50:23 +00008884 // If the memcpy/memmove provides better alignment info than we can
8885 // infer, use it.
8886 SrcAlign = std::max(SrcAlign, CopyAlign);
8887 DstAlign = std::max(DstAlign, CopyAlign);
8888
Chris Lattner08142f22009-08-30 19:47:22 +00008889 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
8890 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00008891 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8892 InsertNewInstBefore(L, *MI);
8893 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8894
8895 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00008896 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00008897 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008898}
Chris Lattner3d69f462004-03-12 05:52:32 +00008899
Chris Lattner69ea9d22008-04-30 06:39:11 +00008900Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8901 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00008902 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008903 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00008904 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00008905 return MI;
8906 }
8907
8908 // Extract the length and alignment and fill if they are constant.
8909 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8910 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Chris Lattner4de84762010-01-04 07:02:48 +00008911 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner69ea9d22008-04-30 06:39:11 +00008912 return 0;
8913 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00008914 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008915
8916 // If the length is zero, this is a no-op
8917 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8918
8919 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8920 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner4de84762010-01-04 07:02:48 +00008921 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00008922
8923 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00008924 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00008925
8926 // Alignment 0 is identity for alignment 1 for memset, but not store.
8927 if (Alignment == 0) Alignment = 1;
8928
8929 // Extract the fill value and store.
8930 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00008931 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00008932 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00008933
8934 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00008935 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00008936 return MI;
8937 }
8938
8939 return 0;
8940}
8941
8942
Chris Lattner8b0ea312006-01-13 20:11:04 +00008943/// visitCallInst - CallInst simplification. This mostly only handles folding
8944/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8945/// the heavy lifting.
8946///
Chris Lattner9fe38862003-06-19 17:00:31 +00008947Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00008948 if (isFreeCall(&CI))
8949 return visitFree(CI);
8950
Chris Lattneraab6ec42009-05-13 17:39:14 +00008951 // If the caller function is nounwind, mark the call as nounwind, even if the
8952 // callee isn't.
8953 if (CI.getParent()->getParent()->doesNotThrow() &&
8954 !CI.doesNotThrow()) {
8955 CI.setDoesNotThrow();
8956 return &CI;
8957 }
8958
Chris Lattner8b0ea312006-01-13 20:11:04 +00008959 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8960 if (!II) return visitCallSite(&CI);
8961
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008962 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8963 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008964 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008965 bool Changed = false;
8966
8967 // memmove/cpy/set of zero bytes is a noop.
8968 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8969 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8970
Chris Lattner35b9e482004-10-12 04:52:52 +00008971 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008972 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008973 // Replace the instruction with just byte operations. We would
8974 // transform other cases to loads/stores, but we don't know if
8975 // alignment is sufficient.
8976 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008977 }
8978
Chris Lattner35b9e482004-10-12 04:52:52 +00008979 // If we have a memmove and the source operation is a constant global,
8980 // then the source and dest pointers can't alias, so we can change this
8981 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008982 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008983 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8984 if (GVSrc->isConstant()) {
8985 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00008986 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
8987 const Type *Tys[1];
8988 Tys[0] = CI.getOperand(3)->getType();
8989 CI.setOperand(0,
8990 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00008991 Changed = true;
8992 }
Eli Friedman0c826d92009-12-17 21:07:31 +00008993 }
Chris Lattnera935db82008-05-28 05:30:41 +00008994
Eli Friedman0c826d92009-12-17 21:07:31 +00008995 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +00008996 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +00008997 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +00008998 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00008999 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009000
Chris Lattner95a959d2006-03-06 20:18:44 +00009001 // If we can determine a pointer alignment that is bigger than currently
9002 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009003 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009004 if (Instruction *I = SimplifyMemTransfer(MI))
9005 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009006 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9007 if (Instruction *I = SimplifyMemSet(MSI))
9008 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009009 }
9010
Chris Lattner8b0ea312006-01-13 20:11:04 +00009011 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009012 }
9013
9014 switch (II->getIntrinsicID()) {
9015 default: break;
9016 case Intrinsic::bswap:
9017 // bswap(bswap(x)) -> x
9018 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9019 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9020 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +00009021
9022 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
9023 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
9024 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
9025 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
9026 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
9027 TI->getType()->getPrimitiveSizeInBits();
9028 Value *CV = ConstantInt::get(Operand->getType(), C);
9029 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
9030 return new TruncInst(V, TI->getType());
9031 }
9032 }
9033
Chris Lattner0521e3c2008-06-18 04:33:20 +00009034 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +00009035 case Intrinsic::powi:
9036 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
9037 // powi(x, 0) -> 1.0
9038 if (Power->isZero())
9039 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
9040 // powi(x, 1) -> x
9041 if (Power->isOne())
9042 return ReplaceInstUsesWith(CI, II->getOperand(1));
9043 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +00009044 if (Power->isAllOnesValue())
9045 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
9046 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +00009047 }
9048 break;
9049
Chris Lattner2bbac752009-11-26 21:42:47 +00009050 case Intrinsic::uadd_with_overflow: {
9051 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
9052 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
9053 uint32_t BitWidth = IT->getBitWidth();
9054 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +00009055 APInt LHSKnownZero(BitWidth, 0);
9056 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00009057 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
9058 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
9059 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
9060
9061 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +00009062 APInt RHSKnownZero(BitWidth, 0);
9063 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00009064 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
9065 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
9066 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
9067 if (LHSKnownNegative && RHSKnownNegative) {
9068 // The sign bit is set in both cases: this MUST overflow.
9069 // Create a simple add instruction, and insert it into the struct.
9070 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
9071 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00009072 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00009073 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00009074 };
Chris Lattner4de84762010-01-04 07:02:48 +00009075 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00009076 return InsertValueInst::Create(Struct, Add, 0);
9077 }
9078
9079 if (LHSKnownPositive && RHSKnownPositive) {
9080 // The sign bit is clear in both cases: this CANNOT overflow.
9081 // Create a simple add instruction, and insert it into the struct.
9082 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
9083 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00009084 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00009085 UndefValue::get(LHS->getType()),
9086 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00009087 };
Chris Lattner4de84762010-01-04 07:02:48 +00009088 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00009089 return InsertValueInst::Create(Struct, Add, 0);
9090 }
9091 }
9092 }
9093 // FALL THROUGH uadd into sadd
9094 case Intrinsic::sadd_with_overflow:
9095 // Canonicalize constants into the RHS.
9096 if (isa<Constant>(II->getOperand(1)) &&
9097 !isa<Constant>(II->getOperand(2))) {
9098 Value *LHS = II->getOperand(1);
9099 II->setOperand(1, II->getOperand(2));
9100 II->setOperand(2, LHS);
9101 return II;
9102 }
9103
9104 // X + undef -> undef
9105 if (isa<UndefValue>(II->getOperand(2)))
9106 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
9107
9108 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
9109 // X + 0 -> {X, false}
9110 if (RHS->isZero()) {
9111 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00009112 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00009113 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00009114 };
Chris Lattner4de84762010-01-04 07:02:48 +00009115 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00009116 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
9117 }
9118 }
9119 break;
9120 case Intrinsic::usub_with_overflow:
9121 case Intrinsic::ssub_with_overflow:
9122 // undef - X -> undef
9123 // X - undef -> undef
9124 if (isa<UndefValue>(II->getOperand(1)) ||
9125 isa<UndefValue>(II->getOperand(2)))
9126 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
9127
9128 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
9129 // X - 0 -> {X, false}
9130 if (RHS->isZero()) {
9131 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00009132 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00009133 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00009134 };
Chris Lattner4de84762010-01-04 07:02:48 +00009135 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00009136 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
9137 }
9138 }
9139 break;
9140 case Intrinsic::umul_with_overflow:
9141 case Intrinsic::smul_with_overflow:
9142 // Canonicalize constants into the RHS.
9143 if (isa<Constant>(II->getOperand(1)) &&
9144 !isa<Constant>(II->getOperand(2))) {
9145 Value *LHS = II->getOperand(1);
9146 II->setOperand(1, II->getOperand(2));
9147 II->setOperand(2, LHS);
9148 return II;
9149 }
9150
9151 // X * undef -> undef
9152 if (isa<UndefValue>(II->getOperand(2)))
9153 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
9154
9155 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
9156 // X*0 -> {0, false}
9157 if (RHSI->isZero())
9158 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
9159
9160 // X * 1 -> {X, false}
9161 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +00009162 Constant *V[] = {
9163 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00009164 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00009165 };
Chris Lattner4de84762010-01-04 07:02:48 +00009166 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +00009167 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00009168 }
9169 }
9170 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009171 case Intrinsic::ppc_altivec_lvx:
9172 case Intrinsic::ppc_altivec_lvxl:
9173 case Intrinsic::x86_sse_loadu_ps:
9174 case Intrinsic::x86_sse2_loadu_pd:
9175 case Intrinsic::x86_sse2_loadu_dq:
9176 // Turn PPC lvx -> load if the pointer is known aligned.
9177 // Turn X86 loadups -> load if the pointer is known aligned.
9178 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009179 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9180 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009181 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009182 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009183 break;
9184 case Intrinsic::ppc_altivec_stvx:
9185 case Intrinsic::ppc_altivec_stvxl:
9186 // Turn stvx -> store if the pointer is known aligned.
9187 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9188 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009189 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009190 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009191 return new StoreInst(II->getOperand(1), Ptr);
9192 }
9193 break;
9194 case Intrinsic::x86_sse_storeu_ps:
9195 case Intrinsic::x86_sse2_storeu_pd:
9196 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009197 // Turn X86 storeu -> store if the pointer is known aligned.
9198 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9199 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009200 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009201 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009202 return new StoreInst(II->getOperand(2), Ptr);
9203 }
9204 break;
9205
9206 case Intrinsic::x86_sse_cvttss2si: {
9207 // These intrinsics only demands the 0th element of its input vector. If
9208 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009209 unsigned VWidth =
9210 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9211 APInt DemandedElts(VWidth, 1);
9212 APInt UndefElts(VWidth, 0);
9213 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009214 UndefElts)) {
9215 II->setOperand(1, V);
9216 return II;
9217 }
9218 break;
9219 }
9220
9221 case Intrinsic::ppc_altivec_vperm:
9222 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9223 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9224 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009225
Chris Lattner0521e3c2008-06-18 04:33:20 +00009226 // Check that all of the elements are integer constants or undefs.
9227 bool AllEltsOk = true;
9228 for (unsigned i = 0; i != 16; ++i) {
9229 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9230 !isa<UndefValue>(Mask->getOperand(i))) {
9231 AllEltsOk = false;
9232 break;
9233 }
9234 }
9235
9236 if (AllEltsOk) {
9237 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009238 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9239 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009240 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009241
Chris Lattner0521e3c2008-06-18 04:33:20 +00009242 // Only extract each element once.
9243 Value *ExtractedElts[32];
9244 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9245
Chris Lattnere2ed0572006-04-06 19:19:17 +00009246 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009247 if (isa<UndefValue>(Mask->getOperand(i)))
9248 continue;
9249 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9250 Idx &= 31; // Match the hardware behavior.
9251
9252 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009253 ExtractedElts[Idx] =
9254 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner4de84762010-01-04 07:02:48 +00009255 ConstantInt::get(Type::getInt32Ty(II->getContext()),
9256 Idx&15, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009257 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009258
Chris Lattner0521e3c2008-06-18 04:33:20 +00009259 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009260 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner4de84762010-01-04 07:02:48 +00009261 ConstantInt::get(Type::getInt32Ty(II->getContext()),
9262 i, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009263 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009264 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009265 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009266 }
9267 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009268
Chris Lattner0521e3c2008-06-18 04:33:20 +00009269 case Intrinsic::stackrestore: {
9270 // If the save is right next to the restore, remove the restore. This can
9271 // happen when variable allocas are DCE'd.
9272 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9273 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9274 BasicBlock::iterator BI = SS;
9275 if (&*++BI == II)
9276 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009277 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009278 }
9279
9280 // Scan down this block to see if there is another stack restore in the
9281 // same block without an intervening call/alloca.
9282 BasicBlock::iterator BI = II;
9283 TerminatorInst *TI = II->getParent()->getTerminator();
9284 bool CannotRemove = false;
9285 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009286 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009287 CannotRemove = true;
9288 break;
9289 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009290 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9291 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9292 // If there is a stackrestore below this one, remove this one.
9293 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9294 return EraseInstFromFunction(CI);
9295 // Otherwise, ignore the intrinsic.
9296 } else {
9297 // If we found a non-intrinsic call, we can't remove the stack
9298 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009299 CannotRemove = true;
9300 break;
9301 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009302 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009303 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009304
9305 // If the stack restore is in a return/unwind block and if there are no
9306 // allocas or calls between the restore and the return, nuke the restore.
9307 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9308 return EraseInstFromFunction(CI);
9309 break;
9310 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009311 }
9312
Chris Lattner8b0ea312006-01-13 20:11:04 +00009313 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009314}
9315
9316// InvokeInst simplification
9317//
9318Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009319 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009320}
9321
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009322/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9323/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009324static bool isSafeToEliminateVarargsCast(const CallSite CS,
9325 const CastInst * const CI,
9326 const TargetData * const TD,
9327 const int ix) {
9328 if (!CI->isLosslessCast())
9329 return false;
9330
9331 // The size of ByVal arguments is derived from the type, so we
9332 // can't change to a type with a different size. If the size were
9333 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009334 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009335 return true;
9336
9337 const Type* SrcTy =
9338 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9339 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9340 if (!SrcTy->isSized() || !DstTy->isSized())
9341 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009342 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009343 return false;
9344 return true;
9345}
9346
Chris Lattnera44d8a22003-10-07 22:32:43 +00009347// visitCallSite - Improvements for call and invoke instructions.
9348//
9349Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009350 bool Changed = false;
9351
9352 // If the callee is a constexpr cast of a function, attempt to move the cast
9353 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009354 if (transformConstExprCastCall(CS)) return 0;
9355
Chris Lattner6c266db2003-10-07 22:54:13 +00009356 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009357
Chris Lattner08b22ec2005-05-13 07:09:09 +00009358 if (Function *CalleeF = dyn_cast<Function>(Callee))
9359 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9360 Instruction *OldCall = CS.getInstruction();
9361 // If the call and callee calling conventions don't match, this call must
9362 // be unreachable, as the call is undefined.
Chris Lattner4de84762010-01-04 07:02:48 +00009363 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
9364 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Andersond672ecb2009-07-03 00:17:18 +00009365 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +00009366 // If OldCall dues not return void then replaceAllUsesWith undef.
9367 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00009368 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00009369 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009370 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9371 return EraseInstFromFunction(*OldCall);
9372 return 0;
9373 }
9374
Chris Lattner17be6352004-10-18 02:59:09 +00009375 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9376 // This instruction is not reachable, just remove it. We insert a store to
9377 // undef so that we know that this code is not reachable, despite the fact
9378 // that we can't modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00009379 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
9380 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner17be6352004-10-18 02:59:09 +00009381 CS.getInstruction());
9382
Devang Patel228ebd02009-10-13 22:56:32 +00009383 // If CS dues not return void then replaceAllUsesWith undef.
9384 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00009385 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00009386 CS.getInstruction()->
9387 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009388
9389 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9390 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009391 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner4de84762010-01-04 07:02:48 +00009392 ConstantInt::getTrue(Callee->getContext()), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009393 }
Chris Lattner17be6352004-10-18 02:59:09 +00009394 return EraseInstFromFunction(*CS.getInstruction());
9395 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009396
Duncan Sandscdb6d922007-09-17 10:26:40 +00009397 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9398 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9399 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9400 return transformCallThroughTrampoline(CS);
9401
Chris Lattner6c266db2003-10-07 22:54:13 +00009402 const PointerType *PTy = cast<PointerType>(Callee->getType());
9403 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9404 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009405 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009406 // See if we can optimize any arguments passed through the varargs area of
9407 // the call.
9408 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009409 E = CS.arg_end(); I != E; ++I, ++ix) {
9410 CastInst *CI = dyn_cast<CastInst>(*I);
9411 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9412 *I = CI->getOperand(0);
9413 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009414 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009415 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009416 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009417
Duncan Sandsf0c33542007-12-19 21:13:37 +00009418 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009419 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009420 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009421 Changed = true;
9422 }
9423
Chris Lattner6c266db2003-10-07 22:54:13 +00009424 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009425}
9426
Chris Lattner9fe38862003-06-19 17:00:31 +00009427// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9428// attempt to move the cast to the arguments of the call/invoke.
9429//
9430bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9431 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9432 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009433 if (CE->getOpcode() != Instruction::BitCast ||
9434 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009435 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009436 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009437 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009438 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009439
9440 // Okay, this is a cast from a function to a different type. Unless doing so
9441 // would cause a type conversion of one of our arguments, change this call to
9442 // be a direct call with arguments casted to the appropriate types.
9443 //
9444 const FunctionType *FT = Callee->getFunctionType();
9445 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009446 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009447
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009448 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009449 return false; // TODO: Handle multiple return values.
9450
Chris Lattnerf78616b2004-01-14 06:06:08 +00009451 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009452 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009453 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009454 // Conversion is ok if changing from one pointer type to another or from
9455 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009456 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009457 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009458 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009459 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00009460 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009461
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009462 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009463 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +00009464 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009465 return false; // Cannot transform this return value.
9466
Chris Lattner58d74912008-03-12 17:45:29 +00009467 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009468 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009469 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009470 return false; // Attribute not compatible with transformed value.
9471 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009472
Chris Lattnerf78616b2004-01-14 06:06:08 +00009473 // If the callsite is an invoke instruction, and the return value is used by
9474 // a PHI node in a successor, we cannot change the return type of the call
9475 // because there is no place to put the cast instruction (without breaking
9476 // the critical edge). Bail out in this case.
9477 if (!Caller->use_empty())
9478 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9479 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9480 UI != E; ++UI)
9481 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9482 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009483 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009484 return false;
9485 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009486
9487 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9488 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009489
Chris Lattner9fe38862003-06-19 17:00:31 +00009490 CallSite::arg_iterator AI = CS.arg_begin();
9491 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9492 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009493 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009494
9495 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009496 return false; // Cannot transform this parameter value.
9497
Devang Patel19c87462008-09-26 22:53:05 +00009498 if (CallerPAL.getParamAttributes(i + 1)
9499 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00009500 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009501
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009502 // Converting from one pointer type to another or between a pointer and an
9503 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009504 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009505 (TD && ((isa<PointerType>(ParamTy) ||
9506 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
9507 (isa<PointerType>(ActTy) ||
9508 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009509 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009510 }
9511
9512 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009513 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009514 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009515
Chris Lattner58d74912008-03-12 17:45:29 +00009516 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9517 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009518 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009519 // won't be dropping them. Check that these extra arguments have attributes
9520 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009521 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9522 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009523 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00009524 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00009525 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00009526 return false;
9527 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009528
Chris Lattner9fe38862003-06-19 17:00:31 +00009529 // Okay, we decided that this is a safe thing to do: go ahead and start
9530 // inserting cast instructions as necessary...
9531 std::vector<Value*> Args;
9532 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00009533 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009534 attrVec.reserve(NumCommonArgs);
9535
9536 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009537 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009538
9539 // If the return value is not being used, the type may not be compatible
9540 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00009541 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009542
9543 // Add the new return attributes.
9544 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00009545 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009546
9547 AI = CS.arg_begin();
9548 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9549 const Type *ParamTy = FT->getParamType(i);
9550 if ((*AI)->getType() == ParamTy) {
9551 Args.push_back(*AI);
9552 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009553 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009554 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009555 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00009556 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009557
9558 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009559 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009560 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009561 }
9562
9563 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009564 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +00009565 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00009566 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +00009567
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009568 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009569 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009570 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00009571 errs() << "WARNING: While resolving call to function '"
9572 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009573 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009574 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +00009575 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9576 const Type *PTy = getPromotedType((*AI)->getType());
9577 if (PTy != (*AI)->getType()) {
9578 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009579 Instruction::CastOps opcode =
9580 CastInst::getCastOpcode(*AI, false, PTy, false);
9581 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00009582 } else {
9583 Args.push_back(*AI);
9584 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009585
Duncan Sandse1e520f2008-01-13 08:02:44 +00009586 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009587 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009588 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00009589 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009590 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009591 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009592
Devang Patel19c87462008-09-26 22:53:05 +00009593 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9594 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9595
Devang Patel9674d152009-10-14 17:29:00 +00009596 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +00009597 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009598
Eric Christophera66297a2009-07-25 02:45:27 +00009599 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
9600 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009601
Chris Lattner9fe38862003-06-19 17:00:31 +00009602 Instruction *NC;
9603 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009604 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009605 Args.begin(), Args.end(),
9606 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009607 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009608 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009609 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009610 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9611 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009612 CallInst *CI = cast<CallInst>(Caller);
9613 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009614 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009615 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009616 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009617 }
9618
Chris Lattner6934a042007-02-11 01:23:03 +00009619 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009620 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009621 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +00009622 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009623 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009624 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009625 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009626
9627 // If this is an invoke instruction, we should insert it after the first
9628 // non-phi, instruction in the normal successor block.
9629 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009630 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009631 InsertNewInstBefore(NC, *I);
9632 } else {
9633 // Otherwise, it's a call, just insert cast right after the call instr
9634 InsertNewInstBefore(NC, *Caller);
9635 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +00009636 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009637 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009638 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009639 }
9640 }
9641
Devang Patel1bf5ebc2009-10-13 21:41:20 +00009642
Chris Lattner931f8f32009-08-31 05:17:58 +00009643 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +00009644 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +00009645
9646 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009647 return true;
9648}
9649
Duncan Sandscdb6d922007-09-17 10:26:40 +00009650// transformCallThroughTrampoline - Turn a call to a function created by the
9651// init_trampoline intrinsic into a direct call to the underlying function.
9652//
9653Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9654 Value *Callee = CS.getCalledValue();
9655 const PointerType *PTy = cast<PointerType>(Callee->getType());
9656 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00009657 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009658
9659 // If the call already has the 'nest' attribute somewhere then give up -
9660 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00009661 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009662 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009663
9664 IntrinsicInst *Tramp =
9665 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9666
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009667 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009668 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9669 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9670
Devang Patel05988662008-09-25 21:00:45 +00009671 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00009672 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009673 unsigned NestIdx = 1;
9674 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00009675 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009676
9677 // Look for a parameter marked with the 'nest' attribute.
9678 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9679 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00009680 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009681 // Record the parameter type and any other attributes.
9682 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00009683 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009684 break;
9685 }
9686
9687 if (NestTy) {
9688 Instruction *Caller = CS.getInstruction();
9689 std::vector<Value*> NewArgs;
9690 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9691
Devang Patel05988662008-09-25 21:00:45 +00009692 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00009693 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009694
Duncan Sandscdb6d922007-09-17 10:26:40 +00009695 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009696 // mean appending it. Likewise for attributes.
9697
Devang Patel19c87462008-09-26 22:53:05 +00009698 // Add any result attributes.
9699 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00009700 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009701
Duncan Sandscdb6d922007-09-17 10:26:40 +00009702 {
9703 unsigned Idx = 1;
9704 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9705 do {
9706 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009707 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009708 Value *NestVal = Tramp->getOperand(3);
9709 if (NestVal->getType() != NestTy)
9710 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9711 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00009712 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009713 }
9714
9715 if (I == E)
9716 break;
9717
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009718 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009719 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00009720 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009721 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00009722 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009723
9724 ++Idx, ++I;
9725 } while (1);
9726 }
9727
Devang Patel19c87462008-09-26 22:53:05 +00009728 // Add any function attributes.
9729 if (Attributes Attr = Attrs.getFnAttributes())
9730 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9731
Duncan Sandscdb6d922007-09-17 10:26:40 +00009732 // The trampoline may have been bitcast to a bogus type (FTy).
9733 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009734 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009735
Duncan Sandscdb6d922007-09-17 10:26:40 +00009736 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009737 NewTypes.reserve(FTy->getNumParams()+1);
9738
Duncan Sandscdb6d922007-09-17 10:26:40 +00009739 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009740 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009741 {
9742 unsigned Idx = 1;
9743 FunctionType::param_iterator I = FTy->param_begin(),
9744 E = FTy->param_end();
9745
9746 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009747 if (Idx == NestIdx)
9748 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009749 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009750
9751 if (I == E)
9752 break;
9753
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009754 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009755 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009756
9757 ++Idx, ++I;
9758 } while (1);
9759 }
9760
9761 // Replace the trampoline call with a direct call. Let the generic
9762 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +00009763 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +00009764 FTy->isVarArg());
9765 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +00009766 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +00009767 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +00009768 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +00009769 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
9770 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009771
9772 Instruction *NewCaller;
9773 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009774 NewCaller = InvokeInst::Create(NewCallee,
9775 II->getNormalDest(), II->getUnwindDest(),
9776 NewArgs.begin(), NewArgs.end(),
9777 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009778 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009779 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009780 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009781 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9782 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009783 if (cast<CallInst>(Caller)->isTailCall())
9784 cast<CallInst>(NewCaller)->setTailCall();
9785 cast<CallInst>(NewCaller)->
9786 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009787 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009788 }
Devang Patel9674d152009-10-14 17:29:00 +00009789 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +00009790 Caller->replaceAllUsesWith(NewCaller);
9791 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +00009792 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009793 return 0;
9794 }
9795 }
9796
9797 // Replace the trampoline call with a direct call. Since there is no 'nest'
9798 // parameter, there is no need to adjust the argument list. Let the generic
9799 // code sort out any function type mismatches.
9800 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +00009801 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +00009802 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009803 CS.setCalledFunction(NewCallee);
9804 return CS.getInstruction();
9805}
9806
Dan Gohman9ad29202009-09-16 16:50:24 +00009807/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
9808/// 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 +00009809/// and a single binop.
9810Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9811 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +00009812 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009813 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009814 Value *LHSVal = FirstInst->getOperand(0);
9815 Value *RHSVal = FirstInst->getOperand(1);
9816
9817 const Type *LHSType = LHSVal->getType();
9818 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009819
Dan Gohman9ad29202009-09-16 16:50:24 +00009820 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +00009821 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009822 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009823 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009824 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009825 // types or GEP's with different index types.
9826 I->getOperand(0)->getType() != LHSType ||
9827 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009828 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009829
9830 // If they are CmpInst instructions, check their predicates
9831 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9832 if (cast<CmpInst>(I)->getPredicate() !=
9833 cast<CmpInst>(FirstInst)->getPredicate())
9834 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009835
9836 // Keep track of which operand needs a phi node.
9837 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9838 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009839 }
Dan Gohman9ad29202009-09-16 16:50:24 +00009840
9841 // If both LHS and RHS would need a PHI, don't do this transformation,
9842 // because it would increase the number of PHIs entering the block,
9843 // which leads to higher register pressure. This is especially
9844 // bad when the PHIs are in the header of a loop.
9845 if (!LHSVal && !RHSVal)
9846 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009847
Chris Lattner38b3dcc2008-12-01 03:42:51 +00009848 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +00009849
Chris Lattner7da52b22006-11-01 04:51:18 +00009850 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009851 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009852 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009853 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009854 NewLHS = PHINode::Create(LHSType,
9855 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009856 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9857 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009858 InsertNewInstBefore(NewLHS, PN);
9859 LHSVal = NewLHS;
9860 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009861
9862 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009863 NewRHS = PHINode::Create(RHSType,
9864 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009865 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9866 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009867 InsertNewInstBefore(NewRHS, PN);
9868 RHSVal = NewRHS;
9869 }
9870
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009871 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +00009872 if (NewLHS || NewRHS) {
9873 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9874 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
9875 if (NewLHS) {
9876 Value *NewInLHS = InInst->getOperand(0);
9877 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9878 }
9879 if (NewRHS) {
9880 Value *NewInRHS = InInst->getOperand(1);
9881 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9882 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009883 }
9884 }
9885
Chris Lattner7da52b22006-11-01 04:51:18 +00009886 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009887 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +00009888 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00009889 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +00009890 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +00009891}
9892
Chris Lattner05f18922008-12-01 02:34:36 +00009893Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
9894 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
9895
9896 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
9897 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +00009898 // This is true if all GEP bases are allocas and if all indices into them are
9899 // constants.
9900 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +00009901
9902 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +00009903 // more than one phi, which leads to higher register pressure. This is
9904 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +00009905 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +00009906
Dan Gohman9ad29202009-09-16 16:50:24 +00009907 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +00009908 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
9909 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
9910 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
9911 GEP->getNumOperands() != FirstInst->getNumOperands())
9912 return 0;
9913
Chris Lattner36d3e322009-02-21 00:46:50 +00009914 // Keep track of whether or not all GEPs are of alloca pointers.
9915 if (AllBasePointersAreAllocas &&
9916 (!isa<AllocaInst>(GEP->getOperand(0)) ||
9917 !GEP->hasAllConstantIndices()))
9918 AllBasePointersAreAllocas = false;
9919
Chris Lattner05f18922008-12-01 02:34:36 +00009920 // Compare the operand lists.
9921 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
9922 if (FirstInst->getOperand(op) == GEP->getOperand(op))
9923 continue;
9924
9925 // Don't merge two GEPs when two operands differ (introducing phi nodes)
9926 // if one of the PHIs has a constant for the index. The index may be
9927 // substantially cheaper to compute for the constants, so making it a
9928 // variable index could pessimize the path. This also handles the case
9929 // for struct indices, which must always be constant.
9930 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
9931 isa<ConstantInt>(GEP->getOperand(op)))
9932 return 0;
9933
9934 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
9935 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +00009936
9937 // If we already needed a PHI for an earlier operand, and another operand
9938 // also requires a PHI, we'd be introducing more PHIs than we're
9939 // eliminating, which increases register pressure on entry to the PHI's
9940 // block.
9941 if (NeededPhi)
9942 return 0;
9943
Chris Lattner05f18922008-12-01 02:34:36 +00009944 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +00009945 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +00009946 }
9947 }
9948
Chris Lattner36d3e322009-02-21 00:46:50 +00009949 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +00009950 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +00009951 // offset calculation, but all the predecessors will have to materialize the
9952 // stack address into a register anyway. We'd actually rather *clone* the
9953 // load up into the predecessors so that we have a load of a gep of an alloca,
9954 // which can usually all be folded into the load.
9955 if (AllBasePointersAreAllocas)
9956 return 0;
9957
Chris Lattner05f18922008-12-01 02:34:36 +00009958 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
9959 // that is variable.
9960 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
9961
9962 bool HasAnyPHIs = false;
9963 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
9964 if (FixedOperands[i]) continue; // operand doesn't need a phi.
9965 Value *FirstOp = FirstInst->getOperand(i);
9966 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
9967 FirstOp->getName()+".pn");
9968 InsertNewInstBefore(NewPN, PN);
9969
9970 NewPN->reserveOperandSpace(e);
9971 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
9972 OperandPhis[i] = NewPN;
9973 FixedOperands[i] = NewPN;
9974 HasAnyPHIs = true;
9975 }
9976
9977
9978 // Add all operands to the new PHIs.
9979 if (HasAnyPHIs) {
9980 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9981 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
9982 BasicBlock *InBB = PN.getIncomingBlock(i);
9983
9984 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
9985 if (PHINode *OpPhi = OperandPhis[op])
9986 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
9987 }
9988 }
9989
9990 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +00009991 return cast<GEPOperator>(FirstInst)->isInBounds() ?
9992 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
9993 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +00009994 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
9995 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +00009996}
9997
9998
Chris Lattner21550882009-02-23 05:56:17 +00009999/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10000/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010001/// obvious the value of the load is not changed from the point of the load to
10002/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010003///
10004/// Finally, it is safe, but not profitable, to sink a load targetting a
10005/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10006/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010007static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010008 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10009
10010 for (++BBI; BBI != E; ++BBI)
10011 if (BBI->mayWriteToMemory())
10012 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010013
10014 // Check for non-address taken alloca. If not address-taken already, it isn't
10015 // profitable to do this xform.
10016 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10017 bool isAddressTaken = false;
10018 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10019 UI != E; ++UI) {
10020 if (isa<LoadInst>(UI)) continue;
10021 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10022 // If storing TO the alloca, then the address isn't taken.
10023 if (SI->getOperand(1) == AI) continue;
10024 }
10025 isAddressTaken = true;
10026 break;
10027 }
10028
Chris Lattner36d3e322009-02-21 00:46:50 +000010029 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010030 return false;
10031 }
10032
Chris Lattner36d3e322009-02-21 00:46:50 +000010033 // If this load is a load from a GEP with a constant offset from an alloca,
10034 // then we don't want to sink it. In its present form, it will be
10035 // load [constant stack offset]. Sinking it will cause us to have to
10036 // materialize the stack addresses in each predecessor in a register only to
10037 // do a shared load from register in the successor.
10038 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10039 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10040 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10041 return false;
10042
Chris Lattner76c73142006-11-01 07:13:54 +000010043 return true;
10044}
10045
Chris Lattner751a3622009-11-01 20:04:24 +000010046Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10047 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10048
10049 // When processing loads, we need to propagate two bits of information to the
10050 // sunk load: whether it is volatile, and what its alignment is. We currently
10051 // don't sink loads when some have their alignment specified and some don't.
10052 // visitLoadInst will propagate an alignment onto the load when TD is around,
10053 // and if TD isn't around, we can't handle the mixed case.
10054 bool isVolatile = FirstLI->isVolatile();
10055 unsigned LoadAlignment = FirstLI->getAlignment();
10056
10057 // We can't sink the load if the loaded value could be modified between the
10058 // load and the PHI.
10059 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10060 !isSafeAndProfitableToSinkLoad(FirstLI))
10061 return 0;
10062
10063 // If the PHI is of volatile loads and the load block has multiple
10064 // successors, sinking it would remove a load of the volatile value from
10065 // the path through the other successor.
10066 if (isVolatile &&
10067 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10068 return 0;
10069
10070 // Check to see if all arguments are the same operation.
10071 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10072 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10073 if (!LI || !LI->hasOneUse())
10074 return 0;
10075
10076 // We can't sink the load if the loaded value could be modified between
10077 // the load and the PHI.
10078 if (LI->isVolatile() != isVolatile ||
10079 LI->getParent() != PN.getIncomingBlock(i) ||
10080 !isSafeAndProfitableToSinkLoad(LI))
10081 return 0;
10082
10083 // If some of the loads have an alignment specified but not all of them,
10084 // we can't do the transformation.
10085 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10086 return 0;
10087
Chris Lattnera664bb72009-11-01 20:07:07 +000010088 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000010089
10090 // If the PHI is of volatile loads and the load block has multiple
10091 // successors, sinking it would remove a load of the volatile value from
10092 // the path through the other successor.
10093 if (isVolatile &&
10094 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10095 return 0;
10096 }
10097
10098 // Okay, they are all the same operation. Create a new PHI node of the
10099 // correct type, and PHI together all of the LHS's of the instructions.
10100 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10101 PN.getName()+".in");
10102 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10103
10104 Value *InVal = FirstLI->getOperand(0);
10105 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10106
10107 // Add all operands to the new PHI.
10108 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10109 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10110 if (NewInVal != InVal)
10111 InVal = 0;
10112 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10113 }
10114
10115 Value *PhiVal;
10116 if (InVal) {
10117 // The new PHI unions all of the same values together. This is really
10118 // common, so we handle it intelligently here for compile-time speed.
10119 PhiVal = InVal;
10120 delete NewPN;
10121 } else {
10122 InsertNewInstBefore(NewPN, PN);
10123 PhiVal = NewPN;
10124 }
10125
10126 // If this was a volatile load that we are merging, make sure to loop through
10127 // and mark all the input loads as non-volatile. If we don't do this, we will
10128 // insert a new volatile load and the old ones will not be deletable.
10129 if (isVolatile)
10130 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10131 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10132
10133 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10134}
10135
Chris Lattner9fe38862003-06-19 17:00:31 +000010136
Chris Lattnerc22d4d12009-11-10 07:23:37 +000010137
10138/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10139/// operator and they all are only used by the PHI, PHI together their
10140/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010141Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10142 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10143
Chris Lattner751a3622009-11-01 20:04:24 +000010144 if (isa<GetElementPtrInst>(FirstInst))
10145 return FoldPHIArgGEPIntoPHI(PN);
10146 if (isa<LoadInst>(FirstInst))
10147 return FoldPHIArgLoadIntoPHI(PN);
10148
Chris Lattnerbac32862004-11-14 19:13:23 +000010149 // Scan the instruction, looking for input operations that can be folded away.
10150 // If all input operands to the phi are the same instruction (e.g. a cast from
10151 // the same type or "+42") we can pull the operation through the PHI, reducing
10152 // code size and simplifying code.
10153 Constant *ConstantOp = 0;
10154 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000010155
Chris Lattnerbac32862004-11-14 19:13:23 +000010156 if (isa<CastInst>(FirstInst)) {
10157 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000010158
10159 // Be careful about transforming integer PHIs. We don't want to pessimize
10160 // the code by turning an i32 into an i1293.
10161 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000010162 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattnerbf382b52009-11-08 21:20:06 +000010163 return 0;
10164 }
Reid Spencer832254e2007-02-02 02:16:23 +000010165 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010166 // Can fold binop, compare or shift here if the RHS is a constant,
10167 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010168 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010169 if (ConstantOp == 0)
10170 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010171 } else {
10172 return 0; // Cannot fold this operation.
10173 }
10174
10175 // Check to see if all arguments are the same operation.
10176 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000010177 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10178 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010179 return 0;
10180 if (CastSrcTy) {
10181 if (I->getOperand(0)->getType() != CastSrcTy)
10182 return 0; // Cast operation must match.
10183 } else if (I->getOperand(1) != ConstantOp) {
10184 return 0;
10185 }
10186 }
10187
10188 // Okay, they are all the same operation. Create a new PHI node of the
10189 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010190 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10191 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010192 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010193
10194 Value *InVal = FirstInst->getOperand(0);
10195 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010196
10197 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010198 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10199 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10200 if (NewInVal != InVal)
10201 InVal = 0;
10202 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10203 }
10204
10205 Value *PhiVal;
10206 if (InVal) {
10207 // The new PHI unions all of the same values together. This is really
10208 // common, so we handle it intelligently here for compile-time speed.
10209 PhiVal = InVal;
10210 delete NewPN;
10211 } else {
10212 InsertNewInstBefore(NewPN, PN);
10213 PhiVal = NewPN;
10214 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010215
Chris Lattnerbac32862004-11-14 19:13:23 +000010216 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000010217 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010218 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000010219
Chris Lattner54545ac2008-04-29 17:13:43 +000010220 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010221 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000010222
Chris Lattner751a3622009-11-01 20:04:24 +000010223 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10224 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10225 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000010226}
Chris Lattnera1be5662002-05-02 17:06:02 +000010227
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010228/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10229/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010230static bool DeadPHICycle(PHINode *PN,
10231 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010232 if (PN->use_empty()) return true;
10233 if (!PN->hasOneUse()) return false;
10234
10235 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010236 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010237 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010238
10239 // Don't scan crazily complex things.
10240 if (PotentiallyDeadPHIs.size() == 16)
10241 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010242
10243 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10244 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010245
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010246 return false;
10247}
10248
Chris Lattnercf5008a2007-11-06 21:52:06 +000010249/// PHIsEqualValue - Return true if this phi node is always equal to
10250/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10251/// z = some value; x = phi (y, z); y = phi (x, z)
10252static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10253 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10254 // See if we already saw this PHI node.
10255 if (!ValueEqualPHIs.insert(PN))
10256 return true;
10257
10258 // Don't scan crazily complex things.
10259 if (ValueEqualPHIs.size() == 16)
10260 return false;
10261
10262 // Scan the operands to see if they are either phi nodes or are equal to
10263 // the value.
10264 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10265 Value *Op = PN->getIncomingValue(i);
10266 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10267 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10268 return false;
10269 } else if (Op != NonPhiInVal)
10270 return false;
10271 }
10272
10273 return true;
10274}
10275
10276
Chris Lattner9956c052009-11-08 19:23:30 +000010277namespace {
10278struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010279 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000010280 unsigned Shift; // The amount shifted.
10281 Instruction *Inst; // The trunc instruction.
10282
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010283 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
10284 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000010285
10286 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010287 if (PHIId < RHS.PHIId) return true;
10288 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000010289 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010290 if (Shift > RHS.Shift) return false;
10291 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000010292 RHS.Inst->getType()->getPrimitiveSizeInBits();
10293 }
10294};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010295
10296struct LoweredPHIRecord {
10297 PHINode *PN; // The PHI that was lowered.
10298 unsigned Shift; // The amount shifted.
10299 unsigned Width; // The width extracted.
10300
10301 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
10302 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
10303
10304 // Ctor form used by DenseMap.
10305 LoweredPHIRecord(PHINode *pn, unsigned Sh)
10306 : PN(pn), Shift(Sh), Width(0) {}
10307};
10308}
10309
10310namespace llvm {
10311 template<>
10312 struct DenseMapInfo<LoweredPHIRecord> {
10313 static inline LoweredPHIRecord getEmptyKey() {
10314 return LoweredPHIRecord(0, 0);
10315 }
10316 static inline LoweredPHIRecord getTombstoneKey() {
10317 return LoweredPHIRecord(0, 1);
10318 }
10319 static unsigned getHashValue(const LoweredPHIRecord &Val) {
10320 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
10321 (Val.Width>>3);
10322 }
10323 static bool isEqual(const LoweredPHIRecord &LHS,
10324 const LoweredPHIRecord &RHS) {
10325 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
10326 LHS.Width == RHS.Width;
10327 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010328 };
Chris Lattner4bbf4ee2009-12-15 07:26:43 +000010329 template <>
10330 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner9956c052009-11-08 19:23:30 +000010331}
10332
10333
10334/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
10335/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
10336/// so, we split the PHI into the various pieces being extracted. This sort of
10337/// thing is introduced when SROA promotes an aggregate to large integer values.
10338///
10339/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
10340/// inttoptr. We should produce new PHIs in the right type.
10341///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010342Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
10343 // PHIUsers - Keep track of all of the truncated values extracted from a set
10344 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000010345 SmallVector<PHIUsageRecord, 16> PHIUsers;
10346
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010347 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
10348 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
10349 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
10350 // check the uses of (to ensure they are all extracts).
10351 SmallVector<PHINode*, 8> PHIsToSlice;
10352 SmallPtrSet<PHINode*, 8> PHIsInspected;
10353
10354 PHIsToSlice.push_back(&FirstPhi);
10355 PHIsInspected.insert(&FirstPhi);
10356
10357 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
10358 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000010359
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000010360 // Scan the input list of the PHI. If any input is an invoke, and if the
10361 // input is defined in the predecessor, then we won't be split the critical
10362 // edge which is required to insert a truncate. Because of this, we have to
10363 // bail out.
10364 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10365 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
10366 if (II == 0) continue;
10367 if (II->getParent() != PN->getIncomingBlock(i))
10368 continue;
10369
10370 // If we have a phi, and if it's directly in the predecessor, then we have
10371 // a critical edge where we need to put the truncate. Since we can't
10372 // split the edge in instcombine, we have to bail out.
10373 return 0;
10374 }
10375
10376
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010377 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
10378 UI != E; ++UI) {
10379 Instruction *User = cast<Instruction>(*UI);
10380
10381 // If the user is a PHI, inspect its uses recursively.
10382 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
10383 if (PHIsInspected.insert(UserPN))
10384 PHIsToSlice.push_back(UserPN);
10385 continue;
10386 }
10387
10388 // Truncates are always ok.
10389 if (isa<TruncInst>(User)) {
10390 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
10391 continue;
10392 }
10393
10394 // Otherwise it must be a lshr which can only be used by one trunc.
10395 if (User->getOpcode() != Instruction::LShr ||
10396 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
10397 !isa<ConstantInt>(User->getOperand(1)))
10398 return 0;
10399
10400 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
10401 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000010402 }
Chris Lattner9956c052009-11-08 19:23:30 +000010403 }
10404
10405 // If we have no users, they must be all self uses, just nuke the PHI.
10406 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010407 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000010408
10409 // If this phi node is transformable, create new PHIs for all the pieces
10410 // extracted out of it. First, sort the users by their offset and size.
10411 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
10412
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010413 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
10414 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
10415 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
10416 );
Chris Lattner9956c052009-11-08 19:23:30 +000010417
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010418 // PredValues - This is a temporary used when rewriting PHI nodes. It is
10419 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000010420 DenseMap<BasicBlock*, Value*> PredValues;
10421
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010422 // ExtractedVals - Each new PHI we introduce is saved here so we don't
10423 // introduce redundant PHIs.
10424 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
10425
10426 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
10427 unsigned PHIId = PHIUsers[UserI].PHIId;
10428 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000010429 unsigned Offset = PHIUsers[UserI].Shift;
10430 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000010431
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010432 PHINode *EltPHI;
10433
10434 // If we've already lowered a user like this, reuse the previously lowered
10435 // value.
10436 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000010437
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010438 // Otherwise, Create the new PHI node for this user.
10439 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
10440 assert(EltPHI->getType() != PN->getType() &&
10441 "Truncate didn't shrink phi?");
10442
10443 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10444 BasicBlock *Pred = PN->getIncomingBlock(i);
10445 Value *&PredVal = PredValues[Pred];
10446
10447 // If we already have a value for this predecessor, reuse it.
10448 if (PredVal) {
10449 EltPHI->addIncoming(PredVal, Pred);
10450 continue;
10451 }
Chris Lattner9956c052009-11-08 19:23:30 +000010452
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010453 // Handle the PHI self-reuse case.
10454 Value *InVal = PN->getIncomingValue(i);
10455 if (InVal == PN) {
10456 PredVal = EltPHI;
10457 EltPHI->addIncoming(PredVal, Pred);
10458 continue;
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000010459 }
10460
10461 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010462 // If the incoming value was a PHI, and if it was one of the PHIs we
10463 // already rewrote it, just use the lowered value.
10464 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
10465 PredVal = Res;
10466 EltPHI->addIncoming(PredVal, Pred);
10467 continue;
10468 }
10469 }
10470
10471 // Otherwise, do an extract in the predecessor.
10472 Builder->SetInsertPoint(Pred, Pred->getTerminator());
10473 Value *Res = InVal;
10474 if (Offset)
10475 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
10476 Offset), "extract");
10477 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
10478 PredVal = Res;
10479 EltPHI->addIncoming(Res, Pred);
10480
10481 // If the incoming value was a PHI, and if it was one of the PHIs we are
10482 // rewriting, we will ultimately delete the code we inserted. This
10483 // means we need to revisit that PHI to make sure we extract out the
10484 // needed piece.
10485 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
10486 if (PHIsInspected.count(OldInVal)) {
10487 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
10488 OldInVal)-PHIsToSlice.begin();
10489 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
10490 cast<Instruction>(Res)));
10491 ++UserE;
10492 }
Chris Lattner9956c052009-11-08 19:23:30 +000010493 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010494 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000010495
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010496 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
10497 << *EltPHI << '\n');
10498 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000010499 }
Chris Lattner9956c052009-11-08 19:23:30 +000010500
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010501 // Replace the use of this piece with the PHI node.
10502 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000010503 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010504
10505 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
10506 // with undefs.
10507 Value *Undef = UndefValue::get(FirstPhi.getType());
10508 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
10509 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
10510 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000010511}
10512
Chris Lattner473945d2002-05-06 18:06:38 +000010513// PHINode simplification
10514//
Chris Lattner7e708292002-06-25 16:13:24 +000010515Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010516 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010517 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010518
Owen Anderson7e057142006-07-10 22:03:18 +000010519 if (Value *V = PN.hasConstantValue())
10520 return ReplaceInstUsesWith(PN, V);
10521
Owen Anderson7e057142006-07-10 22:03:18 +000010522 // If all PHI operands are the same operation, pull them through the PHI,
10523 // reducing code size.
10524 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010525 isa<Instruction>(PN.getIncomingValue(1)) &&
10526 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10527 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10528 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10529 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010530 PN.getIncomingValue(0)->hasOneUse())
10531 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10532 return Result;
10533
10534 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10535 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10536 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010537 if (PN.hasOneUse()) {
10538 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10539 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010540 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010541 PotentiallyDeadPHIs.insert(&PN);
10542 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010543 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010544 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010545
10546 // If this phi has a single use, and if that use just computes a value for
10547 // the next iteration of a loop, delete the phi. This occurs with unused
10548 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10549 // common case here is good because the only other things that catch this
10550 // are induction variable analysis (sometimes) and ADCE, which is only run
10551 // late.
10552 if (PHIUser->hasOneUse() &&
10553 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10554 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010555 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010556 }
10557 }
Owen Anderson7e057142006-07-10 22:03:18 +000010558
Chris Lattnercf5008a2007-11-06 21:52:06 +000010559 // We sometimes end up with phi cycles that non-obviously end up being the
10560 // same value, for example:
10561 // z = some value; x = phi (y, z); y = phi (x, z)
10562 // where the phi nodes don't necessarily need to be in the same block. Do a
10563 // quick check to see if the PHI node only contains a single non-phi value, if
10564 // so, scan to see if the phi cycle is actually equal to that value.
10565 {
10566 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10567 // Scan for the first non-phi operand.
10568 while (InValNo != NumOperandVals &&
10569 isa<PHINode>(PN.getIncomingValue(InValNo)))
10570 ++InValNo;
10571
10572 if (InValNo != NumOperandVals) {
10573 Value *NonPhiInVal = PN.getOperand(InValNo);
10574
10575 // Scan the rest of the operands to see if there are any conflicts, if so
10576 // there is no need to recursively scan other phis.
10577 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10578 Value *OpVal = PN.getIncomingValue(InValNo);
10579 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10580 break;
10581 }
10582
10583 // If we scanned over all operands, then we have one unique value plus
10584 // phi values. Scan PHI nodes to see if they all merge in each other or
10585 // the value.
10586 if (InValNo == NumOperandVals) {
10587 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10588 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10589 return ReplaceInstUsesWith(PN, NonPhiInVal);
10590 }
10591 }
10592 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000010593
Dan Gohman5b097012009-10-31 14:22:52 +000010594 // If there are multiple PHIs, sort their operands so that they all list
10595 // the blocks in the same order. This will help identical PHIs be eliminated
10596 // by other passes. Other passes shouldn't depend on this for correctness
10597 // however.
10598 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
10599 if (&PN != FirstPN)
10600 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000010601 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000010602 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
10603 if (BBA != BBB) {
10604 Value *VA = PN.getIncomingValue(i);
10605 unsigned j = PN.getBasicBlockIndex(BBB);
10606 Value *VB = PN.getIncomingValue(j);
10607 PN.setIncomingBlock(i, BBB);
10608 PN.setIncomingValue(i, VB);
10609 PN.setIncomingBlock(j, BBA);
10610 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000010611 // NOTE: Instcombine normally would want us to "return &PN" if we
10612 // modified any of the operands of an instruction. However, since we
10613 // aren't adding or removing uses (just rearranging them) we don't do
10614 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000010615 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000010616 }
10617
Chris Lattner9956c052009-11-08 19:23:30 +000010618 // If this is an integer PHI and we know that it has an illegal type, see if
10619 // it is only used by trunc or trunc(lshr) operations. If so, we split the
10620 // PHI into the various pieces being extracted. This sort of thing is
10621 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000010622 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000010623 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
10624 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
10625 return Res;
10626
Chris Lattner60921c92003-12-19 05:58:40 +000010627 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010628}
10629
Chris Lattner7e708292002-06-25 16:13:24 +000010630Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +000010631 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
10632
10633 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
10634 return ReplaceInstUsesWith(GEP, V);
10635
Chris Lattner620ce142004-05-07 22:09:22 +000010636 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010637
Chris Lattnere87597f2004-10-16 18:11:37 +000010638 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010639 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010640
Chris Lattner28977af2004-04-05 01:30:19 +000010641 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010642 if (TD) {
10643 bool MadeChange = false;
10644 unsigned PtrSize = TD->getPointerSizeInBits();
10645
10646 gep_type_iterator GTI = gep_type_begin(GEP);
10647 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10648 I != E; ++I, ++GTI) {
10649 if (!isa<SequentialType>(*GTI)) continue;
10650
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010651 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010652 // to what we need. If narrower, sign-extend it to what we need. This
10653 // explicit cast can make subsequent optimizations more obvious.
10654 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000010655 if (OpBits == PtrSize)
10656 continue;
10657
Chris Lattner2345d1d2009-08-30 20:01:10 +000010658 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010659 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010660 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010661 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010662 }
Chris Lattner28977af2004-04-05 01:30:19 +000010663
Chris Lattner90ac28c2002-08-02 19:29:35 +000010664 // Combine Indices - If the source pointer to this getelementptr instruction
10665 // is a getelementptr instruction, combine the indices of the two
10666 // getelementptr instructions into a single instruction.
10667 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010668 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010669 // Note that if our source is a gep chain itself that we wait for that
10670 // chain to be resolved before we perform this transformation. This
10671 // avoids us creating a TON of code in some cases.
10672 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010673 if (GetElementPtrInst *SrcGEP =
10674 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10675 if (SrcGEP->getNumOperands() == 2)
10676 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010677
Chris Lattner72588fc2007-02-15 22:48:32 +000010678 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010679
10680 // Find out whether the last index in the source GEP is a sequential idx.
10681 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010682 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10683 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010684 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010685
Chris Lattner90ac28c2002-08-02 19:29:35 +000010686 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010687 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010688 // Replace: gep (gep %P, long B), long A, ...
10689 // With: T = long A+B; gep %P, T, ...
10690 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010691 Value *Sum;
10692 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10693 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010694 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010695 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010696 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010697 Sum = SO1;
10698 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010699 // If they aren't the same type, then the input hasn't been processed
10700 // by the loop above yet (which canonicalizes sequential index types to
10701 // intptr_t). Just avoid transforming this until the input has been
10702 // normalized.
10703 if (SO1->getType() != GO1->getType())
10704 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010705 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010706 }
Chris Lattner620ce142004-05-07 22:09:22 +000010707
Chris Lattnerab984842009-08-30 05:30:55 +000010708 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010709 if (Src->getNumOperands() == 2) {
10710 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000010711 GEP.setOperand(1, Sum);
10712 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000010713 }
Chris Lattnerab984842009-08-30 05:30:55 +000010714 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010715 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000010716 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000010717 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010718 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010719 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010720 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000010721 Indices.append(Src->op_begin()+1, Src->op_end());
10722 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010723 }
10724
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010725 if (!Indices.empty())
10726 return (cast<GEPOperator>(&GEP)->isInBounds() &&
10727 Src->isInBounds()) ?
10728 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
10729 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010730 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000010731 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000010732 }
10733
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010734 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10735 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000010736 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000010737
Chris Lattner2de23192009-08-30 20:38:21 +000010738 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10739 // want to change the gep until the bitcasts are eliminated.
10740 if (getBitCastOperand(X)) {
10741 Worklist.AddValue(PtrOp);
10742 return 0;
10743 }
10744
Chris Lattnerc514c1f2009-11-27 00:29:05 +000010745 bool HasZeroPointerIndex = false;
10746 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
10747 HasZeroPointerIndex = C->isZero();
10748
Chris Lattner963f4ba2009-08-30 20:36:46 +000010749 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10750 // into : GEP [10 x i8]* X, i32 0, ...
10751 //
10752 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10753 // into : GEP i8* X, ...
10754 //
10755 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000010756 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000010757 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10758 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010759 if (const ArrayType *CATy =
10760 dyn_cast<ArrayType>(CPTy->getElementType())) {
10761 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10762 if (CATy->getElementType() == XTy->getElementType()) {
10763 // -> GEP i8* X, ...
10764 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010765 return cast<GEPOperator>(&GEP)->isInBounds() ?
10766 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
10767 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010768 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10769 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000010770 }
10771
10772 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010773 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000010774 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010775 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010776 // At this point, we know that the cast source type is a pointer
10777 // to an array of the same type as the destination pointer
10778 // array. Because the array type is never stepped over (there
10779 // is a leading zero) we can fold the cast into this GEP.
10780 GEP.setOperand(0, X);
10781 return &GEP;
10782 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010783 }
10784 }
Chris Lattnereed48272005-09-13 00:40:14 +000010785 } else if (GEP.getNumOperands() == 2) {
10786 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010787 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10788 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010789 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10790 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010791 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000010792 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10793 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010794 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +000010795 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +000010796 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010797 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
10798 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010799 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010800 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010801 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010802 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010803
10804 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010805 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010806 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010807 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010808
Chris Lattner4de84762010-01-04 07:02:48 +000010809 if (TD && isa<ArrayType>(SrcElTy) &&
10810 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010811 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000010812 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010813
10814 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10815 // allow either a mul, shift, or constant here.
10816 Value *NewIdx = 0;
10817 ConstantInt *Scale = 0;
10818 if (ArrayEltSize == 1) {
10819 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000010820 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010821 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010822 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010823 Scale = CI;
10824 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10825 if (Inst->getOpcode() == Instruction::Shl &&
10826 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010827 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10828 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000010829 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000010830 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010831 NewIdx = Inst->getOperand(0);
10832 } else if (Inst->getOpcode() == Instruction::Mul &&
10833 isa<ConstantInt>(Inst->getOperand(1))) {
10834 Scale = cast<ConstantInt>(Inst->getOperand(1));
10835 NewIdx = Inst->getOperand(0);
10836 }
10837 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010838
Chris Lattner7835cdd2005-09-13 18:36:04 +000010839 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010840 // out, perform the transformation. Note, we don't know whether Scale is
10841 // signed or not. We'll use unsigned version of division/modulo
10842 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000010843 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010844 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010845 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010846 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010847 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000010848 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10849 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010850 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010851 }
10852
10853 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010854 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +000010855 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +000010856 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010857 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
10858 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
10859 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010860 // The NewGEP must be pointer typed, so must the old one -> BitCast
10861 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010862 }
10863 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010864 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010865 }
Chris Lattner58407792009-01-09 04:53:57 +000010866
Chris Lattner46cd5a12009-01-09 05:44:56 +000010867 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000010868 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000010869 /// Y = gep X, <...constant indices...>
10870 /// into a gep of the original struct. This is important for SROA and alias
10871 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000010872 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010873 if (TD &&
10874 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000010875 // Determine how much the GEP moves the pointer. We are guaranteed to get
10876 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000010877 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000010878 int64_t Offset = OffsetV->getSExtValue();
10879
10880 // If this GEP instruction doesn't move the pointer, just replace the GEP
10881 // with a bitcast of the real input to the dest type.
10882 if (Offset == 0) {
10883 // If the bitcast is of an allocation, and the allocation will be
10884 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000010885 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000010886 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000010887 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10888 if (Instruction *I = visitBitCast(*BCI)) {
10889 if (I != BCI) {
10890 I->takeName(BCI);
10891 BCI->getParent()->getInstList().insert(BCI, I);
10892 ReplaceInstUsesWith(*BCI, I);
10893 }
10894 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000010895 }
Chris Lattner58407792009-01-09 04:53:57 +000010896 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010897 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000010898 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010899
10900 // Otherwise, if the offset is non-zero, we need to find out if there is a
10901 // field at Offset in 'A's type. If so, we can pull the cast through the
10902 // GEP.
10903 SmallVector<Value*, 8> NewIndices;
10904 const Type *InTy =
10905 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner4de84762010-01-04 07:02:48 +000010906 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010907 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
10908 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
10909 NewIndices.end()) :
10910 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
10911 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010912
10913 if (NGEP->getType() == GEP.getType())
10914 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000010915 NGEP->takeName(&GEP);
10916 return new BitCastInst(NGEP, GEP.getType());
10917 }
Chris Lattner58407792009-01-09 04:53:57 +000010918 }
10919 }
10920
Chris Lattner8a2a3112001-12-14 16:52:21 +000010921 return 0;
10922}
10923
Victor Hernandez7b929da2009-10-23 21:09:37 +000010924Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000010925 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010926 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010927 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10928 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010929 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000010930 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000010931 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010932 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000010933
Chris Lattner0864acf2002-11-04 16:18:53 +000010934 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000010935 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000010936 //
10937 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000010938 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000010939
10940 // Now that I is pointing to the first non-allocation-inst in the block,
10941 // insert our getelementptr instruction...
10942 //
Chris Lattner4de84762010-01-04 07:02:48 +000010943 Value *NullIdx =Constant::getNullValue(Type::getInt32Ty(AI.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +000010944 Value *Idx[2];
10945 Idx[0] = NullIdx;
10946 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010947 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
10948 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010949
10950 // Now make everything use the getelementptr instead of the original
10951 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010952 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010953 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000010954 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010955 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010956 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010957
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010958 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000010959 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000010960 // Note that we only do this for alloca's, because malloc should allocate
10961 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000010962 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000010963 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000010964
10965 // If the alignment is 0 (unspecified), assign it the preferred alignment.
10966 if (AI.getAlignment() == 0)
10967 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10968 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010969
Chris Lattner0864acf2002-11-04 16:18:53 +000010970 return 0;
10971}
10972
Victor Hernandez66284e02009-10-24 04:23:03 +000010973Instruction *InstCombiner::visitFree(Instruction &FI) {
10974 Value *Op = FI.getOperand(1);
10975
10976 // free undef -> unreachable.
10977 if (isa<UndefValue>(Op)) {
10978 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +000010979 new StoreInst(ConstantInt::getTrue(FI.getContext()),
10980 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +000010981 return EraseInstFromFunction(FI);
10982 }
10983
10984 // If we have 'free null' delete the instruction. This can happen in stl code
10985 // when lots of inlining happens.
10986 if (isa<ConstantPointerNull>(Op))
10987 return EraseInstFromFunction(FI);
10988
Victor Hernandez046e78c2009-10-26 23:43:48 +000010989 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000010990 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000010991 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
10992 if (Op->hasOneUse() && CI->hasOneUse()) {
10993 EraseInstFromFunction(FI);
10994 EraseInstFromFunction(*CI);
10995 return EraseInstFromFunction(*cast<Instruction>(Op));
10996 }
10997 } else {
10998 // Op is a call to malloc
10999 if (Op->hasOneUse()) {
11000 EraseInstFromFunction(FI);
11001 return EraseInstFromFunction(*cast<Instruction>(Op));
11002 }
11003 }
Dan Gohman7f712a12009-10-27 00:11:02 +000011004 }
Victor Hernandez66284e02009-10-24 04:23:03 +000011005
11006 return 0;
11007}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011008
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011009/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011010static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011011 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011012 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011013 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000011014
Mon P Wang6753f952009-02-07 22:19:29 +000011015 const PointerType *DestTy = cast<PointerType>(CI->getType());
11016 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011017 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011018
11019 // If the address spaces don't match, don't eliminate the cast.
11020 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11021 return 0;
11022
Chris Lattnerb89e0712004-07-13 01:49:43 +000011023 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011024
Reid Spencer42230162007-01-22 05:51:25 +000011025 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011026 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011027 // If the source is an array, the code below will not succeed. Check to
11028 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11029 // constants.
11030 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11031 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11032 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011033 Value *Idxs[2];
Chris Lattner4de84762010-01-04 07:02:48 +000011034 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(LI.getContext()));
Chris Lattnere00c43f2009-10-22 06:44:07 +000011035 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000011036 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011037 SrcTy = cast<PointerType>(CastOp->getType());
11038 SrcPTy = SrcTy->getElementType();
11039 }
11040
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011041 if (IC.getTargetData() &&
11042 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011043 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011044 // Do not allow turning this into a load of an integer, which is then
11045 // casted to a pointer, this pessimizes pointer analysis a lot.
11046 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011047 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11048 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011049
Chris Lattnerf9527852005-01-31 04:50:46 +000011050 // Okay, we are casting from one integer or pointer type to another of
11051 // the same size. Instead of casting the pointer before the load, cast
11052 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011053 Value *NewLoad =
11054 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011055 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011056 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011057 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011058 }
11059 }
11060 return 0;
11061}
11062
Chris Lattner833b8a42003-06-26 05:06:25 +000011063Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11064 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011065
Dan Gohman9941f742007-07-20 16:34:21 +000011066 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011067 if (TD) {
11068 unsigned KnownAlign =
11069 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11070 if (KnownAlign >
11071 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11072 LI.getAlignment()))
11073 LI.setAlignment(KnownAlign);
11074 }
Dan Gohman9941f742007-07-20 16:34:21 +000011075
Chris Lattner963f4ba2009-08-30 20:36:46 +000011076 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011077 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011078 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011079 return Res;
11080
11081 // None of the following transforms are legal for volatile loads.
11082 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011083
Dan Gohman2276a7b2008-10-15 23:19:35 +000011084 // Do really simple store-to-load forwarding and load CSE, to catch cases
11085 // where there are several consequtive memory accesses to the same location,
11086 // separated by a few arithmetic operations.
11087 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011088 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11089 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011090
Chris Lattner878e4942009-10-22 06:25:11 +000011091 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000011092 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11093 const Value *GEPI0 = GEPI->getOperand(0);
11094 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011095 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011096 // Insert a new store to null instruction before the load to indicate
11097 // that this code is not reachable. We do this instead of inserting
11098 // an unreachable instruction directly because we cannot modify the
11099 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011100 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011101 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011102 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011103 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011104 }
Chris Lattner37366c12005-05-01 04:24:53 +000011105
Chris Lattner878e4942009-10-22 06:25:11 +000011106 // load null/undef -> unreachable
11107 // TODO: Consider a target hook for valid address spaces for this xform.
11108 if (isa<UndefValue>(Op) ||
11109 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11110 // Insert a new store to null instruction before the load to indicate that
11111 // this code is not reachable. We do this instead of inserting an
11112 // unreachable instruction directly because we cannot modify the CFG.
11113 new StoreInst(UndefValue::get(LI.getType()),
11114 Constant::getNullValue(Op->getType()), &LI);
11115 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011116 }
Chris Lattner878e4942009-10-22 06:25:11 +000011117
11118 // Instcombine load (constantexpr_cast global) -> cast (load global)
11119 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11120 if (CE->isCast())
11121 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11122 return Res;
11123
Chris Lattner37366c12005-05-01 04:24:53 +000011124 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011125 // Change select and PHI nodes to select values instead of addresses: this
11126 // helps alias analysis out a lot, allows many others simplifications, and
11127 // exposes redundancy in the code.
11128 //
11129 // Note that we cannot do the transformation unless we know that the
11130 // introduced loads cannot trap! Something like this is valid as long as
11131 // the condition is always false: load (select bool %C, int* null, int* %G),
11132 // but it would not be valid if we transformed it to load from null
11133 // unconditionally.
11134 //
11135 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11136 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011137 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11138 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011139 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11140 SI->getOperand(1)->getName()+".val");
11141 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11142 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011143 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011144 }
11145
Chris Lattner684fe212004-09-23 15:46:00 +000011146 // load (select (cond, null, P)) -> load P
11147 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11148 if (C->isNullValue()) {
11149 LI.setOperand(0, SI->getOperand(2));
11150 return &LI;
11151 }
11152
11153 // load (select (cond, P, null)) -> load P
11154 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11155 if (C->isNullValue()) {
11156 LI.setOperand(0, SI->getOperand(1));
11157 return &LI;
11158 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011159 }
11160 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011161 return 0;
11162}
11163
Reid Spencer55af2b52007-01-19 21:20:31 +000011164/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011165/// when possible. This makes it generally easy to do alias analysis and/or
11166/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011167static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11168 User *CI = cast<User>(SI.getOperand(1));
11169 Value *CastOp = CI->getOperand(0);
11170
11171 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011172 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11173 if (SrcTy == 0) return 0;
11174
11175 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011176
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011177 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11178 return 0;
11179
Chris Lattner3914f722009-01-24 01:00:13 +000011180 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11181 /// to its first element. This allows us to handle things like:
11182 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11183 /// on 32-bit hosts.
11184 SmallVector<Value*, 4> NewGEPIndices;
11185
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011186 // If the source is an array, the code below will not succeed. Check to
11187 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11188 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011189 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11190 // Index through pointer.
Chris Lattner4de84762010-01-04 07:02:48 +000011191 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011192 NewGEPIndices.push_back(Zero);
11193
11194 while (1) {
11195 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011196 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011197 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011198 NewGEPIndices.push_back(Zero);
11199 SrcPTy = STy->getElementType(0);
11200 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11201 NewGEPIndices.push_back(Zero);
11202 SrcPTy = ATy->getElementType();
11203 } else {
11204 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011205 }
Chris Lattner3914f722009-01-24 01:00:13 +000011206 }
11207
Owen Andersondebcb012009-07-29 22:17:13 +000011208 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011209 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011210
11211 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11212 return 0;
11213
Chris Lattner71759c42009-01-16 20:12:52 +000011214 // If the pointers point into different address spaces or if they point to
11215 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011216 if (!IC.getTargetData() ||
11217 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011218 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011219 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11220 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011221 return 0;
11222
11223 // Okay, we are casting from one integer or pointer type to another of
11224 // the same size. Instead of casting the pointer before
11225 // the store, cast the value to be stored.
11226 Value *NewCast;
11227 Value *SIOp0 = SI.getOperand(0);
11228 Instruction::CastOps opcode = Instruction::BitCast;
11229 const Type* CastSrcTy = SIOp0->getType();
11230 const Type* CastDstTy = SrcPTy;
11231 if (isa<PointerType>(CastDstTy)) {
11232 if (CastSrcTy->isInteger())
11233 opcode = Instruction::IntToPtr;
11234 } else if (isa<IntegerType>(CastDstTy)) {
11235 if (isa<PointerType>(SIOp0->getType()))
11236 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011237 }
Chris Lattner3914f722009-01-24 01:00:13 +000011238
11239 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11240 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011241 if (!NewGEPIndices.empty())
11242 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11243 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011244
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011245 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11246 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011247 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011248}
11249
Chris Lattner4aebaee2008-11-27 08:56:30 +000011250/// equivalentAddressValues - Test if A and B will obviously have the same
11251/// value. This includes recognizing that %t0 and %t1 will have the same
11252/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011253/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011254/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011255/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011256/// %t2 = load i32* %t1
11257///
11258static bool equivalentAddressValues(Value *A, Value *B) {
11259 // Test if the values are trivially equivalent.
11260 if (A == B) return true;
11261
11262 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011263 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11264 // its only used to compare two uses within the same basic block, which
11265 // means that they'll always either have the same value or one of them
11266 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011267 if (isa<BinaryOperator>(A) ||
11268 isa<CastInst>(A) ||
11269 isa<PHINode>(A) ||
11270 isa<GetElementPtrInst>(A))
11271 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011272 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011273 return true;
11274
11275 // Otherwise they may not be equivalent.
11276 return false;
11277}
11278
Dale Johannesen4945c652009-03-03 21:26:39 +000011279// If this instruction has two uses, one of which is a llvm.dbg.declare,
11280// return the llvm.dbg.declare.
11281DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11282 if (!V->hasNUses(2))
11283 return 0;
11284 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11285 UI != E; ++UI) {
11286 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11287 return DI;
11288 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11289 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11290 return DI;
11291 }
11292 }
11293 return 0;
11294}
11295
Chris Lattner2f503e62005-01-31 05:36:43 +000011296Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11297 Value *Val = SI.getOperand(0);
11298 Value *Ptr = SI.getOperand(1);
11299
Chris Lattner836692d2007-01-15 06:51:56 +000011300 // If the RHS is an alloca with a single use, zapify the store, making the
11301 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011302 // If the RHS is an alloca with a two uses, the other one being a
11303 // llvm.dbg.declare, zapify the store and the declare, making the
11304 // alloca dead. We must do this to prevent declare's from affecting
11305 // codegen.
11306 if (!SI.isVolatile()) {
11307 if (Ptr->hasOneUse()) {
11308 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011309 EraseInstFromFunction(SI);
11310 ++NumCombined;
11311 return 0;
11312 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011313 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11314 if (isa<AllocaInst>(GEP->getOperand(0))) {
11315 if (GEP->getOperand(0)->hasOneUse()) {
11316 EraseInstFromFunction(SI);
11317 ++NumCombined;
11318 return 0;
11319 }
11320 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11321 EraseInstFromFunction(*DI);
11322 EraseInstFromFunction(SI);
11323 ++NumCombined;
11324 return 0;
11325 }
11326 }
11327 }
11328 }
11329 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11330 EraseInstFromFunction(*DI);
11331 EraseInstFromFunction(SI);
11332 ++NumCombined;
11333 return 0;
11334 }
Chris Lattner836692d2007-01-15 06:51:56 +000011335 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011336
Dan Gohman9941f742007-07-20 16:34:21 +000011337 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011338 if (TD) {
11339 unsigned KnownAlign =
11340 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11341 if (KnownAlign >
11342 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11343 SI.getAlignment()))
11344 SI.setAlignment(KnownAlign);
11345 }
Dan Gohman9941f742007-07-20 16:34:21 +000011346
Dale Johannesenacb51a32009-03-03 01:43:03 +000011347 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011348 // stores to the same location, separated by a few arithmetic operations. This
11349 // situation often occurs with bitfield accesses.
11350 BasicBlock::iterator BBI = &SI;
11351 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11352 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011353 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011354 // Don't count debug info directives, lest they affect codegen,
11355 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11356 // It is necessary for correctness to skip those that feed into a
11357 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011358 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011359 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011360 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011361 continue;
11362 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011363
11364 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11365 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011366 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11367 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011368 ++NumDeadStore;
11369 ++BBI;
11370 EraseInstFromFunction(*PrevSI);
11371 continue;
11372 }
11373 break;
11374 }
11375
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011376 // If this is a load, we have to stop. However, if the loaded value is from
11377 // the pointer we're loading and is producing the pointer we're storing,
11378 // then *this* store is dead (X = load P; store X -> P).
11379 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011380 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11381 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011382 EraseInstFromFunction(SI);
11383 ++NumCombined;
11384 return 0;
11385 }
11386 // Otherwise, this is a load from some other location. Stores before it
11387 // may not be dead.
11388 break;
11389 }
11390
Chris Lattner9ca96412006-02-08 03:25:32 +000011391 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011392 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011393 break;
11394 }
11395
11396
11397 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011398
11399 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011400 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011401 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011402 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011403 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011404 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011405 ++NumCombined;
11406 }
11407 return 0; // Do not modify these!
11408 }
11409
11410 // store undef, Ptr -> noop
11411 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011412 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011413 ++NumCombined;
11414 return 0;
11415 }
11416
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011417 // If the pointer destination is a cast, see if we can fold the cast into the
11418 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011419 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011420 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11421 return Res;
11422 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011423 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011424 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11425 return Res;
11426
Chris Lattner408902b2005-09-12 23:23:25 +000011427
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011428 // If this store is the last instruction in the basic block (possibly
11429 // excepting debug info instructions and the pointer bitcasts that feed
11430 // into them), and if the block ends with an unconditional branch, try
11431 // to move it to the successor block.
11432 BBI = &SI;
11433 do {
11434 ++BBI;
11435 } while (isa<DbgInfoIntrinsic>(BBI) ||
11436 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011437 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011438 if (BI->isUnconditional())
11439 if (SimplifyStoreAtEndOfBlock(SI))
11440 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011441
Chris Lattner2f503e62005-01-31 05:36:43 +000011442 return 0;
11443}
11444
Chris Lattner3284d1f2007-04-15 00:07:55 +000011445/// SimplifyStoreAtEndOfBlock - Turn things like:
11446/// if () { *P = v1; } else { *P = v2 }
11447/// into a phi node with a store in the successor.
11448///
Chris Lattner31755a02007-04-15 01:02:18 +000011449/// Simplify things like:
11450/// *P = v1; if () { *P = v2; }
11451/// into a phi node with a store in the successor.
11452///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011453bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11454 BasicBlock *StoreBB = SI.getParent();
11455
11456 // Check to see if the successor block has exactly two incoming edges. If
11457 // so, see if the other predecessor contains a store to the same location.
11458 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011459 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011460
11461 // Determine whether Dest has exactly two predecessors and, if so, compute
11462 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011463 pred_iterator PI = pred_begin(DestBB);
11464 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011465 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011466 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011467 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011468 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011469 return false;
11470
11471 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011472 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011473 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011474 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011475 }
Chris Lattner31755a02007-04-15 01:02:18 +000011476 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011477 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011478
11479 // Bail out if all the relevant blocks aren't distinct (this can happen,
11480 // for example, if SI is in an infinite loop)
11481 if (StoreBB == DestBB || OtherBB == DestBB)
11482 return false;
11483
Chris Lattner31755a02007-04-15 01:02:18 +000011484 // Verify that the other block ends in a branch and is not otherwise empty.
11485 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011486 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011487 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011488 return false;
11489
Chris Lattner31755a02007-04-15 01:02:18 +000011490 // If the other block ends in an unconditional branch, check for the 'if then
11491 // else' case. there is an instruction before the branch.
11492 StoreInst *OtherStore = 0;
11493 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011494 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011495 // Skip over debugging info.
11496 while (isa<DbgInfoIntrinsic>(BBI) ||
11497 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11498 if (BBI==OtherBB->begin())
11499 return false;
11500 --BBI;
11501 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000011502 // If this isn't a store, isn't a store to the same location, or if the
11503 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011504 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000011505 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
11506 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000011507 return false;
11508 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011509 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011510 // destinations is StoreBB, then we have the if/then case.
11511 if (OtherBr->getSuccessor(0) != StoreBB &&
11512 OtherBr->getSuccessor(1) != StoreBB)
11513 return false;
11514
11515 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011516 // if/then triangle. See if there is a store to the same ptr as SI that
11517 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011518 for (;; --BBI) {
11519 // Check to see if we find the matching store.
11520 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000011521 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
11522 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000011523 return false;
11524 break;
11525 }
Eli Friedman6903a242008-06-13 22:02:12 +000011526 // If we find something that may be using or overwriting the stored
11527 // value, or if we run out of instructions, we can't do the xform.
11528 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011529 BBI == OtherBB->begin())
11530 return false;
11531 }
11532
11533 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011534 // make sure nothing reads or overwrites the stored value in
11535 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011536 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11537 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011538 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011539 return false;
11540 }
11541 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011542
Chris Lattner31755a02007-04-15 01:02:18 +000011543 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011544 Value *MergedVal = OtherStore->getOperand(0);
11545 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011546 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011547 PN->reserveOperandSpace(2);
11548 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011549 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11550 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011551 }
11552
11553 // Advance to a place where it is safe to insert the new store and
11554 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011555 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011556 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000011557 OtherStore->isVolatile(),
11558 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011559
11560 // Nuke the old stores.
11561 EraseInstFromFunction(SI);
11562 EraseInstFromFunction(*OtherStore);
11563 ++NumCombined;
11564 return true;
11565}
11566
Chris Lattner2f503e62005-01-31 05:36:43 +000011567
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011568Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11569 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011570 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011571 BasicBlock *TrueDest;
11572 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011573 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011574 !isa<Constant>(X)) {
11575 // Swap Destinations and condition...
11576 BI.setCondition(X);
11577 BI.setSuccessor(0, FalseDest);
11578 BI.setSuccessor(1, TrueDest);
11579 return &BI;
11580 }
11581
Reid Spencere4d87aa2006-12-23 06:05:41 +000011582 // Cannonicalize fcmp_one -> fcmp_oeq
11583 FCmpInst::Predicate FPred; Value *Y;
11584 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011585 TrueDest, FalseDest)) &&
11586 BI.getCondition()->hasOneUse())
11587 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11588 FPred == FCmpInst::FCMP_OGE) {
11589 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11590 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11591
11592 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011593 BI.setSuccessor(0, FalseDest);
11594 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011595 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011596 return &BI;
11597 }
11598
11599 // Cannonicalize icmp_ne -> icmp_eq
11600 ICmpInst::Predicate IPred;
11601 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011602 TrueDest, FalseDest)) &&
11603 BI.getCondition()->hasOneUse())
11604 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11605 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11606 IPred == ICmpInst::ICMP_SGE) {
11607 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11608 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11609 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011610 BI.setSuccessor(0, FalseDest);
11611 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011612 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011613 return &BI;
11614 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011615
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011616 return 0;
11617}
Chris Lattner0864acf2002-11-04 16:18:53 +000011618
Chris Lattner46238a62004-07-03 00:26:11 +000011619Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11620 Value *Cond = SI.getCondition();
11621 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11622 if (I->getOpcode() == Instruction::Add)
11623 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11624 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11625 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011626 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011627 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011628 AddRHS));
11629 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011630 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011631 return &SI;
11632 }
11633 }
11634 return 0;
11635}
11636
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011637Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011638 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011639
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011640 if (!EV.hasIndices())
11641 return ReplaceInstUsesWith(EV, Agg);
11642
11643 if (Constant *C = dyn_cast<Constant>(Agg)) {
11644 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011645 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011646
11647 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000011648 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011649
11650 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11651 // Extract the element indexed by the first index out of the constant
11652 Value *V = C->getOperand(*EV.idx_begin());
11653 if (EV.getNumIndices() > 1)
11654 // Extract the remaining indices out of the constant indexed by the
11655 // first index
11656 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11657 else
11658 return ReplaceInstUsesWith(EV, V);
11659 }
11660 return 0; // Can't handle other constants
11661 }
11662 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11663 // We're extracting from an insertvalue instruction, compare the indices
11664 const unsigned *exti, *exte, *insi, *inse;
11665 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11666 exte = EV.idx_end(), inse = IV->idx_end();
11667 exti != exte && insi != inse;
11668 ++exti, ++insi) {
11669 if (*insi != *exti)
11670 // The insert and extract both reference distinctly different elements.
11671 // This means the extract is not influenced by the insert, and we can
11672 // replace the aggregate operand of the extract with the aggregate
11673 // operand of the insert. i.e., replace
11674 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11675 // %E = extractvalue { i32, { i32 } } %I, 0
11676 // with
11677 // %E = extractvalue { i32, { i32 } } %A, 0
11678 return ExtractValueInst::Create(IV->getAggregateOperand(),
11679 EV.idx_begin(), EV.idx_end());
11680 }
11681 if (exti == exte && insi == inse)
11682 // Both iterators are at the end: Index lists are identical. Replace
11683 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11684 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11685 // with "i32 42"
11686 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11687 if (exti == exte) {
11688 // The extract list is a prefix of the insert list. i.e. replace
11689 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11690 // %E = extractvalue { i32, { i32 } } %I, 1
11691 // with
11692 // %X = extractvalue { i32, { i32 } } %A, 1
11693 // %E = insertvalue { i32 } %X, i32 42, 0
11694 // by switching the order of the insert and extract (though the
11695 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011696 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11697 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011698 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11699 insi, inse);
11700 }
11701 if (insi == inse)
11702 // The insert list is a prefix of the extract list
11703 // We can simply remove the common indices from the extract and make it
11704 // operate on the inserted value instead of the insertvalue result.
11705 // i.e., replace
11706 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11707 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11708 // with
11709 // %E extractvalue { i32 } { i32 42 }, 0
11710 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11711 exti, exte);
11712 }
Chris Lattner7e606e22009-11-09 07:07:56 +000011713 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
11714 // We're extracting from an intrinsic, see if we're the only user, which
11715 // allows us to simplify multiple result intrinsics to simpler things that
11716 // just get one value..
11717 if (II->hasOneUse()) {
11718 // Check if we're grabbing the overflow bit or the result of a 'with
11719 // overflow' intrinsic. If it's the latter we can remove the intrinsic
11720 // and replace it with a traditional binary instruction.
11721 switch (II->getIntrinsicID()) {
11722 case Intrinsic::uadd_with_overflow:
11723 case Intrinsic::sadd_with_overflow:
11724 if (*EV.idx_begin() == 0) { // Normal result.
11725 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
11726 II->replaceAllUsesWith(UndefValue::get(II->getType()));
11727 EraseInstFromFunction(*II);
11728 return BinaryOperator::CreateAdd(LHS, RHS);
11729 }
11730 break;
11731 case Intrinsic::usub_with_overflow:
11732 case Intrinsic::ssub_with_overflow:
11733 if (*EV.idx_begin() == 0) { // Normal result.
11734 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
11735 II->replaceAllUsesWith(UndefValue::get(II->getType()));
11736 EraseInstFromFunction(*II);
11737 return BinaryOperator::CreateSub(LHS, RHS);
11738 }
11739 break;
11740 case Intrinsic::umul_with_overflow:
11741 case Intrinsic::smul_with_overflow:
11742 if (*EV.idx_begin() == 0) { // Normal result.
11743 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
11744 II->replaceAllUsesWith(UndefValue::get(II->getType()));
11745 EraseInstFromFunction(*II);
11746 return BinaryOperator::CreateMul(LHS, RHS);
11747 }
11748 break;
11749 default:
11750 break;
11751 }
11752 }
11753 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011754 // Can't simplify extracts from other values. Note that nested extracts are
11755 // already simplified implicitely by the above (extract ( extract (insert) )
11756 // will be translated into extract ( insert ( extract ) ) first and then just
11757 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011758 return 0;
11759}
11760
Chris Lattner220b0cf2006-03-05 00:22:33 +000011761/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11762/// is to leave as a vector operation.
11763static bool CheapToScalarize(Value *V, bool isConstant) {
11764 if (isa<ConstantAggregateZero>(V))
11765 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011766 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011767 if (isConstant) return true;
11768 // If all elts are the same, we can extract.
11769 Constant *Op0 = C->getOperand(0);
11770 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11771 if (C->getOperand(i) != Op0)
11772 return false;
11773 return true;
11774 }
11775 Instruction *I = dyn_cast<Instruction>(V);
11776 if (!I) return false;
11777
11778 // Insert element gets simplified to the inserted element or is deleted if
11779 // this is constant idx extract element and its a constant idx insertelt.
11780 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11781 isa<ConstantInt>(I->getOperand(2)))
11782 return true;
11783 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11784 return true;
11785 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11786 if (BO->hasOneUse() &&
11787 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11788 CheapToScalarize(BO->getOperand(1), isConstant)))
11789 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011790 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11791 if (CI->hasOneUse() &&
11792 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11793 CheapToScalarize(CI->getOperand(1), isConstant)))
11794 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011795
11796 return false;
11797}
11798
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011799/// Read and decode a shufflevector mask.
11800///
11801/// It turns undef elements into values that are larger than the number of
11802/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011803static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11804 unsigned NElts = SVI->getType()->getNumElements();
11805 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11806 return std::vector<unsigned>(NElts, 0);
11807 if (isa<UndefValue>(SVI->getOperand(2)))
11808 return std::vector<unsigned>(NElts, 2*NElts);
11809
11810 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011811 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000011812 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11813 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000011814 Result.push_back(NElts*2); // undef -> 8
11815 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000011816 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011817 return Result;
11818}
11819
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011820/// FindScalarElement - Given a vector and an element number, see if the scalar
11821/// value is already around as a register, for example if it were inserted then
11822/// extracted from the vector.
Chris Lattner4de84762010-01-04 07:02:48 +000011823static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011824 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11825 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011826 unsigned Width = PTy->getNumElements();
11827 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011828 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011829
11830 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011831 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011832 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000011833 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011834 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011835 return CP->getOperand(EltNo);
11836 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11837 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011838 if (!isa<ConstantInt>(III->getOperand(2)))
11839 return 0;
11840 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011841
11842 // If this is an insert to the element we are looking for, return the
11843 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011844 if (EltNo == IIElt)
11845 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011846
11847 // Otherwise, the insertelement doesn't modify the value, recurse on its
11848 // vector input.
Chris Lattner4de84762010-01-04 07:02:48 +000011849 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011850 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000011851 unsigned LHSWidth =
11852 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000011853 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000011854 if (InEl < LHSWidth)
Chris Lattner4de84762010-01-04 07:02:48 +000011855 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011856 else if (InEl < LHSWidth*2)
Chris Lattner4de84762010-01-04 07:02:48 +000011857 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000011858 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011859 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011860 }
11861
11862 // Otherwise, we don't know.
11863 return 0;
11864}
11865
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011866Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000011867 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011868 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011869 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000011870
Dan Gohman07a96762007-07-16 14:29:03 +000011871 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011872 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000011873 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000011874
Reid Spencer9d6565a2007-02-15 02:26:10 +000011875 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000011876 // If vector val is constant with all elements the same, replace EI with
11877 // that element. When the elements are not identical, we cannot replace yet
11878 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000011879 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000011880 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011881 if (C->getOperand(i) != op0) {
11882 op0 = 0;
11883 break;
11884 }
11885 if (op0)
11886 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011887 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000011888
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011889 // If extracting a specified index from the vector, see if we can recursively
11890 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011891 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011892 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000011893 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000011894
11895 // If this is extracting an invalid index, turn this into undef, to avoid
11896 // crashing the code below.
11897 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011898 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000011899
Chris Lattner867b99f2006-10-05 06:55:50 +000011900 // This instruction only demands the single element from the input vector.
11901 // If the input vector has a single use, simplify it based on this use
11902 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000011903 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000011904 APInt UndefElts(VectorWidth, 0);
11905 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000011906 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000011907 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011908 EI.setOperand(0, V);
11909 return &EI;
11910 }
11911 }
11912
Chris Lattner4de84762010-01-04 07:02:48 +000011913 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011914 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011915
11916 // If the this extractelement is directly using a bitcast from a vector of
11917 // the same number of elements, see if we can find the source element from
11918 // it. In this case, we will end up needing to bitcast the scalars.
11919 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11920 if (const VectorType *VT =
11921 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11922 if (VT->getNumElements() == VectorWidth)
Chris Lattner4de84762010-01-04 07:02:48 +000011923 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011924 return new BitCastInst(Elt, EI.getType());
11925 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011926 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011927
Chris Lattner73fa49d2006-05-25 22:53:38 +000011928 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000011929 // Push extractelement into predecessor operation if legal and
11930 // profitable to do so
11931 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11932 if (I->hasOneUse() &&
11933 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
11934 Value *newEI0 =
11935 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
11936 EI.getName()+".lhs");
11937 Value *newEI1 =
11938 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
11939 EI.getName()+".rhs");
11940 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011941 }
Chris Lattner275a6d62009-09-08 18:48:01 +000011942 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000011943 // Extracting the inserted element?
11944 if (IE->getOperand(2) == EI.getOperand(1))
11945 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11946 // If the inserted and extracted elements are constants, they must not
11947 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000011948 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000011949 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000011950 EI.setOperand(0, IE->getOperand(0));
11951 return &EI;
11952 }
11953 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11954 // If this is extracting an element from a shufflevector, figure out where
11955 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011956 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11957 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011958 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000011959 unsigned LHSWidth =
11960 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11961
11962 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000011963 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011964 else if (SrcIdx < LHSWidth*2) {
11965 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000011966 Src = SVI->getOperand(1);
11967 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011968 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011969 }
Eric Christophera3500da2009-07-25 02:28:41 +000011970 return ExtractElementInst::Create(Src,
Chris Lattner4de84762010-01-04 07:02:48 +000011971 ConstantInt::get(Type::getInt32Ty(EI.getContext()),
11972 SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011973 }
11974 }
Eli Friedman2451a642009-07-18 23:06:53 +000011975 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000011976 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011977 return 0;
11978}
11979
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011980/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11981/// elements from either LHS or RHS, return the shuffle mask and true.
11982/// Otherwise, return false.
11983static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner4de84762010-01-04 07:02:48 +000011984 std::vector<Constant*> &Mask) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011985 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11986 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011987 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011988
11989 if (isa<UndefValue>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +000011990 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011991 return true;
Chris Lattner4de84762010-01-04 07:02:48 +000011992 }
11993
11994 if (V == LHS) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011995 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +000011996 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011997 return true;
Chris Lattner4de84762010-01-04 07:02:48 +000011998 }
11999
12000 if (V == RHS) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012001 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +000012002 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
12003 i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012004 return true;
Chris Lattner4de84762010-01-04 07:02:48 +000012005 }
12006
12007 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012008 // If this is an insert of an extract from some other vector, include it.
12009 Value *VecOp = IEI->getOperand(0);
12010 Value *ScalarOp = IEI->getOperand(1);
12011 Value *IdxOp = IEI->getOperand(2);
12012
Chris Lattnerd929f062006-04-27 21:14:21 +000012013 if (!isa<ConstantInt>(IdxOp))
12014 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012015 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012016
12017 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12018 // Okay, we can handle this if the vector we are insertinting into is
12019 // transitively ok.
Chris Lattner4de84762010-01-04 07:02:48 +000012020 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012021 // If so, update the mask to reflect the inserted undef.
Chris Lattner4de84762010-01-04 07:02:48 +000012022 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
Chris Lattnerd929f062006-04-27 21:14:21 +000012023 return true;
12024 }
12025 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12026 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012027 EI->getOperand(0)->getType() == V->getType()) {
12028 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012029 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012030
12031 // This must be extracting from either LHS or RHS.
12032 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12033 // Okay, we can handle this if the vector we are insertinting into is
12034 // transitively ok.
Chris Lattner4de84762010-01-04 07:02:48 +000012035 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012036 // If so, update the mask to reflect the inserted value.
12037 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012038 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +000012039 ConstantInt::get(Type::getInt32Ty(V->getContext()),
12040 ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012041 } else {
12042 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012043 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +000012044 ConstantInt::get(Type::getInt32Ty(V->getContext()),
12045 ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012046
12047 }
12048 return true;
12049 }
12050 }
12051 }
12052 }
12053 }
12054 // TODO: Handle shufflevector here!
12055
12056 return false;
12057}
12058
12059/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12060/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12061/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012062static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner4de84762010-01-04 07:02:48 +000012063 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012064 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012065 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012066 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012067 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012068
12069 if (isa<UndefValue>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +000012070 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Chris Lattnerefb47352006-04-15 01:39:45 +000012071 return V;
12072 } else if (isa<ConstantAggregateZero>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +000012073 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012074 return V;
12075 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12076 // If this is an insert of an extract from some other vector, include it.
12077 Value *VecOp = IEI->getOperand(0);
12078 Value *ScalarOp = IEI->getOperand(1);
12079 Value *IdxOp = IEI->getOperand(2);
12080
12081 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12082 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12083 EI->getOperand(0)->getType() == V->getType()) {
12084 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012085 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12086 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012087
12088 // Either the extracted from or inserted into vector must be RHSVec,
12089 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012090 if (EI->getOperand(0) == RHS || RHS == 0) {
12091 RHS = EI->getOperand(0);
Chris Lattner4de84762010-01-04 07:02:48 +000012092 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012093 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +000012094 ConstantInt::get(Type::getInt32Ty(V->getContext()),
12095 NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012096 return V;
12097 }
12098
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012099 if (VecOp == RHS) {
Chris Lattner4de84762010-01-04 07:02:48 +000012100 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000012101 // Everything but the extracted element is replaced with the RHS.
12102 for (unsigned i = 0; i != NumElts; ++i) {
12103 if (i != InsertedIdx)
Chris Lattner4de84762010-01-04 07:02:48 +000012104 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()),
12105 NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012106 }
12107 return V;
12108 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012109
12110 // If this insertelement is a chain that comes from exactly these two
12111 // vectors, return the vector and the effective shuffle.
Chris Lattner4de84762010-01-04 07:02:48 +000012112 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012113 return EI->getOperand(0);
Chris Lattnerefb47352006-04-15 01:39:45 +000012114 }
12115 }
12116 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012117 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012118
12119 // Otherwise, can't do anything fancy. Return an identity vector.
12120 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +000012121 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012122 return V;
12123}
12124
12125Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12126 Value *VecOp = IE.getOperand(0);
12127 Value *ScalarOp = IE.getOperand(1);
12128 Value *IdxOp = IE.getOperand(2);
12129
Chris Lattner599ded12007-04-09 01:11:16 +000012130 // Inserting an undef or into an undefined place, remove this.
12131 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12132 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012133
Chris Lattnerefb47352006-04-15 01:39:45 +000012134 // If the inserted element was extracted from some other vector, and if the
12135 // indexes are constant, try to turn this into a shufflevector operation.
12136 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12137 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12138 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012139 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012140 unsigned ExtractedIdx =
12141 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012142 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012143
12144 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12145 return ReplaceInstUsesWith(IE, VecOp);
12146
12147 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012148 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012149
12150 // If we are extracting a value from a vector, then inserting it right
12151 // back into the same place, just use the input vector.
12152 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12153 return ReplaceInstUsesWith(IE, VecOp);
12154
Chris Lattnerefb47352006-04-15 01:39:45 +000012155 // If this insertelement isn't used by some other insertelement, turn it
12156 // (and any insertelements it points to), into one big shuffle.
12157 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12158 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012159 Value *RHS = 0;
Chris Lattner4de84762010-01-04 07:02:48 +000012160 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012161 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012162 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012163 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012164 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012165 }
12166 }
12167 }
12168
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012169 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12170 APInt UndefElts(VWidth, 0);
12171 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12172 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12173 return &IE;
12174
Chris Lattnerefb47352006-04-15 01:39:45 +000012175 return 0;
12176}
12177
12178
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012179Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12180 Value *LHS = SVI.getOperand(0);
12181 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012182 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012183
12184 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012185
Chris Lattner867b99f2006-10-05 06:55:50 +000012186 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012187 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012188 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012189
Dan Gohman488fbfc2008-09-09 18:11:14 +000012190 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012191
12192 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12193 return 0;
12194
Evan Cheng388df622009-02-03 10:05:09 +000012195 APInt UndefElts(VWidth, 0);
12196 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12197 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012198 LHS = SVI.getOperand(0);
12199 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012200 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012201 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012202
Chris Lattner863bcff2006-05-25 23:48:38 +000012203 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12204 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12205 if (LHS == RHS || isa<UndefValue>(LHS)) {
12206 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012207 // shuffle(undef,undef,mask) -> undef.
12208 return ReplaceInstUsesWith(SVI, LHS);
12209 }
12210
Chris Lattner863bcff2006-05-25 23:48:38 +000012211 // Remap any references to RHS to use LHS.
12212 std::vector<Constant*> Elts;
12213 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012214 if (Mask[i] >= 2*e)
Chris Lattner4de84762010-01-04 07:02:48 +000012215 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012216 else {
12217 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012218 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012219 Mask[i] = 2*e; // Turn into undef.
Chris Lattner4de84762010-01-04 07:02:48 +000012220 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Dan Gohman4ce96272008-08-06 18:17:32 +000012221 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012222 Mask[i] = Mask[i] % e; // Force to LHS.
Chris Lattner4de84762010-01-04 07:02:48 +000012223 Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
12224 Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012225 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012226 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012227 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012228 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012229 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012230 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012231 LHS = SVI.getOperand(0);
12232 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012233 MadeChange = true;
12234 }
12235
Chris Lattner7b2e27922006-05-26 00:29:06 +000012236 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012237 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012238
Chris Lattner863bcff2006-05-25 23:48:38 +000012239 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12240 if (Mask[i] >= e*2) continue; // Ignore undef values.
12241 // Is this an identity shuffle of the LHS value?
12242 isLHSID &= (Mask[i] == i);
12243
12244 // Is this an identity shuffle of the RHS value?
12245 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012246 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012247
Chris Lattner863bcff2006-05-25 23:48:38 +000012248 // Eliminate identity shuffles.
12249 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12250 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012251
Chris Lattner7b2e27922006-05-26 00:29:06 +000012252 // If the LHS is a shufflevector itself, see if we can combine it with this
12253 // one without producing an unusual shuffle. Here we are really conservative:
12254 // we are absolutely afraid of producing a shuffle mask not in the input
12255 // program, because the code gen may not be smart enough to turn a merged
12256 // shuffle into two specific shuffles: it may produce worse code. As such,
12257 // we only merge two shuffles if the result is one of the two input shuffle
12258 // masks. In this case, merging the shuffles just removes one instruction,
12259 // which we know is safe. This is good for things like turning:
12260 // (splat(splat)) -> splat.
12261 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12262 if (isa<UndefValue>(RHS)) {
12263 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12264
David Greenef941d292009-11-16 21:52:23 +000012265 if (LHSMask.size() == Mask.size()) {
12266 std::vector<unsigned> NewMask;
12267 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sands76700ba2009-11-20 13:19:51 +000012268 if (Mask[i] >= e)
David Greenef941d292009-11-16 21:52:23 +000012269 NewMask.push_back(2*e);
12270 else
12271 NewMask.push_back(LHSMask[Mask[i]]);
Chris Lattner7b2e27922006-05-26 00:29:06 +000012272
David Greenef941d292009-11-16 21:52:23 +000012273 // If the result mask is equal to the src shuffle or this
12274 // shuffle mask, do the replacement.
12275 if (NewMask == LHSMask || NewMask == Mask) {
12276 unsigned LHSInNElts =
12277 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
12278 getNumElements();
12279 std::vector<Constant*> Elts;
12280 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12281 if (NewMask[i] >= LHSInNElts*2) {
Chris Lattner4de84762010-01-04 07:02:48 +000012282 Elts.push_back(UndefValue::get(
12283 Type::getInt32Ty(SVI.getContext())));
David Greenef941d292009-11-16 21:52:23 +000012284 } else {
Chris Lattner4de84762010-01-04 07:02:48 +000012285 Elts.push_back(ConstantInt::get(
12286 Type::getInt32Ty(SVI.getContext()),
David Greenef941d292009-11-16 21:52:23 +000012287 NewMask[i]));
12288 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012289 }
David Greenef941d292009-11-16 21:52:23 +000012290 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12291 LHSSVI->getOperand(1),
12292 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012293 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012294 }
12295 }
12296 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012297
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012298 return MadeChange ? &SVI : 0;
12299}
12300
12301
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012302
Chris Lattnerea1c4542004-12-08 23:43:58 +000012303
12304/// TryToSinkInstruction - Try to move the specified instruction from its
12305/// current block into the beginning of DestBlock, which can only happen if it's
12306/// safe to move the instruction past all of the instructions between it and the
12307/// end of its block.
12308static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12309 assert(I->hasOneUse() && "Invariants didn't hold!");
12310
Chris Lattner108e9022005-10-27 17:13:11 +000012311 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012312 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012313 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012314
Chris Lattnerea1c4542004-12-08 23:43:58 +000012315 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012316 if (isa<AllocaInst>(I) && I->getParent() ==
12317 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012318 return false;
12319
Chris Lattner96a52a62004-12-09 07:14:34 +000012320 // We can only sink load instructions if there is nothing between the load and
12321 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012322 if (I->mayReadFromMemory()) {
12323 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012324 Scan != E; ++Scan)
12325 if (Scan->mayWriteToMemory())
12326 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012327 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012328
Dan Gohman02dea8b2008-05-23 21:05:58 +000012329 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012330
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012331 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012332 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012333 ++NumSunkInst;
12334 return true;
12335}
12336
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012337
12338/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12339/// all reachable code to the worklist.
12340///
12341/// This has a couple of tricks to make the code faster and more powerful. In
12342/// particular, we constant fold and DCE instructions as we go, to avoid adding
12343/// them to the worklist (this significantly speeds up instcombine on code where
12344/// many instructions are dead or constant). Additionally, if we find a branch
12345/// whose condition is a known constant, we only visit the reachable successors.
12346///
Chris Lattner2ee743b2009-10-15 04:59:28 +000012347static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012348 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012349 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012350 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000012351 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000012352 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012353 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000012354
12355 std::vector<Instruction*> InstrsForInstCombineWorklist;
12356 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012357
Chris Lattner2ee743b2009-10-15 04:59:28 +000012358 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12359
Chris Lattner2c7718a2007-03-23 19:17:18 +000012360 while (!Worklist.empty()) {
12361 BB = Worklist.back();
12362 Worklist.pop_back();
12363
12364 // We have now visited this block! If we've already been here, ignore it.
12365 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012366
Chris Lattner2c7718a2007-03-23 19:17:18 +000012367 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12368 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012369
Chris Lattner2c7718a2007-03-23 19:17:18 +000012370 // DCE instruction if trivially dead.
12371 if (isInstructionTriviallyDead(Inst)) {
12372 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012373 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012374 Inst->eraseFromParent();
12375 continue;
12376 }
12377
12378 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012379 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000012380 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012381 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12382 << *Inst << '\n');
12383 Inst->replaceAllUsesWith(C);
12384 ++NumConstProp;
12385 Inst->eraseFromParent();
12386 continue;
12387 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000012388
12389
12390
12391 if (TD) {
12392 // See if we can constant fold its operands.
12393 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12394 i != e; ++i) {
12395 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12396 if (CE == 0) continue;
12397
12398 // If we already folded this constant, don't try again.
12399 if (!FoldedConstants.insert(CE))
12400 continue;
12401
Chris Lattner7b550cc2009-11-06 04:27:31 +000012402 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000012403 if (NewC && NewC != CE) {
12404 *i = NewC;
12405 MadeIRChange = true;
12406 }
12407 }
12408 }
12409
Devang Patel7fe1dec2008-11-19 18:56:50 +000012410
Chris Lattner67f7d542009-10-12 03:58:40 +000012411 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012412 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012413
12414 // Recursively visit successors. If this is a branch or switch on a
12415 // constant, only visit the reachable successor.
12416 TerminatorInst *TI = BB->getTerminator();
12417 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12418 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12419 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012420 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012421 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012422 continue;
12423 }
12424 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12425 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12426 // See if this is an explicit destination.
12427 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12428 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012429 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012430 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012431 continue;
12432 }
12433
12434 // Otherwise it is the default destination.
12435 Worklist.push_back(SI->getSuccessor(0));
12436 continue;
12437 }
12438 }
12439
12440 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12441 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012442 }
Chris Lattner67f7d542009-10-12 03:58:40 +000012443
12444 // Once we've found all of the instructions to add to instcombine's worklist,
12445 // add them in reverse order. This way instcombine will visit from the top
12446 // of the function down. This jives well with the way that it adds all uses
12447 // of instructions to the worklist after doing a transformation, thus avoiding
12448 // some N^2 behavior in pathological cases.
12449 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12450 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000012451
12452 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012453}
12454
Chris Lattnerec9c3582007-03-03 02:04:50 +000012455bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012456 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012457
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012458 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12459 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012460
Chris Lattnerb3d59702005-07-07 20:40:38 +000012461 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012462 // Do a depth-first traversal of the function, populate the worklist with
12463 // the reachable instructions. Ignore blocks that are not reachable. Keep
12464 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012465 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000012466 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012467
Chris Lattnerb3d59702005-07-07 20:40:38 +000012468 // Do a quick scan over the function. If we find any blocks that are
12469 // unreachable, remove any instructions inside of them. This prevents
12470 // the instcombine code from having to deal with some bad special cases.
12471 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12472 if (!Visited.count(BB)) {
12473 Instruction *Term = BB->getTerminator();
12474 while (Term != BB->begin()) { // Remove instrs bottom-up
12475 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012476
Chris Lattnerbdff5482009-08-23 04:37:46 +000012477 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012478 // A debug intrinsic shouldn't force another iteration if we weren't
12479 // going to do one without it.
12480 if (!isa<DbgInfoIntrinsic>(I)) {
12481 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012482 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012483 }
Devang Patel228ebd02009-10-13 22:56:32 +000012484
Devang Patel228ebd02009-10-13 22:56:32 +000012485 // If I is not void type then replaceAllUsesWith undef.
12486 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000012487 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000012488 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012489 I->eraseFromParent();
12490 }
12491 }
12492 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012493
Chris Lattner873ff012009-08-30 05:55:36 +000012494 while (!Worklist.isEmpty()) {
12495 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012496 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012497
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012498 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012499 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012500 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012501 EraseInstFromFunction(*I);
12502 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012503 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012504 continue;
12505 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012506
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012507 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012508 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000012509 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012510 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012511
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012512 // Add operands to the worklist.
12513 ReplaceInstUsesWith(*I, C);
12514 ++NumConstProp;
12515 EraseInstFromFunction(*I);
12516 MadeIRChange = true;
12517 continue;
12518 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012519
Chris Lattnerea1c4542004-12-08 23:43:58 +000012520 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012521 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012522 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000012523 Instruction *UserInst = cast<Instruction>(I->use_back());
12524 BasicBlock *UserParent;
12525
12526 // Get the block the use occurs in.
12527 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12528 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12529 else
12530 UserParent = UserInst->getParent();
12531
Chris Lattnerea1c4542004-12-08 23:43:58 +000012532 if (UserParent != BB) {
12533 bool UserIsSuccessor = false;
12534 // See if the user is one of our successors.
12535 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12536 if (*SI == UserParent) {
12537 UserIsSuccessor = true;
12538 break;
12539 }
12540
12541 // If the user is one of our immediate successors, and if that successor
12542 // only has us as a predecessors (we'd have to split the critical edge
12543 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000012544 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012545 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012546 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012547 }
12548 }
12549
Chris Lattner74381062009-08-30 07:44:24 +000012550 // Now that we have an instruction, try combining it to simplify it.
12551 Builder->SetInsertPoint(I->getParent(), I);
12552
Reid Spencera9b81012007-03-26 17:44:01 +000012553#ifndef NDEBUG
12554 std::string OrigI;
12555#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012556 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000012557 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12558
Chris Lattner90ac28c2002-08-02 19:29:35 +000012559 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012560 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012561 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012562 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012563 DEBUG(errs() << "IC: Old = " << *I << '\n'
12564 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012565
Chris Lattnerf523d062004-06-09 05:08:07 +000012566 // Everything uses the new instruction now.
12567 I->replaceAllUsesWith(Result);
12568
12569 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012570 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012571 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012572
Chris Lattner6934a042007-02-11 01:23:03 +000012573 // Move the name to the new instruction first.
12574 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012575
12576 // Insert the new instruction into the basic block...
12577 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012578 BasicBlock::iterator InsertPos = I;
12579
12580 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12581 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12582 ++InsertPos;
12583
12584 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012585
Chris Lattner7a1e9242009-08-30 06:13:40 +000012586 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012587 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012588#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012589 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12590 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012591#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012592
Chris Lattner90ac28c2002-08-02 19:29:35 +000012593 // If the instruction was modified, it's possible that it is now dead.
12594 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012595 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012596 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012597 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012598 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012599 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012600 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012601 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012602 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012603 }
12604 }
12605
Chris Lattner873ff012009-08-30 05:55:36 +000012606 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012607 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012608}
12609
Chris Lattnerec9c3582007-03-03 02:04:50 +000012610
12611bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012612 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012613 TD = getAnalysisIfAvailable<TargetData>();
12614
Chris Lattner74381062009-08-30 07:44:24 +000012615
12616 /// Builder - This is an IRBuilder that automatically inserts new
12617 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012618 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000012619 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000012620 InstCombineIRInserter(Worklist));
12621 Builder = &TheBuilder;
12622
Chris Lattnerec9c3582007-03-03 02:04:50 +000012623 bool EverMadeChange = false;
12624
12625 // Iterate while there is work to do.
12626 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012627 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012628 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012629
12630 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012631 return EverMadeChange;
12632}
12633
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012634FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012635 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012636}