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