LLVM  mainline
InstCombineCasts.cpp
Go to the documentation of this file.
00001 //===- InstCombineCasts.cpp -----------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visit functions for cast operations.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombineInternal.h"
00015 #include "llvm/Analysis/ConstantFolding.h"
00016 #include "llvm/IR/DataLayout.h"
00017 #include "llvm/IR/PatternMatch.h"
00018 #include "llvm/Analysis/TargetLibraryInfo.h"
00019 using namespace llvm;
00020 using namespace PatternMatch;
00021 
00022 #define DEBUG_TYPE "instcombine"
00023 
00024 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
00025 /// expression.  If so, decompose it, returning some value X, such that Val is
00026 /// X*Scale+Offset.
00027 ///
00028 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
00029                                         uint64_t &Offset) {
00030   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
00031     Offset = CI->getZExtValue();
00032     Scale  = 0;
00033     return ConstantInt::get(Val->getType(), 0);
00034   }
00035 
00036   if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
00037     // Cannot look past anything that might overflow.
00038     OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
00039     if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
00040       Scale = 1;
00041       Offset = 0;
00042       return Val;
00043     }
00044 
00045     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
00046       if (I->getOpcode() == Instruction::Shl) {
00047         // This is a value scaled by '1 << the shift amt'.
00048         Scale = UINT64_C(1) << RHS->getZExtValue();
00049         Offset = 0;
00050         return I->getOperand(0);
00051       }
00052 
00053       if (I->getOpcode() == Instruction::Mul) {
00054         // This value is scaled by 'RHS'.
00055         Scale = RHS->getZExtValue();
00056         Offset = 0;
00057         return I->getOperand(0);
00058       }
00059 
00060       if (I->getOpcode() == Instruction::Add) {
00061         // We have X+C.  Check to see if we really have (X*C2)+C1,
00062         // where C1 is divisible by C2.
00063         unsigned SubScale;
00064         Value *SubVal =
00065           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
00066         Offset += RHS->getZExtValue();
00067         Scale = SubScale;
00068         return SubVal;
00069       }
00070     }
00071   }
00072 
00073   // Otherwise, we can't look past this.
00074   Scale = 1;
00075   Offset = 0;
00076   return Val;
00077 }
00078 
00079 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
00080 /// try to eliminate the cast by moving the type information into the alloc.
00081 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
00082                                                    AllocaInst &AI) {
00083   PointerType *PTy = cast<PointerType>(CI.getType());
00084 
00085   BuilderTy AllocaBuilder(*Builder);
00086   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
00087 
00088   // Get the type really allocated and the type casted to.
00089   Type *AllocElTy = AI.getAllocatedType();
00090   Type *CastElTy = PTy->getElementType();
00091   if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr;
00092 
00093   unsigned AllocElTyAlign = DL.getABITypeAlignment(AllocElTy);
00094   unsigned CastElTyAlign = DL.getABITypeAlignment(CastElTy);
00095   if (CastElTyAlign < AllocElTyAlign) return nullptr;
00096 
00097   // If the allocation has multiple uses, only promote it if we are strictly
00098   // increasing the alignment of the resultant allocation.  If we keep it the
00099   // same, we open the door to infinite loops of various kinds.
00100   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr;
00101 
00102   uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy);
00103   uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy);
00104   if (CastElTySize == 0 || AllocElTySize == 0) return nullptr;
00105 
00106   // If the allocation has multiple uses, only promote it if we're not
00107   // shrinking the amount of memory being allocated.
00108   uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy);
00109   uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy);
00110   if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr;
00111 
00112   // See if we can satisfy the modulus by pulling a scale out of the array
00113   // size argument.
00114   unsigned ArraySizeScale;
00115   uint64_t ArrayOffset;
00116   Value *NumElements = // See if the array size is a decomposable linear expr.
00117     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
00118 
00119   // If we can now satisfy the modulus, by using a non-1 scale, we really can
00120   // do the xform.
00121   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
00122       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return nullptr;
00123 
00124   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
00125   Value *Amt = nullptr;
00126   if (Scale == 1) {
00127     Amt = NumElements;
00128   } else {
00129     Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
00130     // Insert before the alloca, not before the cast.
00131     Amt = AllocaBuilder.CreateMul(Amt, NumElements);
00132   }
00133 
00134   if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
00135     Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
00136                                   Offset, true);
00137     Amt = AllocaBuilder.CreateAdd(Amt, Off);
00138   }
00139 
00140   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
00141   New->setAlignment(AI.getAlignment());
00142   New->takeName(&AI);
00143   New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
00144 
00145   // If the allocation has multiple real uses, insert a cast and change all
00146   // things that used it to use the new cast.  This will also hack on CI, but it
00147   // will die soon.
00148   if (!AI.hasOneUse()) {
00149     // New is the allocation instruction, pointer typed. AI is the original
00150     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
00151     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
00152     ReplaceInstUsesWith(AI, NewCast);
00153   }
00154   return ReplaceInstUsesWith(CI, New);
00155 }
00156 
00157 /// EvaluateInDifferentType - Given an expression that
00158 /// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
00159 /// insert the code to evaluate the expression.
00160 Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
00161                                              bool isSigned) {
00162   if (Constant *C = dyn_cast<Constant>(V)) {
00163     C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
00164     // If we got a constantexpr back, try to simplify it with DL info.
00165     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
00166       C = ConstantFoldConstantExpression(CE, DL, TLI);
00167     return C;
00168   }
00169 
00170   // Otherwise, it must be an instruction.
00171   Instruction *I = cast<Instruction>(V);
00172   Instruction *Res = nullptr;
00173   unsigned Opc = I->getOpcode();
00174   switch (Opc) {
00175   case Instruction::Add:
00176   case Instruction::Sub:
00177   case Instruction::Mul:
00178   case Instruction::And:
00179   case Instruction::Or:
00180   case Instruction::Xor:
00181   case Instruction::AShr:
00182   case Instruction::LShr:
00183   case Instruction::Shl:
00184   case Instruction::UDiv:
00185   case Instruction::URem: {
00186     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
00187     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
00188     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
00189     break;
00190   }
00191   case Instruction::Trunc:
00192   case Instruction::ZExt:
00193   case Instruction::SExt:
00194     // If the source type of the cast is the type we're trying for then we can
00195     // just return the source.  There's no need to insert it because it is not
00196     // new.
00197     if (I->getOperand(0)->getType() == Ty)
00198       return I->getOperand(0);
00199 
00200     // Otherwise, must be the same type of cast, so just reinsert a new one.
00201     // This also handles the case of zext(trunc(x)) -> zext(x).
00202     Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
00203                                       Opc == Instruction::SExt);
00204     break;
00205   case Instruction::Select: {
00206     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
00207     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
00208     Res = SelectInst::Create(I->getOperand(0), True, False);
00209     break;
00210   }
00211   case Instruction::PHI: {
00212     PHINode *OPN = cast<PHINode>(I);
00213     PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
00214     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
00215       Value *V =
00216           EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
00217       NPN->addIncoming(V, OPN->getIncomingBlock(i));
00218     }
00219     Res = NPN;
00220     break;
00221   }
00222   default:
00223     // TODO: Can handle more cases here.
00224     llvm_unreachable("Unreachable!");
00225   }
00226 
00227   Res->takeName(I);
00228   return InsertNewInstWith(Res, *I);
00229 }
00230 
00231 
00232 /// This function is a wrapper around CastInst::isEliminableCastPair. It
00233 /// simply extracts arguments and returns what that function returns.
00234 static Instruction::CastOps
00235 isEliminableCastPair(const CastInst *CI, ///< First cast instruction
00236                      unsigned opcode,    ///< Opcode for the second cast
00237                      Type *DstTy,        ///< Target type for the second cast
00238                      const DataLayout &DL) {
00239   Type *SrcTy = CI->getOperand(0)->getType();   // A from above
00240   Type *MidTy = CI->getType();                  // B from above
00241 
00242   // Get the opcodes of the two Cast instructions
00243   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
00244   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
00245   Type *SrcIntPtrTy =
00246       SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr;
00247   Type *MidIntPtrTy =
00248       MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr;
00249   Type *DstIntPtrTy =
00250       DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr;
00251   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
00252                                                 DstTy, SrcIntPtrTy, MidIntPtrTy,
00253                                                 DstIntPtrTy);
00254 
00255   // We don't want to form an inttoptr or ptrtoint that converts to an integer
00256   // type that differs from the pointer size.
00257   if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
00258       (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
00259     Res = 0;
00260 
00261   return Instruction::CastOps(Res);
00262 }
00263 
00264 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
00265 /// results in any code being generated and is interesting to optimize out. If
00266 /// the cast can be eliminated by some other simple transformation, we prefer
00267 /// to do the simplification first.
00268 bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
00269                                       Type *Ty) {
00270   // Noop casts and casts of constants should be eliminated trivially.
00271   if (V->getType() == Ty || isa<Constant>(V)) return false;
00272 
00273   // If this is another cast that can be eliminated, we prefer to have it
00274   // eliminated.
00275   if (const CastInst *CI = dyn_cast<CastInst>(V))
00276     if (isEliminableCastPair(CI, opc, Ty, DL))
00277       return false;
00278 
00279   // If this is a vector sext from a compare, then we don't want to break the
00280   // idiom where each element of the extended vector is either zero or all ones.
00281   if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
00282     return false;
00283 
00284   return true;
00285 }
00286 
00287 
00288 /// @brief Implement the transforms common to all CastInst visitors.
00289 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
00290   Value *Src = CI.getOperand(0);
00291 
00292   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
00293   // eliminate it now.
00294   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
00295     if (Instruction::CastOps opc =
00296             isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), DL)) {
00297       // The first cast (CSrc) is eliminable so we need to fix up or replace
00298       // the second cast (CI). CSrc will then have a good chance of being dead.
00299       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
00300     }
00301   }
00302 
00303   // If we are casting a select then fold the cast into the select
00304   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
00305     if (Instruction *NV = FoldOpIntoSelect(CI, SI))
00306       return NV;
00307 
00308   // If we are casting a PHI then fold the cast into the PHI
00309   if (isa<PHINode>(Src)) {
00310     // We don't do this if this would create a PHI node with an illegal type if
00311     // it is currently legal.
00312     if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() ||
00313         ShouldChangeType(CI.getType(), Src->getType()))
00314       if (Instruction *NV = FoldOpIntoPhi(CI))
00315         return NV;
00316   }
00317 
00318   return nullptr;
00319 }
00320 
00321 /// CanEvaluateTruncated - Return true if we can evaluate the specified
00322 /// expression tree as type Ty instead of its larger type, and arrive with the
00323 /// same value.  This is used by code that tries to eliminate truncates.
00324 ///
00325 /// Ty will always be a type smaller than V.  We should return true if trunc(V)
00326 /// can be computed by computing V in the smaller type.  If V is an instruction,
00327 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
00328 /// makes sense if x and y can be efficiently truncated.
00329 ///
00330 /// This function works on both vectors and scalars.
00331 ///
00332 static bool CanEvaluateTruncated(Value *V, Type *Ty, InstCombiner &IC,
00333                                  Instruction *CxtI) {
00334   // We can always evaluate constants in another type.
00335   if (isa<Constant>(V))
00336     return true;
00337 
00338   Instruction *I = dyn_cast<Instruction>(V);
00339   if (!I) return false;
00340 
00341   Type *OrigTy = V->getType();
00342 
00343   // If this is an extension from the dest type, we can eliminate it, even if it
00344   // has multiple uses.
00345   if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
00346       I->getOperand(0)->getType() == Ty)
00347     return true;
00348 
00349   // We can't extend or shrink something that has multiple uses: doing so would
00350   // require duplicating the instruction in general, which isn't profitable.
00351   if (!I->hasOneUse()) return false;
00352 
00353   unsigned Opc = I->getOpcode();
00354   switch (Opc) {
00355   case Instruction::Add:
00356   case Instruction::Sub:
00357   case Instruction::Mul:
00358   case Instruction::And:
00359   case Instruction::Or:
00360   case Instruction::Xor:
00361     // These operators can all arbitrarily be extended or truncated.
00362     return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
00363            CanEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
00364 
00365   case Instruction::UDiv:
00366   case Instruction::URem: {
00367     // UDiv and URem can be truncated if all the truncated bits are zero.
00368     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
00369     uint32_t BitWidth = Ty->getScalarSizeInBits();
00370     if (BitWidth < OrigBitWidth) {
00371       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
00372       if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) &&
00373           IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) {
00374         return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
00375                CanEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
00376       }
00377     }
00378     break;
00379   }
00380   case Instruction::Shl:
00381     // If we are truncating the result of this SHL, and if it's a shift of a
00382     // constant amount, we can always perform a SHL in a smaller type.
00383     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
00384       uint32_t BitWidth = Ty->getScalarSizeInBits();
00385       if (CI->getLimitedValue(BitWidth) < BitWidth)
00386         return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
00387     }
00388     break;
00389   case Instruction::LShr:
00390     // If this is a truncate of a logical shr, we can truncate it to a smaller
00391     // lshr iff we know that the bits we would otherwise be shifting in are
00392     // already zeros.
00393     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
00394       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
00395       uint32_t BitWidth = Ty->getScalarSizeInBits();
00396       if (IC.MaskedValueIsZero(I->getOperand(0),
00397             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth), 0, CxtI) &&
00398           CI->getLimitedValue(BitWidth) < BitWidth) {
00399         return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
00400       }
00401     }
00402     break;
00403   case Instruction::Trunc:
00404     // trunc(trunc(x)) -> trunc(x)
00405     return true;
00406   case Instruction::ZExt:
00407   case Instruction::SExt:
00408     // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
00409     // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
00410     return true;
00411   case Instruction::Select: {
00412     SelectInst *SI = cast<SelectInst>(I);
00413     return CanEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) &&
00414            CanEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI);
00415   }
00416   case Instruction::PHI: {
00417     // We can change a phi if we can change all operands.  Note that we never
00418     // get into trouble with cyclic PHIs here because we only consider
00419     // instructions with a single use.
00420     PHINode *PN = cast<PHINode>(I);
00421     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00422       if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty, IC, CxtI))
00423         return false;
00424     return true;
00425   }
00426   default:
00427     // TODO: Can handle more cases here.
00428     break;
00429   }
00430 
00431   return false;
00432 }
00433 
00434 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
00435   if (Instruction *Result = commonCastTransforms(CI))
00436     return Result;
00437 
00438   // See if we can simplify any instructions used by the input whose sole
00439   // purpose is to compute bits we don't care about.
00440   if (SimplifyDemandedInstructionBits(CI))
00441     return &CI;
00442 
00443   Value *Src = CI.getOperand(0);
00444   Type *DestTy = CI.getType(), *SrcTy = Src->getType();
00445 
00446   // Attempt to truncate the entire input expression tree to the destination
00447   // type.   Only do this if the dest type is a simple type, don't convert the
00448   // expression tree to something weird like i93 unless the source is also
00449   // strange.
00450   if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
00451       CanEvaluateTruncated(Src, DestTy, *this, &CI)) {
00452 
00453     // If this cast is a truncate, evaluting in a different type always
00454     // eliminates the cast, so it is always a win.
00455     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
00456           " to avoid cast: " << CI << '\n');
00457     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
00458     assert(Res->getType() == DestTy);
00459     return ReplaceInstUsesWith(CI, Res);
00460   }
00461 
00462   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
00463   if (DestTy->getScalarSizeInBits() == 1) {
00464     Constant *One = ConstantInt::get(Src->getType(), 1);
00465     Src = Builder->CreateAnd(Src, One);
00466     Value *Zero = Constant::getNullValue(Src->getType());
00467     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
00468   }
00469 
00470   // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
00471   Value *A = nullptr; ConstantInt *Cst = nullptr;
00472   if (Src->hasOneUse() &&
00473       match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
00474     // We have three types to worry about here, the type of A, the source of
00475     // the truncate (MidSize), and the destination of the truncate. We know that
00476     // ASize < MidSize   and MidSize > ResultSize, but don't know the relation
00477     // between ASize and ResultSize.
00478     unsigned ASize = A->getType()->getPrimitiveSizeInBits();
00479 
00480     // If the shift amount is larger than the size of A, then the result is
00481     // known to be zero because all the input bits got shifted out.
00482     if (Cst->getZExtValue() >= ASize)
00483       return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
00484 
00485     // Since we're doing an lshr and a zero extend, and know that the shift
00486     // amount is smaller than ASize, it is always safe to do the shift in A's
00487     // type, then zero extend or truncate to the result.
00488     Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
00489     Shift->takeName(Src);
00490     return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
00491   }
00492 
00493   // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
00494   // type isn't non-native.
00495   if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
00496       ShouldChangeType(Src->getType(), CI.getType()) &&
00497       match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
00498     Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
00499     return BinaryOperator::CreateAnd(NewTrunc,
00500                                      ConstantExpr::getTrunc(Cst, CI.getType()));
00501   }
00502 
00503   return nullptr;
00504 }
00505 
00506 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
00507 /// in order to eliminate the icmp.
00508 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
00509                                              bool DoXform) {
00510   // If we are just checking for a icmp eq of a single bit and zext'ing it
00511   // to an integer, then shift the bit to the appropriate place and then
00512   // cast to integer to avoid the comparison.
00513   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
00514     const APInt &Op1CV = Op1C->getValue();
00515 
00516     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
00517     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
00518     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
00519         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
00520       if (!DoXform) return ICI;
00521 
00522       Value *In = ICI->getOperand(0);
00523       Value *Sh = ConstantInt::get(In->getType(),
00524                                    In->getType()->getScalarSizeInBits()-1);
00525       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
00526       if (In->getType() != CI.getType())
00527         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
00528 
00529       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
00530         Constant *One = ConstantInt::get(In->getType(), 1);
00531         In = Builder->CreateXor(In, One, In->getName()+".not");
00532       }
00533 
00534       return ReplaceInstUsesWith(CI, In);
00535     }
00536 
00537     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
00538     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
00539     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
00540     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
00541     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
00542     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
00543     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
00544     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
00545     if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
00546         // This only works for EQ and NE
00547         ICI->isEquality()) {
00548       // If Op1C some other power of two, convert:
00549       uint32_t BitWidth = Op1C->getType()->getBitWidth();
00550       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00551       computeKnownBits(ICI->getOperand(0), KnownZero, KnownOne, 0, &CI);
00552 
00553       APInt KnownZeroMask(~KnownZero);
00554       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
00555         if (!DoXform) return ICI;
00556 
00557         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
00558         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
00559           // (X&4) == 2 --> false
00560           // (X&4) != 2 --> true
00561           Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
00562                                            isNE);
00563           Res = ConstantExpr::getZExt(Res, CI.getType());
00564           return ReplaceInstUsesWith(CI, Res);
00565         }
00566 
00567         uint32_t ShiftAmt = KnownZeroMask.logBase2();
00568         Value *In = ICI->getOperand(0);
00569         if (ShiftAmt) {
00570           // Perform a logical shr by shiftamt.
00571           // Insert the shift to put the result in the low bit.
00572           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
00573                                    In->getName()+".lobit");
00574         }
00575 
00576         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
00577           Constant *One = ConstantInt::get(In->getType(), 1);
00578           In = Builder->CreateXor(In, One);
00579         }
00580 
00581         if (CI.getType() == In->getType())
00582           return ReplaceInstUsesWith(CI, In);
00583         return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
00584       }
00585     }
00586   }
00587 
00588   // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
00589   // It is also profitable to transform icmp eq into not(xor(A, B)) because that
00590   // may lead to additional simplifications.
00591   if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
00592     if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
00593       uint32_t BitWidth = ITy->getBitWidth();
00594       Value *LHS = ICI->getOperand(0);
00595       Value *RHS = ICI->getOperand(1);
00596 
00597       APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
00598       APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
00599       computeKnownBits(LHS, KnownZeroLHS, KnownOneLHS, 0, &CI);
00600       computeKnownBits(RHS, KnownZeroRHS, KnownOneRHS, 0, &CI);
00601 
00602       if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
00603         APInt KnownBits = KnownZeroLHS | KnownOneLHS;
00604         APInt UnknownBit = ~KnownBits;
00605         if (UnknownBit.countPopulation() == 1) {
00606           if (!DoXform) return ICI;
00607 
00608           Value *Result = Builder->CreateXor(LHS, RHS);
00609 
00610           // Mask off any bits that are set and won't be shifted away.
00611           if (KnownOneLHS.uge(UnknownBit))
00612             Result = Builder->CreateAnd(Result,
00613                                         ConstantInt::get(ITy, UnknownBit));
00614 
00615           // Shift the bit we're testing down to the lsb.
00616           Result = Builder->CreateLShr(
00617                Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
00618 
00619           if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
00620             Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
00621           Result->takeName(ICI);
00622           return ReplaceInstUsesWith(CI, Result);
00623         }
00624       }
00625     }
00626   }
00627 
00628   return nullptr;
00629 }
00630 
00631 /// CanEvaluateZExtd - Determine if the specified value can be computed in the
00632 /// specified wider type and produce the same low bits.  If not, return false.
00633 ///
00634 /// If this function returns true, it can also return a non-zero number of bits
00635 /// (in BitsToClear) which indicates that the value it computes is correct for
00636 /// the zero extend, but that the additional BitsToClear bits need to be zero'd
00637 /// out.  For example, to promote something like:
00638 ///
00639 ///   %B = trunc i64 %A to i32
00640 ///   %C = lshr i32 %B, 8
00641 ///   %E = zext i32 %C to i64
00642 ///
00643 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
00644 /// set to 8 to indicate that the promoted value needs to have bits 24-31
00645 /// cleared in addition to bits 32-63.  Since an 'and' will be generated to
00646 /// clear the top bits anyway, doing this has no extra cost.
00647 ///
00648 /// This function works on both vectors and scalars.
00649 static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear,
00650                              InstCombiner &IC, Instruction *CxtI) {
00651   BitsToClear = 0;
00652   if (isa<Constant>(V))
00653     return true;
00654 
00655   Instruction *I = dyn_cast<Instruction>(V);
00656   if (!I) return false;
00657 
00658   // If the input is a truncate from the destination type, we can trivially
00659   // eliminate it.
00660   if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
00661     return true;
00662 
00663   // We can't extend or shrink something that has multiple uses: doing so would
00664   // require duplicating the instruction in general, which isn't profitable.
00665   if (!I->hasOneUse()) return false;
00666 
00667   unsigned Opc = I->getOpcode(), Tmp;
00668   switch (Opc) {
00669   case Instruction::ZExt:  // zext(zext(x)) -> zext(x).
00670   case Instruction::SExt:  // zext(sext(x)) -> sext(x).
00671   case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
00672     return true;
00673   case Instruction::And:
00674   case Instruction::Or:
00675   case Instruction::Xor:
00676   case Instruction::Add:
00677   case Instruction::Sub:
00678   case Instruction::Mul:
00679     if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) ||
00680         !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI))
00681       return false;
00682     // These can all be promoted if neither operand has 'bits to clear'.
00683     if (BitsToClear == 0 && Tmp == 0)
00684       return true;
00685 
00686     // If the operation is an AND/OR/XOR and the bits to clear are zero in the
00687     // other side, BitsToClear is ok.
00688     if (Tmp == 0 &&
00689         (Opc == Instruction::And || Opc == Instruction::Or ||
00690          Opc == Instruction::Xor)) {
00691       // We use MaskedValueIsZero here for generality, but the case we care
00692       // about the most is constant RHS.
00693       unsigned VSize = V->getType()->getScalarSizeInBits();
00694       if (IC.MaskedValueIsZero(I->getOperand(1),
00695                                APInt::getHighBitsSet(VSize, BitsToClear),
00696                                0, CxtI))
00697         return true;
00698     }
00699 
00700     // Otherwise, we don't know how to analyze this BitsToClear case yet.
00701     return false;
00702 
00703   case Instruction::Shl:
00704     // We can promote shl(x, cst) if we can promote x.  Since shl overwrites the
00705     // upper bits we can reduce BitsToClear by the shift amount.
00706     if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
00707       if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
00708         return false;
00709       uint64_t ShiftAmt = Amt->getZExtValue();
00710       BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
00711       return true;
00712     }
00713     return false;
00714   case Instruction::LShr:
00715     // We can promote lshr(x, cst) if we can promote x.  This requires the
00716     // ultimate 'and' to clear out the high zero bits we're clearing out though.
00717     if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
00718       if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
00719         return false;
00720       BitsToClear += Amt->getZExtValue();
00721       if (BitsToClear > V->getType()->getScalarSizeInBits())
00722         BitsToClear = V->getType()->getScalarSizeInBits();
00723       return true;
00724     }
00725     // Cannot promote variable LSHR.
00726     return false;
00727   case Instruction::Select:
00728     if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) ||
00729         !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) ||
00730         // TODO: If important, we could handle the case when the BitsToClear are
00731         // known zero in the disagreeing side.
00732         Tmp != BitsToClear)
00733       return false;
00734     return true;
00735 
00736   case Instruction::PHI: {
00737     // We can change a phi if we can change all operands.  Note that we never
00738     // get into trouble with cyclic PHIs here because we only consider
00739     // instructions with a single use.
00740     PHINode *PN = cast<PHINode>(I);
00741     if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI))
00742       return false;
00743     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
00744       if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) ||
00745           // TODO: If important, we could handle the case when the BitsToClear
00746           // are known zero in the disagreeing input.
00747           Tmp != BitsToClear)
00748         return false;
00749     return true;
00750   }
00751   default:
00752     // TODO: Can handle more cases here.
00753     return false;
00754   }
00755 }
00756 
00757 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
00758   // If this zero extend is only used by a truncate, let the truncate be
00759   // eliminated before we try to optimize this zext.
00760   if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
00761     return nullptr;
00762 
00763   // If one of the common conversion will work, do it.
00764   if (Instruction *Result = commonCastTransforms(CI))
00765     return Result;
00766 
00767   // See if we can simplify any instructions used by the input whose sole
00768   // purpose is to compute bits we don't care about.
00769   if (SimplifyDemandedInstructionBits(CI))
00770     return &CI;
00771 
00772   Value *Src = CI.getOperand(0);
00773   Type *SrcTy = Src->getType(), *DestTy = CI.getType();
00774 
00775   // Attempt to extend the entire input expression tree to the destination
00776   // type.   Only do this if the dest type is a simple type, don't convert the
00777   // expression tree to something weird like i93 unless the source is also
00778   // strange.
00779   unsigned BitsToClear;
00780   if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
00781       CanEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)) {
00782     assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
00783            "Unreasonable BitsToClear");
00784 
00785     // Okay, we can transform this!  Insert the new expression now.
00786     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
00787           " to avoid zero extend: " << CI);
00788     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
00789     assert(Res->getType() == DestTy);
00790 
00791     uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
00792     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
00793 
00794     // If the high bits are already filled with zeros, just replace this
00795     // cast with the result.
00796     if (MaskedValueIsZero(Res,
00797                           APInt::getHighBitsSet(DestBitSize,
00798                                                 DestBitSize-SrcBitsKept),
00799                              0, &CI))
00800       return ReplaceInstUsesWith(CI, Res);
00801 
00802     // We need to emit an AND to clear the high bits.
00803     Constant *C = ConstantInt::get(Res->getType(),
00804                                APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
00805     return BinaryOperator::CreateAnd(Res, C);
00806   }
00807 
00808   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
00809   // types and if the sizes are just right we can convert this into a logical
00810   // 'and' which will be much cheaper than the pair of casts.
00811   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
00812     // TODO: Subsume this into EvaluateInDifferentType.
00813 
00814     // Get the sizes of the types involved.  We know that the intermediate type
00815     // will be smaller than A or C, but don't know the relation between A and C.
00816     Value *A = CSrc->getOperand(0);
00817     unsigned SrcSize = A->getType()->getScalarSizeInBits();
00818     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
00819     unsigned DstSize = CI.getType()->getScalarSizeInBits();
00820     // If we're actually extending zero bits, then if
00821     // SrcSize <  DstSize: zext(a & mask)
00822     // SrcSize == DstSize: a & mask
00823     // SrcSize  > DstSize: trunc(a) & mask
00824     if (SrcSize < DstSize) {
00825       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
00826       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
00827       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
00828       return new ZExtInst(And, CI.getType());
00829     }
00830 
00831     if (SrcSize == DstSize) {
00832       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
00833       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
00834                                                            AndValue));
00835     }
00836     if (SrcSize > DstSize) {
00837       Value *Trunc = Builder->CreateTrunc(A, CI.getType());
00838       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
00839       return BinaryOperator::CreateAnd(Trunc,
00840                                        ConstantInt::get(Trunc->getType(),
00841                                                         AndValue));
00842     }
00843   }
00844 
00845   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
00846     return transformZExtICmp(ICI, CI);
00847 
00848   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
00849   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
00850     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
00851     // of the (zext icmp) will be transformed.
00852     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
00853     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
00854     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
00855         (transformZExtICmp(LHS, CI, false) ||
00856          transformZExtICmp(RHS, CI, false))) {
00857       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
00858       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
00859       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
00860     }
00861   }
00862 
00863   // zext(trunc(X) & C) -> (X & zext(C)).
00864   Constant *C;
00865   Value *X;
00866   if (SrcI &&
00867       match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
00868       X->getType() == CI.getType())
00869     return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
00870 
00871   // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
00872   Value *And;
00873   if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
00874       match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
00875       X->getType() == CI.getType()) {
00876     Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
00877     return BinaryOperator::CreateXor(Builder->CreateAnd(X, ZC), ZC);
00878   }
00879 
00880   // zext (xor i1 X, true) to i32  --> xor (zext i1 X to i32), 1
00881   if (SrcI && SrcI->hasOneUse() &&
00882       SrcI->getType()->getScalarType()->isIntegerTy(1) &&
00883       match(SrcI, m_Not(m_Value(X))) && (!X->hasOneUse() || !isa<CmpInst>(X))) {
00884     Value *New = Builder->CreateZExt(X, CI.getType());
00885     return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
00886   }
00887 
00888   return nullptr;
00889 }
00890 
00891 /// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
00892 /// in order to eliminate the icmp.
00893 Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
00894   Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
00895   ICmpInst::Predicate Pred = ICI->getPredicate();
00896 
00897   // Don't bother if Op1 isn't of vector or integer type.
00898   if (!Op1->getType()->isIntOrIntVectorTy())
00899     return nullptr;
00900 
00901   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
00902     // (x <s  0) ? -1 : 0 -> ashr x, 31        -> all ones if negative
00903     // (x >s -1) ? -1 : 0 -> not (ashr x, 31)  -> all ones if positive
00904     if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) ||
00905         (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
00906 
00907       Value *Sh = ConstantInt::get(Op0->getType(),
00908                                    Op0->getType()->getScalarSizeInBits()-1);
00909       Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
00910       if (In->getType() != CI.getType())
00911         In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
00912 
00913       if (Pred == ICmpInst::ICMP_SGT)
00914         In = Builder->CreateNot(In, In->getName()+".not");
00915       return ReplaceInstUsesWith(CI, In);
00916     }
00917   }
00918 
00919   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
00920     // If we know that only one bit of the LHS of the icmp can be set and we
00921     // have an equality comparison with zero or a power of 2, we can transform
00922     // the icmp and sext into bitwise/integer operations.
00923     if (ICI->hasOneUse() &&
00924         ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
00925       unsigned BitWidth = Op1C->getType()->getBitWidth();
00926       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00927       computeKnownBits(Op0, KnownZero, KnownOne, 0, &CI);
00928 
00929       APInt KnownZeroMask(~KnownZero);
00930       if (KnownZeroMask.isPowerOf2()) {
00931         Value *In = ICI->getOperand(0);
00932 
00933         // If the icmp tests for a known zero bit we can constant fold it.
00934         if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
00935           Value *V = Pred == ICmpInst::ICMP_NE ?
00936                        ConstantInt::getAllOnesValue(CI.getType()) :
00937                        ConstantInt::getNullValue(CI.getType());
00938           return ReplaceInstUsesWith(CI, V);
00939         }
00940 
00941         if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
00942           // sext ((x & 2^n) == 0)   -> (x >> n) - 1
00943           // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
00944           unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
00945           // Perform a right shift to place the desired bit in the LSB.
00946           if (ShiftAmt)
00947             In = Builder->CreateLShr(In,
00948                                      ConstantInt::get(In->getType(), ShiftAmt));
00949 
00950           // At this point "In" is either 1 or 0. Subtract 1 to turn
00951           // {1, 0} -> {0, -1}.
00952           In = Builder->CreateAdd(In,
00953                                   ConstantInt::getAllOnesValue(In->getType()),
00954                                   "sext");
00955         } else {
00956           // sext ((x & 2^n) != 0)   -> (x << bitwidth-n) a>> bitwidth-1
00957           // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
00958           unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
00959           // Perform a left shift to place the desired bit in the MSB.
00960           if (ShiftAmt)
00961             In = Builder->CreateShl(In,
00962                                     ConstantInt::get(In->getType(), ShiftAmt));
00963 
00964           // Distribute the bit over the whole bit width.
00965           In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
00966                                                         BitWidth - 1), "sext");
00967         }
00968 
00969         if (CI.getType() == In->getType())
00970           return ReplaceInstUsesWith(CI, In);
00971         return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
00972       }
00973     }
00974   }
00975 
00976   return nullptr;
00977 }
00978 
00979 /// CanEvaluateSExtd - Return true if we can take the specified value
00980 /// and return it as type Ty without inserting any new casts and without
00981 /// changing the value of the common low bits.  This is used by code that tries
00982 /// to promote integer operations to a wider types will allow us to eliminate
00983 /// the extension.
00984 ///
00985 /// This function works on both vectors and scalars.
00986 ///
00987 static bool CanEvaluateSExtd(Value *V, Type *Ty) {
00988   assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
00989          "Can't sign extend type to a smaller type");
00990   // If this is a constant, it can be trivially promoted.
00991   if (isa<Constant>(V))
00992     return true;
00993 
00994   Instruction *I = dyn_cast<Instruction>(V);
00995   if (!I) return false;
00996 
00997   // If this is a truncate from the dest type, we can trivially eliminate it.
00998   if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
00999     return true;
01000 
01001   // We can't extend or shrink something that has multiple uses: doing so would
01002   // require duplicating the instruction in general, which isn't profitable.
01003   if (!I->hasOneUse()) return false;
01004 
01005   switch (I->getOpcode()) {
01006   case Instruction::SExt:  // sext(sext(x)) -> sext(x)
01007   case Instruction::ZExt:  // sext(zext(x)) -> zext(x)
01008   case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
01009     return true;
01010   case Instruction::And:
01011   case Instruction::Or:
01012   case Instruction::Xor:
01013   case Instruction::Add:
01014   case Instruction::Sub:
01015   case Instruction::Mul:
01016     // These operators can all arbitrarily be extended if their inputs can.
01017     return CanEvaluateSExtd(I->getOperand(0), Ty) &&
01018            CanEvaluateSExtd(I->getOperand(1), Ty);
01019 
01020   //case Instruction::Shl:   TODO
01021   //case Instruction::LShr:  TODO
01022 
01023   case Instruction::Select:
01024     return CanEvaluateSExtd(I->getOperand(1), Ty) &&
01025            CanEvaluateSExtd(I->getOperand(2), Ty);
01026 
01027   case Instruction::PHI: {
01028     // We can change a phi if we can change all operands.  Note that we never
01029     // get into trouble with cyclic PHIs here because we only consider
01030     // instructions with a single use.
01031     PHINode *PN = cast<PHINode>(I);
01032     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
01033       if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
01034     return true;
01035   }
01036   default:
01037     // TODO: Can handle more cases here.
01038     break;
01039   }
01040 
01041   return false;
01042 }
01043 
01044 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
01045   // If this sign extend is only used by a truncate, let the truncate be
01046   // eliminated before we try to optimize this sext.
01047   if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
01048     return nullptr;
01049 
01050   if (Instruction *I = commonCastTransforms(CI))
01051     return I;
01052 
01053   // See if we can simplify any instructions used by the input whose sole
01054   // purpose is to compute bits we don't care about.
01055   if (SimplifyDemandedInstructionBits(CI))
01056     return &CI;
01057 
01058   Value *Src = CI.getOperand(0);
01059   Type *SrcTy = Src->getType(), *DestTy = CI.getType();
01060 
01061   // If we know that the value being extended is positive, we can use a zext
01062   // instead. 
01063   bool KnownZero, KnownOne;
01064   ComputeSignBit(Src, KnownZero, KnownOne, 0, &CI);
01065   if (KnownZero) {
01066     Value *ZExt = Builder->CreateZExt(Src, DestTy);
01067     return ReplaceInstUsesWith(CI, ZExt);
01068   }
01069 
01070   // Attempt to extend the entire input expression tree to the destination
01071   // type.   Only do this if the dest type is a simple type, don't convert the
01072   // expression tree to something weird like i93 unless the source is also
01073   // strange.
01074   if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
01075       CanEvaluateSExtd(Src, DestTy)) {
01076     // Okay, we can transform this!  Insert the new expression now.
01077     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
01078           " to avoid sign extend: " << CI);
01079     Value *Res = EvaluateInDifferentType(Src, DestTy, true);
01080     assert(Res->getType() == DestTy);
01081 
01082     uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
01083     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
01084 
01085     // If the high bits are already filled with sign bit, just replace this
01086     // cast with the result.
01087     if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize)
01088       return ReplaceInstUsesWith(CI, Res);
01089 
01090     // We need to emit a shl + ashr to do the sign extend.
01091     Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
01092     return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
01093                                       ShAmt);
01094   }
01095 
01096   // If this input is a trunc from our destination, then turn sext(trunc(x))
01097   // into shifts.
01098   if (TruncInst *TI = dyn_cast<TruncInst>(Src))
01099     if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
01100       uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
01101       uint32_t DestBitSize = DestTy->getScalarSizeInBits();
01102 
01103       // We need to emit a shl + ashr to do the sign extend.
01104       Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
01105       Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
01106       return BinaryOperator::CreateAShr(Res, ShAmt);
01107     }
01108 
01109   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
01110     return transformSExtICmp(ICI, CI);
01111 
01112   // If the input is a shl/ashr pair of a same constant, then this is a sign
01113   // extension from a smaller value.  If we could trust arbitrary bitwidth
01114   // integers, we could turn this into a truncate to the smaller bit and then
01115   // use a sext for the whole extension.  Since we don't, look deeper and check
01116   // for a truncate.  If the source and dest are the same type, eliminate the
01117   // trunc and extend and just do shifts.  For example, turn:
01118   //   %a = trunc i32 %i to i8
01119   //   %b = shl i8 %a, 6
01120   //   %c = ashr i8 %b, 6
01121   //   %d = sext i8 %c to i32
01122   // into:
01123   //   %a = shl i32 %i, 30
01124   //   %d = ashr i32 %a, 30
01125   Value *A = nullptr;
01126   // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
01127   ConstantInt *BA = nullptr, *CA = nullptr;
01128   if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
01129                         m_ConstantInt(CA))) &&
01130       BA == CA && A->getType() == CI.getType()) {
01131     unsigned MidSize = Src->getType()->getScalarSizeInBits();
01132     unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
01133     unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
01134     Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
01135     A = Builder->CreateShl(A, ShAmtV, CI.getName());
01136     return BinaryOperator::CreateAShr(A, ShAmtV);
01137   }
01138 
01139   return nullptr;
01140 }
01141 
01142 
01143 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
01144 /// in the specified FP type without changing its value.
01145 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
01146   bool losesInfo;
01147   APFloat F = CFP->getValueAPF();
01148   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
01149   if (!losesInfo)
01150     return ConstantFP::get(CFP->getContext(), F);
01151   return nullptr;
01152 }
01153 
01154 /// LookThroughFPExtensions - If this is an fp extension instruction, look
01155 /// through it until we get the source value.
01156 static Value *LookThroughFPExtensions(Value *V) {
01157   if (Instruction *I = dyn_cast<Instruction>(V))
01158     if (I->getOpcode() == Instruction::FPExt)
01159       return LookThroughFPExtensions(I->getOperand(0));
01160 
01161   // If this value is a constant, return the constant in the smallest FP type
01162   // that can accurately represent it.  This allows us to turn
01163   // (float)((double)X+2.0) into x+2.0f.
01164   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
01165     if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
01166       return V;  // No constant folding of this.
01167     // See if the value can be truncated to half and then reextended.
01168     if (Value *V = FitsInFPType(CFP, APFloat::IEEEhalf))
01169       return V;
01170     // See if the value can be truncated to float and then reextended.
01171     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
01172       return V;
01173     if (CFP->getType()->isDoubleTy())
01174       return V;  // Won't shrink.
01175     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
01176       return V;
01177     // Don't try to shrink to various long double types.
01178   }
01179 
01180   return V;
01181 }
01182 
01183 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
01184   if (Instruction *I = commonCastTransforms(CI))
01185     return I;
01186   // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
01187   // simpilify this expression to avoid one or more of the trunc/extend
01188   // operations if we can do so without changing the numerical results.
01189   //
01190   // The exact manner in which the widths of the operands interact to limit
01191   // what we can and cannot do safely varies from operation to operation, and
01192   // is explained below in the various case statements.
01193   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
01194   if (OpI && OpI->hasOneUse()) {
01195     Value *LHSOrig = LookThroughFPExtensions(OpI->getOperand(0));
01196     Value *RHSOrig = LookThroughFPExtensions(OpI->getOperand(1));
01197     unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
01198     unsigned LHSWidth = LHSOrig->getType()->getFPMantissaWidth();
01199     unsigned RHSWidth = RHSOrig->getType()->getFPMantissaWidth();
01200     unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
01201     unsigned DstWidth = CI.getType()->getFPMantissaWidth();
01202     switch (OpI->getOpcode()) {
01203       default: break;
01204       case Instruction::FAdd:
01205       case Instruction::FSub:
01206         // For addition and subtraction, the infinitely precise result can
01207         // essentially be arbitrarily wide; proving that double rounding
01208         // will not occur because the result of OpI is exact (as we will for
01209         // FMul, for example) is hopeless.  However, we *can* nonetheless
01210         // frequently know that double rounding cannot occur (or that it is
01211         // innocuous) by taking advantage of the specific structure of
01212         // infinitely-precise results that admit double rounding.
01213         //
01214         // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
01215         // to represent both sources, we can guarantee that the double
01216         // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
01217         // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
01218         // for proof of this fact).
01219         //
01220         // Note: Figueroa does not consider the case where DstFormat !=
01221         // SrcFormat.  It's possible (likely even!) that this analysis
01222         // could be tightened for those cases, but they are rare (the main
01223         // case of interest here is (float)((double)float + float)).
01224         if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
01225           if (LHSOrig->getType() != CI.getType())
01226             LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
01227           if (RHSOrig->getType() != CI.getType())
01228             RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
01229           Instruction *RI =
01230             BinaryOperator::Create(OpI->getOpcode(), LHSOrig, RHSOrig);
01231           RI->copyFastMathFlags(OpI);
01232           return RI;
01233         }
01234         break;
01235       case Instruction::FMul:
01236         // For multiplication, the infinitely precise result has at most
01237         // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
01238         // that such a value can be exactly represented, then no double
01239         // rounding can possibly occur; we can safely perform the operation
01240         // in the destination format if it can represent both sources.
01241         if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
01242           if (LHSOrig->getType() != CI.getType())
01243             LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
01244           if (RHSOrig->getType() != CI.getType())
01245             RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
01246           Instruction *RI =
01247             BinaryOperator::CreateFMul(LHSOrig, RHSOrig);
01248           RI->copyFastMathFlags(OpI);
01249           return RI;
01250         }
01251         break;
01252       case Instruction::FDiv:
01253         // For division, we use again use the bound from Figueroa's
01254         // dissertation.  I am entirely certain that this bound can be
01255         // tightened in the unbalanced operand case by an analysis based on
01256         // the diophantine rational approximation bound, but the well-known
01257         // condition used here is a good conservative first pass.
01258         // TODO: Tighten bound via rigorous analysis of the unbalanced case.
01259         if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
01260           if (LHSOrig->getType() != CI.getType())
01261             LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
01262           if (RHSOrig->getType() != CI.getType())
01263             RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
01264           Instruction *RI =
01265             BinaryOperator::CreateFDiv(LHSOrig, RHSOrig);
01266           RI->copyFastMathFlags(OpI);
01267           return RI;
01268         }
01269         break;
01270       case Instruction::FRem:
01271         // Remainder is straightforward.  Remainder is always exact, so the
01272         // type of OpI doesn't enter into things at all.  We simply evaluate
01273         // in whichever source type is larger, then convert to the
01274         // destination type.
01275         if (SrcWidth == OpWidth)
01276           break;
01277         if (LHSWidth < SrcWidth)
01278           LHSOrig = Builder->CreateFPExt(LHSOrig, RHSOrig->getType());
01279         else if (RHSWidth <= SrcWidth)
01280           RHSOrig = Builder->CreateFPExt(RHSOrig, LHSOrig->getType());
01281         if (LHSOrig != OpI->getOperand(0) || RHSOrig != OpI->getOperand(1)) {
01282           Value *ExactResult = Builder->CreateFRem(LHSOrig, RHSOrig);
01283           if (Instruction *RI = dyn_cast<Instruction>(ExactResult))
01284             RI->copyFastMathFlags(OpI);
01285           return CastInst::CreateFPCast(ExactResult, CI.getType());
01286         }
01287     }
01288 
01289     // (fptrunc (fneg x)) -> (fneg (fptrunc x))
01290     if (BinaryOperator::isFNeg(OpI)) {
01291       Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1),
01292                                                  CI.getType());
01293       Instruction *RI = BinaryOperator::CreateFNeg(InnerTrunc);
01294       RI->copyFastMathFlags(OpI);
01295       return RI;
01296     }
01297   }
01298 
01299   // (fptrunc (select cond, R1, Cst)) -->
01300   // (select cond, (fptrunc R1), (fptrunc Cst))
01301   SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0));
01302   if (SI &&
01303       (isa<ConstantFP>(SI->getOperand(1)) ||
01304        isa<ConstantFP>(SI->getOperand(2)))) {
01305     Value *LHSTrunc = Builder->CreateFPTrunc(SI->getOperand(1),
01306                                              CI.getType());
01307     Value *RHSTrunc = Builder->CreateFPTrunc(SI->getOperand(2),
01308                                              CI.getType());
01309     return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc);
01310   }
01311 
01312   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0));
01313   if (II) {
01314     switch (II->getIntrinsicID()) {
01315       default: break;
01316       case Intrinsic::fabs: {
01317         // (fptrunc (fabs x)) -> (fabs (fptrunc x))
01318         Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0),
01319                                                    CI.getType());
01320         Type *IntrinsicType[] = { CI.getType() };
01321         Function *Overload =
01322           Intrinsic::getDeclaration(CI.getParent()->getParent()->getParent(),
01323                                     II->getIntrinsicID(), IntrinsicType);
01324 
01325         Value *Args[] = { InnerTrunc };
01326         return CallInst::Create(Overload, Args, II->getName());
01327       }
01328     }
01329   }
01330 
01331   return nullptr;
01332 }
01333 
01334 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
01335   return commonCastTransforms(CI);
01336 }
01337 
01338 // fpto{s/u}i({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X)
01339 // This is safe if the intermediate type has enough bits in its mantissa to
01340 // accurately represent all values of X.  For example, this won't work with
01341 // i64 -> float -> i64.
01342 Instruction *InstCombiner::FoldItoFPtoI(Instruction &FI) {
01343   if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0)))
01344     return nullptr;
01345   Instruction *OpI = cast<Instruction>(FI.getOperand(0));
01346 
01347   Value *SrcI = OpI->getOperand(0);
01348   Type *FITy = FI.getType();
01349   Type *OpITy = OpI->getType();
01350   Type *SrcTy = SrcI->getType();
01351   bool IsInputSigned = isa<SIToFPInst>(OpI);
01352   bool IsOutputSigned = isa<FPToSIInst>(FI);
01353 
01354   // We can safely assume the conversion won't overflow the output range,
01355   // because (for example) (uint8_t)18293.f is undefined behavior.
01356 
01357   // Since we can assume the conversion won't overflow, our decision as to
01358   // whether the input will fit in the float should depend on the minimum
01359   // of the input range and output range.
01360 
01361   // This means this is also safe for a signed input and unsigned output, since
01362   // a negative input would lead to undefined behavior.
01363   int InputSize = (int)SrcTy->getScalarSizeInBits() - IsInputSigned;
01364   int OutputSize = (int)FITy->getScalarSizeInBits() - IsOutputSigned;
01365   int ActualSize = std::min(InputSize, OutputSize);
01366 
01367   if (ActualSize <= OpITy->getFPMantissaWidth()) {
01368     if (FITy->getScalarSizeInBits() > SrcTy->getScalarSizeInBits()) {
01369       if (IsInputSigned && IsOutputSigned)
01370         return new SExtInst(SrcI, FITy);
01371       return new ZExtInst(SrcI, FITy);
01372     }
01373     if (FITy->getScalarSizeInBits() < SrcTy->getScalarSizeInBits())
01374       return new TruncInst(SrcI, FITy);
01375     if (SrcTy == FITy)
01376       return ReplaceInstUsesWith(FI, SrcI);
01377     return new BitCastInst(SrcI, FITy);
01378   }
01379   return nullptr;
01380 }
01381 
01382 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
01383   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
01384   if (!OpI)
01385     return commonCastTransforms(FI);
01386 
01387   if (Instruction *I = FoldItoFPtoI(FI))
01388     return I;
01389 
01390   return commonCastTransforms(FI);
01391 }
01392 
01393 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
01394   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
01395   if (!OpI)
01396     return commonCastTransforms(FI);
01397 
01398   if (Instruction *I = FoldItoFPtoI(FI))
01399     return I;
01400 
01401   return commonCastTransforms(FI);
01402 }
01403 
01404 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
01405   return commonCastTransforms(CI);
01406 }
01407 
01408 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
01409   return commonCastTransforms(CI);
01410 }
01411 
01412 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
01413   // If the source integer type is not the intptr_t type for this target, do a
01414   // trunc or zext to the intptr_t type, then inttoptr of it.  This allows the
01415   // cast to be exposed to other transforms.
01416   unsigned AS = CI.getAddressSpace();
01417   if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
01418       DL.getPointerSizeInBits(AS)) {
01419     Type *Ty = DL.getIntPtrType(CI.getContext(), AS);
01420     if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
01421       Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
01422 
01423     Value *P = Builder->CreateZExtOrTrunc(CI.getOperand(0), Ty);
01424     return new IntToPtrInst(P, CI.getType());
01425   }
01426 
01427   if (Instruction *I = commonCastTransforms(CI))
01428     return I;
01429 
01430   return nullptr;
01431 }
01432 
01433 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
01434 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
01435   Value *Src = CI.getOperand(0);
01436 
01437   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
01438     // If casting the result of a getelementptr instruction with no offset, turn
01439     // this into a cast of the original pointer!
01440     if (GEP->hasAllZeroIndices() &&
01441         // If CI is an addrspacecast and GEP changes the poiner type, merging
01442         // GEP into CI would undo canonicalizing addrspacecast with different
01443         // pointer types, causing infinite loops.
01444         (!isa<AddrSpaceCastInst>(CI) ||
01445           GEP->getType() == GEP->getPointerOperand()->getType())) {
01446       // Changing the cast operand is usually not a good idea but it is safe
01447       // here because the pointer operand is being replaced with another
01448       // pointer operand so the opcode doesn't need to change.
01449       Worklist.Add(GEP);
01450       CI.setOperand(0, GEP->getOperand(0));
01451       return &CI;
01452     }
01453   }
01454 
01455   return commonCastTransforms(CI);
01456 }
01457 
01458 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
01459   // If the destination integer type is not the intptr_t type for this target,
01460   // do a ptrtoint to intptr_t then do a trunc or zext.  This allows the cast
01461   // to be exposed to other transforms.
01462 
01463   Type *Ty = CI.getType();
01464   unsigned AS = CI.getPointerAddressSpace();
01465 
01466   if (Ty->getScalarSizeInBits() == DL.getPointerSizeInBits(AS))
01467     return commonPointerCastTransforms(CI);
01468 
01469   Type *PtrTy = DL.getIntPtrType(CI.getContext(), AS);
01470   if (Ty->isVectorTy()) // Handle vectors of pointers.
01471     PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
01472 
01473   Value *P = Builder->CreatePtrToInt(CI.getOperand(0), PtrTy);
01474   return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
01475 }
01476 
01477 /// OptimizeVectorResize - This input value (which is known to have vector type)
01478 /// is being zero extended or truncated to the specified vector type.  Try to
01479 /// replace it with a shuffle (and vector/vector bitcast) if possible.
01480 ///
01481 /// The source and destination vector types may have different element types.
01482 static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
01483                                          InstCombiner &IC) {
01484   // We can only do this optimization if the output is a multiple of the input
01485   // element size, or the input is a multiple of the output element size.
01486   // Convert the input type to have the same element type as the output.
01487   VectorType *SrcTy = cast<VectorType>(InVal->getType());
01488 
01489   if (SrcTy->getElementType() != DestTy->getElementType()) {
01490     // The input types don't need to be identical, but for now they must be the
01491     // same size.  There is no specific reason we couldn't handle things like
01492     // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
01493     // there yet.
01494     if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
01495         DestTy->getElementType()->getPrimitiveSizeInBits())
01496       return nullptr;
01497 
01498     SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
01499     InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
01500   }
01501 
01502   // Now that the element types match, get the shuffle mask and RHS of the
01503   // shuffle to use, which depends on whether we're increasing or decreasing the
01504   // size of the input.
01505   SmallVector<uint32_t, 16> ShuffleMask;
01506   Value *V2;
01507 
01508   if (SrcTy->getNumElements() > DestTy->getNumElements()) {
01509     // If we're shrinking the number of elements, just shuffle in the low
01510     // elements from the input and use undef as the second shuffle input.
01511     V2 = UndefValue::get(SrcTy);
01512     for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
01513       ShuffleMask.push_back(i);
01514 
01515   } else {
01516     // If we're increasing the number of elements, shuffle in all of the
01517     // elements from InVal and fill the rest of the result elements with zeros
01518     // from a constant zero.
01519     V2 = Constant::getNullValue(SrcTy);
01520     unsigned SrcElts = SrcTy->getNumElements();
01521     for (unsigned i = 0, e = SrcElts; i != e; ++i)
01522       ShuffleMask.push_back(i);
01523 
01524     // The excess elements reference the first element of the zero input.
01525     for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
01526       ShuffleMask.push_back(SrcElts);
01527   }
01528 
01529   return new ShuffleVectorInst(InVal, V2,
01530                                ConstantDataVector::get(V2->getContext(),
01531                                                        ShuffleMask));
01532 }
01533 
01534 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
01535   return Value % Ty->getPrimitiveSizeInBits() == 0;
01536 }
01537 
01538 static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
01539   return Value / Ty->getPrimitiveSizeInBits();
01540 }
01541 
01542 /// CollectInsertionElements - V is a value which is inserted into a vector of
01543 /// VecEltTy.  Look through the value to see if we can decompose it into
01544 /// insertions into the vector.  See the example in the comment for
01545 /// OptimizeIntegerToVectorInsertions for the pattern this handles.
01546 /// The type of V is always a non-zero multiple of VecEltTy's size.
01547 /// Shift is the number of bits between the lsb of V and the lsb of
01548 /// the vector.
01549 ///
01550 /// This returns false if the pattern can't be matched or true if it can,
01551 /// filling in Elements with the elements found here.
01552 static bool CollectInsertionElements(Value *V, unsigned Shift,
01553                                      SmallVectorImpl<Value *> &Elements,
01554                                      Type *VecEltTy, bool isBigEndian) {
01555   assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
01556          "Shift should be a multiple of the element type size");
01557 
01558   // Undef values never contribute useful bits to the result.
01559   if (isa<UndefValue>(V)) return true;
01560 
01561   // If we got down to a value of the right type, we win, try inserting into the
01562   // right element.
01563   if (V->getType() == VecEltTy) {
01564     // Inserting null doesn't actually insert any elements.
01565     if (Constant *C = dyn_cast<Constant>(V))
01566       if (C->isNullValue())
01567         return true;
01568 
01569     unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
01570     if (isBigEndian)
01571       ElementIndex = Elements.size() - ElementIndex - 1;
01572 
01573     // Fail if multiple elements are inserted into this slot.
01574     if (Elements[ElementIndex])
01575       return false;
01576 
01577     Elements[ElementIndex] = V;
01578     return true;
01579   }
01580 
01581   if (Constant *C = dyn_cast<Constant>(V)) {
01582     // Figure out the # elements this provides, and bitcast it or slice it up
01583     // as required.
01584     unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
01585                                         VecEltTy);
01586     // If the constant is the size of a vector element, we just need to bitcast
01587     // it to the right type so it gets properly inserted.
01588     if (NumElts == 1)
01589       return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
01590                                       Shift, Elements, VecEltTy, isBigEndian);
01591 
01592     // Okay, this is a constant that covers multiple elements.  Slice it up into
01593     // pieces and insert each element-sized piece into the vector.
01594     if (!isa<IntegerType>(C->getType()))
01595       C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
01596                                        C->getType()->getPrimitiveSizeInBits()));
01597     unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
01598     Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
01599 
01600     for (unsigned i = 0; i != NumElts; ++i) {
01601       unsigned ShiftI = Shift+i*ElementSize;
01602       Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
01603                                                                   ShiftI));
01604       Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
01605       if (!CollectInsertionElements(Piece, ShiftI, Elements, VecEltTy,
01606                                     isBigEndian))
01607         return false;
01608     }
01609     return true;
01610   }
01611 
01612   if (!V->hasOneUse()) return false;
01613 
01614   Instruction *I = dyn_cast<Instruction>(V);
01615   if (!I) return false;
01616   switch (I->getOpcode()) {
01617   default: return false; // Unhandled case.
01618   case Instruction::BitCast:
01619     return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
01620                                     isBigEndian);
01621   case Instruction::ZExt:
01622     if (!isMultipleOfTypeSize(
01623                           I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
01624                               VecEltTy))
01625       return false;
01626     return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
01627                                     isBigEndian);
01628   case Instruction::Or:
01629     return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
01630                                     isBigEndian) &&
01631            CollectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy,
01632                                     isBigEndian);
01633   case Instruction::Shl: {
01634     // Must be shifting by a constant that is a multiple of the element size.
01635     ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
01636     if (!CI) return false;
01637     Shift += CI->getZExtValue();
01638     if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
01639     return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
01640                                     isBigEndian);
01641   }
01642 
01643   }
01644 }
01645 
01646 
01647 /// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
01648 /// may be doing shifts and ors to assemble the elements of the vector manually.
01649 /// Try to rip the code out and replace it with insertelements.  This is to
01650 /// optimize code like this:
01651 ///
01652 ///    %tmp37 = bitcast float %inc to i32
01653 ///    %tmp38 = zext i32 %tmp37 to i64
01654 ///    %tmp31 = bitcast float %inc5 to i32
01655 ///    %tmp32 = zext i32 %tmp31 to i64
01656 ///    %tmp33 = shl i64 %tmp32, 32
01657 ///    %ins35 = or i64 %tmp33, %tmp38
01658 ///    %tmp43 = bitcast i64 %ins35 to <2 x float>
01659 ///
01660 /// Into two insertelements that do "buildvector{%inc, %inc5}".
01661 static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
01662                                                 InstCombiner &IC) {
01663   VectorType *DestVecTy = cast<VectorType>(CI.getType());
01664   Value *IntInput = CI.getOperand(0);
01665 
01666   SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
01667   if (!CollectInsertionElements(IntInput, 0, Elements,
01668                                 DestVecTy->getElementType(),
01669                                 IC.getDataLayout().isBigEndian()))
01670     return nullptr;
01671 
01672   // If we succeeded, we know that all of the element are specified by Elements
01673   // or are zero if Elements has a null entry.  Recast this as a set of
01674   // insertions.
01675   Value *Result = Constant::getNullValue(CI.getType());
01676   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
01677     if (!Elements[i]) continue;  // Unset element.
01678 
01679     Result = IC.Builder->CreateInsertElement(Result, Elements[i],
01680                                              IC.Builder->getInt32(i));
01681   }
01682 
01683   return Result;
01684 }
01685 
01686 
01687 /// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
01688 /// bitcast.  The various long double bitcasts can't get in here.
01689 static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI, InstCombiner &IC,
01690                                               const DataLayout &DL) {
01691   Value *Src = CI.getOperand(0);
01692   Type *DestTy = CI.getType();
01693 
01694   // If this is a bitcast from int to float, check to see if the int is an
01695   // extraction from a vector.
01696   Value *VecInput = nullptr;
01697   // bitcast(trunc(bitcast(somevector)))
01698   if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
01699       isa<VectorType>(VecInput->getType())) {
01700     VectorType *VecTy = cast<VectorType>(VecInput->getType());
01701     unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
01702 
01703     if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
01704       // If the element type of the vector doesn't match the result type,
01705       // bitcast it to be a vector type we can extract from.
01706       if (VecTy->getElementType() != DestTy) {
01707         VecTy = VectorType::get(DestTy,
01708                                 VecTy->getPrimitiveSizeInBits() / DestWidth);
01709         VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
01710       }
01711 
01712       unsigned Elt = 0;
01713       if (DL.isBigEndian())
01714         Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1;
01715       return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
01716     }
01717   }
01718 
01719   // bitcast(trunc(lshr(bitcast(somevector), cst))
01720   ConstantInt *ShAmt = nullptr;
01721   if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
01722                                 m_ConstantInt(ShAmt)))) &&
01723       isa<VectorType>(VecInput->getType())) {
01724     VectorType *VecTy = cast<VectorType>(VecInput->getType());
01725     unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
01726     if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
01727         ShAmt->getZExtValue() % DestWidth == 0) {
01728       // If the element type of the vector doesn't match the result type,
01729       // bitcast it to be a vector type we can extract from.
01730       if (VecTy->getElementType() != DestTy) {
01731         VecTy = VectorType::get(DestTy,
01732                                 VecTy->getPrimitiveSizeInBits() / DestWidth);
01733         VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
01734       }
01735 
01736       unsigned Elt = ShAmt->getZExtValue() / DestWidth;
01737       if (DL.isBigEndian())
01738         Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1 - Elt;
01739       return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
01740     }
01741   }
01742   return nullptr;
01743 }
01744 
01745 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
01746   // If the operands are integer typed then apply the integer transforms,
01747   // otherwise just apply the common ones.
01748   Value *Src = CI.getOperand(0);
01749   Type *SrcTy = Src->getType();
01750   Type *DestTy = CI.getType();
01751 
01752   // Get rid of casts from one type to the same type. These are useless and can
01753   // be replaced by the operand.
01754   if (DestTy == Src->getType())
01755     return ReplaceInstUsesWith(CI, Src);
01756 
01757   if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
01758     PointerType *SrcPTy = cast<PointerType>(SrcTy);
01759     Type *DstElTy = DstPTy->getElementType();
01760     Type *SrcElTy = SrcPTy->getElementType();
01761 
01762     // If we are casting a alloca to a pointer to a type of the same
01763     // size, rewrite the allocation instruction to allocate the "right" type.
01764     // There is no need to modify malloc calls because it is their bitcast that
01765     // needs to be cleaned up.
01766     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
01767       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
01768         return V;
01769 
01770     // If the source and destination are pointers, and this cast is equivalent
01771     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
01772     // This can enhance SROA and other transforms that want type-safe pointers.
01773     Constant *ZeroUInt =
01774       Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
01775     unsigned NumZeros = 0;
01776     while (SrcElTy != DstElTy &&
01777            isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
01778            SrcElTy->getNumContainedTypes() /* not "{}" */) {
01779       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
01780       ++NumZeros;
01781     }
01782 
01783     // If we found a path from the src to dest, create the getelementptr now.
01784     if (SrcElTy == DstElTy) {
01785       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
01786       return GetElementPtrInst::CreateInBounds(Src, Idxs);
01787     }
01788   }
01789 
01790   // Try to optimize int -> float bitcasts.
01791   if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
01792     if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this, DL))
01793       return I;
01794 
01795   if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
01796     if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
01797       Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
01798       return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
01799                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
01800       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
01801     }
01802 
01803     if (isa<IntegerType>(SrcTy)) {
01804       // If this is a cast from an integer to vector, check to see if the input
01805       // is a trunc or zext of a bitcast from vector.  If so, we can replace all
01806       // the casts with a shuffle and (potentially) a bitcast.
01807       if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
01808         CastInst *SrcCast = cast<CastInst>(Src);
01809         if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
01810           if (isa<VectorType>(BCIn->getOperand(0)->getType()))
01811             if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
01812                                                cast<VectorType>(DestTy), *this))
01813               return I;
01814       }
01815 
01816       // If the input is an 'or' instruction, we may be doing shifts and ors to
01817       // assemble the elements of the vector manually.  Try to rip the code out
01818       // and replace it with insertelements.
01819       if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
01820         return ReplaceInstUsesWith(CI, V);
01821     }
01822   }
01823 
01824   if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
01825     if (SrcVTy->getNumElements() == 1) {
01826       // If our destination is not a vector, then make this a straight
01827       // scalar-scalar cast.
01828       if (!DestTy->isVectorTy()) {
01829         Value *Elem =
01830           Builder->CreateExtractElement(Src,
01831                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
01832         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
01833       }
01834 
01835       // Otherwise, see if our source is an insert. If so, then use the scalar
01836       // component directly.
01837       if (InsertElementInst *IEI =
01838             dyn_cast<InsertElementInst>(CI.getOperand(0)))
01839         return CastInst::Create(Instruction::BitCast, IEI->getOperand(1),
01840                                 DestTy);
01841     }
01842   }
01843 
01844   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
01845     // Okay, we have (bitcast (shuffle ..)).  Check to see if this is
01846     // a bitcast to a vector with the same # elts.
01847     if (SVI->hasOneUse() && DestTy->isVectorTy() &&
01848         DestTy->getVectorNumElements() == SVI->getType()->getNumElements() &&
01849         SVI->getType()->getNumElements() ==
01850         SVI->getOperand(0)->getType()->getVectorNumElements()) {
01851       BitCastInst *Tmp;
01852       // If either of the operands is a cast from CI.getType(), then
01853       // evaluating the shuffle in the casted destination's type will allow
01854       // us to eliminate at least one cast.
01855       if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
01856            Tmp->getOperand(0)->getType() == DestTy) ||
01857           ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
01858            Tmp->getOperand(0)->getType() == DestTy)) {
01859         Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
01860         Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
01861         // Return a new shuffle vector.  Use the same element ID's, as we
01862         // know the vector types match #elts.
01863         return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
01864       }
01865     }
01866   }
01867 
01868   if (SrcTy->isPointerTy())
01869     return commonPointerCastTransforms(CI);
01870   return commonCastTransforms(CI);
01871 }
01872 
01873 Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
01874   // If the destination pointer element type is not the same as the source's
01875   // first do a bitcast to the destination type, and then the addrspacecast.
01876   // This allows the cast to be exposed to other transforms.
01877   Value *Src = CI.getOperand(0);
01878   PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType());
01879   PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType());
01880 
01881   Type *DestElemTy = DestTy->getElementType();
01882   if (SrcTy->getElementType() != DestElemTy) {
01883     Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace());
01884     if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) {
01885       // Handle vectors of pointers.
01886       MidTy = VectorType::get(MidTy, VT->getNumElements());
01887     }
01888 
01889     Value *NewBitCast = Builder->CreateBitCast(Src, MidTy);
01890     return new AddrSpaceCastInst(NewBitCast, CI.getType());
01891   }
01892 
01893   return commonPointerCastTransforms(CI);
01894 }