LLVM API Documentation

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