1 //===- InstCombineCasts.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visit functions for cast operations.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Target/TargetData.h"
16 #include "llvm/Support/PatternMatch.h"
18 using namespace PatternMatch;
20 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
21 /// expression. If so, decompose it, returning some value X, such that Val is
24 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
26 assert(Val->getType()->isIntegerTy(32) && "Unexpected allocation size type!");
27 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
28 Offset = CI->getZExtValue();
30 return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
33 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
34 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();
39 return I->getOperand(0);
42 if (I->getOpcode() == Instruction::Mul) {
43 // This value is scaled by 'RHS'.
44 Scale = RHS->getZExtValue();
46 return I->getOperand(0);
49 if (I->getOpcode() == Instruction::Add) {
50 // We have X+C. Check to see if we really have (X*C2)+C1,
51 // where C1 is divisible by C2.
54 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
55 Offset += RHS->getZExtValue();
62 // Otherwise, we can't look past this.
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.
70 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
72 // This requires TargetData to get the alloca alignment and size information.
75 const PointerType *PTy = cast<PointerType>(CI.getType());
77 BuilderTy AllocaBuilder(*Builder);
78 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
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;
85 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
86 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
87 if (CastElTyAlign < AllocElTyAlign) return 0;
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;
96 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
97 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
98 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
100 // See if we can satisfy the modulus by pulling a scale out of the array
102 unsigned ArraySizeScale;
104 Value *NumElements = // See if the array size is a decomposable linear expr.
105 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
107 // If we can now satisfy the modulus, by using a non-1 scale, we really can
109 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
110 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
112 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
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");
122 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
123 Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
125 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
128 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
129 New->setAlignment(AI.getAlignment());
132 // If the allocation has one real use plus a dbg.declare, just remove the
134 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
135 EraseInstFromFunction(*(Instruction*)DI);
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
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);
146 return ReplaceInstUsesWith(CI, New);
151 /// EvaluateInDifferentType - Given an expression that
152 /// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
153 /// insert the code to evaluate the expression.
154 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
156 if (Constant *C = dyn_cast<Constant>(V)) {
157 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
158 // If we got a constantexpr back, try to simplify it with TD info.
159 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
160 C = ConstantFoldConstantExpression(CE, TD);
164 // Otherwise, it must be an instruction.
165 Instruction *I = cast<Instruction>(V);
166 Instruction *Res = 0;
167 unsigned Opc = I->getOpcode();
169 case Instruction::Add:
170 case Instruction::Sub:
171 case Instruction::Mul:
172 case Instruction::And:
173 case Instruction::Or:
174 case Instruction::Xor:
175 case Instruction::AShr:
176 case Instruction::LShr:
177 case Instruction::Shl:
178 case Instruction::UDiv:
179 case Instruction::URem: {
180 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
181 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
182 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
185 case Instruction::Trunc:
186 case Instruction::ZExt:
187 case Instruction::SExt:
188 // If the source type of the cast is the type we're trying for then we can
189 // just return the source. There's no need to insert it because it is not
191 if (I->getOperand(0)->getType() == Ty)
192 return I->getOperand(0);
194 // Otherwise, must be the same type of cast, so just reinsert a new one.
195 // This also handles the case of zext(trunc(x)) -> zext(x).
196 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
197 Opc == Instruction::SExt);
199 case Instruction::Select: {
200 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
201 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
202 Res = SelectInst::Create(I->getOperand(0), True, False);
205 case Instruction::PHI: {
206 PHINode *OPN = cast<PHINode>(I);
207 PHINode *NPN = PHINode::Create(Ty);
208 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
209 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
210 NPN->addIncoming(V, OPN->getIncomingBlock(i));
216 // TODO: Can handle more cases here.
217 llvm_unreachable("Unreachable!");
222 return InsertNewInstBefore(Res, *I);
226 /// This function is a wrapper around CastInst::isEliminableCastPair. It
227 /// simply extracts arguments and returns what that function returns.
228 static Instruction::CastOps
229 isEliminableCastPair(
230 const CastInst *CI, ///< The first cast instruction
231 unsigned opcode, ///< The opcode of the second cast instruction
232 const Type *DstTy, ///< The target type for the second cast instruction
233 TargetData *TD ///< The target data for pointer size
236 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
237 const Type *MidTy = CI->getType(); // B from above
239 // Get the opcodes of the two Cast instructions
240 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
241 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
243 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
245 TD ? TD->getIntPtrType(CI->getContext()) : 0);
247 // We don't want to form an inttoptr or ptrtoint that converts to an integer
248 // type that differs from the pointer size.
249 if ((Res == Instruction::IntToPtr &&
250 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
251 (Res == Instruction::PtrToInt &&
252 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
255 return Instruction::CastOps(Res);
258 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
259 /// results in any code being generated and is interesting to optimize out. If
260 /// the cast can be eliminated by some other simple transformation, we prefer
261 /// to do the simplification first.
262 bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
264 // Noop casts and casts of constants should be eliminated trivially.
265 if (V->getType() == Ty || isa<Constant>(V)) return false;
267 // If this is another cast that can be eliminated, we prefer to have it
269 if (const CastInst *CI = dyn_cast<CastInst>(V))
270 if (isEliminableCastPair(CI, opc, Ty, TD))
273 // If this is a vector sext from a compare, then we don't want to break the
274 // idiom where each element of the extended vector is either zero or all ones.
275 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
282 /// @brief Implement the transforms common to all CastInst visitors.
283 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
284 Value *Src = CI.getOperand(0);
286 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
288 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
289 if (Instruction::CastOps opc =
290 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
291 // The first cast (CSrc) is eliminable so we need to fix up or replace
292 // the second cast (CI). CSrc will then have a good chance of being dead.
293 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
297 // If we are casting a select then fold the cast into the select
298 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
299 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
302 // If we are casting a PHI then fold the cast into the PHI
303 if (isa<PHINode>(Src)) {
304 // We don't do this if this would create a PHI node with an illegal type if
305 // it is currently legal.
306 if (!Src->getType()->isIntegerTy() ||
307 !CI.getType()->isIntegerTy() ||
308 ShouldChangeType(CI.getType(), Src->getType()))
309 if (Instruction *NV = FoldOpIntoPhi(CI))
316 /// CanEvaluateTruncated - Return true if we can evaluate the specified
317 /// expression tree as type Ty instead of its larger type, and arrive with the
318 /// same value. This is used by code that tries to eliminate truncates.
320 /// Ty will always be a type smaller than V. We should return true if trunc(V)
321 /// can be computed by computing V in the smaller type. If V is an instruction,
322 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
323 /// makes sense if x and y can be efficiently truncated.
325 /// This function works on both vectors and scalars.
327 static bool CanEvaluateTruncated(Value *V, const Type *Ty) {
328 // We can always evaluate constants in another type.
329 if (isa<Constant>(V))
332 Instruction *I = dyn_cast<Instruction>(V);
333 if (!I) return false;
335 const Type *OrigTy = V->getType();
337 // If this is an extension from the dest type, we can eliminate it, even if it
338 // has multiple uses.
339 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
340 I->getOperand(0)->getType() == Ty)
343 // We can't extend or shrink something that has multiple uses: doing so would
344 // require duplicating the instruction in general, which isn't profitable.
345 if (!I->hasOneUse()) return false;
347 unsigned Opc = I->getOpcode();
349 case Instruction::Add:
350 case Instruction::Sub:
351 case Instruction::Mul:
352 case Instruction::And:
353 case Instruction::Or:
354 case Instruction::Xor:
355 // These operators can all arbitrarily be extended or truncated.
356 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
357 CanEvaluateTruncated(I->getOperand(1), Ty);
359 case Instruction::UDiv:
360 case Instruction::URem: {
361 // UDiv and URem can be truncated if all the truncated bits are zero.
362 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
363 uint32_t BitWidth = Ty->getScalarSizeInBits();
364 if (BitWidth < OrigBitWidth) {
365 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
366 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
367 MaskedValueIsZero(I->getOperand(1), Mask)) {
368 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
369 CanEvaluateTruncated(I->getOperand(1), Ty);
374 case Instruction::Shl:
375 // If we are truncating the result of this SHL, and if it's a shift of a
376 // constant amount, we can always perform a SHL in a smaller type.
377 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
378 uint32_t BitWidth = Ty->getScalarSizeInBits();
379 if (CI->getLimitedValue(BitWidth) < BitWidth)
380 return CanEvaluateTruncated(I->getOperand(0), Ty);
383 case Instruction::LShr:
384 // If this is a truncate of a logical shr, we can truncate it to a smaller
385 // lshr iff we know that the bits we would otherwise be shifting in are
387 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
388 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
389 uint32_t BitWidth = Ty->getScalarSizeInBits();
390 if (MaskedValueIsZero(I->getOperand(0),
391 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
392 CI->getLimitedValue(BitWidth) < BitWidth) {
393 return CanEvaluateTruncated(I->getOperand(0), Ty);
397 case Instruction::Trunc:
398 // trunc(trunc(x)) -> trunc(x)
400 case Instruction::Select: {
401 SelectInst *SI = cast<SelectInst>(I);
402 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
403 CanEvaluateTruncated(SI->getFalseValue(), Ty);
405 case Instruction::PHI: {
406 // We can change a phi if we can change all operands. Note that we never
407 // get into trouble with cyclic PHIs here because we only consider
408 // instructions with a single use.
409 PHINode *PN = cast<PHINode>(I);
410 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
411 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
416 // TODO: Can handle more cases here.
423 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
424 if (Instruction *Result = commonCastTransforms(CI))
427 // See if we can simplify any instructions used by the input whose sole
428 // purpose is to compute bits we don't care about.
429 if (SimplifyDemandedInstructionBits(CI))
432 Value *Src = CI.getOperand(0);
433 const Type *DestTy = CI.getType(), *SrcTy = Src->getType();
435 // Attempt to truncate the entire input expression tree to the destination
436 // type. Only do this if the dest type is a simple type, don't convert the
437 // expression tree to something weird like i93 unless the source is also
439 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
440 CanEvaluateTruncated(Src, DestTy)) {
442 // If this cast is a truncate, evaluting in a different type always
443 // eliminates the cast, so it is always a win.
444 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
445 " to avoid cast: " << CI);
446 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
447 assert(Res->getType() == DestTy);
448 return ReplaceInstUsesWith(CI, Res);
451 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
452 if (DestTy->getScalarSizeInBits() == 1) {
453 Constant *One = ConstantInt::get(Src->getType(), 1);
454 Src = Builder->CreateAnd(Src, One, "tmp");
455 Value *Zero = Constant::getNullValue(Src->getType());
456 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
462 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
463 /// in order to eliminate the icmp.
464 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
466 // If we are just checking for a icmp eq of a single bit and zext'ing it
467 // to an integer, then shift the bit to the appropriate place and then
468 // cast to integer to avoid the comparison.
469 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
470 const APInt &Op1CV = Op1C->getValue();
472 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
473 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
474 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
475 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
476 if (!DoXform) return ICI;
478 Value *In = ICI->getOperand(0);
479 Value *Sh = ConstantInt::get(In->getType(),
480 In->getType()->getScalarSizeInBits()-1);
481 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
482 if (In->getType() != CI.getType())
483 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
485 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
486 Constant *One = ConstantInt::get(In->getType(), 1);
487 In = Builder->CreateXor(In, One, In->getName()+".not");
490 return ReplaceInstUsesWith(CI, In);
495 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
496 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
497 // zext (X == 1) to i32 --> X iff X has only the low bit set.
498 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
499 // zext (X != 0) to i32 --> X iff X has only the low bit set.
500 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
501 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
502 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
503 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
504 // This only works for EQ and NE
506 // If Op1C some other power of two, convert:
507 uint32_t BitWidth = Op1C->getType()->getBitWidth();
508 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
509 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
510 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
512 APInt KnownZeroMask(~KnownZero);
513 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
514 if (!DoXform) return ICI;
516 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
517 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
518 // (X&4) == 2 --> false
519 // (X&4) != 2 --> true
520 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
522 Res = ConstantExpr::getZExt(Res, CI.getType());
523 return ReplaceInstUsesWith(CI, Res);
526 uint32_t ShiftAmt = KnownZeroMask.logBase2();
527 Value *In = ICI->getOperand(0);
529 // Perform a logical shr by shiftamt.
530 // Insert the shift to put the result in the low bit.
531 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
532 In->getName()+".lobit");
535 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
536 Constant *One = ConstantInt::get(In->getType(), 1);
537 In = Builder->CreateXor(In, One, "tmp");
540 if (CI.getType() == In->getType())
541 return ReplaceInstUsesWith(CI, In);
543 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
548 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
549 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
550 // may lead to additional simplifications.
551 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
552 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
553 uint32_t BitWidth = ITy->getBitWidth();
554 Value *LHS = ICI->getOperand(0);
555 Value *RHS = ICI->getOperand(1);
557 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
558 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
559 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
560 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
561 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
563 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
564 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
565 APInt UnknownBit = ~KnownBits;
566 if (UnknownBit.countPopulation() == 1) {
567 if (!DoXform) return ICI;
569 Value *Result = Builder->CreateXor(LHS, RHS);
571 // Mask off any bits that are set and won't be shifted away.
572 if (KnownOneLHS.uge(UnknownBit))
573 Result = Builder->CreateAnd(Result,
574 ConstantInt::get(ITy, UnknownBit));
576 // Shift the bit we're testing down to the lsb.
577 Result = Builder->CreateLShr(
578 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
580 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
581 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
582 Result->takeName(ICI);
583 return ReplaceInstUsesWith(CI, Result);
592 /// CanEvaluateZExtd - Determine if the specified value can be computed in the
593 /// specified wider type and produce the same low bits. If not, return false.
595 /// If this function returns true, it can also return a non-zero number of bits
596 /// (in BitsToClear) which indicates that the value it computes is correct for
597 /// the zero extend, but that the additional BitsToClear bits need to be zero'd
598 /// out. For example, to promote something like:
600 /// %B = trunc i64 %A to i32
601 /// %C = lshr i32 %B, 8
602 /// %E = zext i32 %C to i64
604 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
605 /// set to 8 to indicate that the promoted value needs to have bits 24-31
606 /// cleared in addition to bits 32-63. Since an 'and' will be generated to
607 /// clear the top bits anyway, doing this has no extra cost.
609 /// This function works on both vectors and scalars.
610 static bool CanEvaluateZExtd(Value *V, const Type *Ty, unsigned &BitsToClear) {
612 if (isa<Constant>(V))
615 Instruction *I = dyn_cast<Instruction>(V);
616 if (!I) return false;
618 // If the input is a truncate from the destination type, we can trivially
619 // eliminate it, even if it has multiple uses.
620 // FIXME: This is currently disabled until codegen can handle this without
621 // pessimizing code, PR5997.
622 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
625 // We can't extend or shrink something that has multiple uses: doing so would
626 // require duplicating the instruction in general, which isn't profitable.
627 if (!I->hasOneUse()) return false;
629 unsigned Opc = I->getOpcode(), Tmp;
631 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
632 case Instruction::SExt: // zext(sext(x)) -> sext(x).
633 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
635 case Instruction::And:
636 case Instruction::Or:
637 case Instruction::Xor:
638 case Instruction::Add:
639 case Instruction::Sub:
640 case Instruction::Mul:
641 case Instruction::Shl:
642 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
643 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
645 // These can all be promoted if neither operand has 'bits to clear'.
646 if (BitsToClear == 0 && Tmp == 0)
649 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
650 // other side, BitsToClear is ok.
652 (Opc == Instruction::And || Opc == Instruction::Or ||
653 Opc == Instruction::Xor)) {
654 // We use MaskedValueIsZero here for generality, but the case we care
655 // about the most is constant RHS.
656 unsigned VSize = V->getType()->getScalarSizeInBits();
657 if (MaskedValueIsZero(I->getOperand(1),
658 APInt::getHighBitsSet(VSize, BitsToClear)))
662 // Otherwise, we don't know how to analyze this BitsToClear case yet.
665 case Instruction::LShr:
666 // We can promote lshr(x, cst) if we can promote x. This requires the
667 // ultimate 'and' to clear out the high zero bits we're clearing out though.
668 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
669 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
671 BitsToClear += Amt->getZExtValue();
672 if (BitsToClear > V->getType()->getScalarSizeInBits())
673 BitsToClear = V->getType()->getScalarSizeInBits();
676 // Cannot promote variable LSHR.
678 case Instruction::Select:
679 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
680 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
681 // TODO: If important, we could handle the case when the BitsToClear are
682 // known zero in the disagreeing side.
687 case Instruction::PHI: {
688 // We can change a phi if we can change all operands. Note that we never
689 // get into trouble with cyclic PHIs here because we only consider
690 // instructions with a single use.
691 PHINode *PN = cast<PHINode>(I);
692 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
694 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
695 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
696 // TODO: If important, we could handle the case when the BitsToClear
697 // are known zero in the disagreeing input.
703 // TODO: Can handle more cases here.
708 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
709 // If this zero extend is only used by a truncate, let the truncate by
710 // eliminated before we try to optimize this zext.
711 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
714 // If one of the common conversion will work, do it.
715 if (Instruction *Result = commonCastTransforms(CI))
718 // See if we can simplify any instructions used by the input whose sole
719 // purpose is to compute bits we don't care about.
720 if (SimplifyDemandedInstructionBits(CI))
723 Value *Src = CI.getOperand(0);
724 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
726 // Attempt to extend the entire input expression tree to the destination
727 // type. Only do this if the dest type is a simple type, don't convert the
728 // expression tree to something weird like i93 unless the source is also
730 unsigned BitsToClear;
731 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
732 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
733 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
734 "Unreasonable BitsToClear");
736 // Okay, we can transform this! Insert the new expression now.
737 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
738 " to avoid zero extend: " << CI);
739 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
740 assert(Res->getType() == DestTy);
742 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
743 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
745 // If the high bits are already filled with zeros, just replace this
746 // cast with the result.
747 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
748 DestBitSize-SrcBitsKept)))
749 return ReplaceInstUsesWith(CI, Res);
751 // We need to emit an AND to clear the high bits.
752 Constant *C = ConstantInt::get(Res->getType(),
753 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
754 return BinaryOperator::CreateAnd(Res, C);
757 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
758 // types and if the sizes are just right we can convert this into a logical
759 // 'and' which will be much cheaper than the pair of casts.
760 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
761 // TODO: Subsume this into EvaluateInDifferentType.
763 // Get the sizes of the types involved. We know that the intermediate type
764 // will be smaller than A or C, but don't know the relation between A and C.
765 Value *A = CSrc->getOperand(0);
766 unsigned SrcSize = A->getType()->getScalarSizeInBits();
767 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
768 unsigned DstSize = CI.getType()->getScalarSizeInBits();
769 // If we're actually extending zero bits, then if
770 // SrcSize < DstSize: zext(a & mask)
771 // SrcSize == DstSize: a & mask
772 // SrcSize > DstSize: trunc(a) & mask
773 if (SrcSize < DstSize) {
774 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
775 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
776 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
777 return new ZExtInst(And, CI.getType());
780 if (SrcSize == DstSize) {
781 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
782 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
785 if (SrcSize > DstSize) {
786 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
787 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
788 return BinaryOperator::CreateAnd(Trunc,
789 ConstantInt::get(Trunc->getType(),
794 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
795 return transformZExtICmp(ICI, CI);
797 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
798 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
799 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
800 // of the (zext icmp) will be transformed.
801 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
802 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
803 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
804 (transformZExtICmp(LHS, CI, false) ||
805 transformZExtICmp(RHS, CI, false))) {
806 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
807 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
808 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
812 // zext(trunc(t) & C) -> (t & zext(C)).
813 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
814 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
815 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
816 Value *TI0 = TI->getOperand(0);
817 if (TI0->getType() == CI.getType())
819 BinaryOperator::CreateAnd(TI0,
820 ConstantExpr::getZExt(C, CI.getType()));
823 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
824 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
825 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
826 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
827 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
828 And->getOperand(1) == C)
829 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
830 Value *TI0 = TI->getOperand(0);
831 if (TI0->getType() == CI.getType()) {
832 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
833 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
834 return BinaryOperator::CreateXor(NewAnd, ZC);
838 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
840 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isIntegerTy(1) &&
841 match(SrcI, m_Not(m_Value(X))) &&
842 (!X->hasOneUse() || !isa<CmpInst>(X))) {
843 Value *New = Builder->CreateZExt(X, CI.getType());
844 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
850 /// CanEvaluateSExtd - Return true if we can take the specified value
851 /// and return it as type Ty without inserting any new casts and without
852 /// changing the value of the common low bits. This is used by code that tries
853 /// to promote integer operations to a wider types will allow us to eliminate
856 /// This function works on both vectors and scalars.
858 static bool CanEvaluateSExtd(Value *V, const Type *Ty) {
859 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
860 "Can't sign extend type to a smaller type");
861 // If this is a constant, it can be trivially promoted.
862 if (isa<Constant>(V))
865 Instruction *I = dyn_cast<Instruction>(V);
866 if (!I) return false;
868 // If this is a truncate from the dest type, we can trivially eliminate it,
869 // even if it has multiple uses.
870 // FIXME: This is currently disabled until codegen can handle this without
871 // pessimizing code, PR5997.
872 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
875 // We can't extend or shrink something that has multiple uses: doing so would
876 // require duplicating the instruction in general, which isn't profitable.
877 if (!I->hasOneUse()) return false;
879 switch (I->getOpcode()) {
880 case Instruction::SExt: // sext(sext(x)) -> sext(x)
881 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
882 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
884 case Instruction::And:
885 case Instruction::Or:
886 case Instruction::Xor:
887 case Instruction::Add:
888 case Instruction::Sub:
889 case Instruction::Mul:
890 // These operators can all arbitrarily be extended if their inputs can.
891 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
892 CanEvaluateSExtd(I->getOperand(1), Ty);
894 //case Instruction::Shl: TODO
895 //case Instruction::LShr: TODO
897 case Instruction::Select:
898 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
899 CanEvaluateSExtd(I->getOperand(2), Ty);
901 case Instruction::PHI: {
902 // We can change a phi if we can change all operands. Note that we never
903 // get into trouble with cyclic PHIs here because we only consider
904 // instructions with a single use.
905 PHINode *PN = cast<PHINode>(I);
906 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
907 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
911 // TODO: Can handle more cases here.
918 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
919 // If this sign extend is only used by a truncate, let the truncate by
920 // eliminated before we try to optimize this zext.
921 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
924 if (Instruction *I = commonCastTransforms(CI))
927 // See if we can simplify any instructions used by the input whose sole
928 // purpose is to compute bits we don't care about.
929 if (SimplifyDemandedInstructionBits(CI))
932 Value *Src = CI.getOperand(0);
933 const Type *SrcTy = Src->getType(), *DestTy = CI.getType();
935 // Attempt to extend the entire input expression tree to the destination
936 // type. Only do this if the dest type is a simple type, don't convert the
937 // expression tree to something weird like i93 unless the source is also
939 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
940 CanEvaluateSExtd(Src, DestTy)) {
941 // Okay, we can transform this! Insert the new expression now.
942 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
943 " to avoid sign extend: " << CI);
944 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
945 assert(Res->getType() == DestTy);
947 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
948 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
950 // If the high bits are already filled with sign bit, just replace this
951 // cast with the result.
952 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
953 return ReplaceInstUsesWith(CI, Res);
955 // We need to emit a shl + ashr to do the sign extend.
956 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
957 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
961 // If this input is a trunc from our destination, then turn sext(trunc(x))
963 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
964 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
965 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
966 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
968 // We need to emit a shl + ashr to do the sign extend.
969 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
970 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
971 return BinaryOperator::CreateAShr(Res, ShAmt);
975 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
976 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
978 ICmpInst::Predicate Pred; Value *CmpLHS; ConstantInt *CmpRHS;
979 if (match(Src, m_ICmp(Pred, m_Value(CmpLHS), m_ConstantInt(CmpRHS)))) {
980 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
981 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
982 if ((Pred == ICmpInst::ICMP_SLT && CmpRHS->isZero()) ||
983 (Pred == ICmpInst::ICMP_SGT && CmpRHS->isAllOnesValue())) {
984 Value *Sh = ConstantInt::get(CmpLHS->getType(),
985 CmpLHS->getType()->getScalarSizeInBits()-1);
986 Value *In = Builder->CreateAShr(CmpLHS, Sh, CmpLHS->getName()+".lobit");
987 if (In->getType() != CI.getType())
988 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/, "tmp");
990 if (Pred == ICmpInst::ICMP_SGT)
991 In = Builder->CreateNot(In, In->getName()+".not");
992 return ReplaceInstUsesWith(CI, In);
998 // If the input is a shl/ashr pair of a same constant, then this is a sign
999 // extension from a smaller value. If we could trust arbitrary bitwidth
1000 // integers, we could turn this into a truncate to the smaller bit and then
1001 // use a sext for the whole extension. Since we don't, look deeper and check
1002 // for a truncate. If the source and dest are the same type, eliminate the
1003 // trunc and extend and just do shifts. For example, turn:
1004 // %a = trunc i32 %i to i8
1005 // %b = shl i8 %a, 6
1006 // %c = ashr i8 %b, 6
1007 // %d = sext i8 %c to i32
1009 // %a = shl i32 %i, 30
1010 // %d = ashr i32 %a, 30
1012 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
1013 ConstantInt *BA = 0, *CA = 0;
1014 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
1015 m_ConstantInt(CA))) &&
1016 BA == CA && A->getType() == CI.getType()) {
1017 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1018 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1019 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1020 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1021 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1022 return BinaryOperator::CreateAShr(A, ShAmtV);
1029 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1030 /// in the specified FP type without changing its value.
1031 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1033 APFloat F = CFP->getValueAPF();
1034 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1036 return ConstantFP::get(CFP->getContext(), F);
1040 /// LookThroughFPExtensions - If this is an fp extension instruction, look
1041 /// through it until we get the source value.
1042 static Value *LookThroughFPExtensions(Value *V) {
1043 if (Instruction *I = dyn_cast<Instruction>(V))
1044 if (I->getOpcode() == Instruction::FPExt)
1045 return LookThroughFPExtensions(I->getOperand(0));
1047 // If this value is a constant, return the constant in the smallest FP type
1048 // that can accurately represent it. This allows us to turn
1049 // (float)((double)X+2.0) into x+2.0f.
1050 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1051 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1052 return V; // No constant folding of this.
1053 // See if the value can be truncated to float and then reextended.
1054 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1056 if (CFP->getType()->isDoubleTy())
1057 return V; // Won't shrink.
1058 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1060 // Don't try to shrink to various long double types.
1066 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1067 if (Instruction *I = commonCastTransforms(CI))
1070 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1071 // smaller than the destination type, we can eliminate the truncate by doing
1072 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1073 // as many builtins (sqrt, etc).
1074 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1075 if (OpI && OpI->hasOneUse()) {
1076 switch (OpI->getOpcode()) {
1078 case Instruction::FAdd:
1079 case Instruction::FSub:
1080 case Instruction::FMul:
1081 case Instruction::FDiv:
1082 case Instruction::FRem:
1083 const Type *SrcTy = OpI->getType();
1084 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1085 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1086 if (LHSTrunc->getType() != SrcTy &&
1087 RHSTrunc->getType() != SrcTy) {
1088 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1089 // If the source types were both smaller than the destination type of
1090 // the cast, do this xform.
1091 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1092 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1093 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1094 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1095 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1104 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1105 return commonCastTransforms(CI);
1108 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1109 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1111 return commonCastTransforms(FI);
1113 // fptoui(uitofp(X)) --> X
1114 // fptoui(sitofp(X)) --> X
1115 // This is safe if the intermediate type has enough bits in its mantissa to
1116 // accurately represent all values of X. For example, do not do this with
1117 // i64->float->i64. This is also safe for sitofp case, because any negative
1118 // 'X' value would cause an undefined result for the fptoui.
1119 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1120 OpI->getOperand(0)->getType() == FI.getType() &&
1121 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1122 OpI->getType()->getFPMantissaWidth())
1123 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1125 return commonCastTransforms(FI);
1128 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1129 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1131 return commonCastTransforms(FI);
1133 // fptosi(sitofp(X)) --> X
1134 // fptosi(uitofp(X)) --> X
1135 // This is safe if the intermediate type has enough bits in its mantissa to
1136 // accurately represent all values of X. For example, do not do this with
1137 // i64->float->i64. This is also safe for sitofp case, because any negative
1138 // 'X' value would cause an undefined result for the fptoui.
1139 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1140 OpI->getOperand(0)->getType() == FI.getType() &&
1141 (int)FI.getType()->getScalarSizeInBits() <=
1142 OpI->getType()->getFPMantissaWidth())
1143 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1145 return commonCastTransforms(FI);
1148 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1149 return commonCastTransforms(CI);
1152 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1153 return commonCastTransforms(CI);
1156 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1157 // If the source integer type is not the intptr_t type for this target, do a
1158 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1159 // cast to be exposed to other transforms.
1161 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
1162 TD->getPointerSizeInBits()) {
1163 Value *P = Builder->CreateTrunc(CI.getOperand(0),
1164 TD->getIntPtrType(CI.getContext()), "tmp");
1165 return new IntToPtrInst(P, CI.getType());
1167 if (CI.getOperand(0)->getType()->getScalarSizeInBits() <
1168 TD->getPointerSizeInBits()) {
1169 Value *P = Builder->CreateZExt(CI.getOperand(0),
1170 TD->getIntPtrType(CI.getContext()), "tmp");
1171 return new IntToPtrInst(P, CI.getType());
1175 if (Instruction *I = commonCastTransforms(CI))
1181 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1182 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1183 Value *Src = CI.getOperand(0);
1185 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1186 // If casting the result of a getelementptr instruction with no offset, turn
1187 // this into a cast of the original pointer!
1188 if (GEP->hasAllZeroIndices()) {
1189 // Changing the cast operand is usually not a good idea but it is safe
1190 // here because the pointer operand is being replaced with another
1191 // pointer operand so the opcode doesn't need to change.
1193 CI.setOperand(0, GEP->getOperand(0));
1197 // If the GEP has a single use, and the base pointer is a bitcast, and the
1198 // GEP computes a constant offset, see if we can convert these three
1199 // instructions into fewer. This typically happens with unions and other
1200 // non-type-safe code.
1201 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1202 GEP->hasAllConstantIndices()) {
1203 // We are guaranteed to get a constant from EmitGEPOffset.
1204 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1205 int64_t Offset = OffsetV->getSExtValue();
1207 // Get the base pointer input of the bitcast, and the type it points to.
1208 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1209 const Type *GEPIdxTy =
1210 cast<PointerType>(OrigBase->getType())->getElementType();
1211 SmallVector<Value*, 8> NewIndices;
1212 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1213 // If we were able to index down into an element, create the GEP
1214 // and bitcast the result. This eliminates one bitcast, potentially
1216 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1217 Builder->CreateInBoundsGEP(OrigBase,
1218 NewIndices.begin(), NewIndices.end()) :
1219 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
1220 NGEP->takeName(GEP);
1222 if (isa<BitCastInst>(CI))
1223 return new BitCastInst(NGEP, CI.getType());
1224 assert(isa<PtrToIntInst>(CI));
1225 return new PtrToIntInst(NGEP, CI.getType());
1230 return commonCastTransforms(CI);
1233 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1234 // If the destination integer type is not the intptr_t type for this target,
1235 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1236 // to be exposed to other transforms.
1238 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1239 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1240 TD->getIntPtrType(CI.getContext()),
1242 return new TruncInst(P, CI.getType());
1244 if (CI.getType()->getScalarSizeInBits() > TD->getPointerSizeInBits()) {
1245 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1246 TD->getIntPtrType(CI.getContext()),
1248 return new ZExtInst(P, CI.getType());
1252 return commonPointerCastTransforms(CI);
1255 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1256 // If the operands are integer typed then apply the integer transforms,
1257 // otherwise just apply the common ones.
1258 Value *Src = CI.getOperand(0);
1259 const Type *SrcTy = Src->getType();
1260 const Type *DestTy = CI.getType();
1262 // Get rid of casts from one type to the same type. These are useless and can
1263 // be replaced by the operand.
1264 if (DestTy == Src->getType())
1265 return ReplaceInstUsesWith(CI, Src);
1267 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1268 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
1269 const Type *DstElTy = DstPTy->getElementType();
1270 const Type *SrcElTy = SrcPTy->getElementType();
1272 // If the address spaces don't match, don't eliminate the bitcast, which is
1273 // required for changing types.
1274 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1277 // If we are casting a alloca to a pointer to a type of the same
1278 // size, rewrite the allocation instruction to allocate the "right" type.
1279 // There is no need to modify malloc calls because it is their bitcast that
1280 // needs to be cleaned up.
1281 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1282 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1285 // If the source and destination are pointers, and this cast is equivalent
1286 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1287 // This can enhance SROA and other transforms that want type-safe pointers.
1288 Constant *ZeroUInt =
1289 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1290 unsigned NumZeros = 0;
1291 while (SrcElTy != DstElTy &&
1292 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
1293 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1294 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1298 // If we found a path from the src to dest, create the getelementptr now.
1299 if (SrcElTy == DstElTy) {
1300 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1301 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
1302 ((Instruction*)NULL));
1306 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1307 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
1308 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1309 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1310 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1311 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1315 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1316 if (SrcVTy->getNumElements() == 1 && !DestTy->isVectorTy()) {
1318 Builder->CreateExtractElement(Src,
1319 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1320 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1324 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1325 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
1326 // a bitconvert to a vector with the same # elts.
1327 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
1328 cast<VectorType>(DestTy)->getNumElements() ==
1329 SVI->getType()->getNumElements() &&
1330 SVI->getType()->getNumElements() ==
1331 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1333 // If either of the operands is a cast from CI.getType(), then
1334 // evaluating the shuffle in the casted destination's type will allow
1335 // us to eliminate at least one cast.
1336 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1337 Tmp->getOperand(0)->getType() == DestTy) ||
1338 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1339 Tmp->getOperand(0)->getType() == DestTy)) {
1340 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1341 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1342 // Return a new shuffle vector. Use the same element ID's, as we
1343 // know the vector types match #elts.
1344 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1349 if (SrcTy->isPointerTy())
1350 return commonPointerCastTransforms(CI);
1351 return commonCastTransforms(CI);