blob: c5ddec8b75138d34b637681c6dfefc1891364701 [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) {
Benjamin Kramer11acaa32010-01-05 20:07:06 +000026 assert(Val->getType()->isInteger(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 Lattner5f0290e2010-01-04 07:54:59 +0000150/// CanEvaluateInDifferentType - Return true if we can take the specified value
151/// and return it as type Ty without inserting any new casts and without
152/// changing the computed value. This is used by code that tries to decide
153/// whether promoting or shrinking integer operations to wider or smaller types
154/// will allow us to eliminate a truncate or extend.
155///
156/// This is a truncation operation if Ty is smaller than V->getType(), or an
157/// extension operation if Ty is larger.
158///
159/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
160/// should return true if trunc(V) can be computed by computing V in the smaller
161/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
162/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
163/// efficiently truncated.
164///
165/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
166/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
167/// the final result.
Chris Lattner94aab492010-01-05 22:30:42 +0000168static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
169 unsigned CastOpc, int &NumCastsRemoved) {
Chris Lattner5f0290e2010-01-04 07:54:59 +0000170 // We can always evaluate constants in another type.
171 if (isa<Constant>(V))
172 return true;
173
174 Instruction *I = dyn_cast<Instruction>(V);
175 if (!I) return false;
176
177 const Type *OrigTy = V->getType();
178
179 // If this is an extension or truncate, we can often eliminate it.
180 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
181 // If this is a cast from the destination type, we can trivially eliminate
182 // it, and this will remove a cast overall.
183 if (I->getOperand(0)->getType() == Ty) {
184 // If the first operand is itself a cast, and is eliminable, do not count
185 // this as an eliminable cast. We would prefer to eliminate those two
186 // casts first.
187 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
188 ++NumCastsRemoved;
189 return true;
190 }
191 }
192
193 // We can't extend or shrink something that has multiple uses: doing so would
194 // require duplicating the instruction in general, which isn't profitable.
195 if (!I->hasOneUse()) return false;
196
197 unsigned Opc = I->getOpcode();
198 switch (Opc) {
199 case Instruction::Add:
200 case Instruction::Sub:
201 case Instruction::Mul:
202 case Instruction::And:
203 case Instruction::Or:
204 case Instruction::Xor:
205 // These operators can all arbitrarily be extended or truncated.
206 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
207 NumCastsRemoved) &&
208 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
209 NumCastsRemoved);
210
211 case Instruction::UDiv:
212 case Instruction::URem: {
213 // UDiv and URem can be truncated if all the truncated bits are zero.
214 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
215 uint32_t BitWidth = Ty->getScalarSizeInBits();
216 if (BitWidth < OrigBitWidth) {
217 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
218 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
219 MaskedValueIsZero(I->getOperand(1), Mask)) {
220 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
221 NumCastsRemoved) &&
222 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
223 NumCastsRemoved);
224 }
225 }
226 break;
227 }
228 case Instruction::Shl:
229 // If we are truncating the result of this SHL, and if it's a shift of a
230 // constant amount, we can always perform a SHL in a smaller type.
231 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
232 uint32_t BitWidth = Ty->getScalarSizeInBits();
233 if (BitWidth < OrigTy->getScalarSizeInBits() &&
234 CI->getLimitedValue(BitWidth) < BitWidth)
235 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
236 NumCastsRemoved);
237 }
238 break;
239 case Instruction::LShr:
240 // If this is a truncate of a logical shr, we can truncate it to a smaller
241 // lshr iff we know that the bits we would otherwise be shifting in are
242 // already zeros.
243 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
244 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
245 uint32_t BitWidth = Ty->getScalarSizeInBits();
246 if (BitWidth < OrigBitWidth &&
247 MaskedValueIsZero(I->getOperand(0),
248 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
249 CI->getLimitedValue(BitWidth) < BitWidth) {
250 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
251 NumCastsRemoved);
252 }
253 }
254 break;
255 case Instruction::ZExt:
256 case Instruction::SExt:
257 case Instruction::Trunc:
258 // If this is the same kind of case as our original (e.g. zext+zext), we
259 // can safely replace it. Note that replacing it does not reduce the number
260 // of casts in the input.
261 if (Opc == CastOpc)
262 return true;
263
264 // sext (zext ty1), ty2 -> zext ty2
265 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
266 return true;
267 break;
268 case Instruction::Select: {
269 SelectInst *SI = cast<SelectInst>(I);
270 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
271 NumCastsRemoved) &&
272 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
273 NumCastsRemoved);
274 }
275 case Instruction::PHI: {
Chris Lattner94aab492010-01-05 22:30:42 +0000276 // We can change a phi if we can change all operands. Note that we never
277 // get into trouble with cyclic PHIs here because we only consider
278 // instructions with a single use.
Chris Lattner5f0290e2010-01-04 07:54:59 +0000279 PHINode *PN = cast<PHINode>(I);
280 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
281 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
282 NumCastsRemoved))
283 return false;
284 return true;
285 }
286 default:
287 // TODO: Can handle more cases here.
288 break;
289 }
290
291 return false;
292}
293
294/// EvaluateInDifferentType - Given an expression that
295/// CanEvaluateInDifferentType returns true for, actually insert the code to
296/// evaluate the expression.
297Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
298 bool isSigned) {
299 if (Constant *C = dyn_cast<Constant>(V))
300 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
301
302 // Otherwise, it must be an instruction.
303 Instruction *I = cast<Instruction>(V);
304 Instruction *Res = 0;
305 unsigned Opc = I->getOpcode();
306 switch (Opc) {
307 case Instruction::Add:
308 case Instruction::Sub:
309 case Instruction::Mul:
310 case Instruction::And:
311 case Instruction::Or:
312 case Instruction::Xor:
313 case Instruction::AShr:
314 case Instruction::LShr:
315 case Instruction::Shl:
316 case Instruction::UDiv:
317 case Instruction::URem: {
318 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
319 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
320 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
321 break;
322 }
323 case Instruction::Trunc:
324 case Instruction::ZExt:
325 case Instruction::SExt:
326 // If the source type of the cast is the type we're trying for then we can
327 // just return the source. There's no need to insert it because it is not
328 // new.
329 if (I->getOperand(0)->getType() == Ty)
330 return I->getOperand(0);
331
332 // Otherwise, must be the same type of cast, so just reinsert a new one.
333 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
334 break;
335 case Instruction::Select: {
336 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
337 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
338 Res = SelectInst::Create(I->getOperand(0), True, False);
339 break;
340 }
341 case Instruction::PHI: {
342 PHINode *OPN = cast<PHINode>(I);
343 PHINode *NPN = PHINode::Create(Ty);
344 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
345 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
346 NPN->addIncoming(V, OPN->getIncomingBlock(i));
347 }
348 Res = NPN;
349 break;
350 }
351 default:
352 // TODO: Can handle more cases here.
353 llvm_unreachable("Unreachable!");
354 break;
355 }
356
357 Res->takeName(I);
358 return InsertNewInstBefore(Res, *I);
359}
Chris Lattner80f43d32010-01-04 07:53:58 +0000360
361
362/// This function is a wrapper around CastInst::isEliminableCastPair. It
363/// simply extracts arguments and returns what that function returns.
364static Instruction::CastOps
365isEliminableCastPair(
366 const CastInst *CI, ///< The first cast instruction
367 unsigned opcode, ///< The opcode of the second cast instruction
368 const Type *DstTy, ///< The target type for the second cast instruction
369 TargetData *TD ///< The target data for pointer size
370) {
371
372 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
373 const Type *MidTy = CI->getType(); // B from above
374
375 // Get the opcodes of the two Cast instructions
376 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
377 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
378
379 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
380 DstTy,
381 TD ? TD->getIntPtrType(CI->getContext()) : 0);
382
383 // We don't want to form an inttoptr or ptrtoint that converts to an integer
384 // type that differs from the pointer size.
385 if ((Res == Instruction::IntToPtr &&
386 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
387 (Res == Instruction::PtrToInt &&
388 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
389 Res = 0;
390
391 return Instruction::CastOps(Res);
392}
393
394/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
395/// in any code being generated. It does not require codegen if V is simple
396/// enough or if the cast can be folded into other casts.
397bool InstCombiner::ValueRequiresCast(Instruction::CastOps opcode,const Value *V,
398 const Type *Ty) {
399 if (V->getType() == Ty || isa<Constant>(V)) return false;
400
401 // If this is another cast that can be eliminated, it isn't codegen either.
402 if (const CastInst *CI = dyn_cast<CastInst>(V))
403 if (isEliminableCastPair(CI, opcode, Ty, TD))
404 return false;
405 return true;
406}
407
408
409/// @brief Implement the transforms common to all CastInst visitors.
410Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
411 Value *Src = CI.getOperand(0);
412
413 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
414 // eliminate it now.
415 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
416 if (Instruction::CastOps opc =
417 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
418 // The first cast (CSrc) is eliminable so we need to fix up or replace
419 // the second cast (CI). CSrc will then have a good chance of being dead.
420 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
421 }
422 }
423
424 // If we are casting a select then fold the cast into the select
425 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
426 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
427 return NV;
428
429 // If we are casting a PHI then fold the cast into the PHI
430 if (isa<PHINode>(Src)) {
431 // We don't do this if this would create a PHI node with an illegal type if
432 // it is currently legal.
433 if (!isa<IntegerType>(Src->getType()) ||
434 !isa<IntegerType>(CI.getType()) ||
435 ShouldChangeType(CI.getType(), Src->getType()))
436 if (Instruction *NV = FoldOpIntoPhi(CI))
437 return NV;
438 }
439
440 return 0;
441}
442
Chris Lattner80f43d32010-01-04 07:53:58 +0000443/// commonIntCastTransforms - This function implements the common transforms
444/// for trunc, zext, and sext.
445Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
446 if (Instruction *Result = commonCastTransforms(CI))
447 return Result;
448
Chris Lattner80f43d32010-01-04 07:53:58 +0000449 // See if we can simplify any instructions used by the LHS whose sole
450 // purpose is to compute bits we don't care about.
451 if (SimplifyDemandedInstructionBits(CI))
452 return &CI;
Chris Lattner274ad682010-01-05 22:07:33 +0000453
Chris Lattner80f43d32010-01-04 07:53:58 +0000454 // If the source isn't an instruction or has more than one use then we
455 // can't do anything more.
Chris Lattner274ad682010-01-05 22:07:33 +0000456 Instruction *Src = dyn_cast<Instruction>(CI.getOperand(0));
457 if (!Src || !Src->hasOneUse())
Chris Lattner80f43d32010-01-04 07:53:58 +0000458 return 0;
Chris Lattner274ad682010-01-05 22:07:33 +0000459
460 const Type *SrcTy = Src->getType();
461 const Type *DestTy = CI.getType();
462 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
463 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Chris Lattner80f43d32010-01-04 07:53:58 +0000464
465 // Attempt to propagate the cast into the instruction for int->int casts.
466 int NumCastsRemoved = 0;
467 // Only do this if the dest type is a simple type, don't convert the
468 // expression tree to something weird like i93 unless the source is also
469 // strange.
470 if ((isa<VectorType>(DestTy) ||
Chris Lattner274ad682010-01-05 22:07:33 +0000471 ShouldChangeType(Src->getType(), DestTy)) &&
472 CanEvaluateInDifferentType(Src, DestTy,
Chris Lattner80f43d32010-01-04 07:53:58 +0000473 CI.getOpcode(), NumCastsRemoved)) {
474 // If this cast is a truncate, evaluting in a different type always
475 // eliminates the cast, so it is always a win. If this is a zero-extension,
476 // we need to do an AND to maintain the clear top-part of the computation,
477 // so we require that the input have eliminated at least one cast. If this
478 // is a sign extension, we insert two new casts (to do the extension) so we
479 // require that two casts have been eliminated.
480 bool DoXForm = false;
481 bool JustReplace = false;
482 switch (CI.getOpcode()) {
483 default:
484 // All the others use floating point so we shouldn't actually
485 // get here because of the check above.
486 llvm_unreachable("Unknown cast type");
487 case Instruction::Trunc:
488 DoXForm = true;
489 break;
490 case Instruction::ZExt: {
491 DoXForm = NumCastsRemoved >= 1;
492
493 if (!DoXForm && 0) {
494 // If it's unnecessary to issue an AND to clear the high bits, it's
495 // always profitable to do this xform.
Chris Lattner274ad682010-01-05 22:07:33 +0000496 Value *TryRes = EvaluateInDifferentType(Src, DestTy, false);
Chris Lattner80f43d32010-01-04 07:53:58 +0000497 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
498 if (MaskedValueIsZero(TryRes, Mask))
499 return ReplaceInstUsesWith(CI, TryRes);
500
501 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
502 if (TryI->use_empty())
503 EraseInstFromFunction(*TryI);
504 }
505 break;
506 }
507 case Instruction::SExt: {
508 DoXForm = NumCastsRemoved >= 2;
Chris Lattner274ad682010-01-05 22:07:33 +0000509 if (!DoXForm && !isa<TruncInst>(Src) && 0) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000510 // If we do not have to emit the truncate + sext pair, then it's always
511 // profitable to do this xform.
512 //
513 // It's not safe to eliminate the trunc + sext pair if one of the
514 // eliminated cast is a truncate. e.g.
515 // t2 = trunc i32 t1 to i16
516 // t3 = sext i16 t2 to i32
517 // !=
518 // i32 t1
Chris Lattner274ad682010-01-05 22:07:33 +0000519 Value *TryRes = EvaluateInDifferentType(Src, DestTy, true);
Chris Lattner80f43d32010-01-04 07:53:58 +0000520 unsigned NumSignBits = ComputeNumSignBits(TryRes);
521 if (NumSignBits > (DestBitSize - SrcBitSize))
522 return ReplaceInstUsesWith(CI, TryRes);
523
524 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
525 if (TryI->use_empty())
526 EraseInstFromFunction(*TryI);
527 }
528 break;
529 }
530 }
531
532 if (DoXForm) {
533 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
534 " to avoid cast: " << CI);
Chris Lattner274ad682010-01-05 22:07:33 +0000535 Value *Res = EvaluateInDifferentType(Src, DestTy,
Chris Lattner80f43d32010-01-04 07:53:58 +0000536 CI.getOpcode() == Instruction::SExt);
537 if (JustReplace)
538 // Just replace this cast with the result.
539 return ReplaceInstUsesWith(CI, Res);
540
541 assert(Res->getType() == DestTy);
542 switch (CI.getOpcode()) {
543 default: llvm_unreachable("Unknown cast type!");
544 case Instruction::Trunc:
545 // Just replace this cast with the result.
546 return ReplaceInstUsesWith(CI, Res);
547 case Instruction::ZExt: {
548 assert(SrcBitSize < DestBitSize && "Not a zext?");
549
550 // If the high bits are already zero, just replace this cast with the
551 // result.
552 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
553 if (MaskedValueIsZero(Res, Mask))
554 return ReplaceInstUsesWith(CI, Res);
555
556 // We need to emit an AND to clear the high bits.
557 Constant *C = ConstantInt::get(CI.getContext(),
558 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
559 return BinaryOperator::CreateAnd(Res, C);
560 }
561 case Instruction::SExt: {
562 // If the high bits are already filled with sign bit, just replace this
563 // cast with the result.
564 unsigned NumSignBits = ComputeNumSignBits(Res);
565 if (NumSignBits > (DestBitSize - SrcBitSize))
566 return ReplaceInstUsesWith(CI, Res);
567
568 // We need to emit a cast to truncate, then a cast to sext.
569 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
570 }
571 }
572 }
573 }
574
Chris Lattner80f43d32010-01-04 07:53:58 +0000575 return 0;
576}
577
Chris Lattner80f43d32010-01-04 07:53:58 +0000578Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
579 if (Instruction *Result = commonIntCastTransforms(CI))
580 return Result;
581
582 Value *Src = CI.getOperand(0);
Chris Lattner49bdfef2010-01-05 21:11:17 +0000583 const Type *DestTy = CI.getType();
Chris Lattner80f43d32010-01-04 07:53:58 +0000584
Chris Lattner7a34d6c2010-01-05 22:21:18 +0000585 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
586 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000587 Constant *One = ConstantInt::get(Src->getType(), 1);
588 Src = Builder->CreateAnd(Src, One, "tmp");
589 Value *Zero = Constant::getNullValue(Src->getType());
590 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
591 }
592
Chris Lattner80f43d32010-01-04 07:53:58 +0000593 return 0;
594}
595
596/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
597/// in order to eliminate the icmp.
598Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
599 bool DoXform) {
600 // If we are just checking for a icmp eq of a single bit and zext'ing it
601 // to an integer, then shift the bit to the appropriate place and then
602 // cast to integer to avoid the comparison.
603 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
604 const APInt &Op1CV = Op1C->getValue();
605
606 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
607 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
608 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
609 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
610 if (!DoXform) return ICI;
611
612 Value *In = ICI->getOperand(0);
613 Value *Sh = ConstantInt::get(In->getType(),
614 In->getType()->getScalarSizeInBits()-1);
615 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
616 if (In->getType() != CI.getType())
617 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
618
619 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
620 Constant *One = ConstantInt::get(In->getType(), 1);
621 In = Builder->CreateXor(In, One, In->getName()+".not");
622 }
623
624 return ReplaceInstUsesWith(CI, In);
625 }
626
627
628
629 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
630 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
631 // zext (X == 1) to i32 --> X iff X has only the low bit set.
632 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
633 // zext (X != 0) to i32 --> X iff X has only the low bit set.
634 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
635 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
636 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
637 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
638 // This only works for EQ and NE
639 ICI->isEquality()) {
640 // If Op1C some other power of two, convert:
641 uint32_t BitWidth = Op1C->getType()->getBitWidth();
642 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
643 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
644 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
645
646 APInt KnownZeroMask(~KnownZero);
647 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
648 if (!DoXform) return ICI;
649
650 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
651 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
652 // (X&4) == 2 --> false
653 // (X&4) != 2 --> true
654 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
655 isNE);
656 Res = ConstantExpr::getZExt(Res, CI.getType());
657 return ReplaceInstUsesWith(CI, Res);
658 }
659
660 uint32_t ShiftAmt = KnownZeroMask.logBase2();
661 Value *In = ICI->getOperand(0);
662 if (ShiftAmt) {
663 // Perform a logical shr by shiftamt.
664 // Insert the shift to put the result in the low bit.
665 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
666 In->getName()+".lobit");
667 }
668
669 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
670 Constant *One = ConstantInt::get(In->getType(), 1);
671 In = Builder->CreateXor(In, One, "tmp");
672 }
673
674 if (CI.getType() == In->getType())
675 return ReplaceInstUsesWith(CI, In);
676 else
677 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
678 }
679 }
680 }
681
682 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
683 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
684 // may lead to additional simplifications.
685 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
686 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
687 uint32_t BitWidth = ITy->getBitWidth();
688 Value *LHS = ICI->getOperand(0);
689 Value *RHS = ICI->getOperand(1);
690
691 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
692 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
693 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
694 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
695 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
696
697 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
698 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
699 APInt UnknownBit = ~KnownBits;
700 if (UnknownBit.countPopulation() == 1) {
701 if (!DoXform) return ICI;
702
703 Value *Result = Builder->CreateXor(LHS, RHS);
704
705 // Mask off any bits that are set and won't be shifted away.
706 if (KnownOneLHS.uge(UnknownBit))
707 Result = Builder->CreateAnd(Result,
708 ConstantInt::get(ITy, UnknownBit));
709
710 // Shift the bit we're testing down to the lsb.
711 Result = Builder->CreateLShr(
712 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
713
714 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
715 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
716 Result->takeName(ICI);
717 return ReplaceInstUsesWith(CI, Result);
718 }
719 }
720 }
721 }
722
723 return 0;
724}
725
726Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
727 // If one of the common conversion will work, do it.
728 if (Instruction *Result = commonIntCastTransforms(CI))
729 return Result;
730
731 Value *Src = CI.getOperand(0);
732
733 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
734 // types and if the sizes are just right we can convert this into a logical
735 // 'and' which will be much cheaper than the pair of casts.
736 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
737 // Get the sizes of the types involved. We know that the intermediate type
738 // will be smaller than A or C, but don't know the relation between A and C.
739 Value *A = CSrc->getOperand(0);
740 unsigned SrcSize = A->getType()->getScalarSizeInBits();
741 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
742 unsigned DstSize = CI.getType()->getScalarSizeInBits();
743 // If we're actually extending zero bits, then if
744 // SrcSize < DstSize: zext(a & mask)
745 // SrcSize == DstSize: a & mask
746 // SrcSize > DstSize: trunc(a) & mask
747 if (SrcSize < DstSize) {
748 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
749 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
750 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
751 return new ZExtInst(And, CI.getType());
752 }
753
754 if (SrcSize == DstSize) {
755 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
756 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
757 AndValue));
758 }
759 if (SrcSize > DstSize) {
760 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
761 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
762 return BinaryOperator::CreateAnd(Trunc,
763 ConstantInt::get(Trunc->getType(),
764 AndValue));
765 }
766 }
767
768 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
769 return transformZExtICmp(ICI, CI);
770
771 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
772 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
773 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
774 // of the (zext icmp) will be transformed.
775 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
776 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
777 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
778 (transformZExtICmp(LHS, CI, false) ||
779 transformZExtICmp(RHS, CI, false))) {
780 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
781 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
782 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
783 }
784 }
785
786 // zext(trunc(t) & C) -> (t & zext(C)).
787 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
788 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
789 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
790 Value *TI0 = TI->getOperand(0);
791 if (TI0->getType() == CI.getType())
792 return
793 BinaryOperator::CreateAnd(TI0,
794 ConstantExpr::getZExt(C, CI.getType()));
795 }
796
797 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
798 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
799 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
800 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
801 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
802 And->getOperand(1) == C)
803 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
804 Value *TI0 = TI->getOperand(0);
805 if (TI0->getType() == CI.getType()) {
806 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
807 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
808 return BinaryOperator::CreateXor(NewAnd, ZC);
809 }
810 }
811
Chris Lattner718bf3f2010-01-05 21:04:47 +0000812 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
813 Value *X;
Chris Lattner49bdfef2010-01-05 21:11:17 +0000814 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isInteger(1) &&
815 match(SrcI, m_Not(m_Value(X))) &&
Chris Lattner718bf3f2010-01-05 21:04:47 +0000816 (!X->hasOneUse() || !isa<CmpInst>(X))) {
817 Value *New = Builder->CreateZExt(X, CI.getType());
818 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
819 }
820
Chris Lattner80f43d32010-01-04 07:53:58 +0000821 return 0;
822}
823
824Instruction *InstCombiner::visitSExt(SExtInst &CI) {
825 if (Instruction *I = commonIntCastTransforms(CI))
826 return I;
827
828 Value *Src = CI.getOperand(0);
829
830 // Canonicalize sign-extend from i1 to a select.
Benjamin Kramer11acaa32010-01-05 20:07:06 +0000831 if (Src->getType()->isInteger(1))
Chris Lattner80f43d32010-01-04 07:53:58 +0000832 return SelectInst::Create(Src,
833 Constant::getAllOnesValue(CI.getType()),
834 Constant::getNullValue(CI.getType()));
835
836 // See if the value being truncated is already sign extended. If so, just
837 // eliminate the trunc/sext pair.
838 if (Operator::getOpcode(Src) == Instruction::Trunc) {
839 Value *Op = cast<User>(Src)->getOperand(0);
840 unsigned OpBits = Op->getType()->getScalarSizeInBits();
841 unsigned MidBits = Src->getType()->getScalarSizeInBits();
842 unsigned DestBits = CI.getType()->getScalarSizeInBits();
843 unsigned NumSignBits = ComputeNumSignBits(Op);
844
845 if (OpBits == DestBits) {
846 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
847 // bits, it is already ready.
848 if (NumSignBits > DestBits-MidBits)
849 return ReplaceInstUsesWith(CI, Op);
850 } else if (OpBits < DestBits) {
851 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
852 // bits, just sext from i32.
853 if (NumSignBits > OpBits-MidBits)
854 return new SExtInst(Op, CI.getType(), "tmp");
855 } else {
856 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
857 // bits, just truncate to i32.
858 if (NumSignBits > OpBits-MidBits)
859 return new TruncInst(Op, CI.getType(), "tmp");
860 }
861 }
862
863 // If the input is a shl/ashr pair of a same constant, then this is a sign
864 // extension from a smaller value. If we could trust arbitrary bitwidth
865 // integers, we could turn this into a truncate to the smaller bit and then
866 // use a sext for the whole extension. Since we don't, look deeper and check
867 // for a truncate. If the source and dest are the same type, eliminate the
868 // trunc and extend and just do shifts. For example, turn:
869 // %a = trunc i32 %i to i8
870 // %b = shl i8 %a, 6
871 // %c = ashr i8 %b, 6
872 // %d = sext i8 %c to i32
873 // into:
874 // %a = shl i32 %i, 30
875 // %d = ashr i32 %a, 30
876 Value *A = 0;
877 ConstantInt *BA = 0, *CA = 0;
878 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
879 m_ConstantInt(CA))) &&
880 BA == CA && isa<TruncInst>(A)) {
881 Value *I = cast<TruncInst>(A)->getOperand(0);
882 if (I->getType() == CI.getType()) {
883 unsigned MidSize = Src->getType()->getScalarSizeInBits();
884 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
885 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
886 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
887 I = Builder->CreateShl(I, ShAmtV, CI.getName());
888 return BinaryOperator::CreateAShr(I, ShAmtV);
889 }
890 }
891
892 return 0;
893}
894
895
896/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
897/// in the specified FP type without changing its value.
898static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
899 bool losesInfo;
900 APFloat F = CFP->getValueAPF();
901 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
902 if (!losesInfo)
903 return ConstantFP::get(CFP->getContext(), F);
904 return 0;
905}
906
907/// LookThroughFPExtensions - If this is an fp extension instruction, look
908/// through it until we get the source value.
909static Value *LookThroughFPExtensions(Value *V) {
910 if (Instruction *I = dyn_cast<Instruction>(V))
911 if (I->getOpcode() == Instruction::FPExt)
912 return LookThroughFPExtensions(I->getOperand(0));
913
914 // If this value is a constant, return the constant in the smallest FP type
915 // that can accurately represent it. This allows us to turn
916 // (float)((double)X+2.0) into x+2.0f.
917 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
918 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
919 return V; // No constant folding of this.
920 // See if the value can be truncated to float and then reextended.
921 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
922 return V;
Benjamin Kramerf0127052010-01-05 13:12:22 +0000923 if (CFP->getType()->isDoubleTy())
Chris Lattner80f43d32010-01-04 07:53:58 +0000924 return V; // Won't shrink.
925 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
926 return V;
927 // Don't try to shrink to various long double types.
928 }
929
930 return V;
931}
932
933Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
934 if (Instruction *I = commonCastTransforms(CI))
935 return I;
936
937 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
938 // smaller than the destination type, we can eliminate the truncate by doing
939 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
940 // as many builtins (sqrt, etc).
941 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
942 if (OpI && OpI->hasOneUse()) {
943 switch (OpI->getOpcode()) {
944 default: break;
945 case Instruction::FAdd:
946 case Instruction::FSub:
947 case Instruction::FMul:
948 case Instruction::FDiv:
949 case Instruction::FRem:
950 const Type *SrcTy = OpI->getType();
951 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
952 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
953 if (LHSTrunc->getType() != SrcTy &&
954 RHSTrunc->getType() != SrcTy) {
955 unsigned DstSize = CI.getType()->getScalarSizeInBits();
956 // If the source types were both smaller than the destination type of
957 // the cast, do this xform.
958 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
959 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
960 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
961 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
962 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
963 }
964 }
965 break;
966 }
967 }
968 return 0;
969}
970
971Instruction *InstCombiner::visitFPExt(CastInst &CI) {
972 return commonCastTransforms(CI);
973}
974
975Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
976 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
977 if (OpI == 0)
978 return commonCastTransforms(FI);
979
980 // fptoui(uitofp(X)) --> X
981 // fptoui(sitofp(X)) --> X
982 // This is safe if the intermediate type has enough bits in its mantissa to
983 // accurately represent all values of X. For example, do not do this with
984 // i64->float->i64. This is also safe for sitofp case, because any negative
985 // 'X' value would cause an undefined result for the fptoui.
986 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
987 OpI->getOperand(0)->getType() == FI.getType() &&
988 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
989 OpI->getType()->getFPMantissaWidth())
990 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
991
992 return commonCastTransforms(FI);
993}
994
995Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
996 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
997 if (OpI == 0)
998 return commonCastTransforms(FI);
999
1000 // fptosi(sitofp(X)) --> X
1001 // fptosi(uitofp(X)) --> X
1002 // This is safe if the intermediate type has enough bits in its mantissa to
1003 // accurately represent all values of X. For example, do not do this with
1004 // i64->float->i64. This is also safe for sitofp case, because any negative
1005 // 'X' value would cause an undefined result for the fptoui.
1006 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1007 OpI->getOperand(0)->getType() == FI.getType() &&
1008 (int)FI.getType()->getScalarSizeInBits() <=
1009 OpI->getType()->getFPMantissaWidth())
1010 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1011
1012 return commonCastTransforms(FI);
1013}
1014
1015Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1016 return commonCastTransforms(CI);
1017}
1018
1019Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1020 return commonCastTransforms(CI);
1021}
1022
Chris Lattner80f43d32010-01-04 07:53:58 +00001023Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1024 // If the source integer type is larger than the intptr_t type for
1025 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
1026 // allows the trunc to be exposed to other transforms. Don't do this for
1027 // extending inttoptr's, because we don't know if the target sign or zero
1028 // extends to pointers.
1029 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
1030 TD->getPointerSizeInBits()) {
1031 Value *P = Builder->CreateTrunc(CI.getOperand(0),
1032 TD->getIntPtrType(CI.getContext()), "tmp");
1033 return new IntToPtrInst(P, CI.getType());
1034 }
1035
1036 if (Instruction *I = commonCastTransforms(CI))
1037 return I;
1038
1039 return 0;
1040}
1041
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001042/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1043Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1044 Value *Src = CI.getOperand(0);
1045
1046 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1047 // If casting the result of a getelementptr instruction with no offset, turn
1048 // this into a cast of the original pointer!
1049 if (GEP->hasAllZeroIndices()) {
1050 // Changing the cast operand is usually not a good idea but it is safe
1051 // here because the pointer operand is being replaced with another
1052 // pointer operand so the opcode doesn't need to change.
1053 Worklist.Add(GEP);
1054 CI.setOperand(0, GEP->getOperand(0));
1055 return &CI;
1056 }
1057
1058 // If the GEP has a single use, and the base pointer is a bitcast, and the
1059 // GEP computes a constant offset, see if we can convert these three
1060 // instructions into fewer. This typically happens with unions and other
1061 // non-type-safe code.
1062 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1063 GEP->hasAllConstantIndices()) {
1064 // We are guaranteed to get a constant from EmitGEPOffset.
1065 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1066 int64_t Offset = OffsetV->getSExtValue();
1067
1068 // Get the base pointer input of the bitcast, and the type it points to.
1069 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1070 const Type *GEPIdxTy =
1071 cast<PointerType>(OrigBase->getType())->getElementType();
1072 SmallVector<Value*, 8> NewIndices;
1073 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1074 // If we were able to index down into an element, create the GEP
1075 // and bitcast the result. This eliminates one bitcast, potentially
1076 // two.
1077 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1078 Builder->CreateInBoundsGEP(OrigBase,
1079 NewIndices.begin(), NewIndices.end()) :
1080 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1081 NGEP->takeName(GEP);
1082
1083 if (isa<BitCastInst>(CI))
1084 return new BitCastInst(NGEP, CI.getType());
1085 assert(isa<PtrToIntInst>(CI));
1086 return new PtrToIntInst(NGEP, CI.getType());
1087 }
1088 }
1089 }
1090
1091 return commonCastTransforms(CI);
1092}
1093
1094Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1095 // If the destination integer type is smaller than the intptr_t type for
1096 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
1097 // trunc to be exposed to other transforms. Don't do this for extending
1098 // ptrtoint's, because we don't know if the target sign or zero extends its
1099 // pointers.
1100 if (TD &&
1101 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1102 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1103 TD->getIntPtrType(CI.getContext()),
1104 "tmp");
1105 return new TruncInst(P, CI.getType());
1106 }
1107
1108 return commonPointerCastTransforms(CI);
1109}
1110
Chris Lattner80f43d32010-01-04 07:53:58 +00001111Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1112 // If the operands are integer typed then apply the integer transforms,
1113 // otherwise just apply the common ones.
1114 Value *Src = CI.getOperand(0);
1115 const Type *SrcTy = Src->getType();
1116 const Type *DestTy = CI.getType();
1117
Chris Lattner80f43d32010-01-04 07:53:58 +00001118 // Get rid of casts from one type to the same type. These are useless and can
1119 // be replaced by the operand.
1120 if (DestTy == Src->getType())
1121 return ReplaceInstUsesWith(CI, Src);
1122
1123 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1124 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1125 const Type *DstElTy = DstPTy->getElementType();
1126 const Type *SrcElTy = SrcPTy->getElementType();
1127
1128 // If the address spaces don't match, don't eliminate the bitcast, which is
1129 // required for changing types.
1130 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1131 return 0;
1132
1133 // If we are casting a alloca to a pointer to a type of the same
1134 // size, rewrite the allocation instruction to allocate the "right" type.
1135 // There is no need to modify malloc calls because it is their bitcast that
1136 // needs to be cleaned up.
1137 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1138 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1139 return V;
1140
1141 // If the source and destination are pointers, and this cast is equivalent
1142 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1143 // This can enhance SROA and other transforms that want type-safe pointers.
1144 Constant *ZeroUInt =
1145 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1146 unsigned NumZeros = 0;
1147 while (SrcElTy != DstElTy &&
1148 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
1149 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1150 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1151 ++NumZeros;
1152 }
1153
1154 // If we found a path from the src to dest, create the getelementptr now.
1155 if (SrcElTy == DstElTy) {
1156 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1157 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001158 ((Instruction*)NULL));
Chris Lattner80f43d32010-01-04 07:53:58 +00001159 }
1160 }
1161
1162 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001163 if (DestVTy->getNumElements() == 1 && !isa<VectorType>(SrcTy)) {
1164 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1165 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner80f43d32010-01-04 07:53:58 +00001166 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner80f43d32010-01-04 07:53:58 +00001167 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1168 }
1169 }
1170
1171 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001172 if (SrcVTy->getNumElements() == 1 && !isa<VectorType>(DestTy)) {
1173 Value *Elem =
1174 Builder->CreateExtractElement(Src,
1175 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1176 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
Chris Lattner80f43d32010-01-04 07:53:58 +00001177 }
1178 }
1179
1180 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001181 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
1182 // a bitconvert to a vector with the same # elts.
1183 if (SVI->hasOneUse() && isa<VectorType>(DestTy) &&
1184 cast<VectorType>(DestTy)->getNumElements() ==
1185 SVI->getType()->getNumElements() &&
1186 SVI->getType()->getNumElements() ==
1187 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1188 BitCastInst *Tmp;
1189 // If either of the operands is a cast from CI.getType(), then
1190 // evaluating the shuffle in the casted destination's type will allow
1191 // us to eliminate at least one cast.
1192 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1193 Tmp->getOperand(0)->getType() == DestTy) ||
1194 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1195 Tmp->getOperand(0)->getType() == DestTy)) {
1196 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1197 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1198 // Return a new shuffle vector. Use the same element ID's, as we
1199 // know the vector types match #elts.
1200 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner80f43d32010-01-04 07:53:58 +00001201 }
1202 }
1203 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001204
1205 if (isa<PointerType>(SrcTy))
1206 return commonPointerCastTransforms(CI);
1207 return commonCastTransforms(CI);
Chris Lattner80f43d32010-01-04 07:53:58 +00001208}