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