blob: 1372a1891fa5a0d29d723355b9d24f5861f54f2b [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,
Dan Gohman28d2e0a2010-05-28 04:33:04 +000025 uint64_t &Offset) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000026 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
27 Offset = CI->getZExtValue();
28 Scale = 0;
Dan Gohman28d2e0a2010-05-28 04:33:04 +000029 return ConstantInt::get(Val->getType(), 0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000030 }
31
32 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000033 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
34 if (I->getOpcode() == Instruction::Shl) {
35 // This is a value scaled by '1 << the shift amt'.
Dan Gohman28d2e0a2010-05-28 04:33:04 +000036 Scale = UINT64_C(1) << RHS->getZExtValue();
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000037 Offset = 0;
38 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000039 }
40
41 if (I->getOpcode() == Instruction::Mul) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000042 // This value is scaled by 'RHS'.
43 Scale = RHS->getZExtValue();
44 Offset = 0;
45 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000046 }
47
48 if (I->getOpcode() == Instruction::Add) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000049 // We have X+C. Check to see if we really have (X*C2)+C1,
50 // where C1 is divisible by C2.
51 unsigned SubScale;
52 Value *SubVal =
53 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
54 Offset += RHS->getZExtValue();
55 Scale = SubScale;
56 return SubVal;
57 }
58 }
59 }
60
61 // Otherwise, we can't look past this.
62 Scale = 1;
63 Offset = 0;
64 return Val;
65}
66
67/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
68/// try to eliminate the cast by moving the type information into the alloc.
69Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
70 AllocaInst &AI) {
71 // This requires TargetData to get the alloca alignment and size information.
72 if (!TD) return 0;
73
74 const PointerType *PTy = cast<PointerType>(CI.getType());
75
76 BuilderTy AllocaBuilder(*Builder);
77 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
78
79 // Get the type really allocated and the type casted to.
80 const Type *AllocElTy = AI.getAllocatedType();
81 const Type *CastElTy = PTy->getElementType();
82 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
83
84 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
85 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
86 if (CastElTyAlign < AllocElTyAlign) return 0;
87
88 // If the allocation has multiple uses, only promote it if we are strictly
89 // increasing the alignment of the resultant allocation. If we keep it the
90 // same, we open the door to infinite loops of various kinds. (A reference
91 // from a dbg.declare doesn't count as a use for this purpose.)
92 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
93 CastElTyAlign == AllocElTyAlign) return 0;
94
95 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
96 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
97 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
98
99 // See if we can satisfy the modulus by pulling a scale out of the array
100 // size argument.
101 unsigned ArraySizeScale;
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000102 uint64_t ArrayOffset;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000103 Value *NumElements = // See if the array size is a decomposable linear expr.
104 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
105
106 // If we can now satisfy the modulus, by using a non-1 scale, we really can
107 // do the xform.
108 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
109 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
110
111 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
112 Value *Amt = 0;
113 if (Scale == 1) {
114 Amt = NumElements;
115 } else {
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000116 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000117 // Insert before the alloca, not before the cast.
118 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
119 }
120
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000121 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
122 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000123 Offset, true);
124 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
125 }
126
127 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
128 New->setAlignment(AI.getAlignment());
129 New->takeName(&AI);
130
131 // If the allocation has one real use plus a dbg.declare, just remove the
132 // declare.
133 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
134 EraseInstFromFunction(*(Instruction*)DI);
135 }
136 // If the allocation has multiple real uses, insert a cast and change all
137 // things that used it to use the new cast. This will also hack on CI, but it
138 // will die soon.
139 else if (!AI.hasOneUse()) {
140 // New is the allocation instruction, pointer typed. AI is the original
141 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
142 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
143 AI.replaceAllUsesWith(NewCast);
144 }
145 return ReplaceInstUsesWith(CI, New);
146}
147
148
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000149
Chris Lattner5f0290e2010-01-04 07:54:59 +0000150/// EvaluateInDifferentType - Given an expression that
Chris Lattner14bf8f02010-01-08 19:19:23 +0000151/// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000152/// insert the code to evaluate the expression.
Chris Lattner5f0290e2010-01-04 07:54:59 +0000153Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
154 bool isSigned) {
Chris Lattnerc8b3fce2010-01-08 19:28:47 +0000155 if (Constant *C = dyn_cast<Constant>(V)) {
156 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
157 // If we got a constantexpr back, try to simplify it with TD info.
158 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
159 C = ConstantFoldConstantExpression(CE, TD);
160 return C;
161 }
Chris Lattner5f0290e2010-01-04 07:54:59 +0000162
163 // Otherwise, it must be an instruction.
164 Instruction *I = cast<Instruction>(V);
165 Instruction *Res = 0;
166 unsigned Opc = I->getOpcode();
167 switch (Opc) {
168 case Instruction::Add:
169 case Instruction::Sub:
170 case Instruction::Mul:
171 case Instruction::And:
172 case Instruction::Or:
173 case Instruction::Xor:
174 case Instruction::AShr:
175 case Instruction::LShr:
176 case Instruction::Shl:
177 case Instruction::UDiv:
178 case Instruction::URem: {
179 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
180 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
181 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
182 break;
183 }
184 case Instruction::Trunc:
185 case Instruction::ZExt:
186 case Instruction::SExt:
187 // If the source type of the cast is the type we're trying for then we can
188 // just return the source. There's no need to insert it because it is not
189 // new.
190 if (I->getOperand(0)->getType() == Ty)
191 return I->getOperand(0);
192
193 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000194 // This also handles the case of zext(trunc(x)) -> zext(x).
195 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
196 Opc == Instruction::SExt);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000197 break;
198 case Instruction::Select: {
199 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
200 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
201 Res = SelectInst::Create(I->getOperand(0), True, False);
202 break;
203 }
204 case Instruction::PHI: {
205 PHINode *OPN = cast<PHINode>(I);
206 PHINode *NPN = PHINode::Create(Ty);
207 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
208 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
209 NPN->addIncoming(V, OPN->getIncomingBlock(i));
210 }
211 Res = NPN;
212 break;
213 }
214 default:
215 // TODO: Can handle more cases here.
216 llvm_unreachable("Unreachable!");
217 break;
218 }
219
220 Res->takeName(I);
221 return InsertNewInstBefore(Res, *I);
222}
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.
227static Instruction::CastOps
228isEliminableCastPair(
229 const CastInst *CI, ///< The first cast instruction
230 unsigned opcode, ///< The opcode of the second cast instruction
231 const Type *DstTy, ///< The target type for the second cast instruction
232 TargetData *TD ///< The target data for pointer size
233) {
234
235 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
236 const Type *MidTy = CI->getType(); // B from above
237
238 // Get the opcodes of the two Cast instructions
239 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
240 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
241
242 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
243 DstTy,
244 TD ? TD->getIntPtrType(CI->getContext()) : 0);
245
246 // We don't want to form an inttoptr or ptrtoint that converts to an integer
247 // type that differs from the pointer size.
248 if ((Res == Instruction::IntToPtr &&
249 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
250 (Res == Instruction::PtrToInt &&
251 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
252 Res = 0;
253
254 return Instruction::CastOps(Res);
255}
256
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000257/// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
258/// results in any code being generated and is interesting to optimize out. If
259/// the cast can be eliminated by some other simple transformation, we prefer
260/// to do the simplification first.
261bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
262 const Type *Ty) {
263 // Noop casts and casts of constants should be eliminated trivially.
Chris Lattner80f43d32010-01-04 07:53:58 +0000264 if (V->getType() == Ty || isa<Constant>(V)) return false;
265
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000266 // If this is another cast that can be eliminated, we prefer to have it
267 // eliminated.
Chris Lattner80f43d32010-01-04 07:53:58 +0000268 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000269 if (isEliminableCastPair(CI, opc, Ty, TD))
Chris Lattner80f43d32010-01-04 07:53:58 +0000270 return false;
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000271
272 // If this is a vector sext from a compare, then we don't want to break the
273 // idiom where each element of the extended vector is either zero or all ones.
Duncan Sands1df98592010-02-16 11:11:14 +0000274 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000275 return false;
276
Chris Lattner80f43d32010-01-04 07:53:58 +0000277 return true;
278}
279
280
281/// @brief Implement the transforms common to all CastInst visitors.
282Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
283 Value *Src = CI.getOperand(0);
284
285 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
286 // eliminate it now.
287 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
288 if (Instruction::CastOps opc =
289 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
290 // The first cast (CSrc) is eliminable so we need to fix up or replace
291 // the second cast (CI). CSrc will then have a good chance of being dead.
292 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
293 }
294 }
295
296 // If we are casting a select then fold the cast into the select
297 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
298 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
299 return NV;
300
301 // If we are casting a PHI then fold the cast into the PHI
302 if (isa<PHINode>(Src)) {
303 // We don't do this if this would create a PHI node with an illegal type if
304 // it is currently legal.
Duncan Sands1df98592010-02-16 11:11:14 +0000305 if (!Src->getType()->isIntegerTy() ||
306 !CI.getType()->isIntegerTy() ||
Chris Lattner80f43d32010-01-04 07:53:58 +0000307 ShouldChangeType(CI.getType(), Src->getType()))
308 if (Instruction *NV = FoldOpIntoPhi(CI))
309 return NV;
310 }
311
312 return 0;
313}
314
Chris Lattner75215c92010-01-10 00:58:42 +0000315/// CanEvaluateTruncated - Return true if we can evaluate the specified
316/// expression tree as type Ty instead of its larger type, and arrive with the
317/// same value. This is used by code that tries to eliminate truncates.
318///
319/// Ty will always be a type smaller than V. We should return true if trunc(V)
320/// can be computed by computing V in the smaller type. If V is an instruction,
321/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
322/// makes sense if x and y can be efficiently truncated.
323///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000324/// This function works on both vectors and scalars.
325///
Chris Lattner75215c92010-01-10 00:58:42 +0000326static bool CanEvaluateTruncated(Value *V, const Type *Ty) {
327 // We can always evaluate constants in another type.
328 if (isa<Constant>(V))
329 return true;
Chris Lattner68c6e892010-01-05 23:00:30 +0000330
Chris Lattner75215c92010-01-10 00:58:42 +0000331 Instruction *I = dyn_cast<Instruction>(V);
332 if (!I) return false;
333
334 const Type *OrigTy = V->getType();
335
Chris Lattnera958cbf2010-01-11 22:45:25 +0000336 // If this is an extension from the dest type, we can eliminate it, even if it
337 // has multiple uses.
Chris Lattner53af2d12010-01-11 22:49:40 +0000338 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000339 I->getOperand(0)->getType() == Ty)
340 return true;
341
342 // We can't extend or shrink something that has multiple uses: doing so would
343 // require duplicating the instruction in general, which isn't profitable.
344 if (!I->hasOneUse()) return false;
345
346 unsigned Opc = I->getOpcode();
347 switch (Opc) {
348 case Instruction::Add:
349 case Instruction::Sub:
350 case Instruction::Mul:
351 case Instruction::And:
352 case Instruction::Or:
353 case Instruction::Xor:
354 // These operators can all arbitrarily be extended or truncated.
355 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
356 CanEvaluateTruncated(I->getOperand(1), Ty);
357
358 case Instruction::UDiv:
359 case Instruction::URem: {
360 // UDiv and URem can be truncated if all the truncated bits are zero.
361 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
362 uint32_t BitWidth = Ty->getScalarSizeInBits();
363 if (BitWidth < OrigBitWidth) {
364 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
365 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
366 MaskedValueIsZero(I->getOperand(1), Mask)) {
367 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
368 CanEvaluateTruncated(I->getOperand(1), Ty);
369 }
370 }
371 break;
372 }
373 case Instruction::Shl:
374 // If we are truncating the result of this SHL, and if it's a shift of a
375 // constant amount, we can always perform a SHL in a smaller type.
376 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
377 uint32_t BitWidth = Ty->getScalarSizeInBits();
378 if (CI->getLimitedValue(BitWidth) < BitWidth)
379 return CanEvaluateTruncated(I->getOperand(0), Ty);
380 }
381 break;
382 case Instruction::LShr:
383 // If this is a truncate of a logical shr, we can truncate it to a smaller
384 // lshr iff we know that the bits we would otherwise be shifting in are
385 // already zeros.
386 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
387 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
388 uint32_t BitWidth = Ty->getScalarSizeInBits();
389 if (MaskedValueIsZero(I->getOperand(0),
390 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
391 CI->getLimitedValue(BitWidth) < BitWidth) {
392 return CanEvaluateTruncated(I->getOperand(0), Ty);
393 }
394 }
395 break;
396 case Instruction::Trunc:
397 // trunc(trunc(x)) -> trunc(x)
398 return true;
399 case Instruction::Select: {
400 SelectInst *SI = cast<SelectInst>(I);
401 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
402 CanEvaluateTruncated(SI->getFalseValue(), Ty);
403 }
404 case Instruction::PHI: {
405 // We can change a phi if we can change all operands. Note that we never
406 // get into trouble with cyclic PHIs here because we only consider
407 // instructions with a single use.
408 PHINode *PN = cast<PHINode>(I);
409 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
410 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
411 return false;
412 return true;
413 }
414 default:
415 // TODO: Can handle more cases here.
416 break;
417 }
418
419 return false;
420}
421
422Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000423 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner75215c92010-01-10 00:58:42 +0000424 return Result;
425
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000426 // See if we can simplify any instructions used by the input whose sole
427 // purpose is to compute bits we don't care about.
428 if (SimplifyDemandedInstructionBits(CI))
429 return &CI;
430
Chris Lattner75215c92010-01-10 00:58:42 +0000431 Value *Src = CI.getOperand(0);
432 const Type *DestTy = CI.getType(), *SrcTy = Src->getType();
433
434 // Attempt to truncate the entire input expression tree to the destination
435 // type. Only do this if the dest type is a simple type, don't convert the
Chris Lattner80f43d32010-01-04 07:53:58 +0000436 // expression tree to something weird like i93 unless the source is also
437 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +0000438 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000439 CanEvaluateTruncated(Src, DestTy)) {
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000440
Chris Lattner80f43d32010-01-04 07:53:58 +0000441 // If this cast is a truncate, evaluting in a different type always
Chris Lattner68c6e892010-01-05 23:00:30 +0000442 // eliminates the cast, so it is always a win.
Chris Lattner075f6922010-01-07 23:41:00 +0000443 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Dan Gohman5b71dce2010-05-25 21:50:35 +0000444 " to avoid cast: " << CI << '\n');
Chris Lattner075f6922010-01-07 23:41:00 +0000445 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
446 assert(Res->getType() == DestTy);
447 return ReplaceInstUsesWith(CI, Res);
448 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000449
Chris Lattner7a34d6c2010-01-05 22:21:18 +0000450 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
451 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000452 Constant *One = ConstantInt::get(Src->getType(), 1);
453 Src = Builder->CreateAnd(Src, One, "tmp");
454 Value *Zero = Constant::getNullValue(Src->getType());
455 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
456 }
Chris Lattner784f3332010-08-27 18:31:05 +0000457
458 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
459 Value *A = 0; ConstantInt *Cst = 0;
460 if (match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst))) &&
461 Src->hasOneUse()) {
462 // We have three types to worry about here, the type of A, the source of
463 // the truncate (MidSize), and the destination of the truncate. We know that
464 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
465 // between ASize and ResultSize.
466 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
467
468 // If the shift amount is larger than the size of A, then the result is
469 // known to be zero because all the input bits got shifted out.
470 if (Cst->getZExtValue() >= ASize)
471 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
472
473 // Since we're doing an lshr and a zero extend, and know that the shift
474 // amount is smaller than ASize, it is always safe to do the shift in A's
475 // type, then zero extend or truncate to the result.
476 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
477 Shift->takeName(Src);
478 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
479 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000480
Chris Lattner80f43d32010-01-04 07:53:58 +0000481 return 0;
482}
483
484/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
485/// in order to eliminate the icmp.
486Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
487 bool DoXform) {
488 // If we are just checking for a icmp eq of a single bit and zext'ing it
489 // to an integer, then shift the bit to the appropriate place and then
490 // cast to integer to avoid the comparison.
491 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
492 const APInt &Op1CV = Op1C->getValue();
493
494 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
495 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
496 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
497 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
498 if (!DoXform) return ICI;
499
500 Value *In = ICI->getOperand(0);
501 Value *Sh = ConstantInt::get(In->getType(),
502 In->getType()->getScalarSizeInBits()-1);
503 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
504 if (In->getType() != CI.getType())
505 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
506
507 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
508 Constant *One = ConstantInt::get(In->getType(), 1);
509 In = Builder->CreateXor(In, One, In->getName()+".not");
510 }
511
512 return ReplaceInstUsesWith(CI, In);
513 }
514
515
516
517 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
518 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
519 // zext (X == 1) to i32 --> X iff X has only the low bit set.
520 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
521 // zext (X != 0) to i32 --> X iff X has only the low bit set.
522 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
523 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
524 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
525 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
526 // This only works for EQ and NE
527 ICI->isEquality()) {
528 // If Op1C some other power of two, convert:
529 uint32_t BitWidth = Op1C->getType()->getBitWidth();
530 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
531 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
532 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
533
534 APInt KnownZeroMask(~KnownZero);
535 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
536 if (!DoXform) return ICI;
537
538 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
539 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
540 // (X&4) == 2 --> false
541 // (X&4) != 2 --> true
542 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
543 isNE);
544 Res = ConstantExpr::getZExt(Res, CI.getType());
545 return ReplaceInstUsesWith(CI, Res);
546 }
547
548 uint32_t ShiftAmt = KnownZeroMask.logBase2();
549 Value *In = ICI->getOperand(0);
550 if (ShiftAmt) {
551 // Perform a logical shr by shiftamt.
552 // Insert the shift to put the result in the low bit.
553 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
554 In->getName()+".lobit");
555 }
556
557 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
558 Constant *One = ConstantInt::get(In->getType(), 1);
559 In = Builder->CreateXor(In, One, "tmp");
560 }
561
562 if (CI.getType() == In->getType())
563 return ReplaceInstUsesWith(CI, In);
564 else
565 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
566 }
567 }
568 }
569
570 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
571 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
572 // may lead to additional simplifications.
573 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
574 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
575 uint32_t BitWidth = ITy->getBitWidth();
576 Value *LHS = ICI->getOperand(0);
577 Value *RHS = ICI->getOperand(1);
578
579 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
580 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
581 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
582 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
583 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
584
585 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
586 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
587 APInt UnknownBit = ~KnownBits;
588 if (UnknownBit.countPopulation() == 1) {
589 if (!DoXform) return ICI;
590
591 Value *Result = Builder->CreateXor(LHS, RHS);
592
593 // Mask off any bits that are set and won't be shifted away.
594 if (KnownOneLHS.uge(UnknownBit))
595 Result = Builder->CreateAnd(Result,
596 ConstantInt::get(ITy, UnknownBit));
597
598 // Shift the bit we're testing down to the lsb.
599 Result = Builder->CreateLShr(
600 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
601
602 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
603 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
604 Result->takeName(ICI);
605 return ReplaceInstUsesWith(CI, Result);
606 }
607 }
608 }
609 }
610
611 return 0;
612}
613
Chris Lattner75215c92010-01-10 00:58:42 +0000614/// CanEvaluateZExtd - Determine if the specified value can be computed in the
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000615/// specified wider type and produce the same low bits. If not, return false.
616///
Chris Lattner789162a2010-01-11 03:32:00 +0000617/// If this function returns true, it can also return a non-zero number of bits
618/// (in BitsToClear) which indicates that the value it computes is correct for
619/// the zero extend, but that the additional BitsToClear bits need to be zero'd
620/// out. For example, to promote something like:
621///
622/// %B = trunc i64 %A to i32
623/// %C = lshr i32 %B, 8
624/// %E = zext i32 %C to i64
625///
626/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
627/// set to 8 to indicate that the promoted value needs to have bits 24-31
628/// cleared in addition to bits 32-63. Since an 'and' will be generated to
629/// clear the top bits anyway, doing this has no extra cost.
630///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000631/// This function works on both vectors and scalars.
Chris Lattner789162a2010-01-11 03:32:00 +0000632static bool CanEvaluateZExtd(Value *V, const Type *Ty, unsigned &BitsToClear) {
633 BitsToClear = 0;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000634 if (isa<Constant>(V))
635 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000636
637 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner9e390dd2010-01-10 02:50:04 +0000638 if (!I) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000639
640 // If the input is a truncate from the destination type, we can trivially
Chris Lattnera958cbf2010-01-11 22:45:25 +0000641 // eliminate it, even if it has multiple uses.
642 // FIXME: This is currently disabled until codegen can handle this without
643 // pessimizing code, PR5997.
644 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattner9e390dd2010-01-10 02:50:04 +0000645 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000646
647 // We can't extend or shrink something that has multiple uses: doing so would
648 // require duplicating the instruction in general, which isn't profitable.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000649 if (!I->hasOneUse()) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000650
Chris Lattner789162a2010-01-11 03:32:00 +0000651 unsigned Opc = I->getOpcode(), Tmp;
Chris Lattner75215c92010-01-10 00:58:42 +0000652 switch (Opc) {
Chris Lattner9ee947c2010-01-10 20:25:54 +0000653 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
654 case Instruction::SExt: // zext(sext(x)) -> sext(x).
655 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
656 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000657 case Instruction::And:
Chris Lattner75215c92010-01-10 00:58:42 +0000658 case Instruction::Or:
659 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +0000660 case Instruction::Add:
661 case Instruction::Sub:
662 case Instruction::Mul:
Chris Lattnerd26c9e12010-01-10 02:22:12 +0000663 case Instruction::Shl:
Chris Lattner789162a2010-01-11 03:32:00 +0000664 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
665 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
666 return false;
667 // These can all be promoted if neither operand has 'bits to clear'.
668 if (BitsToClear == 0 && Tmp == 0)
669 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000670
Chris Lattner7acc4b12010-01-11 04:05:13 +0000671 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
672 // other side, BitsToClear is ok.
673 if (Tmp == 0 &&
674 (Opc == Instruction::And || Opc == Instruction::Or ||
675 Opc == Instruction::Xor)) {
676 // We use MaskedValueIsZero here for generality, but the case we care
677 // about the most is constant RHS.
678 unsigned VSize = V->getType()->getScalarSizeInBits();
679 if (MaskedValueIsZero(I->getOperand(1),
680 APInt::getHighBitsSet(VSize, BitsToClear)))
681 return true;
682 }
683
684 // Otherwise, we don't know how to analyze this BitsToClear case yet.
Chris Lattner789162a2010-01-11 03:32:00 +0000685 return false;
Chris Lattnerd26c9e12010-01-10 02:22:12 +0000686
Chris Lattner789162a2010-01-11 03:32:00 +0000687 case Instruction::LShr:
688 // We can promote lshr(x, cst) if we can promote x. This requires the
689 // ultimate 'and' to clear out the high zero bits we're clearing out though.
690 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
691 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
692 return false;
693 BitsToClear += Amt->getZExtValue();
694 if (BitsToClear > V->getType()->getScalarSizeInBits())
695 BitsToClear = V->getType()->getScalarSizeInBits();
696 return true;
697 }
698 // Cannot promote variable LSHR.
699 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000700 case Instruction::Select:
Chris Lattner789162a2010-01-11 03:32:00 +0000701 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
702 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000703 // TODO: If important, we could handle the case when the BitsToClear are
704 // known zero in the disagreeing side.
Chris Lattner789162a2010-01-11 03:32:00 +0000705 Tmp != BitsToClear)
706 return false;
707 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000708
709 case Instruction::PHI: {
710 // We can change a phi if we can change all operands. Note that we never
711 // get into trouble with cyclic PHIs here because we only consider
712 // instructions with a single use.
713 PHINode *PN = cast<PHINode>(I);
Chris Lattner789162a2010-01-11 03:32:00 +0000714 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
715 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000716 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner789162a2010-01-11 03:32:00 +0000717 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000718 // TODO: If important, we could handle the case when the BitsToClear
719 // are known zero in the disagreeing input.
Chris Lattner789162a2010-01-11 03:32:00 +0000720 Tmp != BitsToClear)
721 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000722 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000723 }
724 default:
725 // TODO: Can handle more cases here.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000726 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000727 }
728}
729
Chris Lattner80f43d32010-01-04 07:53:58 +0000730Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Chris Lattner5324d802010-01-10 02:39:31 +0000731 // If this zero extend is only used by a truncate, let the truncate by
732 // eliminated before we try to optimize this zext.
733 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
734 return 0;
735
Chris Lattner80f43d32010-01-04 07:53:58 +0000736 // If one of the common conversion will work, do it.
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000737 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +0000738 return Result;
739
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000740 // See if we can simplify any instructions used by the input whose sole
741 // purpose is to compute bits we don't care about.
742 if (SimplifyDemandedInstructionBits(CI))
743 return &CI;
Chris Lattner75215c92010-01-10 00:58:42 +0000744
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000745 Value *Src = CI.getOperand(0);
Chris Lattner75215c92010-01-10 00:58:42 +0000746 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
747
748 // Attempt to extend the entire input expression tree to the destination
749 // type. Only do this if the dest type is a simple type, don't convert the
750 // expression tree to something weird like i93 unless the source is also
751 // strange.
Chris Lattner789162a2010-01-11 03:32:00 +0000752 unsigned BitsToClear;
Duncan Sands1df98592010-02-16 11:11:14 +0000753 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner789162a2010-01-11 03:32:00 +0000754 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
755 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
756 "Unreasonable BitsToClear");
757
Chris Lattner5324d802010-01-10 02:39:31 +0000758 // Okay, we can transform this! Insert the new expression now.
759 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
760 " to avoid zero extend: " << CI);
761 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
762 assert(Res->getType() == DestTy);
763
Chris Lattner789162a2010-01-11 03:32:00 +0000764 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
765 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
766
Chris Lattner5324d802010-01-10 02:39:31 +0000767 // If the high bits are already filled with zeros, just replace this
768 // cast with the result.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000769 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
Chris Lattner789162a2010-01-11 03:32:00 +0000770 DestBitSize-SrcBitsKept)))
Chris Lattner5324d802010-01-10 02:39:31 +0000771 return ReplaceInstUsesWith(CI, Res);
772
773 // We need to emit an AND to clear the high bits.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000774 Constant *C = ConstantInt::get(Res->getType(),
Chris Lattner789162a2010-01-11 03:32:00 +0000775 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
Chris Lattner5324d802010-01-10 02:39:31 +0000776 return BinaryOperator::CreateAnd(Res, C);
Chris Lattner75215c92010-01-10 00:58:42 +0000777 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000778
779 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
780 // types and if the sizes are just right we can convert this into a logical
781 // 'and' which will be much cheaper than the pair of casts.
782 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000783 // TODO: Subsume this into EvaluateInDifferentType.
784
Chris Lattner80f43d32010-01-04 07:53:58 +0000785 // Get the sizes of the types involved. We know that the intermediate type
786 // will be smaller than A or C, but don't know the relation between A and C.
787 Value *A = CSrc->getOperand(0);
788 unsigned SrcSize = A->getType()->getScalarSizeInBits();
789 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
790 unsigned DstSize = CI.getType()->getScalarSizeInBits();
791 // If we're actually extending zero bits, then if
792 // SrcSize < DstSize: zext(a & mask)
793 // SrcSize == DstSize: a & mask
794 // SrcSize > DstSize: trunc(a) & mask
795 if (SrcSize < DstSize) {
796 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
797 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
798 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
799 return new ZExtInst(And, CI.getType());
800 }
801
802 if (SrcSize == DstSize) {
803 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
804 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
805 AndValue));
806 }
807 if (SrcSize > DstSize) {
808 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
809 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
810 return BinaryOperator::CreateAnd(Trunc,
811 ConstantInt::get(Trunc->getType(),
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000812 AndValue));
Chris Lattner80f43d32010-01-04 07:53:58 +0000813 }
814 }
815
816 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
817 return transformZExtICmp(ICI, CI);
818
819 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
820 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
821 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
822 // of the (zext icmp) will be transformed.
823 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
824 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
825 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
826 (transformZExtICmp(LHS, CI, false) ||
827 transformZExtICmp(RHS, CI, false))) {
828 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
829 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
830 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
831 }
832 }
833
834 // zext(trunc(t) & C) -> (t & zext(C)).
835 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
836 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
837 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
838 Value *TI0 = TI->getOperand(0);
839 if (TI0->getType() == CI.getType())
840 return
841 BinaryOperator::CreateAnd(TI0,
842 ConstantExpr::getZExt(C, CI.getType()));
843 }
844
845 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
846 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
847 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
848 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
849 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
850 And->getOperand(1) == C)
851 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
852 Value *TI0 = TI->getOperand(0);
853 if (TI0->getType() == CI.getType()) {
854 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
855 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
856 return BinaryOperator::CreateXor(NewAnd, ZC);
857 }
858 }
859
Chris Lattner718bf3f2010-01-05 21:04:47 +0000860 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
861 Value *X;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000862 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isIntegerTy(1) &&
Chris Lattner49bdfef2010-01-05 21:11:17 +0000863 match(SrcI, m_Not(m_Value(X))) &&
Chris Lattner718bf3f2010-01-05 21:04:47 +0000864 (!X->hasOneUse() || !isa<CmpInst>(X))) {
865 Value *New = Builder->CreateZExt(X, CI.getType());
866 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
867 }
868
Chris Lattner80f43d32010-01-04 07:53:58 +0000869 return 0;
870}
871
Chris Lattner75215c92010-01-10 00:58:42 +0000872/// CanEvaluateSExtd - Return true if we can take the specified value
873/// and return it as type Ty without inserting any new casts and without
874/// changing the value of the common low bits. This is used by code that tries
875/// to promote integer operations to a wider types will allow us to eliminate
876/// the extension.
877///
Chris Lattneraa9c8942010-01-10 07:57:20 +0000878/// This function works on both vectors and scalars.
Chris Lattner75215c92010-01-10 00:58:42 +0000879///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000880static bool CanEvaluateSExtd(Value *V, const Type *Ty) {
Chris Lattner75215c92010-01-10 00:58:42 +0000881 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
882 "Can't sign extend type to a smaller type");
Chris Lattneraa9c8942010-01-10 07:57:20 +0000883 // If this is a constant, it can be trivially promoted.
884 if (isa<Constant>(V))
885 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000886
887 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattneraa9c8942010-01-10 07:57:20 +0000888 if (!I) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000889
Chris Lattnera958cbf2010-01-11 22:45:25 +0000890 // If this is a truncate from the dest type, we can trivially eliminate it,
891 // even if it has multiple uses.
892 // FIXME: This is currently disabled until codegen can handle this without
893 // pessimizing code, PR5997.
894 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattneraa9c8942010-01-10 07:57:20 +0000895 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000896
897 // We can't extend or shrink something that has multiple uses: doing so would
898 // require duplicating the instruction in general, which isn't profitable.
Chris Lattneraa9c8942010-01-10 07:57:20 +0000899 if (!I->hasOneUse()) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000900
Chris Lattneraa9c8942010-01-10 07:57:20 +0000901 switch (I->getOpcode()) {
Chris Lattner11ea8122010-01-10 20:30:41 +0000902 case Instruction::SExt: // sext(sext(x)) -> sext(x)
903 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
904 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
905 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000906 case Instruction::And:
907 case Instruction::Or:
908 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +0000909 case Instruction::Add:
910 case Instruction::Sub:
Chris Lattner75215c92010-01-10 00:58:42 +0000911 case Instruction::Mul:
Chris Lattneraa9c8942010-01-10 07:57:20 +0000912 // These operators can all arbitrarily be extended if their inputs can.
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000913 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
914 CanEvaluateSExtd(I->getOperand(1), Ty);
Chris Lattner75215c92010-01-10 00:58:42 +0000915
916 //case Instruction::Shl: TODO
917 //case Instruction::LShr: TODO
Chris Lattner75215c92010-01-10 00:58:42 +0000918
Chris Lattneraa9c8942010-01-10 07:57:20 +0000919 case Instruction::Select:
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000920 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
921 CanEvaluateSExtd(I->getOperand(2), Ty);
Chris Lattner9ee947c2010-01-10 20:25:54 +0000922
Chris Lattner75215c92010-01-10 00:58:42 +0000923 case Instruction::PHI: {
924 // We can change a phi if we can change all operands. Note that we never
925 // get into trouble with cyclic PHIs here because we only consider
926 // instructions with a single use.
927 PHINode *PN = cast<PHINode>(I);
Chris Lattner9ee947c2010-01-10 20:25:54 +0000928 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000929 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
Chris Lattneraa9c8942010-01-10 07:57:20 +0000930 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000931 }
932 default:
933 // TODO: Can handle more cases here.
934 break;
935 }
936
Chris Lattneraa9c8942010-01-10 07:57:20 +0000937 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000938}
939
Chris Lattner80f43d32010-01-04 07:53:58 +0000940Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattner5324d802010-01-10 02:39:31 +0000941 // If this sign extend is only used by a truncate, let the truncate by
942 // eliminated before we try to optimize this zext.
943 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
944 return 0;
945
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000946 if (Instruction *I = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +0000947 return I;
948
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000949 // See if we can simplify any instructions used by the input whose sole
950 // purpose is to compute bits we don't care about.
951 if (SimplifyDemandedInstructionBits(CI))
952 return &CI;
953
Chris Lattner80f43d32010-01-04 07:53:58 +0000954 Value *Src = CI.getOperand(0);
Chris Lattner75215c92010-01-10 00:58:42 +0000955 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
956
Chris Lattner75215c92010-01-10 00:58:42 +0000957 // Attempt to extend the entire input expression tree to the destination
958 // type. Only do this if the dest type is a simple type, don't convert the
959 // expression tree to something weird like i93 unless the source is also
960 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +0000961 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000962 CanEvaluateSExtd(Src, DestTy)) {
Chris Lattnerdde5ee52010-01-10 07:40:50 +0000963 // Okay, we can transform this! Insert the new expression now.
964 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
965 " to avoid sign extend: " << CI);
966 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
967 assert(Res->getType() == DestTy);
968
Chris Lattner75215c92010-01-10 00:58:42 +0000969 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
970 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Chris Lattnerdde5ee52010-01-10 07:40:50 +0000971
972 // If the high bits are already filled with sign bit, just replace this
973 // cast with the result.
Chris Lattneraa9c8942010-01-10 07:57:20 +0000974 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
Chris Lattnerdde5ee52010-01-10 07:40:50 +0000975 return ReplaceInstUsesWith(CI, Res);
Chris Lattner75215c92010-01-10 00:58:42 +0000976
Chris Lattnerdde5ee52010-01-10 07:40:50 +0000977 // We need to emit a shl + ashr to do the sign extend.
978 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
979 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
980 ShAmt);
Chris Lattner75215c92010-01-10 00:58:42 +0000981 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000982
Chris Lattnercd5adbb2010-01-18 22:19:16 +0000983 // If this input is a trunc from our destination, then turn sext(trunc(x))
984 // into shifts.
985 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
986 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
987 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
988 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
989
990 // We need to emit a shl + ashr to do the sign extend.
991 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
992 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
993 return BinaryOperator::CreateAShr(Res, ShAmt);
994 }
995
Chris Lattnerabb992d2010-01-24 00:09:49 +0000996
997 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
998 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
999 {
1000 ICmpInst::Predicate Pred; Value *CmpLHS; ConstantInt *CmpRHS;
1001 if (match(Src, m_ICmp(Pred, m_Value(CmpLHS), m_ConstantInt(CmpRHS)))) {
1002 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
1003 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
1004 if ((Pred == ICmpInst::ICMP_SLT && CmpRHS->isZero()) ||
1005 (Pred == ICmpInst::ICMP_SGT && CmpRHS->isAllOnesValue())) {
1006 Value *Sh = ConstantInt::get(CmpLHS->getType(),
1007 CmpLHS->getType()->getScalarSizeInBits()-1);
1008 Value *In = Builder->CreateAShr(CmpLHS, Sh, CmpLHS->getName()+".lobit");
1009 if (In->getType() != CI.getType())
1010 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/, "tmp");
1011
1012 if (Pred == ICmpInst::ICMP_SGT)
1013 In = Builder->CreateNot(In, In->getName()+".not");
1014 return ReplaceInstUsesWith(CI, In);
1015 }
1016 }
1017 }
1018
1019
Chris Lattner80f43d32010-01-04 07:53:58 +00001020 // If the input is a shl/ashr pair of a same constant, then this is a sign
1021 // extension from a smaller value. If we could trust arbitrary bitwidth
1022 // integers, we could turn this into a truncate to the smaller bit and then
1023 // use a sext for the whole extension. Since we don't, look deeper and check
1024 // for a truncate. If the source and dest are the same type, eliminate the
1025 // trunc and extend and just do shifts. For example, turn:
1026 // %a = trunc i32 %i to i8
1027 // %b = shl i8 %a, 6
1028 // %c = ashr i8 %b, 6
1029 // %d = sext i8 %c to i32
1030 // into:
1031 // %a = shl i32 %i, 30
1032 // %d = ashr i32 %a, 30
1033 Value *A = 0;
Chris Lattner4f379782010-01-10 01:04:31 +00001034 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
Chris Lattner80f43d32010-01-04 07:53:58 +00001035 ConstantInt *BA = 0, *CA = 0;
Chris Lattner4f379782010-01-10 01:04:31 +00001036 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
Chris Lattner80f43d32010-01-04 07:53:58 +00001037 m_ConstantInt(CA))) &&
Chris Lattner4f379782010-01-10 01:04:31 +00001038 BA == CA && A->getType() == CI.getType()) {
1039 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1040 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1041 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1042 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1043 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1044 return BinaryOperator::CreateAShr(A, ShAmtV);
Chris Lattner80f43d32010-01-04 07:53:58 +00001045 }
1046
1047 return 0;
1048}
1049
1050
1051/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1052/// in the specified FP type without changing its value.
1053static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1054 bool losesInfo;
1055 APFloat F = CFP->getValueAPF();
1056 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1057 if (!losesInfo)
1058 return ConstantFP::get(CFP->getContext(), F);
1059 return 0;
1060}
1061
1062/// LookThroughFPExtensions - If this is an fp extension instruction, look
1063/// through it until we get the source value.
1064static Value *LookThroughFPExtensions(Value *V) {
1065 if (Instruction *I = dyn_cast<Instruction>(V))
1066 if (I->getOpcode() == Instruction::FPExt)
1067 return LookThroughFPExtensions(I->getOperand(0));
1068
1069 // If this value is a constant, return the constant in the smallest FP type
1070 // that can accurately represent it. This allows us to turn
1071 // (float)((double)X+2.0) into x+2.0f.
1072 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1073 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1074 return V; // No constant folding of this.
1075 // See if the value can be truncated to float and then reextended.
1076 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1077 return V;
Benjamin Kramerf0127052010-01-05 13:12:22 +00001078 if (CFP->getType()->isDoubleTy())
Chris Lattner80f43d32010-01-04 07:53:58 +00001079 return V; // Won't shrink.
1080 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1081 return V;
1082 // Don't try to shrink to various long double types.
1083 }
1084
1085 return V;
1086}
1087
1088Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1089 if (Instruction *I = commonCastTransforms(CI))
1090 return I;
1091
1092 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1093 // smaller than the destination type, we can eliminate the truncate by doing
1094 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1095 // as many builtins (sqrt, etc).
1096 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1097 if (OpI && OpI->hasOneUse()) {
1098 switch (OpI->getOpcode()) {
1099 default: break;
1100 case Instruction::FAdd:
1101 case Instruction::FSub:
1102 case Instruction::FMul:
1103 case Instruction::FDiv:
1104 case Instruction::FRem:
1105 const Type *SrcTy = OpI->getType();
1106 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1107 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1108 if (LHSTrunc->getType() != SrcTy &&
1109 RHSTrunc->getType() != SrcTy) {
1110 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1111 // If the source types were both smaller than the destination type of
1112 // the cast, do this xform.
1113 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1114 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1115 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1116 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1117 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1118 }
1119 }
1120 break;
1121 }
1122 }
Owen Andersond9029012010-07-19 08:09:34 +00001123
1124 // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
1125 // NOTE: This should be disabled by -fno-builtin-sqrt if we ever support it.
1126 CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
1127 if (Call && Call->getCalledFunction() &&
1128 Call->getCalledFunction()->getName() == "sqrt" &&
1129 Call->getNumArgOperands() == 1) {
1130 CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
1131 if (Arg && Arg->getOpcode() == Instruction::FPExt &&
Owen Anderson5f23a932010-07-19 19:23:32 +00001132 CI.getType()->isFloatTy() &&
1133 Call->getType()->isDoubleTy() &&
1134 Arg->getType()->isDoubleTy() &&
1135 Arg->getOperand(0)->getType()->isFloatTy()) {
1136 Function *Callee = Call->getCalledFunction();
1137 Module *M = CI.getParent()->getParent()->getParent();
Owen Andersond9029012010-07-19 08:09:34 +00001138 Constant* SqrtfFunc = M->getOrInsertFunction("sqrtf",
Owen Anderson5f23a932010-07-19 19:23:32 +00001139 Callee->getAttributes(),
Owen Andersond9029012010-07-19 08:09:34 +00001140 Builder->getFloatTy(),
1141 Builder->getFloatTy(),
1142 NULL);
1143 CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
1144 "sqrtfcall");
Owen Anderson5f23a932010-07-19 19:23:32 +00001145 ret->setAttributes(Callee->getAttributes());
Owen Andersond9029012010-07-19 08:09:34 +00001146 return ret;
1147 }
1148 }
1149
Chris Lattner80f43d32010-01-04 07:53:58 +00001150 return 0;
1151}
1152
1153Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1154 return commonCastTransforms(CI);
1155}
1156
1157Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1158 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1159 if (OpI == 0)
1160 return commonCastTransforms(FI);
1161
1162 // fptoui(uitofp(X)) --> X
1163 // fptoui(sitofp(X)) --> X
1164 // This is safe if the intermediate type has enough bits in its mantissa to
1165 // accurately represent all values of X. For example, do not do this with
1166 // i64->float->i64. This is also safe for sitofp case, because any negative
1167 // 'X' value would cause an undefined result for the fptoui.
1168 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1169 OpI->getOperand(0)->getType() == FI.getType() &&
1170 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1171 OpI->getType()->getFPMantissaWidth())
1172 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1173
1174 return commonCastTransforms(FI);
1175}
1176
1177Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1178 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1179 if (OpI == 0)
1180 return commonCastTransforms(FI);
1181
1182 // fptosi(sitofp(X)) --> X
1183 // fptosi(uitofp(X)) --> X
1184 // This is safe if the intermediate type has enough bits in its mantissa to
1185 // accurately represent all values of X. For example, do not do this with
1186 // i64->float->i64. This is also safe for sitofp case, because any negative
1187 // 'X' value would cause an undefined result for the fptoui.
1188 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1189 OpI->getOperand(0)->getType() == FI.getType() &&
1190 (int)FI.getType()->getScalarSizeInBits() <=
1191 OpI->getType()->getFPMantissaWidth())
1192 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1193
1194 return commonCastTransforms(FI);
1195}
1196
1197Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1198 return commonCastTransforms(CI);
1199}
1200
1201Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1202 return commonCastTransforms(CI);
1203}
1204
Chris Lattner80f43d32010-01-04 07:53:58 +00001205Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001206 // If the source integer type is not the intptr_t type for this target, do a
1207 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1208 // cast to be exposed to other transforms.
1209 if (TD) {
1210 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
1211 TD->getPointerSizeInBits()) {
1212 Value *P = Builder->CreateTrunc(CI.getOperand(0),
1213 TD->getIntPtrType(CI.getContext()), "tmp");
1214 return new IntToPtrInst(P, CI.getType());
1215 }
1216 if (CI.getOperand(0)->getType()->getScalarSizeInBits() <
1217 TD->getPointerSizeInBits()) {
1218 Value *P = Builder->CreateZExt(CI.getOperand(0),
1219 TD->getIntPtrType(CI.getContext()), "tmp");
1220 return new IntToPtrInst(P, CI.getType());
1221 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001222 }
1223
1224 if (Instruction *I = commonCastTransforms(CI))
1225 return I;
1226
1227 return 0;
1228}
1229
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001230/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1231Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1232 Value *Src = CI.getOperand(0);
1233
1234 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1235 // If casting the result of a getelementptr instruction with no offset, turn
1236 // this into a cast of the original pointer!
1237 if (GEP->hasAllZeroIndices()) {
1238 // Changing the cast operand is usually not a good idea but it is safe
1239 // here because the pointer operand is being replaced with another
1240 // pointer operand so the opcode doesn't need to change.
1241 Worklist.Add(GEP);
1242 CI.setOperand(0, GEP->getOperand(0));
1243 return &CI;
1244 }
1245
1246 // If the GEP has a single use, and the base pointer is a bitcast, and the
1247 // GEP computes a constant offset, see if we can convert these three
1248 // instructions into fewer. This typically happens with unions and other
1249 // non-type-safe code.
1250 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1251 GEP->hasAllConstantIndices()) {
1252 // We are guaranteed to get a constant from EmitGEPOffset.
1253 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1254 int64_t Offset = OffsetV->getSExtValue();
1255
1256 // Get the base pointer input of the bitcast, and the type it points to.
1257 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1258 const Type *GEPIdxTy =
1259 cast<PointerType>(OrigBase->getType())->getElementType();
1260 SmallVector<Value*, 8> NewIndices;
1261 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1262 // If we were able to index down into an element, create the GEP
1263 // and bitcast the result. This eliminates one bitcast, potentially
1264 // two.
1265 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1266 Builder->CreateInBoundsGEP(OrigBase,
1267 NewIndices.begin(), NewIndices.end()) :
1268 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1269 NGEP->takeName(GEP);
1270
1271 if (isa<BitCastInst>(CI))
1272 return new BitCastInst(NGEP, CI.getType());
1273 assert(isa<PtrToIntInst>(CI));
1274 return new PtrToIntInst(NGEP, CI.getType());
1275 }
1276 }
1277 }
1278
1279 return commonCastTransforms(CI);
1280}
1281
1282Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001283 // If the destination integer type is not the intptr_t type for this target,
1284 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1285 // to be exposed to other transforms.
1286 if (TD) {
1287 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1288 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1289 TD->getIntPtrType(CI.getContext()),
1290 "tmp");
1291 return new TruncInst(P, CI.getType());
1292 }
1293 if (CI.getType()->getScalarSizeInBits() > TD->getPointerSizeInBits()) {
1294 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1295 TD->getIntPtrType(CI.getContext()),
1296 "tmp");
1297 return new ZExtInst(P, CI.getType());
1298 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001299 }
1300
1301 return commonPointerCastTransforms(CI);
1302}
1303
Chris Lattner67451912010-05-08 21:50:26 +00001304/// OptimizeVectorResize - This input value (which is known to have vector type)
1305/// is being zero extended or truncated to the specified vector type. Try to
1306/// replace it with a shuffle (and vector/vector bitcast) if possible.
1307///
1308/// The source and destination vector types may have different element types.
1309static Instruction *OptimizeVectorResize(Value *InVal, const VectorType *DestTy,
1310 InstCombiner &IC) {
1311 // We can only do this optimization if the output is a multiple of the input
1312 // element size, or the input is a multiple of the output element size.
1313 // Convert the input type to have the same element type as the output.
1314 const VectorType *SrcTy = cast<VectorType>(InVal->getType());
1315
1316 if (SrcTy->getElementType() != DestTy->getElementType()) {
1317 // The input types don't need to be identical, but for now they must be the
1318 // same size. There is no specific reason we couldn't handle things like
1319 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1320 // there yet.
1321 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1322 DestTy->getElementType()->getPrimitiveSizeInBits())
1323 return 0;
1324
1325 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1326 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1327 }
1328
1329 // Now that the element types match, get the shuffle mask and RHS of the
1330 // shuffle to use, which depends on whether we're increasing or decreasing the
1331 // size of the input.
1332 SmallVector<Constant*, 16> ShuffleMask;
1333 Value *V2;
1334 const IntegerType *Int32Ty = Type::getInt32Ty(SrcTy->getContext());
1335
1336 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1337 // If we're shrinking the number of elements, just shuffle in the low
1338 // elements from the input and use undef as the second shuffle input.
1339 V2 = UndefValue::get(SrcTy);
1340 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
1341 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1342
1343 } else {
1344 // If we're increasing the number of elements, shuffle in all of the
1345 // elements from InVal and fill the rest of the result elements with zeros
1346 // from a constant zero.
1347 V2 = Constant::getNullValue(SrcTy);
1348 unsigned SrcElts = SrcTy->getNumElements();
1349 for (unsigned i = 0, e = SrcElts; i != e; ++i)
1350 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1351
1352 // The excess elements reference the first element of the zero input.
1353 ShuffleMask.append(DestTy->getNumElements()-SrcElts,
1354 ConstantInt::get(Int32Ty, SrcElts));
1355 }
1356
1357 Constant *Mask = ConstantVector::get(ShuffleMask.data(), ShuffleMask.size());
1358 return new ShuffleVectorInst(InVal, V2, Mask);
1359}
1360
Chris Lattnere5a14262010-08-26 21:55:42 +00001361/// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1362/// bitcast. The various long double bitcasts can't get in here.
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001363static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
Chris Lattnere5a14262010-08-26 21:55:42 +00001364 Value *Src = CI.getOperand(0);
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001365 const Type *DestTy = CI.getType();
Chris Lattnere5a14262010-08-26 21:55:42 +00001366
1367 // If this is a bitcast from int to float, check to see if the int is an
1368 // extraction from a vector.
1369 Value *VecInput = 0;
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001370 // bitcast(trunc(bitcast(somevector)))
Chris Lattnere5a14262010-08-26 21:55:42 +00001371 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1372 isa<VectorType>(VecInput->getType())) {
1373 const VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001374 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1375
1376 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1377 // If the element type of the vector doesn't match the result type,
1378 // bitcast it to be a vector type we can extract from.
1379 if (VecTy->getElementType() != DestTy) {
1380 VecTy = VectorType::get(DestTy,
1381 VecTy->getPrimitiveSizeInBits() / DestWidth);
1382 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1383 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001384
Chris Lattnere5a14262010-08-26 21:55:42 +00001385 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(0));
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001386 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001387 }
1388
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001389 // bitcast(trunc(lshr(bitcast(somevector), cst))
1390 ConstantInt *ShAmt = 0;
1391 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1392 m_ConstantInt(ShAmt)))) &&
1393 isa<VectorType>(VecInput->getType())) {
1394 const VectorType *VecTy = cast<VectorType>(VecInput->getType());
1395 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1396 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1397 ShAmt->getZExtValue() % DestWidth == 0) {
1398 // If the element type of the vector doesn't match the result type,
1399 // bitcast it to be a vector type we can extract from.
1400 if (VecTy->getElementType() != DestTy) {
1401 VecTy = VectorType::get(DestTy,
1402 VecTy->getPrimitiveSizeInBits() / DestWidth);
1403 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1404 }
1405
1406 unsigned Elt = ShAmt->getZExtValue() / DestWidth;
1407 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1408 }
1409 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001410 return 0;
1411}
Chris Lattner67451912010-05-08 21:50:26 +00001412
Chris Lattner80f43d32010-01-04 07:53:58 +00001413Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1414 // If the operands are integer typed then apply the integer transforms,
1415 // otherwise just apply the common ones.
1416 Value *Src = CI.getOperand(0);
1417 const Type *SrcTy = Src->getType();
1418 const Type *DestTy = CI.getType();
1419
Chris Lattner80f43d32010-01-04 07:53:58 +00001420 // Get rid of casts from one type to the same type. These are useless and can
1421 // be replaced by the operand.
1422 if (DestTy == Src->getType())
1423 return ReplaceInstUsesWith(CI, Src);
1424
1425 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1426 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1427 const Type *DstElTy = DstPTy->getElementType();
1428 const Type *SrcElTy = SrcPTy->getElementType();
1429
1430 // If the address spaces don't match, don't eliminate the bitcast, which is
1431 // required for changing types.
1432 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1433 return 0;
1434
1435 // If we are casting a alloca to a pointer to a type of the same
1436 // size, rewrite the allocation instruction to allocate the "right" type.
1437 // There is no need to modify malloc calls because it is their bitcast that
1438 // needs to be cleaned up.
1439 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1440 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1441 return V;
1442
1443 // If the source and destination are pointers, and this cast is equivalent
1444 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1445 // This can enhance SROA and other transforms that want type-safe pointers.
1446 Constant *ZeroUInt =
1447 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1448 unsigned NumZeros = 0;
1449 while (SrcElTy != DstElTy &&
Duncan Sands1df98592010-02-16 11:11:14 +00001450 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
Chris Lattner80f43d32010-01-04 07:53:58 +00001451 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1452 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1453 ++NumZeros;
1454 }
1455
1456 // If we found a path from the src to dest, create the getelementptr now.
1457 if (SrcElTy == DstElTy) {
1458 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1459 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001460 ((Instruction*)NULL));
Chris Lattner80f43d32010-01-04 07:53:58 +00001461 }
1462 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001463
1464 // Try to optimize int -> float bitcasts.
1465 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1466 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1467 return I;
Chris Lattner80f43d32010-01-04 07:53:58 +00001468
1469 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Duncan Sands1df98592010-02-16 11:11:14 +00001470 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001471 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1472 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner80f43d32010-01-04 07:53:58 +00001473 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner80f43d32010-01-04 07:53:58 +00001474 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1475 }
Chris Lattner67451912010-05-08 21:50:26 +00001476
1477 // If this is a cast from an integer to vector, check to see if the input
1478 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1479 // the casts with a shuffle and (potentially) a bitcast.
1480 if (isa<IntegerType>(SrcTy) && (isa<TruncInst>(Src) || isa<ZExtInst>(Src))){
1481 CastInst *SrcCast = cast<CastInst>(Src);
1482 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1483 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1484 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
1485 cast<VectorType>(DestTy), *this))
1486 return I;
1487 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001488 }
1489
1490 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Duncan Sands1df98592010-02-16 11:11:14 +00001491 if (SrcVTy->getNumElements() == 1 && !DestTy->isVectorTy()) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001492 Value *Elem =
1493 Builder->CreateExtractElement(Src,
1494 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1495 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
Chris Lattner80f43d32010-01-04 07:53:58 +00001496 }
1497 }
1498
1499 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001500 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
Dan Gohmana5ced592010-04-07 23:22:42 +00001501 // a bitcast to a vector with the same # elts.
Duncan Sands1df98592010-02-16 11:11:14 +00001502 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001503 cast<VectorType>(DestTy)->getNumElements() ==
1504 SVI->getType()->getNumElements() &&
1505 SVI->getType()->getNumElements() ==
1506 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1507 BitCastInst *Tmp;
1508 // If either of the operands is a cast from CI.getType(), then
1509 // evaluating the shuffle in the casted destination's type will allow
1510 // us to eliminate at least one cast.
1511 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1512 Tmp->getOperand(0)->getType() == DestTy) ||
1513 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1514 Tmp->getOperand(0)->getType() == DestTy)) {
1515 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1516 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1517 // Return a new shuffle vector. Use the same element ID's, as we
1518 // know the vector types match #elts.
1519 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner80f43d32010-01-04 07:53:58 +00001520 }
1521 }
1522 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001523
Duncan Sands1df98592010-02-16 11:11:14 +00001524 if (SrcTy->isPointerTy())
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001525 return commonPointerCastTransforms(CI);
1526 return commonCastTransforms(CI);
Chris Lattner80f43d32010-01-04 07:53:58 +00001527}