blob: 01f49d2ca53540025dd93bd517d61d05650c5118 [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"
15#include "llvm/Target/TargetData.h"
16#include "llvm/Support/PatternMatch.h"
17using namespace llvm;
18using namespace PatternMatch;
19
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000020/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
21/// expression. If so, decompose it, returning some value X, such that Val is
22/// X*Scale+Offset.
23///
24static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
25 int &Offset) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +000026 assert(Val->getType()->isIntegerTy(32) && "Unexpected allocation size type!");
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000027 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
28 Offset = CI->getZExtValue();
29 Scale = 0;
30 return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000031 }
32
33 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000034 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
35 if (I->getOpcode() == Instruction::Shl) {
36 // This is a value scaled by '1 << the shift amt'.
37 Scale = 1U << RHS->getZExtValue();
38 Offset = 0;
39 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000040 }
41
42 if (I->getOpcode() == Instruction::Mul) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000043 // This value is scaled by 'RHS'.
44 Scale = RHS->getZExtValue();
45 Offset = 0;
46 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000047 }
48
49 if (I->getOpcode() == Instruction::Add) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000050 // We have X+C. Check to see if we really have (X*C2)+C1,
51 // where C1 is divisible by C2.
52 unsigned SubScale;
53 Value *SubVal =
54 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
55 Offset += RHS->getZExtValue();
56 Scale = SubScale;
57 return SubVal;
58 }
59 }
60 }
61
62 // Otherwise, we can't look past this.
63 Scale = 1;
64 Offset = 0;
65 return Val;
66}
67
68/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
69/// try to eliminate the cast by moving the type information into the alloc.
70Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
71 AllocaInst &AI) {
72 // This requires TargetData to get the alloca alignment and size information.
73 if (!TD) return 0;
74
75 const PointerType *PTy = cast<PointerType>(CI.getType());
76
77 BuilderTy AllocaBuilder(*Builder);
78 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
79
80 // Get the type really allocated and the type casted to.
81 const Type *AllocElTy = AI.getAllocatedType();
82 const Type *CastElTy = PTy->getElementType();
83 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
84
85 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
86 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
87 if (CastElTyAlign < AllocElTyAlign) return 0;
88
89 // If the allocation has multiple uses, only promote it if we are strictly
90 // increasing the alignment of the resultant allocation. If we keep it the
91 // same, we open the door to infinite loops of various kinds. (A reference
92 // from a dbg.declare doesn't count as a use for this purpose.)
93 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
94 CastElTyAlign == AllocElTyAlign) return 0;
95
96 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
97 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
98 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
99
100 // See if we can satisfy the modulus by pulling a scale out of the array
101 // size argument.
102 unsigned ArraySizeScale;
103 int ArrayOffset;
104 Value *NumElements = // See if the array size is a decomposable linear expr.
105 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
106
107 // If we can now satisfy the modulus, by using a non-1 scale, we really can
108 // do the xform.
109 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
110 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
111
112 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
113 Value *Amt = 0;
114 if (Scale == 1) {
115 Amt = NumElements;
116 } else {
117 Amt = ConstantInt::get(Type::getInt32Ty(CI.getContext()), Scale);
118 // Insert before the alloca, not before the cast.
119 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
120 }
121
122 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
123 Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
124 Offset, true);
125 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
126 }
127
128 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
129 New->setAlignment(AI.getAlignment());
130 New->takeName(&AI);
131
132 // If the allocation has one real use plus a dbg.declare, just remove the
133 // declare.
134 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
135 EraseInstFromFunction(*(Instruction*)DI);
136 }
137 // If the allocation has multiple real uses, insert a cast and change all
138 // things that used it to use the new cast. This will also hack on CI, but it
139 // will die soon.
140 else if (!AI.hasOneUse()) {
141 // New is the allocation instruction, pointer typed. AI is the original
142 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
143 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
144 AI.replaceAllUsesWith(NewCast);
145 }
146 return ReplaceInstUsesWith(CI, New);
147}
148
149
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000150
Chris Lattner5f0290e2010-01-04 07:54:59 +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.
Chris Lattner5f0290e2010-01-04 07:54:59 +0000154Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
155 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))
160 C = ConstantFoldConstantExpression(CE, TD);
161 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;
184 }
185 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);
193
194 // 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);
207 PHINode *NPN = PHINode::Create(Ty);
208 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 }
215 default:
216 // TODO: Can handle more cases here.
217 llvm_unreachable("Unreachable!");
218 break;
219 }
220
221 Res->takeName(I);
222 return InsertNewInstBefore(Res, *I);
223}
Chris Lattner80f43d32010-01-04 07:53:58 +0000224
225
226/// This function is a wrapper around CastInst::isEliminableCastPair. It
227/// simply extracts arguments and returns what that function returns.
228static Instruction::CastOps
229isEliminableCastPair(
230 const CastInst *CI, ///< The first cast instruction
231 unsigned opcode, ///< The opcode of the second cast instruction
232 const Type *DstTy, ///< The target type for the second cast instruction
233 TargetData *TD ///< The target data for pointer size
234) {
235
236 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
237 const Type *MidTy = CI->getType(); // B from above
238
239 // Get the opcodes of the two Cast instructions
240 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
241 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
242
243 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
244 DstTy,
245 TD ? TD->getIntPtrType(CI->getContext()) : 0);
246
247 // We don't want to form an inttoptr or ptrtoint that converts to an integer
248 // type that differs from the pointer size.
249 if ((Res == Instruction::IntToPtr &&
250 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
251 (Res == Instruction::PtrToInt &&
252 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
253 Res = 0;
254
255 return Instruction::CastOps(Res);
256}
257
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000258/// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
259/// results in any code being generated and is interesting to optimize out. If
260/// the cast can be eliminated by some other simple transformation, we prefer
261/// to do the simplification first.
262bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
263 const Type *Ty) {
264 // Noop casts and casts of constants should be eliminated trivially.
Chris Lattner80f43d32010-01-04 07:53:58 +0000265 if (V->getType() == Ty || isa<Constant>(V)) return false;
266
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000267 // If this is another cast that can be eliminated, we prefer to have it
268 // eliminated.
Chris Lattner80f43d32010-01-04 07:53:58 +0000269 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000270 if (isEliminableCastPair(CI, opc, Ty, TD))
Chris Lattner80f43d32010-01-04 07:53:58 +0000271 return false;
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000272
273 // If this is a vector sext from a compare, then we don't want to break the
274 // idiom where each element of the extended vector is either zero or all ones.
Duncan Sands1df98592010-02-16 11:11:14 +0000275 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000276 return false;
277
Chris Lattner80f43d32010-01-04 07:53:58 +0000278 return true;
279}
280
281
282/// @brief Implement the transforms common to all CastInst visitors.
283Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
284 Value *Src = CI.getOperand(0);
285
286 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
287 // eliminate it now.
288 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
289 if (Instruction::CastOps opc =
290 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
291 // The first cast (CSrc) is eliminable so we need to fix up or replace
292 // the second cast (CI). CSrc will then have a good chance of being dead.
293 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
294 }
295 }
296
297 // If we are casting a select then fold the cast into the select
298 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
299 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
300 return NV;
301
302 // If we are casting a PHI then fold the cast into the PHI
303 if (isa<PHINode>(Src)) {
304 // We don't do this if this would create a PHI node with an illegal type if
305 // it is currently legal.
Duncan Sands1df98592010-02-16 11:11:14 +0000306 if (!Src->getType()->isIntegerTy() ||
307 !CI.getType()->isIntegerTy() ||
Chris Lattner80f43d32010-01-04 07:53:58 +0000308 ShouldChangeType(CI.getType(), Src->getType()))
309 if (Instruction *NV = FoldOpIntoPhi(CI))
310 return NV;
311 }
312
313 return 0;
314}
315
Chris Lattner75215c92010-01-10 00:58:42 +0000316/// CanEvaluateTruncated - Return true if we can evaluate the specified
317/// expression tree as type Ty instead of its larger type, and arrive with the
318/// same value. This is used by code that tries to eliminate truncates.
319///
320/// Ty will always be a type smaller than V. We should return true if trunc(V)
321/// can be computed by computing V in the smaller type. If V is an instruction,
322/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
323/// makes sense if x and y can be efficiently truncated.
324///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000325/// This function works on both vectors and scalars.
326///
Chris Lattner75215c92010-01-10 00:58:42 +0000327static bool CanEvaluateTruncated(Value *V, const Type *Ty) {
328 // We can always evaluate constants in another type.
329 if (isa<Constant>(V))
330 return true;
Chris Lattner68c6e892010-01-05 23:00:30 +0000331
Chris Lattner75215c92010-01-10 00:58:42 +0000332 Instruction *I = dyn_cast<Instruction>(V);
333 if (!I) return false;
334
335 const Type *OrigTy = V->getType();
336
Chris Lattnera958cbf2010-01-11 22:45:25 +0000337 // If this is an extension from the dest type, we can eliminate it, even if it
338 // has multiple uses.
Chris Lattner53af2d12010-01-11 22:49:40 +0000339 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000340 I->getOperand(0)->getType() == Ty)
341 return true;
342
343 // We can't extend or shrink something that has multiple uses: doing so would
344 // require duplicating the instruction in general, which isn't profitable.
345 if (!I->hasOneUse()) return false;
346
347 unsigned Opc = I->getOpcode();
348 switch (Opc) {
349 case Instruction::Add:
350 case Instruction::Sub:
351 case Instruction::Mul:
352 case Instruction::And:
353 case Instruction::Or:
354 case Instruction::Xor:
355 // These operators can all arbitrarily be extended or truncated.
356 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
357 CanEvaluateTruncated(I->getOperand(1), Ty);
358
359 case Instruction::UDiv:
360 case Instruction::URem: {
361 // UDiv and URem can be truncated if all the truncated bits are zero.
362 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
363 uint32_t BitWidth = Ty->getScalarSizeInBits();
364 if (BitWidth < OrigBitWidth) {
365 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
366 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
367 MaskedValueIsZero(I->getOperand(1), Mask)) {
368 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
369 CanEvaluateTruncated(I->getOperand(1), Ty);
370 }
371 }
372 break;
373 }
374 case Instruction::Shl:
375 // If we are truncating the result of this SHL, and if it's a shift of a
376 // constant amount, we can always perform a SHL in a smaller type.
377 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
378 uint32_t BitWidth = Ty->getScalarSizeInBits();
379 if (CI->getLimitedValue(BitWidth) < BitWidth)
380 return CanEvaluateTruncated(I->getOperand(0), Ty);
381 }
382 break;
383 case Instruction::LShr:
384 // If this is a truncate of a logical shr, we can truncate it to a smaller
385 // lshr iff we know that the bits we would otherwise be shifting in are
386 // already zeros.
387 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
388 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
389 uint32_t BitWidth = Ty->getScalarSizeInBits();
390 if (MaskedValueIsZero(I->getOperand(0),
391 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
392 CI->getLimitedValue(BitWidth) < BitWidth) {
393 return CanEvaluateTruncated(I->getOperand(0), Ty);
394 }
395 }
396 break;
397 case Instruction::Trunc:
398 // trunc(trunc(x)) -> trunc(x)
399 return true;
400 case Instruction::Select: {
401 SelectInst *SI = cast<SelectInst>(I);
402 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
403 CanEvaluateTruncated(SI->getFalseValue(), Ty);
404 }
405 case Instruction::PHI: {
406 // We can change a phi if we can change all operands. Note that we never
407 // get into trouble with cyclic PHIs here because we only consider
408 // instructions with a single use.
409 PHINode *PN = cast<PHINode>(I);
410 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
411 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
412 return false;
413 return true;
414 }
415 default:
416 // TODO: Can handle more cases here.
417 break;
418 }
419
420 return false;
421}
422
423Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000424 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner75215c92010-01-10 00:58:42 +0000425 return Result;
426
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000427 // See if we can simplify any instructions used by the input whose sole
428 // purpose is to compute bits we don't care about.
429 if (SimplifyDemandedInstructionBits(CI))
430 return &CI;
431
Chris Lattner75215c92010-01-10 00:58:42 +0000432 Value *Src = CI.getOperand(0);
433 const Type *DestTy = CI.getType(), *SrcTy = Src->getType();
434
435 // Attempt to truncate the entire input expression tree to the destination
436 // type. Only do this if the dest type is a simple type, don't convert the
Chris Lattner80f43d32010-01-04 07:53:58 +0000437 // expression tree to something weird like i93 unless the source is also
438 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +0000439 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000440 CanEvaluateTruncated(Src, DestTy)) {
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000441
Chris Lattner80f43d32010-01-04 07:53:58 +0000442 // If this cast is a truncate, evaluting in a different type always
Chris Lattner68c6e892010-01-05 23:00:30 +0000443 // eliminates the cast, so it is always a win.
Chris Lattner075f6922010-01-07 23:41:00 +0000444 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
445 " to avoid cast: " << CI);
446 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
447 assert(Res->getType() == DestTy);
448 return ReplaceInstUsesWith(CI, Res);
449 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000450
Chris Lattner7a34d6c2010-01-05 22:21:18 +0000451 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
452 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000453 Constant *One = ConstantInt::get(Src->getType(), 1);
454 Src = Builder->CreateAnd(Src, One, "tmp");
455 Value *Zero = Constant::getNullValue(Src->getType());
456 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
457 }
458
Chris Lattner80f43d32010-01-04 07:53:58 +0000459 return 0;
460}
461
462/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
463/// in order to eliminate the icmp.
464Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
465 bool DoXform) {
466 // If we are just checking for a icmp eq of a single bit and zext'ing it
467 // to an integer, then shift the bit to the appropriate place and then
468 // cast to integer to avoid the comparison.
469 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
470 const APInt &Op1CV = Op1C->getValue();
471
472 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
473 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
474 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
475 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
476 if (!DoXform) return ICI;
477
478 Value *In = ICI->getOperand(0);
479 Value *Sh = ConstantInt::get(In->getType(),
480 In->getType()->getScalarSizeInBits()-1);
481 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
482 if (In->getType() != CI.getType())
483 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
484
485 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
486 Constant *One = ConstantInt::get(In->getType(), 1);
487 In = Builder->CreateXor(In, One, In->getName()+".not");
488 }
489
490 return ReplaceInstUsesWith(CI, In);
491 }
492
493
494
495 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
496 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
497 // zext (X == 1) to i32 --> X iff X has only the low bit set.
498 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
499 // zext (X != 0) to i32 --> X iff X has only the low bit set.
500 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
501 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
502 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
503 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
504 // This only works for EQ and NE
505 ICI->isEquality()) {
506 // If Op1C some other power of two, convert:
507 uint32_t BitWidth = Op1C->getType()->getBitWidth();
508 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
509 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
510 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
511
512 APInt KnownZeroMask(~KnownZero);
513 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
514 if (!DoXform) return ICI;
515
516 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
517 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
518 // (X&4) == 2 --> false
519 // (X&4) != 2 --> true
520 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
521 isNE);
522 Res = ConstantExpr::getZExt(Res, CI.getType());
523 return ReplaceInstUsesWith(CI, Res);
524 }
525
526 uint32_t ShiftAmt = KnownZeroMask.logBase2();
527 Value *In = ICI->getOperand(0);
528 if (ShiftAmt) {
529 // Perform a logical shr by shiftamt.
530 // Insert the shift to put the result in the low bit.
531 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
532 In->getName()+".lobit");
533 }
534
535 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
536 Constant *One = ConstantInt::get(In->getType(), 1);
537 In = Builder->CreateXor(In, One, "tmp");
538 }
539
540 if (CI.getType() == In->getType())
541 return ReplaceInstUsesWith(CI, In);
542 else
543 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
544 }
545 }
546 }
547
548 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
549 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
550 // may lead to additional simplifications.
551 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
552 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
553 uint32_t BitWidth = ITy->getBitWidth();
554 Value *LHS = ICI->getOperand(0);
555 Value *RHS = ICI->getOperand(1);
556
557 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
558 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
559 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
560 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
561 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
562
563 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
564 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
565 APInt UnknownBit = ~KnownBits;
566 if (UnknownBit.countPopulation() == 1) {
567 if (!DoXform) return ICI;
568
569 Value *Result = Builder->CreateXor(LHS, RHS);
570
571 // Mask off any bits that are set and won't be shifted away.
572 if (KnownOneLHS.uge(UnknownBit))
573 Result = Builder->CreateAnd(Result,
574 ConstantInt::get(ITy, UnknownBit));
575
576 // Shift the bit we're testing down to the lsb.
577 Result = Builder->CreateLShr(
578 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
579
580 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
581 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
582 Result->takeName(ICI);
583 return ReplaceInstUsesWith(CI, Result);
584 }
585 }
586 }
587 }
588
589 return 0;
590}
591
Chris Lattner75215c92010-01-10 00:58:42 +0000592/// CanEvaluateZExtd - Determine if the specified value can be computed in the
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000593/// specified wider type and produce the same low bits. If not, return false.
594///
Chris Lattner789162a2010-01-11 03:32:00 +0000595/// If this function returns true, it can also return a non-zero number of bits
596/// (in BitsToClear) which indicates that the value it computes is correct for
597/// the zero extend, but that the additional BitsToClear bits need to be zero'd
598/// out. For example, to promote something like:
599///
600/// %B = trunc i64 %A to i32
601/// %C = lshr i32 %B, 8
602/// %E = zext i32 %C to i64
603///
604/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
605/// set to 8 to indicate that the promoted value needs to have bits 24-31
606/// cleared in addition to bits 32-63. Since an 'and' will be generated to
607/// clear the top bits anyway, doing this has no extra cost.
608///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000609/// This function works on both vectors and scalars.
Chris Lattner789162a2010-01-11 03:32:00 +0000610static bool CanEvaluateZExtd(Value *V, const Type *Ty, unsigned &BitsToClear) {
611 BitsToClear = 0;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000612 if (isa<Constant>(V))
613 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000614
615 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner9e390dd2010-01-10 02:50:04 +0000616 if (!I) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000617
618 // If the input is a truncate from the destination type, we can trivially
Chris Lattnera958cbf2010-01-11 22:45:25 +0000619 // eliminate it, even if it has multiple uses.
620 // FIXME: This is currently disabled until codegen can handle this without
621 // pessimizing code, PR5997.
622 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattner9e390dd2010-01-10 02:50:04 +0000623 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000624
625 // We can't extend or shrink something that has multiple uses: doing so would
626 // require duplicating the instruction in general, which isn't profitable.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000627 if (!I->hasOneUse()) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000628
Chris Lattner789162a2010-01-11 03:32:00 +0000629 unsigned Opc = I->getOpcode(), Tmp;
Chris Lattner75215c92010-01-10 00:58:42 +0000630 switch (Opc) {
Chris Lattner9ee947c2010-01-10 20:25:54 +0000631 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
632 case Instruction::SExt: // zext(sext(x)) -> sext(x).
633 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
634 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000635 case Instruction::And:
Chris Lattner75215c92010-01-10 00:58:42 +0000636 case Instruction::Or:
637 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +0000638 case Instruction::Add:
639 case Instruction::Sub:
640 case Instruction::Mul:
Chris Lattnerd26c9e12010-01-10 02:22:12 +0000641 case Instruction::Shl:
Chris Lattner789162a2010-01-11 03:32:00 +0000642 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
643 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
644 return false;
645 // These can all be promoted if neither operand has 'bits to clear'.
646 if (BitsToClear == 0 && Tmp == 0)
647 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000648
Chris Lattner7acc4b12010-01-11 04:05:13 +0000649 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
650 // other side, BitsToClear is ok.
651 if (Tmp == 0 &&
652 (Opc == Instruction::And || Opc == Instruction::Or ||
653 Opc == Instruction::Xor)) {
654 // We use MaskedValueIsZero here for generality, but the case we care
655 // about the most is constant RHS.
656 unsigned VSize = V->getType()->getScalarSizeInBits();
657 if (MaskedValueIsZero(I->getOperand(1),
658 APInt::getHighBitsSet(VSize, BitsToClear)))
659 return true;
660 }
661
662 // Otherwise, we don't know how to analyze this BitsToClear case yet.
Chris Lattner789162a2010-01-11 03:32:00 +0000663 return false;
Chris Lattnerd26c9e12010-01-10 02:22:12 +0000664
Chris Lattner789162a2010-01-11 03:32:00 +0000665 case Instruction::LShr:
666 // We can promote lshr(x, cst) if we can promote x. This requires the
667 // ultimate 'and' to clear out the high zero bits we're clearing out though.
668 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
669 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
670 return false;
671 BitsToClear += Amt->getZExtValue();
672 if (BitsToClear > V->getType()->getScalarSizeInBits())
673 BitsToClear = V->getType()->getScalarSizeInBits();
674 return true;
675 }
676 // Cannot promote variable LSHR.
677 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000678 case Instruction::Select:
Chris Lattner789162a2010-01-11 03:32:00 +0000679 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
680 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000681 // TODO: If important, we could handle the case when the BitsToClear are
682 // known zero in the disagreeing side.
Chris Lattner789162a2010-01-11 03:32:00 +0000683 Tmp != BitsToClear)
684 return false;
685 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000686
687 case Instruction::PHI: {
688 // We can change a phi if we can change all operands. Note that we never
689 // get into trouble with cyclic PHIs here because we only consider
690 // instructions with a single use.
691 PHINode *PN = cast<PHINode>(I);
Chris Lattner789162a2010-01-11 03:32:00 +0000692 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
693 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000694 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner789162a2010-01-11 03:32:00 +0000695 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000696 // TODO: If important, we could handle the case when the BitsToClear
697 // are known zero in the disagreeing input.
Chris Lattner789162a2010-01-11 03:32:00 +0000698 Tmp != BitsToClear)
699 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000700 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000701 }
702 default:
703 // TODO: Can handle more cases here.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000704 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000705 }
706}
707
Chris Lattner80f43d32010-01-04 07:53:58 +0000708Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Chris Lattner5324d802010-01-10 02:39:31 +0000709 // If this zero extend is only used by a truncate, let the truncate by
710 // eliminated before we try to optimize this zext.
711 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
712 return 0;
713
Chris Lattner80f43d32010-01-04 07:53:58 +0000714 // If one of the common conversion will work, do it.
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000715 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +0000716 return Result;
717
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000718 // See if we can simplify any instructions used by the input whose sole
719 // purpose is to compute bits we don't care about.
720 if (SimplifyDemandedInstructionBits(CI))
721 return &CI;
Chris Lattner75215c92010-01-10 00:58:42 +0000722
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000723 Value *Src = CI.getOperand(0);
Chris Lattner75215c92010-01-10 00:58:42 +0000724 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
725
726 // Attempt to extend the entire input expression tree to the destination
727 // type. Only do this if the dest type is a simple type, don't convert the
728 // expression tree to something weird like i93 unless the source is also
729 // strange.
Chris Lattner789162a2010-01-11 03:32:00 +0000730 unsigned BitsToClear;
Duncan Sands1df98592010-02-16 11:11:14 +0000731 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner789162a2010-01-11 03:32:00 +0000732 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
733 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
734 "Unreasonable BitsToClear");
735
Chris Lattner5324d802010-01-10 02:39:31 +0000736 // Okay, we can transform this! Insert the new expression now.
737 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
738 " to avoid zero extend: " << CI);
739 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
740 assert(Res->getType() == DestTy);
741
Chris Lattner789162a2010-01-11 03:32:00 +0000742 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
743 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
744
Chris Lattner5324d802010-01-10 02:39:31 +0000745 // If the high bits are already filled with zeros, just replace this
746 // cast with the result.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000747 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
Chris Lattner789162a2010-01-11 03:32:00 +0000748 DestBitSize-SrcBitsKept)))
Chris Lattner5324d802010-01-10 02:39:31 +0000749 return ReplaceInstUsesWith(CI, Res);
750
751 // We need to emit an AND to clear the high bits.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000752 Constant *C = ConstantInt::get(Res->getType(),
Chris Lattner789162a2010-01-11 03:32:00 +0000753 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
Chris Lattner5324d802010-01-10 02:39:31 +0000754 return BinaryOperator::CreateAnd(Res, C);
Chris Lattner75215c92010-01-10 00:58:42 +0000755 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000756
757 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
758 // types and if the sizes are just right we can convert this into a logical
759 // 'and' which will be much cheaper than the pair of casts.
760 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000761 // TODO: Subsume this into EvaluateInDifferentType.
762
Chris Lattner80f43d32010-01-04 07:53:58 +0000763 // Get the sizes of the types involved. We know that the intermediate type
764 // will be smaller than A or C, but don't know the relation between A and C.
765 Value *A = CSrc->getOperand(0);
766 unsigned SrcSize = A->getType()->getScalarSizeInBits();
767 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
768 unsigned DstSize = CI.getType()->getScalarSizeInBits();
769 // If we're actually extending zero bits, then if
770 // SrcSize < DstSize: zext(a & mask)
771 // SrcSize == DstSize: a & mask
772 // SrcSize > DstSize: trunc(a) & mask
773 if (SrcSize < DstSize) {
774 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
775 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
776 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
777 return new ZExtInst(And, CI.getType());
778 }
779
780 if (SrcSize == DstSize) {
781 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
782 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
783 AndValue));
784 }
785 if (SrcSize > DstSize) {
786 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
787 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
788 return BinaryOperator::CreateAnd(Trunc,
789 ConstantInt::get(Trunc->getType(),
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000790 AndValue));
Chris Lattner80f43d32010-01-04 07:53:58 +0000791 }
792 }
793
794 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
795 return transformZExtICmp(ICI, CI);
796
797 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
798 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
799 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
800 // of the (zext icmp) will be transformed.
801 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
802 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
803 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
804 (transformZExtICmp(LHS, CI, false) ||
805 transformZExtICmp(RHS, CI, false))) {
806 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
807 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
808 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
809 }
810 }
811
812 // zext(trunc(t) & C) -> (t & zext(C)).
813 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
814 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
815 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
816 Value *TI0 = TI->getOperand(0);
817 if (TI0->getType() == CI.getType())
818 return
819 BinaryOperator::CreateAnd(TI0,
820 ConstantExpr::getZExt(C, CI.getType()));
821 }
822
823 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
824 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
825 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
826 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
827 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
828 And->getOperand(1) == C)
829 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
830 Value *TI0 = TI->getOperand(0);
831 if (TI0->getType() == CI.getType()) {
832 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
833 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
834 return BinaryOperator::CreateXor(NewAnd, ZC);
835 }
836 }
837
Chris Lattner718bf3f2010-01-05 21:04:47 +0000838 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
839 Value *X;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000840 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isIntegerTy(1) &&
Chris Lattner49bdfef2010-01-05 21:11:17 +0000841 match(SrcI, m_Not(m_Value(X))) &&
Chris Lattner718bf3f2010-01-05 21:04:47 +0000842 (!X->hasOneUse() || !isa<CmpInst>(X))) {
843 Value *New = Builder->CreateZExt(X, CI.getType());
844 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
845 }
846
Chris Lattner80f43d32010-01-04 07:53:58 +0000847 return 0;
848}
849
Chris Lattner75215c92010-01-10 00:58:42 +0000850/// CanEvaluateSExtd - Return true if we can take the specified value
851/// and return it as type Ty without inserting any new casts and without
852/// changing the value of the common low bits. This is used by code that tries
853/// to promote integer operations to a wider types will allow us to eliminate
854/// the extension.
855///
Chris Lattneraa9c8942010-01-10 07:57:20 +0000856/// This function works on both vectors and scalars.
Chris Lattner75215c92010-01-10 00:58:42 +0000857///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000858static bool CanEvaluateSExtd(Value *V, const Type *Ty) {
Chris Lattner75215c92010-01-10 00:58:42 +0000859 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
860 "Can't sign extend type to a smaller type");
Chris Lattneraa9c8942010-01-10 07:57:20 +0000861 // If this is a constant, it can be trivially promoted.
862 if (isa<Constant>(V))
863 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000864
865 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattneraa9c8942010-01-10 07:57:20 +0000866 if (!I) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000867
Chris Lattnera958cbf2010-01-11 22:45:25 +0000868 // If this is a truncate from the dest type, we can trivially eliminate it,
869 // even if it has multiple uses.
870 // FIXME: This is currently disabled until codegen can handle this without
871 // pessimizing code, PR5997.
872 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattneraa9c8942010-01-10 07:57:20 +0000873 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000874
875 // We can't extend or shrink something that has multiple uses: doing so would
876 // require duplicating the instruction in general, which isn't profitable.
Chris Lattneraa9c8942010-01-10 07:57:20 +0000877 if (!I->hasOneUse()) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000878
Chris Lattneraa9c8942010-01-10 07:57:20 +0000879 switch (I->getOpcode()) {
Chris Lattner11ea8122010-01-10 20:30:41 +0000880 case Instruction::SExt: // sext(sext(x)) -> sext(x)
881 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
882 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
883 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000884 case Instruction::And:
885 case Instruction::Or:
886 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +0000887 case Instruction::Add:
888 case Instruction::Sub:
Chris Lattner75215c92010-01-10 00:58:42 +0000889 case Instruction::Mul:
Chris Lattneraa9c8942010-01-10 07:57:20 +0000890 // These operators can all arbitrarily be extended if their inputs can.
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000891 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
892 CanEvaluateSExtd(I->getOperand(1), Ty);
Chris Lattner75215c92010-01-10 00:58:42 +0000893
894 //case Instruction::Shl: TODO
895 //case Instruction::LShr: TODO
Chris Lattner75215c92010-01-10 00:58:42 +0000896
Chris Lattneraa9c8942010-01-10 07:57:20 +0000897 case Instruction::Select:
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000898 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
899 CanEvaluateSExtd(I->getOperand(2), Ty);
Chris Lattner9ee947c2010-01-10 20:25:54 +0000900
Chris Lattner75215c92010-01-10 00:58:42 +0000901 case Instruction::PHI: {
902 // We can change a phi if we can change all operands. Note that we never
903 // get into trouble with cyclic PHIs here because we only consider
904 // instructions with a single use.
905 PHINode *PN = cast<PHINode>(I);
Chris Lattner9ee947c2010-01-10 20:25:54 +0000906 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000907 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
Chris Lattneraa9c8942010-01-10 07:57:20 +0000908 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000909 }
910 default:
911 // TODO: Can handle more cases here.
912 break;
913 }
914
Chris Lattneraa9c8942010-01-10 07:57:20 +0000915 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000916}
917
Chris Lattner80f43d32010-01-04 07:53:58 +0000918Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattner5324d802010-01-10 02:39:31 +0000919 // If this sign extend is only used by a truncate, let the truncate by
920 // eliminated before we try to optimize this zext.
921 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
922 return 0;
923
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000924 if (Instruction *I = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +0000925 return I;
926
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000927 // See if we can simplify any instructions used by the input whose sole
928 // purpose is to compute bits we don't care about.
929 if (SimplifyDemandedInstructionBits(CI))
930 return &CI;
931
Chris Lattner80f43d32010-01-04 07:53:58 +0000932 Value *Src = CI.getOperand(0);
Chris Lattner75215c92010-01-10 00:58:42 +0000933 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
934
Chris Lattner75215c92010-01-10 00:58:42 +0000935 // Attempt to extend the entire input expression tree to the destination
936 // type. Only do this if the dest type is a simple type, don't convert the
937 // expression tree to something weird like i93 unless the source is also
938 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +0000939 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000940 CanEvaluateSExtd(Src, DestTy)) {
Chris Lattnerdde5ee52010-01-10 07:40:50 +0000941 // Okay, we can transform this! Insert the new expression now.
942 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
943 " to avoid sign extend: " << CI);
944 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
945 assert(Res->getType() == DestTy);
946
Chris Lattner75215c92010-01-10 00:58:42 +0000947 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
948 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Chris Lattnerdde5ee52010-01-10 07:40:50 +0000949
950 // If the high bits are already filled with sign bit, just replace this
951 // cast with the result.
Chris Lattneraa9c8942010-01-10 07:57:20 +0000952 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
Chris Lattnerdde5ee52010-01-10 07:40:50 +0000953 return ReplaceInstUsesWith(CI, Res);
Chris Lattner75215c92010-01-10 00:58:42 +0000954
Chris Lattnerdde5ee52010-01-10 07:40:50 +0000955 // We need to emit a shl + ashr to do the sign extend.
956 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
957 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
958 ShAmt);
Chris Lattner75215c92010-01-10 00:58:42 +0000959 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000960
Chris Lattnercd5adbb2010-01-18 22:19:16 +0000961 // If this input is a trunc from our destination, then turn sext(trunc(x))
962 // into shifts.
963 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
964 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
965 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
966 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
967
968 // We need to emit a shl + ashr to do the sign extend.
969 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
970 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
971 return BinaryOperator::CreateAShr(Res, ShAmt);
972 }
973
Chris Lattnerabb992d2010-01-24 00:09:49 +0000974
975 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
976 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
977 {
978 ICmpInst::Predicate Pred; Value *CmpLHS; ConstantInt *CmpRHS;
979 if (match(Src, m_ICmp(Pred, m_Value(CmpLHS), m_ConstantInt(CmpRHS)))) {
980 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
981 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
982 if ((Pred == ICmpInst::ICMP_SLT && CmpRHS->isZero()) ||
983 (Pred == ICmpInst::ICMP_SGT && CmpRHS->isAllOnesValue())) {
984 Value *Sh = ConstantInt::get(CmpLHS->getType(),
985 CmpLHS->getType()->getScalarSizeInBits()-1);
986 Value *In = Builder->CreateAShr(CmpLHS, Sh, CmpLHS->getName()+".lobit");
987 if (In->getType() != CI.getType())
988 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/, "tmp");
989
990 if (Pred == ICmpInst::ICMP_SGT)
991 In = Builder->CreateNot(In, In->getName()+".not");
992 return ReplaceInstUsesWith(CI, In);
993 }
994 }
995 }
996
997
Chris Lattner80f43d32010-01-04 07:53:58 +0000998 // If the input is a shl/ashr pair of a same constant, then this is a sign
999 // extension from a smaller value. If we could trust arbitrary bitwidth
1000 // integers, we could turn this into a truncate to the smaller bit and then
1001 // use a sext for the whole extension. Since we don't, look deeper and check
1002 // for a truncate. If the source and dest are the same type, eliminate the
1003 // trunc and extend and just do shifts. For example, turn:
1004 // %a = trunc i32 %i to i8
1005 // %b = shl i8 %a, 6
1006 // %c = ashr i8 %b, 6
1007 // %d = sext i8 %c to i32
1008 // into:
1009 // %a = shl i32 %i, 30
1010 // %d = ashr i32 %a, 30
1011 Value *A = 0;
Chris Lattner4f379782010-01-10 01:04:31 +00001012 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
Chris Lattner80f43d32010-01-04 07:53:58 +00001013 ConstantInt *BA = 0, *CA = 0;
Chris Lattner4f379782010-01-10 01:04:31 +00001014 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
Chris Lattner80f43d32010-01-04 07:53:58 +00001015 m_ConstantInt(CA))) &&
Chris Lattner4f379782010-01-10 01:04:31 +00001016 BA == CA && A->getType() == CI.getType()) {
1017 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1018 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1019 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1020 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1021 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1022 return BinaryOperator::CreateAShr(A, ShAmtV);
Chris Lattner80f43d32010-01-04 07:53:58 +00001023 }
1024
1025 return 0;
1026}
1027
1028
1029/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1030/// in the specified FP type without changing its value.
1031static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1032 bool losesInfo;
1033 APFloat F = CFP->getValueAPF();
1034 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1035 if (!losesInfo)
1036 return ConstantFP::get(CFP->getContext(), F);
1037 return 0;
1038}
1039
1040/// LookThroughFPExtensions - If this is an fp extension instruction, look
1041/// through it until we get the source value.
1042static Value *LookThroughFPExtensions(Value *V) {
1043 if (Instruction *I = dyn_cast<Instruction>(V))
1044 if (I->getOpcode() == Instruction::FPExt)
1045 return LookThroughFPExtensions(I->getOperand(0));
1046
1047 // If this value is a constant, return the constant in the smallest FP type
1048 // that can accurately represent it. This allows us to turn
1049 // (float)((double)X+2.0) into x+2.0f.
1050 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1051 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1052 return V; // No constant folding of this.
1053 // See if the value can be truncated to float and then reextended.
1054 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1055 return V;
Benjamin Kramerf0127052010-01-05 13:12:22 +00001056 if (CFP->getType()->isDoubleTy())
Chris Lattner80f43d32010-01-04 07:53:58 +00001057 return V; // Won't shrink.
1058 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1059 return V;
1060 // Don't try to shrink to various long double types.
1061 }
1062
1063 return V;
1064}
1065
1066Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1067 if (Instruction *I = commonCastTransforms(CI))
1068 return I;
1069
1070 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1071 // smaller than the destination type, we can eliminate the truncate by doing
1072 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1073 // as many builtins (sqrt, etc).
1074 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1075 if (OpI && OpI->hasOneUse()) {
1076 switch (OpI->getOpcode()) {
1077 default: break;
1078 case Instruction::FAdd:
1079 case Instruction::FSub:
1080 case Instruction::FMul:
1081 case Instruction::FDiv:
1082 case Instruction::FRem:
1083 const Type *SrcTy = OpI->getType();
1084 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1085 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1086 if (LHSTrunc->getType() != SrcTy &&
1087 RHSTrunc->getType() != SrcTy) {
1088 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1089 // If the source types were both smaller than the destination type of
1090 // the cast, do this xform.
1091 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1092 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1093 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1094 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1095 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1096 }
1097 }
1098 break;
1099 }
1100 }
1101 return 0;
1102}
1103
1104Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1105 return commonCastTransforms(CI);
1106}
1107
1108Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1109 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1110 if (OpI == 0)
1111 return commonCastTransforms(FI);
1112
1113 // fptoui(uitofp(X)) --> X
1114 // fptoui(sitofp(X)) --> X
1115 // This is safe if the intermediate type has enough bits in its mantissa to
1116 // accurately represent all values of X. For example, do not do this with
1117 // i64->float->i64. This is also safe for sitofp case, because any negative
1118 // 'X' value would cause an undefined result for the fptoui.
1119 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1120 OpI->getOperand(0)->getType() == FI.getType() &&
1121 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1122 OpI->getType()->getFPMantissaWidth())
1123 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1124
1125 return commonCastTransforms(FI);
1126}
1127
1128Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1129 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1130 if (OpI == 0)
1131 return commonCastTransforms(FI);
1132
1133 // fptosi(sitofp(X)) --> X
1134 // fptosi(uitofp(X)) --> X
1135 // This is safe if the intermediate type has enough bits in its mantissa to
1136 // accurately represent all values of X. For example, do not do this with
1137 // i64->float->i64. This is also safe for sitofp case, because any negative
1138 // 'X' value would cause an undefined result for the fptoui.
1139 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1140 OpI->getOperand(0)->getType() == FI.getType() &&
1141 (int)FI.getType()->getScalarSizeInBits() <=
1142 OpI->getType()->getFPMantissaWidth())
1143 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1144
1145 return commonCastTransforms(FI);
1146}
1147
1148Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1149 return commonCastTransforms(CI);
1150}
1151
1152Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1153 return commonCastTransforms(CI);
1154}
1155
Chris Lattner80f43d32010-01-04 07:53:58 +00001156Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001157 // If the source integer type is not the intptr_t type for this target, do a
1158 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1159 // cast to be exposed to other transforms.
1160 if (TD) {
1161 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
1162 TD->getPointerSizeInBits()) {
1163 Value *P = Builder->CreateTrunc(CI.getOperand(0),
1164 TD->getIntPtrType(CI.getContext()), "tmp");
1165 return new IntToPtrInst(P, CI.getType());
1166 }
1167 if (CI.getOperand(0)->getType()->getScalarSizeInBits() <
1168 TD->getPointerSizeInBits()) {
1169 Value *P = Builder->CreateZExt(CI.getOperand(0),
1170 TD->getIntPtrType(CI.getContext()), "tmp");
1171 return new IntToPtrInst(P, CI.getType());
1172 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001173 }
1174
1175 if (Instruction *I = commonCastTransforms(CI))
1176 return I;
1177
1178 return 0;
1179}
1180
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001181/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1182Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1183 Value *Src = CI.getOperand(0);
1184
1185 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1186 // If casting the result of a getelementptr instruction with no offset, turn
1187 // this into a cast of the original pointer!
1188 if (GEP->hasAllZeroIndices()) {
1189 // Changing the cast operand is usually not a good idea but it is safe
1190 // here because the pointer operand is being replaced with another
1191 // pointer operand so the opcode doesn't need to change.
1192 Worklist.Add(GEP);
1193 CI.setOperand(0, GEP->getOperand(0));
1194 return &CI;
1195 }
1196
1197 // If the GEP has a single use, and the base pointer is a bitcast, and the
1198 // GEP computes a constant offset, see if we can convert these three
1199 // instructions into fewer. This typically happens with unions and other
1200 // non-type-safe code.
1201 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1202 GEP->hasAllConstantIndices()) {
1203 // We are guaranteed to get a constant from EmitGEPOffset.
1204 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1205 int64_t Offset = OffsetV->getSExtValue();
1206
1207 // Get the base pointer input of the bitcast, and the type it points to.
1208 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1209 const Type *GEPIdxTy =
1210 cast<PointerType>(OrigBase->getType())->getElementType();
1211 SmallVector<Value*, 8> NewIndices;
1212 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1213 // If we were able to index down into an element, create the GEP
1214 // and bitcast the result. This eliminates one bitcast, potentially
1215 // two.
1216 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1217 Builder->CreateInBoundsGEP(OrigBase,
1218 NewIndices.begin(), NewIndices.end()) :
1219 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1220 NGEP->takeName(GEP);
1221
1222 if (isa<BitCastInst>(CI))
1223 return new BitCastInst(NGEP, CI.getType());
1224 assert(isa<PtrToIntInst>(CI));
1225 return new PtrToIntInst(NGEP, CI.getType());
1226 }
1227 }
1228 }
1229
1230 return commonCastTransforms(CI);
1231}
1232
1233Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001234 // If the destination integer type is not the intptr_t type for this target,
1235 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1236 // to be exposed to other transforms.
1237 if (TD) {
1238 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1239 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1240 TD->getIntPtrType(CI.getContext()),
1241 "tmp");
1242 return new TruncInst(P, CI.getType());
1243 }
1244 if (CI.getType()->getScalarSizeInBits() > TD->getPointerSizeInBits()) {
1245 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1246 TD->getIntPtrType(CI.getContext()),
1247 "tmp");
1248 return new ZExtInst(P, CI.getType());
1249 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001250 }
1251
1252 return commonPointerCastTransforms(CI);
1253}
1254
Chris Lattner67451912010-05-08 21:50:26 +00001255/// OptimizeVectorResize - This input value (which is known to have vector type)
1256/// is being zero extended or truncated to the specified vector type. Try to
1257/// replace it with a shuffle (and vector/vector bitcast) if possible.
1258///
1259/// The source and destination vector types may have different element types.
1260static Instruction *OptimizeVectorResize(Value *InVal, const VectorType *DestTy,
1261 InstCombiner &IC) {
1262 // We can only do this optimization if the output is a multiple of the input
1263 // element size, or the input is a multiple of the output element size.
1264 // Convert the input type to have the same element type as the output.
1265 const VectorType *SrcTy = cast<VectorType>(InVal->getType());
1266
1267 if (SrcTy->getElementType() != DestTy->getElementType()) {
1268 // The input types don't need to be identical, but for now they must be the
1269 // same size. There is no specific reason we couldn't handle things like
1270 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1271 // there yet.
1272 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1273 DestTy->getElementType()->getPrimitiveSizeInBits())
1274 return 0;
1275
1276 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1277 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1278 }
1279
1280 // Now that the element types match, get the shuffle mask and RHS of the
1281 // shuffle to use, which depends on whether we're increasing or decreasing the
1282 // size of the input.
1283 SmallVector<Constant*, 16> ShuffleMask;
1284 Value *V2;
1285 const IntegerType *Int32Ty = Type::getInt32Ty(SrcTy->getContext());
1286
1287 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1288 // If we're shrinking the number of elements, just shuffle in the low
1289 // elements from the input and use undef as the second shuffle input.
1290 V2 = UndefValue::get(SrcTy);
1291 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
1292 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1293
1294 } else {
1295 // If we're increasing the number of elements, shuffle in all of the
1296 // elements from InVal and fill the rest of the result elements with zeros
1297 // from a constant zero.
1298 V2 = Constant::getNullValue(SrcTy);
1299 unsigned SrcElts = SrcTy->getNumElements();
1300 for (unsigned i = 0, e = SrcElts; i != e; ++i)
1301 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1302
1303 // The excess elements reference the first element of the zero input.
1304 ShuffleMask.append(DestTy->getNumElements()-SrcElts,
1305 ConstantInt::get(Int32Ty, SrcElts));
1306 }
1307
1308 Constant *Mask = ConstantVector::get(ShuffleMask.data(), ShuffleMask.size());
1309 return new ShuffleVectorInst(InVal, V2, Mask);
1310}
1311
1312
Chris Lattner80f43d32010-01-04 07:53:58 +00001313Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1314 // If the operands are integer typed then apply the integer transforms,
1315 // otherwise just apply the common ones.
1316 Value *Src = CI.getOperand(0);
1317 const Type *SrcTy = Src->getType();
1318 const Type *DestTy = CI.getType();
1319
Chris Lattner80f43d32010-01-04 07:53:58 +00001320 // Get rid of casts from one type to the same type. These are useless and can
1321 // be replaced by the operand.
1322 if (DestTy == Src->getType())
1323 return ReplaceInstUsesWith(CI, Src);
1324
1325 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1326 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1327 const Type *DstElTy = DstPTy->getElementType();
1328 const Type *SrcElTy = SrcPTy->getElementType();
1329
1330 // If the address spaces don't match, don't eliminate the bitcast, which is
1331 // required for changing types.
1332 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1333 return 0;
1334
1335 // If we are casting a alloca to a pointer to a type of the same
1336 // size, rewrite the allocation instruction to allocate the "right" type.
1337 // There is no need to modify malloc calls because it is their bitcast that
1338 // needs to be cleaned up.
1339 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1340 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1341 return V;
1342
1343 // If the source and destination are pointers, and this cast is equivalent
1344 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1345 // This can enhance SROA and other transforms that want type-safe pointers.
1346 Constant *ZeroUInt =
1347 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1348 unsigned NumZeros = 0;
1349 while (SrcElTy != DstElTy &&
Duncan Sands1df98592010-02-16 11:11:14 +00001350 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
Chris Lattner80f43d32010-01-04 07:53:58 +00001351 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1352 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1353 ++NumZeros;
1354 }
1355
1356 // If we found a path from the src to dest, create the getelementptr now.
1357 if (SrcElTy == DstElTy) {
1358 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1359 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001360 ((Instruction*)NULL));
Chris Lattner80f43d32010-01-04 07:53:58 +00001361 }
1362 }
1363
1364 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Duncan Sands1df98592010-02-16 11:11:14 +00001365 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001366 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1367 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner80f43d32010-01-04 07:53:58 +00001368 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner80f43d32010-01-04 07:53:58 +00001369 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1370 }
Chris Lattner67451912010-05-08 21:50:26 +00001371
1372 // If this is a cast from an integer to vector, check to see if the input
1373 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1374 // the casts with a shuffle and (potentially) a bitcast.
1375 if (isa<IntegerType>(SrcTy) && (isa<TruncInst>(Src) || isa<ZExtInst>(Src))){
1376 CastInst *SrcCast = cast<CastInst>(Src);
1377 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1378 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1379 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
1380 cast<VectorType>(DestTy), *this))
1381 return I;
1382 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001383 }
1384
1385 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Duncan Sands1df98592010-02-16 11:11:14 +00001386 if (SrcVTy->getNumElements() == 1 && !DestTy->isVectorTy()) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001387 Value *Elem =
1388 Builder->CreateExtractElement(Src,
1389 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1390 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
Chris Lattner80f43d32010-01-04 07:53:58 +00001391 }
1392 }
1393
1394 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001395 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
Dan Gohmana5ced592010-04-07 23:22:42 +00001396 // a bitcast to a vector with the same # elts.
Duncan Sands1df98592010-02-16 11:11:14 +00001397 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001398 cast<VectorType>(DestTy)->getNumElements() ==
1399 SVI->getType()->getNumElements() &&
1400 SVI->getType()->getNumElements() ==
1401 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1402 BitCastInst *Tmp;
1403 // If either of the operands is a cast from CI.getType(), then
1404 // evaluating the shuffle in the casted destination's type will allow
1405 // us to eliminate at least one cast.
1406 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1407 Tmp->getOperand(0)->getType() == DestTy) ||
1408 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1409 Tmp->getOperand(0)->getType() == DestTy)) {
1410 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1411 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1412 // Return a new shuffle vector. Use the same element ID's, as we
1413 // know the vector types match #elts.
1414 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner80f43d32010-01-04 07:53:58 +00001415 }
1416 }
1417 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001418
Duncan Sands1df98592010-02-16 11:11:14 +00001419 if (SrcTy->isPointerTy())
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001420 return commonPointerCastTransforms(CI);
1421 return commonCastTransforms(CI);
Chris Lattner80f43d32010-01-04 07:53:58 +00001422}