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