blob: 230dc288a737cf71897cf8c5a7937669fd0b797f [file] [log] [blame]
Chris Lattner80f43d32010-01-04 07:53:58 +00001//===- InstCombineCasts.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for cast operations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
Eli Friedman74703252011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000016#include "llvm/IR/DataLayout.h"
Chris Lattner80f43d32010-01-04 07:53:58 +000017#include "llvm/Support/PatternMatch.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner80f43d32010-01-04 07:53:58 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000022/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
23/// expression. If so, decompose it, returning some value X, such that Val is
24/// X*Scale+Offset.
25///
26static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Dan Gohman28d2e0a2010-05-28 04:33:04 +000027 uint64_t &Offset) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000028 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
29 Offset = CI->getZExtValue();
30 Scale = 0;
Dan Gohman28d2e0a2010-05-28 04:33:04 +000031 return ConstantInt::get(Val->getType(), 0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000032 }
Craig Topperb57c2922013-01-24 05:22:40 +000033
Chris Lattnerf86d7992010-01-05 20:57:30 +000034 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
Bob Wilsone2e86f62011-07-08 22:09:33 +000035 // Cannot look past anything that might overflow.
36 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
Stepan Dyatkovskiy3f71cf12012-05-05 07:09:40 +000037 if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
Bob Wilsone2e86f62011-07-08 22:09:33 +000038 Scale = 1;
39 Offset = 0;
40 return Val;
41 }
42
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000043 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
44 if (I->getOpcode() == Instruction::Shl) {
45 // This is a value scaled by '1 << the shift amt'.
Dan Gohman28d2e0a2010-05-28 04:33:04 +000046 Scale = UINT64_C(1) << RHS->getZExtValue();
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000047 Offset = 0;
48 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000049 }
Craig Topperb57c2922013-01-24 05:22:40 +000050
Chris Lattnerf86d7992010-01-05 20:57:30 +000051 if (I->getOpcode() == Instruction::Mul) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000052 // This value is scaled by 'RHS'.
53 Scale = RHS->getZExtValue();
54 Offset = 0;
55 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000056 }
Craig Topperb57c2922013-01-24 05:22:40 +000057
Chris Lattnerf86d7992010-01-05 20:57:30 +000058 if (I->getOpcode() == Instruction::Add) {
Craig Topperb57c2922013-01-24 05:22:40 +000059 // We have X+C. Check to see if we really have (X*C2)+C1,
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000060 // where C1 is divisible by C2.
61 unsigned SubScale;
Craig Topperb57c2922013-01-24 05:22:40 +000062 Value *SubVal =
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000063 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
64 Offset += RHS->getZExtValue();
65 Scale = SubScale;
66 return SubVal;
67 }
68 }
69 }
70
71 // Otherwise, we can't look past this.
72 Scale = 1;
73 Offset = 0;
74 return Val;
75}
76
77/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
78/// try to eliminate the cast by moving the type information into the alloc.
79Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
80 AllocaInst &AI) {
Micah Villmow3574eca2012-10-08 16:38:25 +000081 // This requires DataLayout to get the alloca alignment and size information.
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000082 if (!TD) return 0;
83
Chris Lattnerdb125cf2011-07-18 04:54:35 +000084 PointerType *PTy = cast<PointerType>(CI.getType());
Craig Topperb57c2922013-01-24 05:22:40 +000085
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000086 BuilderTy AllocaBuilder(*Builder);
87 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
88
89 // Get the type really allocated and the type casted to.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000090 Type *AllocElTy = AI.getAllocatedType();
91 Type *CastElTy = PTy->getElementType();
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000092 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
93
94 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
95 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
96 if (CastElTyAlign < AllocElTyAlign) return 0;
97
98 // If the allocation has multiple uses, only promote it if we are strictly
99 // increasing the alignment of the resultant allocation. If we keep it the
Devang Patel5aa3fa62011-03-08 22:12:11 +0000100 // same, we open the door to infinite loops of various kinds.
101 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000102
103 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
104 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
105 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
106
107 // See if we can satisfy the modulus by pulling a scale out of the array
108 // size argument.
109 unsigned ArraySizeScale;
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000110 uint64_t ArrayOffset;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000111 Value *NumElements = // See if the array size is a decomposable linear expr.
112 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
Craig Topperb57c2922013-01-24 05:22:40 +0000113
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000114 // If we can now satisfy the modulus, by using a non-1 scale, we really can
115 // do the xform.
116 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
117 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
118
119 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
120 Value *Amt = 0;
121 if (Scale == 1) {
122 Amt = NumElements;
123 } else {
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000124 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000125 // Insert before the alloca, not before the cast.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000126 Amt = AllocaBuilder.CreateMul(Amt, NumElements);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000127 }
Craig Topperb57c2922013-01-24 05:22:40 +0000128
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000129 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
130 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000131 Offset, true);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000132 Amt = AllocaBuilder.CreateAdd(Amt, Off);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000133 }
Craig Topperb57c2922013-01-24 05:22:40 +0000134
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000135 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
136 New->setAlignment(AI.getAlignment());
137 New->takeName(&AI);
Craig Topperb57c2922013-01-24 05:22:40 +0000138
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000139 // If the allocation has multiple real uses, insert a cast and change all
140 // things that used it to use the new cast. This will also hack on CI, but it
141 // will die soon.
Devang Patel5aa3fa62011-03-08 22:12:11 +0000142 if (!AI.hasOneUse()) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000143 // New is the allocation instruction, pointer typed. AI is the original
144 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
145 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Eli Friedman3e22cb92011-05-18 00:32:01 +0000146 ReplaceInstUsesWith(AI, NewCast);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000147 }
148 return ReplaceInstUsesWith(CI, New);
149}
150
Craig Topperb57c2922013-01-24 05:22:40 +0000151/// EvaluateInDifferentType - Given an expression that
Chris Lattner14bf8f02010-01-08 19:19:23 +0000152/// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000153/// insert the code to evaluate the expression.
Craig Topperb57c2922013-01-24 05:22:40 +0000154Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
Chris Lattner5f0290e2010-01-04 07:54:59 +0000155 bool isSigned) {
Chris Lattnerc8b3fce2010-01-08 19:28:47 +0000156 if (Constant *C = dyn_cast<Constant>(V)) {
157 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
158 // If we got a constantexpr back, try to simplify it with TD info.
159 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Chad Rosier00737bd2011-12-01 21:29:16 +0000160 C = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattnerc8b3fce2010-01-08 19:28:47 +0000161 return C;
162 }
Chris Lattner5f0290e2010-01-04 07:54:59 +0000163
164 // Otherwise, it must be an instruction.
165 Instruction *I = cast<Instruction>(V);
166 Instruction *Res = 0;
167 unsigned Opc = I->getOpcode();
168 switch (Opc) {
169 case Instruction::Add:
170 case Instruction::Sub:
171 case Instruction::Mul:
172 case Instruction::And:
173 case Instruction::Or:
174 case Instruction::Xor:
175 case Instruction::AShr:
176 case Instruction::LShr:
177 case Instruction::Shl:
178 case Instruction::UDiv:
179 case Instruction::URem: {
180 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
181 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
182 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
183 break;
Craig Topperb57c2922013-01-24 05:22:40 +0000184 }
Chris Lattner5f0290e2010-01-04 07:54:59 +0000185 case Instruction::Trunc:
186 case Instruction::ZExt:
187 case Instruction::SExt:
188 // If the source type of the cast is the type we're trying for then we can
189 // just return the source. There's no need to insert it because it is not
190 // new.
191 if (I->getOperand(0)->getType() == Ty)
192 return I->getOperand(0);
Craig Topperb57c2922013-01-24 05:22:40 +0000193
Chris Lattner5f0290e2010-01-04 07:54:59 +0000194 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000195 // This also handles the case of zext(trunc(x)) -> zext(x).
196 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
197 Opc == Instruction::SExt);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000198 break;
199 case Instruction::Select: {
200 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
201 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
202 Res = SelectInst::Create(I->getOperand(0), True, False);
203 break;
204 }
205 case Instruction::PHI: {
206 PHINode *OPN = cast<PHINode>(I);
Jay Foad3ecfc862011-03-30 11:28:46 +0000207 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
Chris Lattner5f0290e2010-01-04 07:54:59 +0000208 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
209 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
210 NPN->addIncoming(V, OPN->getIncomingBlock(i));
211 }
212 Res = NPN;
213 break;
214 }
Craig Topperb57c2922013-01-24 05:22:40 +0000215 default:
Chris Lattner5f0290e2010-01-04 07:54:59 +0000216 // TODO: Can handle more cases here.
217 llvm_unreachable("Unreachable!");
Chris Lattner5f0290e2010-01-04 07:54:59 +0000218 }
Craig Topperb57c2922013-01-24 05:22:40 +0000219
Chris Lattner5f0290e2010-01-04 07:54:59 +0000220 Res->takeName(I);
Eli Friedmana311c342011-05-27 00:19:40 +0000221 return InsertNewInstWith(Res, *I);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000222}
Chris Lattner80f43d32010-01-04 07:53:58 +0000223
224
225/// This function is a wrapper around CastInst::isEliminableCastPair. It
226/// simply extracts arguments and returns what that function returns.
Craig Topperb57c2922013-01-24 05:22:40 +0000227static Instruction::CastOps
Chris Lattner80f43d32010-01-04 07:53:58 +0000228isEliminableCastPair(
229 const CastInst *CI, ///< The first cast instruction
230 unsigned opcode, ///< The opcode of the second cast instruction
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000231 Type *DstTy, ///< The target type for the second cast instruction
Micah Villmow3574eca2012-10-08 16:38:25 +0000232 DataLayout *TD ///< The target data for pointer size
Chris Lattner80f43d32010-01-04 07:53:58 +0000233) {
234
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000235 Type *SrcTy = CI->getOperand(0)->getType(); // A from above
236 Type *MidTy = CI->getType(); // B from above
Chris Lattner80f43d32010-01-04 07:53:58 +0000237
238 // Get the opcodes of the two Cast instructions
239 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
240 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Duncan Sands446cf942012-10-30 16:03:32 +0000241 Type *SrcIntPtrTy = TD && SrcTy->isPtrOrPtrVectorTy() ?
242 TD->getIntPtrType(SrcTy) : 0;
243 Type *MidIntPtrTy = TD && MidTy->isPtrOrPtrVectorTy() ?
244 TD->getIntPtrType(MidTy) : 0;
245 Type *DstIntPtrTy = TD && DstTy->isPtrOrPtrVectorTy() ?
246 TD->getIntPtrType(DstTy) : 0;
Chris Lattner80f43d32010-01-04 07:53:58 +0000247 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Duncan Sands446cf942012-10-30 16:03:32 +0000248 DstTy, SrcIntPtrTy, MidIntPtrTy,
249 DstIntPtrTy);
Micah Villmowaa76e9e2012-10-24 15:52:52 +0000250
Chris Lattner80f43d32010-01-04 07:53:58 +0000251 // We don't want to form an inttoptr or ptrtoint that converts to an integer
252 // type that differs from the pointer size.
Duncan Sands446cf942012-10-30 16:03:32 +0000253 if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
254 (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
Chris Lattner80f43d32010-01-04 07:53:58 +0000255 Res = 0;
Craig Topperb57c2922013-01-24 05:22:40 +0000256
Chris Lattner80f43d32010-01-04 07:53:58 +0000257 return Instruction::CastOps(Res);
258}
259
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000260/// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
261/// results in any code being generated and is interesting to optimize out. If
262/// the cast can be eliminated by some other simple transformation, we prefer
263/// to do the simplification first.
264bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000265 Type *Ty) {
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000266 // Noop casts and casts of constants should be eliminated trivially.
Chris Lattner80f43d32010-01-04 07:53:58 +0000267 if (V->getType() == Ty || isa<Constant>(V)) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000268
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000269 // If this is another cast that can be eliminated, we prefer to have it
270 // eliminated.
Chris Lattner80f43d32010-01-04 07:53:58 +0000271 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000272 if (isEliminableCastPair(CI, opc, Ty, TD))
Chris Lattner80f43d32010-01-04 07:53:58 +0000273 return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000274
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000275 // If this is a vector sext from a compare, then we don't want to break the
276 // idiom where each element of the extended vector is either zero or all ones.
Duncan Sands1df98592010-02-16 11:11:14 +0000277 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000278 return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000279
Chris Lattner80f43d32010-01-04 07:53:58 +0000280 return true;
281}
282
283
284/// @brief Implement the transforms common to all CastInst visitors.
285Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
286 Value *Src = CI.getOperand(0);
287
288 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
289 // eliminate it now.
290 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Craig Topperb57c2922013-01-24 05:22:40 +0000291 if (Instruction::CastOps opc =
Chris Lattner80f43d32010-01-04 07:53:58 +0000292 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
293 // The first cast (CSrc) is eliminable so we need to fix up or replace
294 // the second cast (CI). CSrc will then have a good chance of being dead.
295 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
296 }
297 }
298
299 // If we are casting a select then fold the cast into the select
300 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
301 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
302 return NV;
303
304 // If we are casting a PHI then fold the cast into the PHI
305 if (isa<PHINode>(Src)) {
306 // We don't do this if this would create a PHI node with an illegal type if
307 // it is currently legal.
Duncan Sands1df98592010-02-16 11:11:14 +0000308 if (!Src->getType()->isIntegerTy() ||
309 !CI.getType()->isIntegerTy() ||
Chris Lattner80f43d32010-01-04 07:53:58 +0000310 ShouldChangeType(CI.getType(), Src->getType()))
311 if (Instruction *NV = FoldOpIntoPhi(CI))
312 return NV;
313 }
Craig Topperb57c2922013-01-24 05:22:40 +0000314
Chris Lattner80f43d32010-01-04 07:53:58 +0000315 return 0;
316}
317
Chris Lattner75215c92010-01-10 00:58:42 +0000318/// CanEvaluateTruncated - Return true if we can evaluate the specified
319/// expression tree as type Ty instead of its larger type, and arrive with the
320/// same value. This is used by code that tries to eliminate truncates.
321///
322/// Ty will always be a type smaller than V. We should return true if trunc(V)
323/// can be computed by computing V in the smaller type. If V is an instruction,
324/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
325/// makes sense if x and y can be efficiently truncated.
326///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000327/// This function works on both vectors and scalars.
328///
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000329static bool CanEvaluateTruncated(Value *V, Type *Ty) {
Chris Lattner75215c92010-01-10 00:58:42 +0000330 // We can always evaluate constants in another type.
331 if (isa<Constant>(V))
332 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000333
Chris Lattner75215c92010-01-10 00:58:42 +0000334 Instruction *I = dyn_cast<Instruction>(V);
335 if (!I) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000336
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000337 Type *OrigTy = V->getType();
Craig Topperb57c2922013-01-24 05:22:40 +0000338
Chris Lattnera958cbf2010-01-11 22:45:25 +0000339 // If this is an extension from the dest type, we can eliminate it, even if it
340 // has multiple uses.
Craig Topperb57c2922013-01-24 05:22:40 +0000341 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000342 I->getOperand(0)->getType() == Ty)
343 return true;
344
345 // We can't extend or shrink something that has multiple uses: doing so would
346 // require duplicating the instruction in general, which isn't profitable.
347 if (!I->hasOneUse()) return false;
348
349 unsigned Opc = I->getOpcode();
350 switch (Opc) {
351 case Instruction::Add:
352 case Instruction::Sub:
353 case Instruction::Mul:
354 case Instruction::And:
355 case Instruction::Or:
356 case Instruction::Xor:
357 // These operators can all arbitrarily be extended or truncated.
358 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
359 CanEvaluateTruncated(I->getOperand(1), Ty);
360
361 case Instruction::UDiv:
362 case Instruction::URem: {
363 // UDiv and URem can be truncated if all the truncated bits are zero.
364 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
365 uint32_t BitWidth = Ty->getScalarSizeInBits();
366 if (BitWidth < OrigBitWidth) {
367 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
368 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
369 MaskedValueIsZero(I->getOperand(1), Mask)) {
370 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
371 CanEvaluateTruncated(I->getOperand(1), Ty);
372 }
373 }
374 break;
375 }
376 case Instruction::Shl:
377 // If we are truncating the result of this SHL, and if it's a shift of a
378 // constant amount, we can always perform a SHL in a smaller type.
379 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
380 uint32_t BitWidth = Ty->getScalarSizeInBits();
381 if (CI->getLimitedValue(BitWidth) < BitWidth)
382 return CanEvaluateTruncated(I->getOperand(0), Ty);
383 }
384 break;
385 case Instruction::LShr:
386 // If this is a truncate of a logical shr, we can truncate it to a smaller
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000387 // lshr iff we know that the bits we would otherwise be shifting in are
Chris Lattner75215c92010-01-10 00:58:42 +0000388 // already zeros.
389 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
390 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
391 uint32_t BitWidth = Ty->getScalarSizeInBits();
392 if (MaskedValueIsZero(I->getOperand(0),
393 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
394 CI->getLimitedValue(BitWidth) < BitWidth) {
395 return CanEvaluateTruncated(I->getOperand(0), Ty);
396 }
397 }
398 break;
399 case Instruction::Trunc:
400 // trunc(trunc(x)) -> trunc(x)
401 return true;
Chris Lattnerf9d05ab2010-08-27 20:32:06 +0000402 case Instruction::ZExt:
403 case Instruction::SExt:
404 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
405 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
406 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000407 case Instruction::Select: {
408 SelectInst *SI = cast<SelectInst>(I);
409 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
410 CanEvaluateTruncated(SI->getFalseValue(), Ty);
411 }
412 case Instruction::PHI: {
413 // We can change a phi if we can change all operands. Note that we never
414 // get into trouble with cyclic PHIs here because we only consider
415 // instructions with a single use.
416 PHINode *PN = cast<PHINode>(I);
417 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
418 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
419 return false;
420 return true;
421 }
422 default:
423 // TODO: Can handle more cases here.
424 break;
425 }
Craig Topperb57c2922013-01-24 05:22:40 +0000426
Chris Lattner75215c92010-01-10 00:58:42 +0000427 return false;
428}
429
430Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000431 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner75215c92010-01-10 00:58:42 +0000432 return Result;
Craig Topperb57c2922013-01-24 05:22:40 +0000433
434 // See if we can simplify any instructions used by the input whose sole
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000435 // purpose is to compute bits we don't care about.
436 if (SimplifyDemandedInstructionBits(CI))
437 return &CI;
Craig Topperb57c2922013-01-24 05:22:40 +0000438
Chris Lattner75215c92010-01-10 00:58:42 +0000439 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000440 Type *DestTy = CI.getType(), *SrcTy = Src->getType();
Craig Topperb57c2922013-01-24 05:22:40 +0000441
Chris Lattner75215c92010-01-10 00:58:42 +0000442 // Attempt to truncate the entire input expression tree to the destination
443 // type. Only do this if the dest type is a simple type, don't convert the
Chris Lattner80f43d32010-01-04 07:53:58 +0000444 // expression tree to something weird like i93 unless the source is also
445 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +0000446 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000447 CanEvaluateTruncated(Src, DestTy)) {
Craig Topperb57c2922013-01-24 05:22:40 +0000448
Chris Lattner80f43d32010-01-04 07:53:58 +0000449 // If this cast is a truncate, evaluting in a different type always
Chris Lattner68c6e892010-01-05 23:00:30 +0000450 // eliminates the cast, so it is always a win.
Chris Lattner075f6922010-01-07 23:41:00 +0000451 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Dan Gohman5b71dce2010-05-25 21:50:35 +0000452 " to avoid cast: " << CI << '\n');
Chris Lattner075f6922010-01-07 23:41:00 +0000453 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
454 assert(Res->getType() == DestTy);
455 return ReplaceInstUsesWith(CI, Res);
456 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000457
Chris Lattner7a34d6c2010-01-05 22:21:18 +0000458 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
459 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000460 Constant *One = ConstantInt::get(Src->getType(), 1);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000461 Src = Builder->CreateAnd(Src, One);
Chris Lattner80f43d32010-01-04 07:53:58 +0000462 Value *Zero = Constant::getNullValue(Src->getType());
463 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
464 }
Craig Topperb57c2922013-01-24 05:22:40 +0000465
Chris Lattner784f3332010-08-27 18:31:05 +0000466 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
467 Value *A = 0; ConstantInt *Cst = 0;
Chris Lattner62fe4062011-01-15 06:32:33 +0000468 if (Src->hasOneUse() &&
469 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
Chris Lattner784f3332010-08-27 18:31:05 +0000470 // We have three types to worry about here, the type of A, the source of
471 // the truncate (MidSize), and the destination of the truncate. We know that
472 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
473 // between ASize and ResultSize.
474 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
Craig Topperb57c2922013-01-24 05:22:40 +0000475
Chris Lattner784f3332010-08-27 18:31:05 +0000476 // If the shift amount is larger than the size of A, then the result is
477 // known to be zero because all the input bits got shifted out.
478 if (Cst->getZExtValue() >= ASize)
479 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
480
481 // Since we're doing an lshr and a zero extend, and know that the shift
482 // amount is smaller than ASize, it is always safe to do the shift in A's
483 // type, then zero extend or truncate to the result.
484 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
485 Shift->takeName(Src);
486 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
487 }
Craig Topperb57c2922013-01-24 05:22:40 +0000488
Chris Lattner62fe4062011-01-15 06:32:33 +0000489 // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
490 // type isn't non-native.
491 if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
492 ShouldChangeType(Src->getType(), CI.getType()) &&
493 match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
494 Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
495 return BinaryOperator::CreateAnd(NewTrunc,
496 ConstantExpr::getTrunc(Cst, CI.getType()));
497 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000498
Chris Lattner80f43d32010-01-04 07:53:58 +0000499 return 0;
500}
501
502/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
503/// in order to eliminate the icmp.
504Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
505 bool DoXform) {
506 // If we are just checking for a icmp eq of a single bit and zext'ing it
507 // to an integer, then shift the bit to the appropriate place and then
508 // cast to integer to avoid the comparison.
509 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
510 const APInt &Op1CV = Op1C->getValue();
Craig Topperb57c2922013-01-24 05:22:40 +0000511
Chris Lattner80f43d32010-01-04 07:53:58 +0000512 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
513 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
514 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
515 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
516 if (!DoXform) return ICI;
517
518 Value *In = ICI->getOperand(0);
519 Value *Sh = ConstantInt::get(In->getType(),
520 In->getType()->getScalarSizeInBits()-1);
521 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
522 if (In->getType() != CI.getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000523 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner80f43d32010-01-04 07:53:58 +0000524
525 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
526 Constant *One = ConstantInt::get(In->getType(), 1);
527 In = Builder->CreateXor(In, One, In->getName()+".not");
528 }
529
530 return ReplaceInstUsesWith(CI, In);
531 }
Chad Rosiercaebb1e2011-11-30 01:59:59 +0000532
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000533 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
534 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
535 // zext (X == 1) to i32 --> X iff X has only the low bit set.
536 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
537 // zext (X != 0) to i32 --> X iff X has only the low bit set.
538 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
539 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
540 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Craig Topperb57c2922013-01-24 05:22:40 +0000541 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
Chris Lattner80f43d32010-01-04 07:53:58 +0000542 // This only works for EQ and NE
543 ICI->isEquality()) {
544 // If Op1C some other power of two, convert:
545 uint32_t BitWidth = Op1C->getType()->getBitWidth();
546 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000547 ComputeMaskedBits(ICI->getOperand(0), KnownZero, KnownOne);
Craig Topperb57c2922013-01-24 05:22:40 +0000548
Chris Lattner80f43d32010-01-04 07:53:58 +0000549 APInt KnownZeroMask(~KnownZero);
550 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
551 if (!DoXform) return ICI;
552
553 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
554 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
555 // (X&4) == 2 --> false
556 // (X&4) != 2 --> true
557 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
558 isNE);
559 Res = ConstantExpr::getZExt(Res, CI.getType());
560 return ReplaceInstUsesWith(CI, Res);
561 }
Craig Topperb57c2922013-01-24 05:22:40 +0000562
Chris Lattner80f43d32010-01-04 07:53:58 +0000563 uint32_t ShiftAmt = KnownZeroMask.logBase2();
564 Value *In = ICI->getOperand(0);
565 if (ShiftAmt) {
566 // Perform a logical shr by shiftamt.
567 // Insert the shift to put the result in the low bit.
568 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
569 In->getName()+".lobit");
570 }
Craig Topperb57c2922013-01-24 05:22:40 +0000571
Chris Lattner80f43d32010-01-04 07:53:58 +0000572 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
573 Constant *One = ConstantInt::get(In->getType(), 1);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000574 In = Builder->CreateXor(In, One);
Chris Lattner80f43d32010-01-04 07:53:58 +0000575 }
Craig Topperb57c2922013-01-24 05:22:40 +0000576
Chris Lattner80f43d32010-01-04 07:53:58 +0000577 if (CI.getType() == In->getType())
578 return ReplaceInstUsesWith(CI, In);
Chris Lattner29cc0b32010-08-27 22:24:38 +0000579 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner80f43d32010-01-04 07:53:58 +0000580 }
581 }
582 }
583
584 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
585 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
586 // may lead to additional simplifications.
587 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000588 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000589 uint32_t BitWidth = ITy->getBitWidth();
590 Value *LHS = ICI->getOperand(0);
591 Value *RHS = ICI->getOperand(1);
592
593 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
594 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000595 ComputeMaskedBits(LHS, KnownZeroLHS, KnownOneLHS);
596 ComputeMaskedBits(RHS, KnownZeroRHS, KnownOneRHS);
Chris Lattner80f43d32010-01-04 07:53:58 +0000597
598 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
599 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
600 APInt UnknownBit = ~KnownBits;
601 if (UnknownBit.countPopulation() == 1) {
602 if (!DoXform) return ICI;
603
604 Value *Result = Builder->CreateXor(LHS, RHS);
605
606 // Mask off any bits that are set and won't be shifted away.
607 if (KnownOneLHS.uge(UnknownBit))
608 Result = Builder->CreateAnd(Result,
609 ConstantInt::get(ITy, UnknownBit));
610
611 // Shift the bit we're testing down to the lsb.
612 Result = Builder->CreateLShr(
613 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
614
615 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
616 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
617 Result->takeName(ICI);
618 return ReplaceInstUsesWith(CI, Result);
619 }
620 }
621 }
622 }
623
624 return 0;
625}
626
Chris Lattner75215c92010-01-10 00:58:42 +0000627/// CanEvaluateZExtd - Determine if the specified value can be computed in the
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000628/// specified wider type and produce the same low bits. If not, return false.
629///
Chris Lattner789162a2010-01-11 03:32:00 +0000630/// If this function returns true, it can also return a non-zero number of bits
631/// (in BitsToClear) which indicates that the value it computes is correct for
632/// the zero extend, but that the additional BitsToClear bits need to be zero'd
633/// out. For example, to promote something like:
634///
635/// %B = trunc i64 %A to i32
636/// %C = lshr i32 %B, 8
637/// %E = zext i32 %C to i64
638///
639/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
640/// set to 8 to indicate that the promoted value needs to have bits 24-31
641/// cleared in addition to bits 32-63. Since an 'and' will be generated to
642/// clear the top bits anyway, doing this has no extra cost.
643///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000644/// This function works on both vectors and scalars.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000645static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear) {
Chris Lattner789162a2010-01-11 03:32:00 +0000646 BitsToClear = 0;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000647 if (isa<Constant>(V))
648 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000649
Chris Lattner75215c92010-01-10 00:58:42 +0000650 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner9e390dd2010-01-10 02:50:04 +0000651 if (!I) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000652
Chris Lattner75215c92010-01-10 00:58:42 +0000653 // If the input is a truncate from the destination type, we can trivially
Jakob Stoklund Olesen7ee3ca12012-06-22 16:36:43 +0000654 // eliminate it.
655 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattner9e390dd2010-01-10 02:50:04 +0000656 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000657
Chris Lattner75215c92010-01-10 00:58:42 +0000658 // We can't extend or shrink something that has multiple uses: doing so would
659 // require duplicating the instruction in general, which isn't profitable.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000660 if (!I->hasOneUse()) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000661
Chris Lattner789162a2010-01-11 03:32:00 +0000662 unsigned Opc = I->getOpcode(), Tmp;
Chris Lattner75215c92010-01-10 00:58:42 +0000663 switch (Opc) {
Chris Lattner9ee947c2010-01-10 20:25:54 +0000664 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
665 case Instruction::SExt: // zext(sext(x)) -> sext(x).
666 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
667 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000668 case Instruction::And:
Chris Lattner75215c92010-01-10 00:58:42 +0000669 case Instruction::Or:
670 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +0000671 case Instruction::Add:
672 case Instruction::Sub:
673 case Instruction::Mul:
Chris Lattnerd26c9e12010-01-10 02:22:12 +0000674 case Instruction::Shl:
Chris Lattner789162a2010-01-11 03:32:00 +0000675 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
676 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
677 return false;
678 // These can all be promoted if neither operand has 'bits to clear'.
679 if (BitsToClear == 0 && Tmp == 0)
680 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000681
Chris Lattner7acc4b12010-01-11 04:05:13 +0000682 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
683 // other side, BitsToClear is ok.
684 if (Tmp == 0 &&
685 (Opc == Instruction::And || Opc == Instruction::Or ||
686 Opc == Instruction::Xor)) {
687 // We use MaskedValueIsZero here for generality, but the case we care
688 // about the most is constant RHS.
689 unsigned VSize = V->getType()->getScalarSizeInBits();
690 if (MaskedValueIsZero(I->getOperand(1),
691 APInt::getHighBitsSet(VSize, BitsToClear)))
692 return true;
693 }
Craig Topperb57c2922013-01-24 05:22:40 +0000694
Chris Lattner7acc4b12010-01-11 04:05:13 +0000695 // Otherwise, we don't know how to analyze this BitsToClear case yet.
Chris Lattner789162a2010-01-11 03:32:00 +0000696 return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000697
Chris Lattner789162a2010-01-11 03:32:00 +0000698 case Instruction::LShr:
699 // We can promote lshr(x, cst) if we can promote x. This requires the
700 // ultimate 'and' to clear out the high zero bits we're clearing out though.
701 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
702 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
703 return false;
704 BitsToClear += Amt->getZExtValue();
705 if (BitsToClear > V->getType()->getScalarSizeInBits())
706 BitsToClear = V->getType()->getScalarSizeInBits();
707 return true;
708 }
709 // Cannot promote variable LSHR.
710 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000711 case Instruction::Select:
Chris Lattner789162a2010-01-11 03:32:00 +0000712 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
713 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000714 // TODO: If important, we could handle the case when the BitsToClear are
715 // known zero in the disagreeing side.
Chris Lattner789162a2010-01-11 03:32:00 +0000716 Tmp != BitsToClear)
717 return false;
718 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000719
Chris Lattner75215c92010-01-10 00:58:42 +0000720 case Instruction::PHI: {
721 // We can change a phi if we can change all operands. Note that we never
722 // get into trouble with cyclic PHIs here because we only consider
723 // instructions with a single use.
724 PHINode *PN = cast<PHINode>(I);
Chris Lattner789162a2010-01-11 03:32:00 +0000725 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
726 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000727 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner789162a2010-01-11 03:32:00 +0000728 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000729 // TODO: If important, we could handle the case when the BitsToClear
730 // are known zero in the disagreeing input.
Chris Lattner789162a2010-01-11 03:32:00 +0000731 Tmp != BitsToClear)
732 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000733 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000734 }
735 default:
736 // TODO: Can handle more cases here.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000737 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000738 }
739}
740
Chris Lattner80f43d32010-01-04 07:53:58 +0000741Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Nick Lewyckyeb3ac452013-01-14 20:56:10 +0000742 // If this zero extend is only used by a truncate, let the truncate be
Chris Lattner5324d802010-01-10 02:39:31 +0000743 // eliminated before we try to optimize this zext.
744 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
745 return 0;
Craig Topperb57c2922013-01-24 05:22:40 +0000746
Chris Lattner80f43d32010-01-04 07:53:58 +0000747 // If one of the common conversion will work, do it.
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000748 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +0000749 return Result;
750
Craig Topperb57c2922013-01-24 05:22:40 +0000751 // See if we can simplify any instructions used by the input whose sole
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000752 // purpose is to compute bits we don't care about.
753 if (SimplifyDemandedInstructionBits(CI))
754 return &CI;
Craig Topperb57c2922013-01-24 05:22:40 +0000755
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000756 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000757 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Craig Topperb57c2922013-01-24 05:22:40 +0000758
Chris Lattner75215c92010-01-10 00:58:42 +0000759 // Attempt to extend the entire input expression tree to the destination
760 // type. Only do this if the dest type is a simple type, don't convert the
761 // expression tree to something weird like i93 unless the source is also
762 // strange.
Chris Lattner789162a2010-01-11 03:32:00 +0000763 unsigned BitsToClear;
Duncan Sands1df98592010-02-16 11:11:14 +0000764 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Craig Topperb57c2922013-01-24 05:22:40 +0000765 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
Chris Lattner789162a2010-01-11 03:32:00 +0000766 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
767 "Unreasonable BitsToClear");
Craig Topperb57c2922013-01-24 05:22:40 +0000768
Chris Lattner5324d802010-01-10 02:39:31 +0000769 // Okay, we can transform this! Insert the new expression now.
770 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
771 " to avoid zero extend: " << CI);
772 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
773 assert(Res->getType() == DestTy);
Craig Topperb57c2922013-01-24 05:22:40 +0000774
Chris Lattner789162a2010-01-11 03:32:00 +0000775 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
776 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topperb57c2922013-01-24 05:22:40 +0000777
Chris Lattner5324d802010-01-10 02:39:31 +0000778 // If the high bits are already filled with zeros, just replace this
779 // cast with the result.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000780 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
Chris Lattner789162a2010-01-11 03:32:00 +0000781 DestBitSize-SrcBitsKept)))
Chris Lattner5324d802010-01-10 02:39:31 +0000782 return ReplaceInstUsesWith(CI, Res);
Craig Topperb57c2922013-01-24 05:22:40 +0000783
Chris Lattner5324d802010-01-10 02:39:31 +0000784 // We need to emit an AND to clear the high bits.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000785 Constant *C = ConstantInt::get(Res->getType(),
Chris Lattner789162a2010-01-11 03:32:00 +0000786 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
Chris Lattner5324d802010-01-10 02:39:31 +0000787 return BinaryOperator::CreateAnd(Res, C);
Chris Lattner75215c92010-01-10 00:58:42 +0000788 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000789
790 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
791 // types and if the sizes are just right we can convert this into a logical
792 // 'and' which will be much cheaper than the pair of casts.
793 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000794 // TODO: Subsume this into EvaluateInDifferentType.
Craig Topperb57c2922013-01-24 05:22:40 +0000795
Chris Lattner80f43d32010-01-04 07:53:58 +0000796 // Get the sizes of the types involved. We know that the intermediate type
797 // will be smaller than A or C, but don't know the relation between A and C.
798 Value *A = CSrc->getOperand(0);
799 unsigned SrcSize = A->getType()->getScalarSizeInBits();
800 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
801 unsigned DstSize = CI.getType()->getScalarSizeInBits();
802 // If we're actually extending zero bits, then if
803 // SrcSize < DstSize: zext(a & mask)
804 // SrcSize == DstSize: a & mask
805 // SrcSize > DstSize: trunc(a) & mask
806 if (SrcSize < DstSize) {
807 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
808 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
809 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
810 return new ZExtInst(And, CI.getType());
811 }
Craig Topperb57c2922013-01-24 05:22:40 +0000812
Chris Lattner80f43d32010-01-04 07:53:58 +0000813 if (SrcSize == DstSize) {
814 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
815 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
816 AndValue));
817 }
818 if (SrcSize > DstSize) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000819 Value *Trunc = Builder->CreateTrunc(A, CI.getType());
Chris Lattner80f43d32010-01-04 07:53:58 +0000820 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Craig Topperb57c2922013-01-24 05:22:40 +0000821 return BinaryOperator::CreateAnd(Trunc,
Chris Lattner80f43d32010-01-04 07:53:58 +0000822 ConstantInt::get(Trunc->getType(),
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000823 AndValue));
Chris Lattner80f43d32010-01-04 07:53:58 +0000824 }
825 }
826
827 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
828 return transformZExtICmp(ICI, CI);
829
830 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
831 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
832 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
833 // of the (zext icmp) will be transformed.
834 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
835 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
836 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
837 (transformZExtICmp(LHS, CI, false) ||
838 transformZExtICmp(RHS, CI, false))) {
839 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
840 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
841 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
842 }
843 }
844
845 // zext(trunc(t) & C) -> (t & zext(C)).
846 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
847 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
848 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
849 Value *TI0 = TI->getOperand(0);
850 if (TI0->getType() == CI.getType())
851 return
852 BinaryOperator::CreateAnd(TI0,
853 ConstantExpr::getZExt(C, CI.getType()));
854 }
855
856 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
857 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
858 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
859 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
860 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
861 And->getOperand(1) == C)
862 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
863 Value *TI0 = TI->getOperand(0);
864 if (TI0->getType() == CI.getType()) {
865 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Benjamin Kramera9390a42011-09-27 20:39:19 +0000866 Value *NewAnd = Builder->CreateAnd(TI0, ZC);
Chris Lattner80f43d32010-01-04 07:53:58 +0000867 return BinaryOperator::CreateXor(NewAnd, ZC);
868 }
869 }
870
Chris Lattner718bf3f2010-01-05 21:04:47 +0000871 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
872 Value *X;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000873 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isIntegerTy(1) &&
Chris Lattner49bdfef2010-01-05 21:11:17 +0000874 match(SrcI, m_Not(m_Value(X))) &&
Chris Lattner718bf3f2010-01-05 21:04:47 +0000875 (!X->hasOneUse() || !isa<CmpInst>(X))) {
876 Value *New = Builder->CreateZExt(X, CI.getType());
877 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
878 }
Craig Topperb57c2922013-01-24 05:22:40 +0000879
Chris Lattner80f43d32010-01-04 07:53:58 +0000880 return 0;
881}
882
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000883/// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
884/// in order to eliminate the icmp.
885Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
886 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
887 ICmpInst::Predicate Pred = ICI->getPredicate();
888
889 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Benjamin Kramer406a6502011-04-01 22:29:18 +0000890 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
891 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000892 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isZero()) ||
893 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
894
895 Value *Sh = ConstantInt::get(Op0->getType(),
896 Op0->getType()->getScalarSizeInBits()-1);
897 Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
898 if (In->getType() != CI.getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000899 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000900
901 if (Pred == ICmpInst::ICMP_SGT)
902 In = Builder->CreateNot(In, In->getName()+".not");
903 return ReplaceInstUsesWith(CI, In);
904 }
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000905
906 // If we know that only one bit of the LHS of the icmp can be set and we
907 // have an equality comparison with zero or a power of 2, we can transform
908 // the icmp and sext into bitwise/integer operations.
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000909 if (ICI->hasOneUse() &&
910 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000911 unsigned BitWidth = Op1C->getType()->getBitWidth();
912 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000913 ComputeMaskedBits(Op0, KnownZero, KnownOne);
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000914
Benjamin Kramerce1498b2011-04-01 20:15:16 +0000915 APInt KnownZeroMask(~KnownZero);
916 if (KnownZeroMask.isPowerOf2()) {
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000917 Value *In = ICI->getOperand(0);
918
Benjamin Kramerf5b75932011-04-02 18:50:58 +0000919 // If the icmp tests for a known zero bit we can constant fold it.
920 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
921 Value *V = Pred == ICmpInst::ICMP_NE ?
922 ConstantInt::getAllOnesValue(CI.getType()) :
923 ConstantInt::getNullValue(CI.getType());
924 return ReplaceInstUsesWith(CI, V);
925 }
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000926
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000927 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
928 // sext ((x & 2^n) == 0) -> (x >> n) - 1
929 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
930 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
931 // Perform a right shift to place the desired bit in the LSB.
932 if (ShiftAmt)
933 In = Builder->CreateLShr(In,
934 ConstantInt::get(In->getType(), ShiftAmt));
935
936 // At this point "In" is either 1 or 0. Subtract 1 to turn
937 // {1, 0} -> {0, -1}.
938 In = Builder->CreateAdd(In,
939 ConstantInt::getAllOnesValue(In->getType()),
940 "sext");
941 } else {
942 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000943 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000944 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
945 // Perform a left shift to place the desired bit in the MSB.
946 if (ShiftAmt)
947 In = Builder->CreateShl(In,
948 ConstantInt::get(In->getType(), ShiftAmt));
949
950 // Distribute the bit over the whole bit width.
951 In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
952 BitWidth - 1), "sext");
953 }
954
955 if (CI.getType() == In->getType())
956 return ReplaceInstUsesWith(CI, In);
957 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
958 }
959 }
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000960 }
961
962 // vector (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000963 if (VectorType *VTy = dyn_cast<VectorType>(CI.getType())) {
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000964 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_Zero()) &&
965 Op0->getType() == CI.getType()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000966 Type *EltTy = VTy->getElementType();
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000967
968 // splat the shift constant to a constant vector.
969 Constant *VSh = ConstantInt::get(VTy, EltTy->getScalarSizeInBits()-1);
970 Value *In = Builder->CreateAShr(Op0, VSh, Op0->getName()+".lobit");
971 return ReplaceInstUsesWith(CI, In);
972 }
973 }
974
975 return 0;
976}
977
Chris Lattner75215c92010-01-10 00:58:42 +0000978/// CanEvaluateSExtd - Return true if we can take the specified value
979/// and return it as type Ty without inserting any new casts and without
980/// changing the value of the common low bits. This is used by code that tries
981/// to promote integer operations to a wider types will allow us to eliminate
982/// the extension.
983///
Chris Lattneraa9c8942010-01-10 07:57:20 +0000984/// This function works on both vectors and scalars.
Chris Lattner75215c92010-01-10 00:58:42 +0000985///
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000986static bool CanEvaluateSExtd(Value *V, Type *Ty) {
Chris Lattner75215c92010-01-10 00:58:42 +0000987 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
988 "Can't sign extend type to a smaller type");
Chris Lattneraa9c8942010-01-10 07:57:20 +0000989 // If this is a constant, it can be trivially promoted.
990 if (isa<Constant>(V))
991 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000992
Chris Lattner75215c92010-01-10 00:58:42 +0000993 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattneraa9c8942010-01-10 07:57:20 +0000994 if (!I) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000995
Jakob Stoklund Olesen7ee3ca12012-06-22 16:36:43 +0000996 // If this is a truncate from the dest type, we can trivially eliminate it.
997 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattneraa9c8942010-01-10 07:57:20 +0000998 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000999
Chris Lattner75215c92010-01-10 00:58:42 +00001000 // We can't extend or shrink something that has multiple uses: doing so would
1001 // require duplicating the instruction in general, which isn't profitable.
Chris Lattneraa9c8942010-01-10 07:57:20 +00001002 if (!I->hasOneUse()) return false;
Chris Lattner75215c92010-01-10 00:58:42 +00001003
Chris Lattneraa9c8942010-01-10 07:57:20 +00001004 switch (I->getOpcode()) {
Chris Lattner11ea8122010-01-10 20:30:41 +00001005 case Instruction::SExt: // sext(sext(x)) -> sext(x)
1006 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1007 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1008 return true;
Chris Lattner75215c92010-01-10 00:58:42 +00001009 case Instruction::And:
1010 case Instruction::Or:
1011 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +00001012 case Instruction::Add:
1013 case Instruction::Sub:
Chris Lattner75215c92010-01-10 00:58:42 +00001014 case Instruction::Mul:
Chris Lattneraa9c8942010-01-10 07:57:20 +00001015 // These operators can all arbitrarily be extended if their inputs can.
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001016 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
1017 CanEvaluateSExtd(I->getOperand(1), Ty);
Craig Topperb57c2922013-01-24 05:22:40 +00001018
Chris Lattner75215c92010-01-10 00:58:42 +00001019 //case Instruction::Shl: TODO
1020 //case Instruction::LShr: TODO
Craig Topperb57c2922013-01-24 05:22:40 +00001021
Chris Lattneraa9c8942010-01-10 07:57:20 +00001022 case Instruction::Select:
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001023 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
1024 CanEvaluateSExtd(I->getOperand(2), Ty);
Craig Topperb57c2922013-01-24 05:22:40 +00001025
Chris Lattner75215c92010-01-10 00:58:42 +00001026 case Instruction::PHI: {
1027 // We can change a phi if we can change all operands. Note that we never
1028 // get into trouble with cyclic PHIs here because we only consider
1029 // instructions with a single use.
1030 PHINode *PN = cast<PHINode>(I);
Chris Lattner9ee947c2010-01-10 20:25:54 +00001031 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001032 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
Chris Lattneraa9c8942010-01-10 07:57:20 +00001033 return true;
Chris Lattner75215c92010-01-10 00:58:42 +00001034 }
1035 default:
1036 // TODO: Can handle more cases here.
1037 break;
1038 }
Craig Topperb57c2922013-01-24 05:22:40 +00001039
Chris Lattneraa9c8942010-01-10 07:57:20 +00001040 return false;
Chris Lattner75215c92010-01-10 00:58:42 +00001041}
1042
Chris Lattner80f43d32010-01-04 07:53:58 +00001043Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattner5324d802010-01-10 02:39:31 +00001044 // If this sign extend is only used by a truncate, let the truncate by
1045 // eliminated before we try to optimize this zext.
1046 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
1047 return 0;
Craig Topperb57c2922013-01-24 05:22:40 +00001048
Chris Lattnerd84dfa42010-01-10 01:00:46 +00001049 if (Instruction *I = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +00001050 return I;
Craig Topperb57c2922013-01-24 05:22:40 +00001051
1052 // See if we can simplify any instructions used by the input whose sole
Chris Lattnerd84dfa42010-01-10 01:00:46 +00001053 // purpose is to compute bits we don't care about.
1054 if (SimplifyDemandedInstructionBits(CI))
1055 return &CI;
Craig Topperb57c2922013-01-24 05:22:40 +00001056
Chris Lattner80f43d32010-01-04 07:53:58 +00001057 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001058 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Chris Lattner75215c92010-01-10 00:58:42 +00001059
Chris Lattner75215c92010-01-10 00:58:42 +00001060 // Attempt to extend the entire input expression tree to the destination
1061 // type. Only do this if the dest type is a simple type, don't convert the
1062 // expression tree to something weird like i93 unless the source is also
1063 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +00001064 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001065 CanEvaluateSExtd(Src, DestTy)) {
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001066 // Okay, we can transform this! Insert the new expression now.
1067 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1068 " to avoid sign extend: " << CI);
1069 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1070 assert(Res->getType() == DestTy);
1071
Chris Lattner75215c92010-01-10 00:58:42 +00001072 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1073 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001074
1075 // If the high bits are already filled with sign bit, just replace this
1076 // cast with the result.
Chris Lattneraa9c8942010-01-10 07:57:20 +00001077 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001078 return ReplaceInstUsesWith(CI, Res);
Craig Topperb57c2922013-01-24 05:22:40 +00001079
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001080 // We need to emit a shl + ashr to do the sign extend.
1081 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1082 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1083 ShAmt);
Chris Lattner75215c92010-01-10 00:58:42 +00001084 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001085
Chris Lattnercd5adbb2010-01-18 22:19:16 +00001086 // If this input is a trunc from our destination, then turn sext(trunc(x))
1087 // into shifts.
1088 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1089 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1090 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1091 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topperb57c2922013-01-24 05:22:40 +00001092
Chris Lattnercd5adbb2010-01-18 22:19:16 +00001093 // We need to emit a shl + ashr to do the sign extend.
1094 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1095 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1096 return BinaryOperator::CreateAShr(Res, ShAmt);
1097 }
Nate Begeman9a3dc552010-12-17 23:12:19 +00001098
Benjamin Kramer0a30c422011-04-01 20:09:03 +00001099 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1100 return transformSExtICmp(ICI, CI);
Bill Wendling2d0537c2010-12-17 23:27:41 +00001101
Chris Lattner80f43d32010-01-04 07:53:58 +00001102 // If the input is a shl/ashr pair of a same constant, then this is a sign
1103 // extension from a smaller value. If we could trust arbitrary bitwidth
1104 // integers, we could turn this into a truncate to the smaller bit and then
1105 // use a sext for the whole extension. Since we don't, look deeper and check
1106 // for a truncate. If the source and dest are the same type, eliminate the
1107 // trunc and extend and just do shifts. For example, turn:
1108 // %a = trunc i32 %i to i8
1109 // %b = shl i8 %a, 6
1110 // %c = ashr i8 %b, 6
1111 // %d = sext i8 %c to i32
1112 // into:
1113 // %a = shl i32 %i, 30
1114 // %d = ashr i32 %a, 30
1115 Value *A = 0;
Chris Lattner4f379782010-01-10 01:04:31 +00001116 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
Chris Lattner80f43d32010-01-04 07:53:58 +00001117 ConstantInt *BA = 0, *CA = 0;
Chris Lattner4f379782010-01-10 01:04:31 +00001118 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
Chris Lattner80f43d32010-01-04 07:53:58 +00001119 m_ConstantInt(CA))) &&
Chris Lattner4f379782010-01-10 01:04:31 +00001120 BA == CA && A->getType() == CI.getType()) {
1121 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1122 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1123 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1124 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1125 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1126 return BinaryOperator::CreateAShr(A, ShAmtV);
Chris Lattner80f43d32010-01-04 07:53:58 +00001127 }
Craig Topperb57c2922013-01-24 05:22:40 +00001128
Chris Lattner80f43d32010-01-04 07:53:58 +00001129 return 0;
1130}
1131
1132
1133/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1134/// in the specified FP type without changing its value.
1135static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1136 bool losesInfo;
1137 APFloat F = CFP->getValueAPF();
1138 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1139 if (!losesInfo)
1140 return ConstantFP::get(CFP->getContext(), F);
1141 return 0;
1142}
1143
1144/// LookThroughFPExtensions - If this is an fp extension instruction, look
1145/// through it until we get the source value.
1146static Value *LookThroughFPExtensions(Value *V) {
1147 if (Instruction *I = dyn_cast<Instruction>(V))
1148 if (I->getOpcode() == Instruction::FPExt)
1149 return LookThroughFPExtensions(I->getOperand(0));
Craig Topperb57c2922013-01-24 05:22:40 +00001150
Chris Lattner80f43d32010-01-04 07:53:58 +00001151 // If this value is a constant, return the constant in the smallest FP type
1152 // that can accurately represent it. This allows us to turn
1153 // (float)((double)X+2.0) into x+2.0f.
1154 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1155 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1156 return V; // No constant folding of this.
Dan Gohmance163392011-12-17 00:04:22 +00001157 // See if the value can be truncated to half and then reextended.
1158 if (Value *V = FitsInFPType(CFP, APFloat::IEEEhalf))
1159 return V;
Chris Lattner80f43d32010-01-04 07:53:58 +00001160 // See if the value can be truncated to float and then reextended.
1161 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1162 return V;
Benjamin Kramerf0127052010-01-05 13:12:22 +00001163 if (CFP->getType()->isDoubleTy())
Chris Lattner80f43d32010-01-04 07:53:58 +00001164 return V; // Won't shrink.
1165 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1166 return V;
1167 // Don't try to shrink to various long double types.
1168 }
Craig Topperb57c2922013-01-24 05:22:40 +00001169
Chris Lattner80f43d32010-01-04 07:53:58 +00001170 return V;
1171}
1172
1173Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1174 if (Instruction *I = commonCastTransforms(CI))
1175 return I;
Craig Topperb57c2922013-01-24 05:22:40 +00001176
Chris Lattner80f43d32010-01-04 07:53:58 +00001177 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1178 // smaller than the destination type, we can eliminate the truncate by doing
1179 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1180 // as many builtins (sqrt, etc).
1181 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1182 if (OpI && OpI->hasOneUse()) {
1183 switch (OpI->getOpcode()) {
1184 default: break;
1185 case Instruction::FAdd:
1186 case Instruction::FSub:
1187 case Instruction::FMul:
1188 case Instruction::FDiv:
1189 case Instruction::FRem:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001190 Type *SrcTy = OpI->getType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001191 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1192 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
Craig Topperb57c2922013-01-24 05:22:40 +00001193 if (LHSTrunc->getType() != SrcTy &&
Chris Lattner80f43d32010-01-04 07:53:58 +00001194 RHSTrunc->getType() != SrcTy) {
1195 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1196 // If the source types were both smaller than the destination type of
1197 // the cast, do this xform.
1198 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1199 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1200 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1201 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1202 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1203 }
1204 }
Craig Topperb57c2922013-01-24 05:22:40 +00001205 break;
Chris Lattner80f43d32010-01-04 07:53:58 +00001206 }
Owen Andersone9d4eba2013-01-10 22:06:52 +00001207
1208 // (fptrunc (fneg x)) -> (fneg (fptrunc x))
1209 if (BinaryOperator::isFNeg(OpI)) {
1210 Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1),
1211 CI.getType());
1212 return BinaryOperator::CreateFNeg(InnerTrunc);
1213 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001214 }
Owen Andersone9d4eba2013-01-10 22:06:52 +00001215
1216 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0));
1217 if (II) {
1218 switch (II->getIntrinsicID()) {
1219 default: break;
1220 case Intrinsic::fabs: {
1221 // (fptrunc (fabs x)) -> (fabs (fptrunc x))
1222 Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0),
1223 CI.getType());
1224 Type *IntrinsicType[] = { CI.getType() };
1225 Function *Overload =
1226 Intrinsic::getDeclaration(CI.getParent()->getParent()->getParent(),
1227 II->getIntrinsicID(), IntrinsicType);
1228
1229 Value *Args[] = { InnerTrunc };
1230 return CallInst::Create(Overload, Args, II->getName());
1231 }
1232 }
1233 }
1234
Owen Andersond9029012010-07-19 08:09:34 +00001235 // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
Owen Andersond9029012010-07-19 08:09:34 +00001236 CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
Chad Rosier00737bd2011-12-01 21:29:16 +00001237 if (Call && Call->getCalledFunction() && TLI->has(LibFunc::sqrtf) &&
1238 Call->getCalledFunction()->getName() == TLI->getName(LibFunc::sqrt) &&
Evan Cheng93a635c2011-07-13 19:08:16 +00001239 Call->getNumArgOperands() == 1 &&
1240 Call->hasOneUse()) {
Owen Andersond9029012010-07-19 08:09:34 +00001241 CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
1242 if (Arg && Arg->getOpcode() == Instruction::FPExt &&
Owen Anderson5f23a932010-07-19 19:23:32 +00001243 CI.getType()->isFloatTy() &&
1244 Call->getType()->isDoubleTy() &&
1245 Arg->getType()->isDoubleTy() &&
1246 Arg->getOperand(0)->getType()->isFloatTy()) {
1247 Function *Callee = Call->getCalledFunction();
1248 Module *M = CI.getParent()->getParent()->getParent();
Craig Topperb57c2922013-01-24 05:22:40 +00001249 Constant *SqrtfFunc = M->getOrInsertFunction("sqrtf",
Owen Anderson5f23a932010-07-19 19:23:32 +00001250 Callee->getAttributes(),
Owen Andersond9029012010-07-19 08:09:34 +00001251 Builder->getFloatTy(),
1252 Builder->getFloatTy(),
1253 NULL);
1254 CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
1255 "sqrtfcall");
Owen Anderson5f23a932010-07-19 19:23:32 +00001256 ret->setAttributes(Callee->getAttributes());
Craig Topperb57c2922013-01-24 05:22:40 +00001257
1258
Chris Lattner979ed442010-09-07 20:01:38 +00001259 // Remove the old Call. With -fmath-errno, it won't get marked readnone.
Eli Friedman3e22cb92011-05-18 00:32:01 +00001260 ReplaceInstUsesWith(*Call, UndefValue::get(Call->getType()));
Chris Lattner979ed442010-09-07 20:01:38 +00001261 EraseInstFromFunction(*Call);
Owen Andersond9029012010-07-19 08:09:34 +00001262 return ret;
1263 }
1264 }
Craig Topperb57c2922013-01-24 05:22:40 +00001265
Chris Lattner80f43d32010-01-04 07:53:58 +00001266 return 0;
1267}
1268
1269Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1270 return commonCastTransforms(CI);
1271}
1272
1273Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1274 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1275 if (OpI == 0)
1276 return commonCastTransforms(FI);
1277
1278 // fptoui(uitofp(X)) --> X
1279 // fptoui(sitofp(X)) --> X
1280 // This is safe if the intermediate type has enough bits in its mantissa to
1281 // accurately represent all values of X. For example, do not do this with
1282 // i64->float->i64. This is also safe for sitofp case, because any negative
Craig Topperb57c2922013-01-24 05:22:40 +00001283 // 'X' value would cause an undefined result for the fptoui.
Chris Lattner80f43d32010-01-04 07:53:58 +00001284 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1285 OpI->getOperand(0)->getType() == FI.getType() &&
1286 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1287 OpI->getType()->getFPMantissaWidth())
1288 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1289
1290 return commonCastTransforms(FI);
1291}
1292
1293Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1294 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1295 if (OpI == 0)
1296 return commonCastTransforms(FI);
Craig Topperb57c2922013-01-24 05:22:40 +00001297
Chris Lattner80f43d32010-01-04 07:53:58 +00001298 // fptosi(sitofp(X)) --> X
1299 // fptosi(uitofp(X)) --> X
1300 // This is safe if the intermediate type has enough bits in its mantissa to
1301 // accurately represent all values of X. For example, do not do this with
1302 // i64->float->i64. This is also safe for sitofp case, because any negative
Craig Topperb57c2922013-01-24 05:22:40 +00001303 // 'X' value would cause an undefined result for the fptoui.
Chris Lattner80f43d32010-01-04 07:53:58 +00001304 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1305 OpI->getOperand(0)->getType() == FI.getType() &&
1306 (int)FI.getType()->getScalarSizeInBits() <=
1307 OpI->getType()->getFPMantissaWidth())
1308 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Craig Topperb57c2922013-01-24 05:22:40 +00001309
Chris Lattner80f43d32010-01-04 07:53:58 +00001310 return commonCastTransforms(FI);
1311}
1312
1313Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1314 return commonCastTransforms(CI);
1315}
1316
1317Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1318 return commonCastTransforms(CI);
1319}
1320
Chris Lattner80f43d32010-01-04 07:53:58 +00001321Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001322 // If the source integer type is not the intptr_t type for this target, do a
1323 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1324 // cast to be exposed to other transforms.
1325 if (TD) {
1326 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chandler Carruth426c2bf2012-11-01 09:14:31 +00001327 TD->getPointerSizeInBits()) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001328 Value *P = Builder->CreateTrunc(CI.getOperand(0),
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001329 TD->getIntPtrType(CI.getContext()));
Dan Gohman3b5487e2010-02-02 01:44:02 +00001330 return new IntToPtrInst(P, CI.getType());
1331 }
1332 if (CI.getOperand(0)->getType()->getScalarSizeInBits() <
Chandler Carruth426c2bf2012-11-01 09:14:31 +00001333 TD->getPointerSizeInBits()) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001334 Value *P = Builder->CreateZExt(CI.getOperand(0),
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001335 TD->getIntPtrType(CI.getContext()));
Dan Gohman3b5487e2010-02-02 01:44:02 +00001336 return new IntToPtrInst(P, CI.getType());
1337 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001338 }
Craig Topperb57c2922013-01-24 05:22:40 +00001339
Chris Lattner80f43d32010-01-04 07:53:58 +00001340 if (Instruction *I = commonCastTransforms(CI))
1341 return I;
1342
1343 return 0;
1344}
1345
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001346/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1347Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1348 Value *Src = CI.getOperand(0);
Craig Topperb57c2922013-01-24 05:22:40 +00001349
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001350 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1351 // If casting the result of a getelementptr instruction with no offset, turn
1352 // this into a cast of the original pointer!
1353 if (GEP->hasAllZeroIndices()) {
1354 // Changing the cast operand is usually not a good idea but it is safe
Craig Topperb57c2922013-01-24 05:22:40 +00001355 // here because the pointer operand is being replaced with another
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001356 // pointer operand so the opcode doesn't need to change.
1357 Worklist.Add(GEP);
1358 CI.setOperand(0, GEP->getOperand(0));
1359 return &CI;
1360 }
Craig Topperb57c2922013-01-24 05:22:40 +00001361
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001362 // If the GEP has a single use, and the base pointer is a bitcast, and the
1363 // GEP computes a constant offset, see if we can convert these three
1364 // instructions into fewer. This typically happens with unions and other
1365 // non-type-safe code.
Nuno Lopes98281a22012-12-30 16:25:48 +00001366 APInt Offset(TD ? TD->getPointerSizeInBits() : 1, 0);
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001367 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
Nuno Lopes98281a22012-12-30 16:25:48 +00001368 GEP->accumulateConstantOffset(*TD, Offset)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001369 // Get the base pointer input of the bitcast, and the type it points to.
1370 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001371 Type *GEPIdxTy =
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001372 cast<PointerType>(OrigBase->getType())->getElementType();
1373 SmallVector<Value*, 8> NewIndices;
Nuno Lopes98281a22012-12-30 16:25:48 +00001374 if (FindElementAtOffset(GEPIdxTy, Offset.getSExtValue(), NewIndices)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001375 // If we were able to index down into an element, create the GEP
1376 // and bitcast the result. This eliminates one bitcast, potentially
1377 // two.
1378 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +00001379 Builder->CreateInBoundsGEP(OrigBase, NewIndices) :
1380 Builder->CreateGEP(OrigBase, NewIndices);
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001381 NGEP->takeName(GEP);
Craig Topperb57c2922013-01-24 05:22:40 +00001382
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001383 if (isa<BitCastInst>(CI))
1384 return new BitCastInst(NGEP, CI.getType());
1385 assert(isa<PtrToIntInst>(CI));
1386 return new PtrToIntInst(NGEP, CI.getType());
Craig Topperb57c2922013-01-24 05:22:40 +00001387 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001388 }
1389 }
Craig Topperb57c2922013-01-24 05:22:40 +00001390
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001391 return commonCastTransforms(CI);
1392}
1393
1394Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001395 // If the destination integer type is not the intptr_t type for this target,
1396 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1397 // to be exposed to other transforms.
Benjamin Kramer1018fa22013-02-05 19:21:56 +00001398 if (TD && CI.getType()->getScalarSizeInBits() != TD->getPointerSizeInBits()) {
1399 Type *Ty = TD->getIntPtrType(CI.getContext());
1400 if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
1401 Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
1402
1403 Value *P = Builder->CreatePtrToInt(CI.getOperand(0), Ty);
1404 return CastInst::CreateIntegerCast(P, CI.getType(), /*isSigned=*/false);
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001405 }
Craig Topperb57c2922013-01-24 05:22:40 +00001406
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001407 return commonPointerCastTransforms(CI);
1408}
1409
Chris Lattner67451912010-05-08 21:50:26 +00001410/// OptimizeVectorResize - This input value (which is known to have vector type)
1411/// is being zero extended or truncated to the specified vector type. Try to
1412/// replace it with a shuffle (and vector/vector bitcast) if possible.
1413///
1414/// The source and destination vector types may have different element types.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001415static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
Chris Lattner67451912010-05-08 21:50:26 +00001416 InstCombiner &IC) {
1417 // We can only do this optimization if the output is a multiple of the input
1418 // element size, or the input is a multiple of the output element size.
1419 // Convert the input type to have the same element type as the output.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001420 VectorType *SrcTy = cast<VectorType>(InVal->getType());
Craig Topperb57c2922013-01-24 05:22:40 +00001421
Chris Lattner67451912010-05-08 21:50:26 +00001422 if (SrcTy->getElementType() != DestTy->getElementType()) {
1423 // The input types don't need to be identical, but for now they must be the
1424 // same size. There is no specific reason we couldn't handle things like
1425 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
Craig Topperb57c2922013-01-24 05:22:40 +00001426 // there yet.
Chris Lattner67451912010-05-08 21:50:26 +00001427 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1428 DestTy->getElementType()->getPrimitiveSizeInBits())
1429 return 0;
Craig Topperb57c2922013-01-24 05:22:40 +00001430
Chris Lattner67451912010-05-08 21:50:26 +00001431 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1432 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1433 }
Craig Topperb57c2922013-01-24 05:22:40 +00001434
Chris Lattner67451912010-05-08 21:50:26 +00001435 // Now that the element types match, get the shuffle mask and RHS of the
1436 // shuffle to use, which depends on whether we're increasing or decreasing the
1437 // size of the input.
Chris Lattner7302d802012-02-06 21:56:39 +00001438 SmallVector<uint32_t, 16> ShuffleMask;
Chris Lattner67451912010-05-08 21:50:26 +00001439 Value *V2;
Craig Topperb57c2922013-01-24 05:22:40 +00001440
Chris Lattner67451912010-05-08 21:50:26 +00001441 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1442 // If we're shrinking the number of elements, just shuffle in the low
1443 // elements from the input and use undef as the second shuffle input.
1444 V2 = UndefValue::get(SrcTy);
1445 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
Chris Lattner7302d802012-02-06 21:56:39 +00001446 ShuffleMask.push_back(i);
Craig Topperb57c2922013-01-24 05:22:40 +00001447
Chris Lattner67451912010-05-08 21:50:26 +00001448 } else {
1449 // If we're increasing the number of elements, shuffle in all of the
1450 // elements from InVal and fill the rest of the result elements with zeros
1451 // from a constant zero.
1452 V2 = Constant::getNullValue(SrcTy);
1453 unsigned SrcElts = SrcTy->getNumElements();
1454 for (unsigned i = 0, e = SrcElts; i != e; ++i)
Chris Lattner7302d802012-02-06 21:56:39 +00001455 ShuffleMask.push_back(i);
Chris Lattner67451912010-05-08 21:50:26 +00001456
1457 // The excess elements reference the first element of the zero input.
Chris Lattner7302d802012-02-06 21:56:39 +00001458 for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
1459 ShuffleMask.push_back(SrcElts);
Chris Lattner67451912010-05-08 21:50:26 +00001460 }
Craig Topperb57c2922013-01-24 05:22:40 +00001461
Chris Lattner7302d802012-02-06 21:56:39 +00001462 return new ShuffleVectorInst(InVal, V2,
1463 ConstantDataVector::get(V2->getContext(),
1464 ShuffleMask));
Chris Lattner67451912010-05-08 21:50:26 +00001465}
1466
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001467static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001468 return Value % Ty->getPrimitiveSizeInBits() == 0;
1469}
1470
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001471static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001472 return Value / Ty->getPrimitiveSizeInBits();
1473}
1474
1475/// CollectInsertionElements - V is a value which is inserted into a vector of
1476/// VecEltTy. Look through the value to see if we can decompose it into
1477/// insertions into the vector. See the example in the comment for
1478/// OptimizeIntegerToVectorInsertions for the pattern this handles.
1479/// The type of V is always a non-zero multiple of VecEltTy's size.
1480///
1481/// This returns false if the pattern can't be matched or true if it can,
1482/// filling in Elements with the elements found here.
1483static bool CollectInsertionElements(Value *V, unsigned ElementIndex,
1484 SmallVectorImpl<Value*> &Elements,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001485 Type *VecEltTy) {
Chris Lattner157d4ea2010-08-28 03:36:51 +00001486 // Undef values never contribute useful bits to the result.
1487 if (isa<UndefValue>(V)) return true;
Craig Topperb57c2922013-01-24 05:22:40 +00001488
Chris Lattner3dd08732010-08-28 01:20:38 +00001489 // If we got down to a value of the right type, we win, try inserting into the
1490 // right element.
1491 if (V->getType() == VecEltTy) {
Chris Lattner79007792010-08-28 01:50:57 +00001492 // Inserting null doesn't actually insert any elements.
1493 if (Constant *C = dyn_cast<Constant>(V))
1494 if (C->isNullValue())
1495 return true;
Craig Topperb57c2922013-01-24 05:22:40 +00001496
Chris Lattner3dd08732010-08-28 01:20:38 +00001497 // Fail if multiple elements are inserted into this slot.
1498 if (ElementIndex >= Elements.size() || Elements[ElementIndex] != 0)
1499 return false;
Craig Topperb57c2922013-01-24 05:22:40 +00001500
Chris Lattner3dd08732010-08-28 01:20:38 +00001501 Elements[ElementIndex] = V;
1502 return true;
1503 }
Craig Topperb57c2922013-01-24 05:22:40 +00001504
Chris Lattner79007792010-08-28 01:50:57 +00001505 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001506 // Figure out the # elements this provides, and bitcast it or slice it up
1507 // as required.
Chris Lattner79007792010-08-28 01:50:57 +00001508 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1509 VecEltTy);
1510 // If the constant is the size of a vector element, we just need to bitcast
1511 // it to the right type so it gets properly inserted.
1512 if (NumElts == 1)
1513 return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
1514 ElementIndex, Elements, VecEltTy);
Craig Topperb57c2922013-01-24 05:22:40 +00001515
Chris Lattner79007792010-08-28 01:50:57 +00001516 // Okay, this is a constant that covers multiple elements. Slice it up into
1517 // pieces and insert each element-sized piece into the vector.
1518 if (!isa<IntegerType>(C->getType()))
1519 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1520 C->getType()->getPrimitiveSizeInBits()));
1521 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001522 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
Craig Topperb57c2922013-01-24 05:22:40 +00001523
Chris Lattner79007792010-08-28 01:50:57 +00001524 for (unsigned i = 0; i != NumElts; ++i) {
1525 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
1526 i*ElementSize));
1527 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
1528 if (!CollectInsertionElements(Piece, ElementIndex+i, Elements, VecEltTy))
1529 return false;
1530 }
1531 return true;
1532 }
Craig Topperb57c2922013-01-24 05:22:40 +00001533
Chris Lattner3dd08732010-08-28 01:20:38 +00001534 if (!V->hasOneUse()) return false;
Craig Topperb57c2922013-01-24 05:22:40 +00001535
Chris Lattner3dd08732010-08-28 01:20:38 +00001536 Instruction *I = dyn_cast<Instruction>(V);
1537 if (I == 0) return false;
1538 switch (I->getOpcode()) {
1539 default: return false; // Unhandled case.
1540 case Instruction::BitCast:
1541 return CollectInsertionElements(I->getOperand(0), ElementIndex,
Craig Topperb57c2922013-01-24 05:22:40 +00001542 Elements, VecEltTy);
Chris Lattner3dd08732010-08-28 01:20:38 +00001543 case Instruction::ZExt:
1544 if (!isMultipleOfTypeSize(
1545 I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1546 VecEltTy))
1547 return false;
1548 return CollectInsertionElements(I->getOperand(0), ElementIndex,
Craig Topperb57c2922013-01-24 05:22:40 +00001549 Elements, VecEltTy);
Chris Lattner3dd08732010-08-28 01:20:38 +00001550 case Instruction::Or:
1551 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1552 Elements, VecEltTy) &&
1553 CollectInsertionElements(I->getOperand(1), ElementIndex,
1554 Elements, VecEltTy);
1555 case Instruction::Shl: {
1556 // Must be shifting by a constant that is a multiple of the element size.
1557 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1558 if (CI == 0) return false;
1559 if (!isMultipleOfTypeSize(CI->getZExtValue(), VecEltTy)) return false;
1560 unsigned IndexShift = getTypeSizeIndex(CI->getZExtValue(), VecEltTy);
Craig Topperb57c2922013-01-24 05:22:40 +00001561
Chris Lattner3dd08732010-08-28 01:20:38 +00001562 return CollectInsertionElements(I->getOperand(0), ElementIndex+IndexShift,
1563 Elements, VecEltTy);
1564 }
Craig Topperb57c2922013-01-24 05:22:40 +00001565
Chris Lattner3dd08732010-08-28 01:20:38 +00001566 }
1567}
1568
1569
1570/// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
1571/// may be doing shifts and ors to assemble the elements of the vector manually.
1572/// Try to rip the code out and replace it with insertelements. This is to
1573/// optimize code like this:
1574///
1575/// %tmp37 = bitcast float %inc to i32
1576/// %tmp38 = zext i32 %tmp37 to i64
1577/// %tmp31 = bitcast float %inc5 to i32
1578/// %tmp32 = zext i32 %tmp31 to i64
1579/// %tmp33 = shl i64 %tmp32, 32
1580/// %ins35 = or i64 %tmp33, %tmp38
1581/// %tmp43 = bitcast i64 %ins35 to <2 x float>
1582///
1583/// Into two insertelements that do "buildvector{%inc, %inc5}".
1584static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
1585 InstCombiner &IC) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001586 VectorType *DestVecTy = cast<VectorType>(CI.getType());
Chris Lattner3dd08732010-08-28 01:20:38 +00001587 Value *IntInput = CI.getOperand(0);
1588
1589 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1590 if (!CollectInsertionElements(IntInput, 0, Elements,
1591 DestVecTy->getElementType()))
1592 return 0;
1593
1594 // If we succeeded, we know that all of the element are specified by Elements
1595 // or are zero if Elements has a null entry. Recast this as a set of
1596 // insertions.
1597 Value *Result = Constant::getNullValue(CI.getType());
1598 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
1599 if (Elements[i] == 0) continue; // Unset element.
Craig Topperb57c2922013-01-24 05:22:40 +00001600
Chris Lattner3dd08732010-08-28 01:20:38 +00001601 Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1602 IC.Builder->getInt32(i));
1603 }
Craig Topperb57c2922013-01-24 05:22:40 +00001604
Chris Lattner3dd08732010-08-28 01:20:38 +00001605 return Result;
1606}
1607
1608
Chris Lattnere5a14262010-08-26 21:55:42 +00001609/// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1610/// bitcast. The various long double bitcasts can't get in here.
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001611static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
Chris Lattnere5a14262010-08-26 21:55:42 +00001612 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001613 Type *DestTy = CI.getType();
Chris Lattnere5a14262010-08-26 21:55:42 +00001614
1615 // If this is a bitcast from int to float, check to see if the int is an
1616 // extraction from a vector.
1617 Value *VecInput = 0;
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001618 // bitcast(trunc(bitcast(somevector)))
Chris Lattnere5a14262010-08-26 21:55:42 +00001619 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1620 isa<VectorType>(VecInput->getType())) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001621 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001622 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1623
1624 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1625 // If the element type of the vector doesn't match the result type,
1626 // bitcast it to be a vector type we can extract from.
1627 if (VecTy->getElementType() != DestTy) {
1628 VecTy = VectorType::get(DestTy,
1629 VecTy->getPrimitiveSizeInBits() / DestWidth);
1630 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1631 }
Craig Topperb57c2922013-01-24 05:22:40 +00001632
Chris Lattnere5a14262010-08-26 21:55:42 +00001633 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(0));
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001634 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001635 }
Craig Topperb57c2922013-01-24 05:22:40 +00001636
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001637 // bitcast(trunc(lshr(bitcast(somevector), cst))
1638 ConstantInt *ShAmt = 0;
1639 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1640 m_ConstantInt(ShAmt)))) &&
1641 isa<VectorType>(VecInput->getType())) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001642 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001643 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1644 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1645 ShAmt->getZExtValue() % DestWidth == 0) {
1646 // If the element type of the vector doesn't match the result type,
1647 // bitcast it to be a vector type we can extract from.
1648 if (VecTy->getElementType() != DestTy) {
1649 VecTy = VectorType::get(DestTy,
1650 VecTy->getPrimitiveSizeInBits() / DestWidth);
1651 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1652 }
Craig Topperb57c2922013-01-24 05:22:40 +00001653
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001654 unsigned Elt = ShAmt->getZExtValue() / DestWidth;
1655 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1656 }
1657 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001658 return 0;
1659}
Chris Lattner67451912010-05-08 21:50:26 +00001660
Chris Lattner80f43d32010-01-04 07:53:58 +00001661Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1662 // If the operands are integer typed then apply the integer transforms,
1663 // otherwise just apply the common ones.
1664 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001665 Type *SrcTy = Src->getType();
1666 Type *DestTy = CI.getType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001667
Chris Lattner80f43d32010-01-04 07:53:58 +00001668 // Get rid of casts from one type to the same type. These are useless and can
1669 // be replaced by the operand.
1670 if (DestTy == Src->getType())
1671 return ReplaceInstUsesWith(CI, Src);
1672
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001673 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1674 PointerType *SrcPTy = cast<PointerType>(SrcTy);
1675 Type *DstElTy = DstPTy->getElementType();
1676 Type *SrcElTy = SrcPTy->getElementType();
Craig Topperb57c2922013-01-24 05:22:40 +00001677
Chris Lattner80f43d32010-01-04 07:53:58 +00001678 // If the address spaces don't match, don't eliminate the bitcast, which is
1679 // required for changing types.
1680 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1681 return 0;
Craig Topperb57c2922013-01-24 05:22:40 +00001682
Chris Lattner80f43d32010-01-04 07:53:58 +00001683 // If we are casting a alloca to a pointer to a type of the same
1684 // size, rewrite the allocation instruction to allocate the "right" type.
1685 // There is no need to modify malloc calls because it is their bitcast that
1686 // needs to be cleaned up.
1687 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1688 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1689 return V;
Craig Topperb57c2922013-01-24 05:22:40 +00001690
Chris Lattner80f43d32010-01-04 07:53:58 +00001691 // If the source and destination are pointers, and this cast is equivalent
1692 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1693 // This can enhance SROA and other transforms that want type-safe pointers.
1694 Constant *ZeroUInt =
1695 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1696 unsigned NumZeros = 0;
Craig Topperb57c2922013-01-24 05:22:40 +00001697 while (SrcElTy != DstElTy &&
Duncan Sands1df98592010-02-16 11:11:14 +00001698 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
Chris Lattner80f43d32010-01-04 07:53:58 +00001699 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1700 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1701 ++NumZeros;
1702 }
1703
1704 // If we found a path from the src to dest, create the getelementptr now.
1705 if (SrcElTy == DstElTy) {
1706 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Jay Foada9203102011-07-25 09:48:08 +00001707 return GetElementPtrInst::CreateInBounds(Src, Idxs);
Chris Lattner80f43d32010-01-04 07:53:58 +00001708 }
1709 }
Craig Topperb57c2922013-01-24 05:22:40 +00001710
Chris Lattnere5a14262010-08-26 21:55:42 +00001711 // Try to optimize int -> float bitcasts.
1712 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1713 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1714 return I;
Chris Lattner80f43d32010-01-04 07:53:58 +00001715
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001716 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Duncan Sands1df98592010-02-16 11:11:14 +00001717 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001718 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1719 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner80f43d32010-01-04 07:53:58 +00001720 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner80f43d32010-01-04 07:53:58 +00001721 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1722 }
Craig Topperb57c2922013-01-24 05:22:40 +00001723
Chris Lattner3dd08732010-08-28 01:20:38 +00001724 if (isa<IntegerType>(SrcTy)) {
1725 // If this is a cast from an integer to vector, check to see if the input
1726 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1727 // the casts with a shuffle and (potentially) a bitcast.
1728 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1729 CastInst *SrcCast = cast<CastInst>(Src);
1730 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1731 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1732 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
Chris Lattner67451912010-05-08 21:50:26 +00001733 cast<VectorType>(DestTy), *this))
Chris Lattner3dd08732010-08-28 01:20:38 +00001734 return I;
1735 }
Craig Topperb57c2922013-01-24 05:22:40 +00001736
Chris Lattner3dd08732010-08-28 01:20:38 +00001737 // If the input is an 'or' instruction, we may be doing shifts and ors to
1738 // assemble the elements of the vector manually. Try to rip the code out
1739 // and replace it with insertelements.
1740 if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
1741 return ReplaceInstUsesWith(CI, V);
Chris Lattner67451912010-05-08 21:50:26 +00001742 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001743 }
1744
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001745 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Duncan Sands1df98592010-02-16 11:11:14 +00001746 if (SrcVTy->getNumElements() == 1 && !DestTy->isVectorTy()) {
Craig Topperb57c2922013-01-24 05:22:40 +00001747 Value *Elem =
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001748 Builder->CreateExtractElement(Src,
1749 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1750 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
Chris Lattner80f43d32010-01-04 07:53:58 +00001751 }
1752 }
1753
1754 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001755 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
Dan Gohmana5ced592010-04-07 23:22:42 +00001756 // a bitcast to a vector with the same # elts.
Craig Topperb57c2922013-01-24 05:22:40 +00001757 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001758 cast<VectorType>(DestTy)->getNumElements() ==
1759 SVI->getType()->getNumElements() &&
1760 SVI->getType()->getNumElements() ==
1761 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1762 BitCastInst *Tmp;
1763 // If either of the operands is a cast from CI.getType(), then
1764 // evaluating the shuffle in the casted destination's type will allow
1765 // us to eliminate at least one cast.
Craig Topperb57c2922013-01-24 05:22:40 +00001766 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001767 Tmp->getOperand(0)->getType() == DestTy) ||
Craig Topperb57c2922013-01-24 05:22:40 +00001768 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001769 Tmp->getOperand(0)->getType() == DestTy)) {
1770 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1771 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1772 // Return a new shuffle vector. Use the same element ID's, as we
1773 // know the vector types match #elts.
1774 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner80f43d32010-01-04 07:53:58 +00001775 }
1776 }
1777 }
Craig Topperb57c2922013-01-24 05:22:40 +00001778
Duncan Sands1df98592010-02-16 11:11:14 +00001779 if (SrcTy->isPointerTy())
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001780 return commonPointerCastTransforms(CI);
1781 return commonCastTransforms(CI);
Chris Lattner80f43d32010-01-04 07:53:58 +00001782}