#include "InstCombineInternal.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Transforms/InstCombine/InstCombiner.h"
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "instcombine"
static Value *decomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
uint64_t &Offset) {
if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Offset = CI->getZExtValue();
Scale = 0;
return ConstantInt::get(Val->getType(), 0);
}
if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
if (OBI && !OBI->hasNoUnsignedWrap()) {
Scale = 1;
Offset = 0;
return Val;
}
if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
if (I->getOpcode() == Instruction::Shl) {
Scale = UINT64_C(1) << RHS->getZExtValue();
Offset = 0;
return I->getOperand(0);
}
if (I->getOpcode() == Instruction::Mul) {
Scale = RHS->getZExtValue();
Offset = 0;
return I->getOperand(0);
}
if (I->getOpcode() == Instruction::Add) {
unsigned SubScale;
Value *SubVal =
decomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
Offset += RHS->getZExtValue();
Scale = SubScale;
return SubVal;
}
}
}
Scale = 1;
Offset = 0;
return Val;
}
Instruction *InstCombinerImpl::PromoteCastOfAllocation(BitCastInst &CI,
AllocaInst &AI) {
PointerType *PTy = cast<PointerType>(CI.getType());
if (PTy->isOpaque())
return nullptr;
IRBuilderBase::InsertPointGuard Guard(Builder);
Builder.SetInsertPoint(&AI);
Type *AllocElTy = AI.getAllocatedType();
Type *CastElTy = PTy->getNonOpaquePointerElementType();
if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr;
bool AllocIsScalable = isa<ScalableVectorType>(AllocElTy);
bool CastIsScalable = isa<ScalableVectorType>(CastElTy);
if (AllocIsScalable != CastIsScalable) return nullptr;
Align AllocElTyAlign = DL.getABITypeAlign(AllocElTy);
Align CastElTyAlign = DL.getABITypeAlign(CastElTy);
if (CastElTyAlign < AllocElTyAlign) return nullptr;
if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr;
uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy).getKnownMinSize();
uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy).getKnownMinSize();
if (CastElTySize == 0 || AllocElTySize == 0) return nullptr;
uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy).getKnownMinSize();
uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy).getKnownMinSize();
if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr;
unsigned ArraySizeScale;
uint64_t ArrayOffset;
Value *NumElements = decomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
(AllocElTySize*ArrayOffset ) % CastElTySize != 0) return nullptr;
assert(!AllocIsScalable || (ArrayOffset == 1 && ArraySizeScale == 0));
unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
Value *Amt = nullptr;
if (Scale == 1) {
Amt = NumElements;
} else {
Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
Amt = Builder.CreateMul(Amt, NumElements);
}
if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
Offset, true);
Amt = Builder.CreateAdd(Amt, Off);
}
AllocaInst *New = Builder.CreateAlloca(CastElTy, AI.getAddressSpace(), Amt);
New->setAlignment(AI.getAlign());
New->takeName(&AI);
New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
if (!AI.hasOneUse()) {
Value *NewCast = Builder.CreateBitCast(New, AI.getType(), "tmpcast");
replaceInstUsesWith(AI, NewCast);
eraseInstFromFunction(AI);
}
return replaceInstUsesWith(CI, New);
}
Value *InstCombinerImpl::EvaluateInDifferentType(Value *V, Type *Ty,
bool isSigned) {
if (Constant *C = dyn_cast<Constant>(V)) {
C = ConstantExpr::getIntegerCast(C, Ty, isSigned );
return ConstantFoldConstant(C, DL, &TLI);
}
Instruction *I = cast<Instruction>(V);
Instruction *Res = nullptr;
unsigned Opc = I->getOpcode();
switch (Opc) {
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::AShr:
case Instruction::LShr:
case Instruction::Shl:
case Instruction::UDiv:
case Instruction::URem: {
Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
break;
}
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
if (I->getOperand(0)->getType() == Ty)
return I->getOperand(0);
Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
Opc == Instruction::SExt);
break;
case Instruction::Select: {
Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
Res = SelectInst::Create(I->getOperand(0), True, False);
break;
}
case Instruction::PHI: {
PHINode *OPN = cast<PHINode>(I);
PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
Value *V =
EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
NPN->addIncoming(V, OPN->getIncomingBlock(i));
}
Res = NPN;
break;
}
default:
llvm_unreachable("Unreachable!");
}
Res->takeName(I);
return InsertNewInstWith(Res, *I);
}
Instruction::CastOps
InstCombinerImpl::isEliminableCastPair(const CastInst *CI1,
const CastInst *CI2) {
Type *SrcTy = CI1->getSrcTy();
Type *MidTy = CI1->getDestTy();
Type *DstTy = CI2->getDestTy();
Instruction::CastOps firstOp = CI1->getOpcode();
Instruction::CastOps secondOp = CI2->getOpcode();
Type *SrcIntPtrTy =
SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr;
Type *MidIntPtrTy =
MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr;
Type *DstIntPtrTy =
DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr;
unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
DstTy, SrcIntPtrTy, MidIntPtrTy,
DstIntPtrTy);
if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
(Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
Res = 0;
return Instruction::CastOps(Res);
}
Instruction *InstCombinerImpl::commonCastTransforms(CastInst &CI) {
Value *Src = CI.getOperand(0);
Type *Ty = CI.getType();
if (auto *CSrc = dyn_cast<CastInst>(Src)) { if (Instruction::CastOps NewOpc = isEliminableCastPair(CSrc, &CI)) {
auto *Res = CastInst::Create(NewOpc, CSrc->getOperand(0), Ty);
if (CSrc->hasOneUse())
replaceAllDbgUsesWith(*CSrc, *Res, CI, DT);
return Res;
}
}
if (auto *Sel = dyn_cast<SelectInst>(Src)) {
auto *Cmp = dyn_cast<CmpInst>(Sel->getCondition());
if (!Cmp || Cmp->getOperand(0)->getType() != Sel->getType() ||
(CI.getOpcode() == Instruction::Trunc &&
shouldChangeType(CI.getSrcTy(), CI.getType()))) {
if (Instruction *NV = FoldOpIntoSelect(CI, Sel)) {
replaceAllDbgUsesWith(*Sel, *NV, CI, DT);
return NV;
}
}
}
if (auto *PN = dyn_cast<PHINode>(Src)) {
if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() ||
shouldChangeType(CI.getSrcTy(), CI.getType()))
if (Instruction *NV = foldOpIntoPhi(CI, PN))
return NV;
}
Value *X;
ArrayRef<int> Mask;
if (match(Src, m_OneUse(m_Shuffle(m_Value(X), m_Undef(), m_Mask(Mask))))) {
auto *SrcTy = dyn_cast<FixedVectorType>(X->getType());
auto *DestTy = dyn_cast<FixedVectorType>(Ty);
if (SrcTy && DestTy &&
SrcTy->getNumElements() == DestTy->getNumElements() &&
SrcTy->getPrimitiveSizeInBits() == DestTy->getPrimitiveSizeInBits()) {
Value *CastX = Builder.CreateCast(CI.getOpcode(), X, DestTy);
return new ShuffleVectorInst(CastX, Mask);
}
}
return nullptr;
}
static bool canAlwaysEvaluateInType(Value *V, Type *Ty) {
if (isa<Constant>(V))
return true;
Value *X;
if ((match(V, m_ZExtOrSExt(m_Value(X))) || match(V, m_Trunc(m_Value(X)))) &&
X->getType() == Ty)
return true;
return false;
}
static bool canNotEvaluateInType(Value *V, Type *Ty) {
assert(!isa<Constant>(V) && "Constant should already be handled.");
if (!isa<Instruction>(V))
return true;
if (!V->hasOneUse())
return true;
return false;
}
static bool canEvaluateTruncated(Value *V, Type *Ty, InstCombinerImpl &IC,
Instruction *CxtI) {
if (canAlwaysEvaluateInType(V, Ty))
return true;
if (canNotEvaluateInType(V, Ty))
return false;
auto *I = cast<Instruction>(V);
Type *OrigTy = V->getType();
switch (I->getOpcode()) {
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
case Instruction::UDiv:
case Instruction::URem: {
uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
uint32_t BitWidth = Ty->getScalarSizeInBits();
assert(BitWidth < OrigBitWidth && "Unexpected bitwidths!");
APInt Mask = APInt::getBitsSetFrom(OrigBitWidth, BitWidth);
if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) &&
IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) {
return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
}
break;
}
case Instruction::Shl: {
uint32_t BitWidth = Ty->getScalarSizeInBits();
KnownBits AmtKnownBits =
llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout());
if (AmtKnownBits.getMaxValue().ult(BitWidth))
return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
break;
}
case Instruction::LShr: {
uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
uint32_t BitWidth = Ty->getScalarSizeInBits();
KnownBits AmtKnownBits =
llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout());
APInt ShiftedBits = APInt::getBitsSetFrom(OrigBitWidth, BitWidth);
if (AmtKnownBits.getMaxValue().ult(BitWidth) &&
IC.MaskedValueIsZero(I->getOperand(0), ShiftedBits, 0, CxtI)) {
return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
}
break;
}
case Instruction::AShr: {
uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
uint32_t BitWidth = Ty->getScalarSizeInBits();
KnownBits AmtKnownBits =
llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout());
unsigned ShiftedBits = OrigBitWidth - BitWidth;
if (AmtKnownBits.getMaxValue().ult(BitWidth) &&
ShiftedBits < IC.ComputeNumSignBits(I->getOperand(0), 0, CxtI))
return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
break;
}
case Instruction::Trunc:
return true;
case Instruction::ZExt:
case Instruction::SExt:
return true;
case Instruction::Select: {
SelectInst *SI = cast<SelectInst>(I);
return canEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) &&
canEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI);
}
case Instruction::PHI: {
PHINode *PN = cast<PHINode>(I);
for (Value *IncValue : PN->incoming_values())
if (!canEvaluateTruncated(IncValue, Ty, IC, CxtI))
return false;
return true;
}
default:
break;
}
return false;
}
static Instruction *foldVecTruncToExtElt(TruncInst &Trunc,
InstCombinerImpl &IC) {
Value *TruncOp = Trunc.getOperand(0);
Type *DestType = Trunc.getType();
if (!TruncOp->hasOneUse() || !isa<IntegerType>(DestType))
return nullptr;
Value *VecInput = nullptr;
ConstantInt *ShiftVal = nullptr;
if (!match(TruncOp, m_CombineOr(m_BitCast(m_Value(VecInput)),
m_LShr(m_BitCast(m_Value(VecInput)),
m_ConstantInt(ShiftVal)))) ||
!isa<VectorType>(VecInput->getType()))
return nullptr;
VectorType *VecType = cast<VectorType>(VecInput->getType());
unsigned VecWidth = VecType->getPrimitiveSizeInBits();
unsigned DestWidth = DestType->getPrimitiveSizeInBits();
unsigned ShiftAmount = ShiftVal ? ShiftVal->getZExtValue() : 0;
if ((VecWidth % DestWidth != 0) || (ShiftAmount % DestWidth != 0))
return nullptr;
unsigned NumVecElts = VecWidth / DestWidth;
if (VecType->getElementType() != DestType) {
VecType = FixedVectorType::get(DestType, NumVecElts);
VecInput = IC.Builder.CreateBitCast(VecInput, VecType, "bc");
}
unsigned Elt = ShiftAmount / DestWidth;
if (IC.getDataLayout().isBigEndian())
Elt = NumVecElts - 1 - Elt;
return ExtractElementInst::Create(VecInput, IC.Builder.getInt32(Elt));
}
Instruction *InstCombinerImpl::narrowFunnelShift(TruncInst &Trunc) {
assert((isa<VectorType>(Trunc.getSrcTy()) ||
shouldChangeType(Trunc.getSrcTy(), Trunc.getType())) &&
"Don't narrow to an illegal scalar type");
Type *DestTy = Trunc.getType();
unsigned NarrowWidth = DestTy->getScalarSizeInBits();
unsigned WideWidth = Trunc.getSrcTy()->getScalarSizeInBits();
if (!isPowerOf2_32(NarrowWidth))
return nullptr;
BinaryOperator *Or0, *Or1;
if (!match(Trunc.getOperand(0), m_OneUse(m_Or(m_BinOp(Or0), m_BinOp(Or1)))))
return nullptr;
Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) ||
!match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) ||
Or0->getOpcode() == Or1->getOpcode())
return nullptr;
if (Or0->getOpcode() == BinaryOperator::LShr) {
std::swap(Or0, Or1);
std::swap(ShVal0, ShVal1);
std::swap(ShAmt0, ShAmt1);
}
assert(Or0->getOpcode() == BinaryOperator::Shl &&
Or1->getOpcode() == BinaryOperator::LShr &&
"Illegal or(shift,shift) pair");
auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
unsigned MaxShiftAmountWidth = Log2_32(NarrowWidth);
APInt HiBitMask = ~APInt::getLowBitsSet(WideWidth, MaxShiftAmountWidth);
if (ShVal0 == ShVal1 || MaskedValueIsZero(L, HiBitMask))
if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L)))))
return L;
if (ShVal0 != ShVal1)
return nullptr;
Value *X;
unsigned Mask = Width - 1;
if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))
return X;
if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))))
return X;
return nullptr;
};
Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, NarrowWidth);
bool IsFshl = true; if (!ShAmt) {
ShAmt = matchShiftAmount(ShAmt1, ShAmt0, NarrowWidth);
IsFshl = false; }
if (!ShAmt)
return nullptr;
APInt HiBitMask = APInt::getHighBitsSet(WideWidth, WideWidth - NarrowWidth);
if (!MaskedValueIsZero(ShVal1, HiBitMask, 0, &Trunc))
return nullptr;
Value *NarrowShAmt = Builder.CreateTrunc(ShAmt, DestTy);
Value *X, *Y;
X = Y = Builder.CreateTrunc(ShVal0, DestTy);
if (ShVal0 != ShVal1)
Y = Builder.CreateTrunc(ShVal1, DestTy);
Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
Function *F = Intrinsic::getDeclaration(Trunc.getModule(), IID, DestTy);
return CallInst::Create(F, {X, Y, NarrowShAmt});
}
Instruction *InstCombinerImpl::narrowBinOp(TruncInst &Trunc) {
Type *SrcTy = Trunc.getSrcTy();
Type *DestTy = Trunc.getType();
unsigned SrcWidth = SrcTy->getScalarSizeInBits();
unsigned DestWidth = DestTy->getScalarSizeInBits();
if (!isa<VectorType>(SrcTy) && !shouldChangeType(SrcTy, DestTy))
return nullptr;
BinaryOperator *BinOp;
if (!match(Trunc.getOperand(0), m_OneUse(m_BinOp(BinOp))))
return nullptr;
Value *BinOp0 = BinOp->getOperand(0);
Value *BinOp1 = BinOp->getOperand(1);
switch (BinOp->getOpcode()) {
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul: {
Constant *C;
if (match(BinOp0, m_Constant(C))) {
Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy);
Value *TruncX = Builder.CreateTrunc(BinOp1, DestTy);
return BinaryOperator::Create(BinOp->getOpcode(), NarrowC, TruncX);
}
if (match(BinOp1, m_Constant(C))) {
Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy);
Value *TruncX = Builder.CreateTrunc(BinOp0, DestTy);
return BinaryOperator::Create(BinOp->getOpcode(), TruncX, NarrowC);
}
Value *X;
if (match(BinOp0, m_ZExtOrSExt(m_Value(X))) && X->getType() == DestTy) {
Value *NarrowOp1 = Builder.CreateTrunc(BinOp1, DestTy);
return BinaryOperator::Create(BinOp->getOpcode(), X, NarrowOp1);
}
if (match(BinOp1, m_ZExtOrSExt(m_Value(X))) && X->getType() == DestTy) {
Value *NarrowOp0 = Builder.CreateTrunc(BinOp0, DestTy);
return BinaryOperator::Create(BinOp->getOpcode(), NarrowOp0, X);
}
break;
}
case Instruction::LShr:
case Instruction::AShr: {
Value *A;
Constant *C;
if (match(BinOp0, m_Trunc(m_Value(A))) && match(BinOp1, m_Constant(C))) {
unsigned MaxShiftAmt = SrcWidth - DestWidth;
if (match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULE,
APInt(SrcWidth, MaxShiftAmt)))) {
auto *OldShift = cast<Instruction>(Trunc.getOperand(0));
bool IsExact = OldShift->isExact();
auto *ShAmt = ConstantExpr::getIntegerCast(C, A->getType(), true);
ShAmt = Constant::mergeUndefsWith(ShAmt, C);
Value *Shift =
OldShift->getOpcode() == Instruction::AShr
? Builder.CreateAShr(A, ShAmt, OldShift->getName(), IsExact)
: Builder.CreateLShr(A, ShAmt, OldShift->getName(), IsExact);
return CastInst::CreateTruncOrBitCast(Shift, DestTy);
}
}
break;
}
default: break;
}
if (Instruction *NarrowOr = narrowFunnelShift(Trunc))
return NarrowOr;
return nullptr;
}
static Instruction *shrinkSplatShuffle(TruncInst &Trunc,
InstCombiner::BuilderTy &Builder) {
auto *Shuf = dyn_cast<ShuffleVectorInst>(Trunc.getOperand(0));
if (Shuf && Shuf->hasOneUse() && match(Shuf->getOperand(1), m_Undef()) &&
is_splat(Shuf->getShuffleMask()) &&
Shuf->getType() == Shuf->getOperand(0)->getType()) {
Value *NarrowOp = Builder.CreateTrunc(Shuf->getOperand(0), Trunc.getType());
return new ShuffleVectorInst(NarrowOp, Shuf->getShuffleMask());
}
return nullptr;
}
static Instruction *shrinkInsertElt(CastInst &Trunc,
InstCombiner::BuilderTy &Builder) {
Instruction::CastOps Opcode = Trunc.getOpcode();
assert((Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) &&
"Unexpected instruction for shrinking");
auto *InsElt = dyn_cast<InsertElementInst>(Trunc.getOperand(0));
if (!InsElt || !InsElt->hasOneUse())
return nullptr;
Type *DestTy = Trunc.getType();
Type *DestScalarTy = DestTy->getScalarType();
Value *VecOp = InsElt->getOperand(0);
Value *ScalarOp = InsElt->getOperand(1);
Value *Index = InsElt->getOperand(2);
if (match(VecOp, m_Undef())) {
UndefValue *NarrowUndef = UndefValue::get(DestTy);
Value *NarrowOp = Builder.CreateCast(Opcode, ScalarOp, DestScalarTy);
return InsertElementInst::Create(NarrowUndef, NarrowOp, Index);
}
return nullptr;
}
Instruction *InstCombinerImpl::visitTrunc(TruncInst &Trunc) {
if (Instruction *Result = commonCastTransforms(Trunc))
return Result;
Value *Src = Trunc.getOperand(0);
Type *DestTy = Trunc.getType(), *SrcTy = Src->getType();
unsigned DestWidth = DestTy->getScalarSizeInBits();
unsigned SrcWidth = SrcTy->getScalarSizeInBits();
if ((DestTy->isVectorTy() || shouldChangeType(SrcTy, DestTy)) &&
canEvaluateTruncated(Src, DestTy, *this, &Trunc)) {
LLVM_DEBUG(
dbgs() << "ICE: EvaluateInDifferentType converting expression type"
" to avoid cast: "
<< Trunc << '\n');
Value *Res = EvaluateInDifferentType(Src, DestTy, false);
assert(Res->getType() == DestTy);
return replaceInstUsesWith(Trunc, Res);
}
if (auto *DestITy = dyn_cast<IntegerType>(DestTy)) {
if (DestWidth * 2 < SrcWidth) {
auto *NewDestTy = DestITy->getExtendedType();
if (shouldChangeType(SrcTy, NewDestTy) &&
canEvaluateTruncated(Src, NewDestTy, *this, &Trunc)) {
LLVM_DEBUG(
dbgs() << "ICE: EvaluateInDifferentType converting expression type"
" to reduce the width of operand of"
<< Trunc << '\n');
Value *Res = EvaluateInDifferentType(Src, NewDestTy, false);
return new TruncInst(Res, DestTy);
}
}
}
Value *LHS, *RHS;
if (SelectInst *Sel = dyn_cast<SelectInst>(Src))
if (matchSelectPattern(Sel, LHS, RHS).Flavor != SPF_UNKNOWN)
return nullptr;
if (SimplifyDemandedInstructionBits(Trunc))
return &Trunc;
if (DestWidth == 1) {
Value *Zero = Constant::getNullValue(SrcTy);
if (DestTy->isIntegerTy()) {
Value *And = Builder.CreateAnd(Src, ConstantInt::get(SrcTy, 1));
return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
}
Value *X;
Constant *C;
if (match(Src, m_OneUse(m_LShr(m_Value(X), m_Constant(C))))) {
Constant *One = ConstantInt::get(SrcTy, APInt(SrcWidth, 1));
Constant *MaskC = ConstantExpr::getShl(One, C);
Value *And = Builder.CreateAnd(X, MaskC);
return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
}
if (match(Src, m_OneUse(m_c_Or(m_LShr(m_Value(X), m_Constant(C)),
m_Deferred(X))))) {
Constant *One = ConstantInt::get(SrcTy, APInt(SrcWidth, 1));
Constant *MaskC = ConstantExpr::getShl(One, C);
MaskC = ConstantExpr::getOr(MaskC, One);
Value *And = Builder.CreateAnd(X, MaskC);
return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
}
}
Value *A, *B;
Constant *C;
if (match(Src, m_LShr(m_SExt(m_Value(A)), m_Constant(C)))) {
unsigned AWidth = A->getType()->getScalarSizeInBits();
unsigned MaxShiftAmt = SrcWidth - std::max(DestWidth, AWidth);
auto *OldSh = cast<Instruction>(Src);
bool IsExact = OldSh->isExact();
if (match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULE,
APInt(SrcWidth, MaxShiftAmt)))) {
if (A->getType() == DestTy) {
Constant *MaxAmt = ConstantInt::get(SrcTy, DestWidth - 1, false);
Constant *ShAmt = ConstantExpr::getUMin(C, MaxAmt);
ShAmt = ConstantExpr::getTrunc(ShAmt, A->getType());
ShAmt = Constant::mergeUndefsWith(ShAmt, C);
return IsExact ? BinaryOperator::CreateExactAShr(A, ShAmt)
: BinaryOperator::CreateAShr(A, ShAmt);
}
if (Src->hasOneUse()) {
Constant *MaxAmt = ConstantInt::get(SrcTy, AWidth - 1, false);
Constant *ShAmt = ConstantExpr::getUMin(C, MaxAmt);
ShAmt = ConstantExpr::getTrunc(ShAmt, A->getType());
Value *Shift = Builder.CreateAShr(A, ShAmt, "", IsExact);
return CastInst::CreateIntegerCast(Shift, DestTy, true);
}
}
}
if (Instruction *I = narrowBinOp(Trunc))
return I;
if (Instruction *I = shrinkSplatShuffle(Trunc, Builder))
return I;
if (Instruction *I = shrinkInsertElt(Trunc, Builder))
return I;
if (Src->hasOneUse() &&
(isa<VectorType>(SrcTy) || shouldChangeType(SrcTy, DestTy))) {
if (match(Src, m_Shl(m_Value(A), m_Constant(C))) &&
!match(A, m_Shr(m_Value(), m_Constant()))) {
APInt Threshold = APInt(C->getType()->getScalarSizeInBits(), DestWidth);
if (match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold))) {
Value *NewTrunc = Builder.CreateTrunc(A, DestTy, A->getName() + ".tr");
return BinaryOperator::Create(Instruction::Shl, NewTrunc,
ConstantExpr::getTrunc(C, DestTy));
}
}
}
if (Instruction *I = foldVecTruncToExtElt(Trunc, *this))
return I;
Value *VecOp;
ConstantInt *Cst;
if (match(Src, m_OneUse(m_ExtractElt(m_Value(VecOp), m_ConstantInt(Cst))))) {
auto *VecOpTy = cast<VectorType>(VecOp->getType());
auto VecElts = VecOpTy->getElementCount();
if (SrcWidth % DestWidth == 0) {
uint64_t TruncRatio = SrcWidth / DestWidth;
uint64_t BitCastNumElts = VecElts.getKnownMinValue() * TruncRatio;
uint64_t VecOpIdx = Cst->getZExtValue();
uint64_t NewIdx = DL.isBigEndian() ? (VecOpIdx + 1) * TruncRatio - 1
: VecOpIdx * TruncRatio;
assert(BitCastNumElts <= std::numeric_limits<uint32_t>::max() &&
"overflow 32-bits");
auto *BitCastTo =
VectorType::get(DestTy, BitCastNumElts, VecElts.isScalable());
Value *BitCast = Builder.CreateBitCast(VecOp, BitCastTo);
return ExtractElementInst::Create(BitCast, Builder.getInt32(NewIdx));
}
}
if (match(Src, m_OneUse(m_Intrinsic<Intrinsic::ctlz>(m_ZExt(m_Value(A)),
m_Value(B))))) {
unsigned AWidth = A->getType()->getScalarSizeInBits();
if (AWidth == DestWidth && AWidth > Log2_32(SrcWidth)) {
Value *WidthDiff = ConstantInt::get(A->getType(), SrcWidth - AWidth);
Value *NarrowCtlz =
Builder.CreateIntrinsic(Intrinsic::ctlz, {Trunc.getType()}, {A, B});
return BinaryOperator::CreateAdd(NarrowCtlz, WidthDiff);
}
}
if (match(Src, m_VScale(DL))) {
if (Trunc.getFunction() &&
Trunc.getFunction()->hasFnAttribute(Attribute::VScaleRange)) {
Attribute Attr =
Trunc.getFunction()->getFnAttribute(Attribute::VScaleRange);
if (Optional<unsigned> MaxVScale = Attr.getVScaleRangeMax()) {
if (Log2_32(*MaxVScale) < DestWidth) {
Value *VScale = Builder.CreateVScale(ConstantInt::get(DestTy, 1));
return replaceInstUsesWith(Trunc, VScale);
}
}
}
}
return nullptr;
}
Instruction *InstCombinerImpl::transformZExtICmp(ICmpInst *Cmp, ZExtInst &Zext) {
const APInt *Op1CV;
if (match(Cmp->getOperand(1), m_APInt(Op1CV))) {
if (Cmp->getPredicate() == ICmpInst::ICMP_SLT && Op1CV->isZero()) {
Value *In = Cmp->getOperand(0);
Value *Sh = ConstantInt::get(In->getType(),
In->getType()->getScalarSizeInBits() - 1);
In = Builder.CreateLShr(In, Sh, In->getName() + ".lobit");
if (In->getType() != Zext.getType())
In = Builder.CreateIntCast(In, Zext.getType(), false );
return replaceInstUsesWith(Zext, In);
}
if ((Op1CV->isZero() || Op1CV->isPowerOf2()) &&
Cmp->isEquality()) {
KnownBits Known = computeKnownBits(Cmp->getOperand(0), 0, &Zext);
APInt KnownZeroMask(~Known.Zero);
if (KnownZeroMask.isPowerOf2()) { bool isNE = Cmp->getPredicate() == ICmpInst::ICMP_NE;
if (!Op1CV->isZero() && (*Op1CV != KnownZeroMask)) {
Constant *Res = ConstantInt::get(Zext.getType(), isNE);
return replaceInstUsesWith(Zext, Res);
}
uint32_t ShAmt = KnownZeroMask.logBase2();
Value *In = Cmp->getOperand(0);
if (ShAmt) {
In = Builder.CreateLShr(In, ConstantInt::get(In->getType(), ShAmt),
In->getName() + ".lobit");
}
if (!Op1CV->isZero() == isNE) { Constant *One = ConstantInt::get(In->getType(), 1);
In = Builder.CreateXor(In, One);
}
if (Zext.getType() == In->getType())
return replaceInstUsesWith(Zext, In);
Value *IntCast = Builder.CreateIntCast(In, Zext.getType(), false);
return replaceInstUsesWith(Zext, IntCast);
}
}
}
if (Cmp->isEquality() && Zext.getType() == Cmp->getOperand(0)->getType()) {
Value *X, *ShAmt;
if (Cmp->hasOneUse() && match(Cmp->getOperand(1), m_ZeroInt()) &&
match(Cmp->getOperand(0),
m_OneUse(m_c_And(m_Shl(m_One(), m_Value(ShAmt)), m_Value(X))))) {
if (Cmp->getPredicate() == ICmpInst::ICMP_EQ)
X = Builder.CreateNot(X);
Value *Lshr = Builder.CreateLShr(X, ShAmt);
Value *And1 = Builder.CreateAnd(Lshr, ConstantInt::get(X->getType(), 1));
return replaceInstUsesWith(Zext, And1);
}
if (IntegerType *ITy = dyn_cast<IntegerType>(Zext.getType())) {
Value *LHS = Cmp->getOperand(0);
Value *RHS = Cmp->getOperand(1);
KnownBits KnownLHS = computeKnownBits(LHS, 0, &Zext);
KnownBits KnownRHS = computeKnownBits(RHS, 0, &Zext);
if (KnownLHS == KnownRHS) {
APInt KnownBits = KnownLHS.Zero | KnownLHS.One;
APInt UnknownBit = ~KnownBits;
if (UnknownBit.countPopulation() == 1) {
Value *Result = Builder.CreateXor(LHS, RHS);
if (KnownLHS.One.uge(UnknownBit))
Result = Builder.CreateAnd(Result,
ConstantInt::get(ITy, UnknownBit));
Result = Builder.CreateLShr(
Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
if (Cmp->getPredicate() == ICmpInst::ICMP_EQ)
Result = Builder.CreateXor(Result, ConstantInt::get(ITy, 1));
Result->takeName(Cmp);
return replaceInstUsesWith(Zext, Result);
}
}
}
}
return nullptr;
}
static bool canEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear,
InstCombinerImpl &IC, Instruction *CxtI) {
BitsToClear = 0;
if (canAlwaysEvaluateInType(V, Ty))
return true;
if (canNotEvaluateInType(V, Ty))
return false;
auto *I = cast<Instruction>(V);
unsigned Tmp;
switch (I->getOpcode()) {
case Instruction::ZExt: case Instruction::SExt: case Instruction::Trunc: return true;
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) ||
!canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI))
return false;
if (BitsToClear == 0 && Tmp == 0)
return true;
if (Tmp == 0 && I->isBitwiseLogicOp()) {
unsigned VSize = V->getType()->getScalarSizeInBits();
if (IC.MaskedValueIsZero(I->getOperand(1),
APInt::getHighBitsSet(VSize, BitsToClear),
0, CxtI)) {
if (I->getOpcode() == Instruction::And)
BitsToClear = 0;
return true;
}
}
return false;
case Instruction::Shl: {
const APInt *Amt;
if (match(I->getOperand(1), m_APInt(Amt))) {
if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
return false;
uint64_t ShiftAmt = Amt->getZExtValue();
BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
return true;
}
return false;
}
case Instruction::LShr: {
const APInt *Amt;
if (match(I->getOperand(1), m_APInt(Amt))) {
if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
return false;
BitsToClear += Amt->getZExtValue();
if (BitsToClear > V->getType()->getScalarSizeInBits())
BitsToClear = V->getType()->getScalarSizeInBits();
return true;
}
return false;
}
case Instruction::Select:
if (!canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) ||
!canEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) ||
Tmp != BitsToClear)
return false;
return true;
case Instruction::PHI: {
PHINode *PN = cast<PHINode>(I);
if (!canEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI))
return false;
for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
if (!canEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) ||
Tmp != BitsToClear)
return false;
return true;
}
default:
return false;
}
}
Instruction *InstCombinerImpl::visitZExt(ZExtInst &CI) {
if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
return nullptr;
if (Instruction *Result = commonCastTransforms(CI))
return Result;
Value *Src = CI.getOperand(0);
Type *SrcTy = Src->getType(), *DestTy = CI.getType();
unsigned BitsToClear;
if (shouldChangeType(SrcTy, DestTy) &&
canEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)) {
assert(BitsToClear <= SrcTy->getScalarSizeInBits() &&
"Can't clear more bits than in SrcTy");
LLVM_DEBUG(
dbgs() << "ICE: EvaluateInDifferentType converting expression type"
" to avoid zero extend: "
<< CI << '\n');
Value *Res = EvaluateInDifferentType(Src, DestTy, false);
assert(Res->getType() == DestTy);
if (auto *SrcOp = dyn_cast<Instruction>(Src))
if (SrcOp->hasOneUse())
replaceAllDbgUsesWith(*SrcOp, *Res, CI, DT);
uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
uint32_t DestBitSize = DestTy->getScalarSizeInBits();
if (MaskedValueIsZero(Res,
APInt::getHighBitsSet(DestBitSize,
DestBitSize-SrcBitsKept),
0, &CI))
return replaceInstUsesWith(CI, Res);
Constant *C = ConstantInt::get(Res->getType(),
APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
return BinaryOperator::CreateAnd(Res, C);
}
if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {
Value *A = CSrc->getOperand(0);
unsigned SrcSize = A->getType()->getScalarSizeInBits();
unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
unsigned DstSize = CI.getType()->getScalarSizeInBits();
if (SrcSize < DstSize) {
APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Value *And = Builder.CreateAnd(A, AndConst, CSrc->getName() + ".mask");
return new ZExtInst(And, CI.getType());
}
if (SrcSize == DstSize) {
APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
AndValue));
}
if (SrcSize > DstSize) {
Value *Trunc = Builder.CreateTrunc(A, CI.getType());
APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
return BinaryOperator::CreateAnd(Trunc,
ConstantInt::get(Trunc->getType(),
AndValue));
}
}
if (ICmpInst *Cmp = dyn_cast<ICmpInst>(Src))
return transformZExtICmp(Cmp, CI);
Constant *C;
Value *X;
if (match(Src, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
X->getType() == CI.getType())
return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
Value *And;
if (match(Src, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
X->getType() == CI.getType()) {
Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
return BinaryOperator::CreateXor(Builder.CreateAnd(X, ZC), ZC);
}
if (match(Src, m_VScale(DL))) {
if (CI.getFunction() &&
CI.getFunction()->hasFnAttribute(Attribute::VScaleRange)) {
Attribute Attr = CI.getFunction()->getFnAttribute(Attribute::VScaleRange);
if (Optional<unsigned> MaxVScale = Attr.getVScaleRangeMax()) {
unsigned TypeWidth = Src->getType()->getScalarSizeInBits();
if (Log2_32(*MaxVScale) < TypeWidth) {
Value *VScale = Builder.CreateVScale(ConstantInt::get(DestTy, 1));
return replaceInstUsesWith(CI, VScale);
}
}
}
}
return nullptr;
}
Instruction *InstCombinerImpl::transformSExtICmp(ICmpInst *ICI,
Instruction &CI) {
Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
ICmpInst::Predicate Pred = ICI->getPredicate();
if (!Op1->getType()->isIntOrIntVectorTy())
return nullptr;
if ((Pred == ICmpInst::ICMP_SLT && match(Op1, m_ZeroInt())) ||
(Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))) {
Value *Sh = ConstantInt::get(Op0->getType(),
Op0->getType()->getScalarSizeInBits() - 1);
Value *In = Builder.CreateAShr(Op0, Sh, Op0->getName() + ".lobit");
if (In->getType() != CI.getType())
In = Builder.CreateIntCast(In, CI.getType(), true );
if (Pred == ICmpInst::ICMP_SGT)
In = Builder.CreateNot(In, In->getName() + ".not");
return replaceInstUsesWith(CI, In);
}
if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
if (ICI->hasOneUse() &&
ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
KnownBits Known = computeKnownBits(Op0, 0, &CI);
APInt KnownZeroMask(~Known.Zero);
if (KnownZeroMask.isPowerOf2()) {
Value *In = ICI->getOperand(0);
if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
Value *V = Pred == ICmpInst::ICMP_NE ?
ConstantInt::getAllOnesValue(CI.getType()) :
ConstantInt::getNullValue(CI.getType());
return replaceInstUsesWith(CI, V);
}
if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
if (ShiftAmt)
In = Builder.CreateLShr(In,
ConstantInt::get(In->getType(), ShiftAmt));
In = Builder.CreateAdd(In,
ConstantInt::getAllOnesValue(In->getType()),
"sext");
} else {
unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
if (ShiftAmt)
In = Builder.CreateShl(In,
ConstantInt::get(In->getType(), ShiftAmt));
In = Builder.CreateAShr(In, ConstantInt::get(In->getType(),
KnownZeroMask.getBitWidth() - 1), "sext");
}
if (CI.getType() == In->getType())
return replaceInstUsesWith(CI, In);
return CastInst::CreateIntegerCast(In, CI.getType(), true);
}
}
}
return nullptr;
}
static bool canEvaluateSExtd(Value *V, Type *Ty) {
assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
"Can't sign extend type to a smaller type");
if (canAlwaysEvaluateInType(V, Ty))
return true;
if (canNotEvaluateInType(V, Ty))
return false;
auto *I = cast<Instruction>(V);
switch (I->getOpcode()) {
case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc: return true;
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
return canEvaluateSExtd(I->getOperand(0), Ty) &&
canEvaluateSExtd(I->getOperand(1), Ty);
case Instruction::Select:
return canEvaluateSExtd(I->getOperand(1), Ty) &&
canEvaluateSExtd(I->getOperand(2), Ty);
case Instruction::PHI: {
PHINode *PN = cast<PHINode>(I);
for (Value *IncValue : PN->incoming_values())
if (!canEvaluateSExtd(IncValue, Ty)) return false;
return true;
}
default:
break;
}
return false;
}
Instruction *InstCombinerImpl::visitSExt(SExtInst &CI) {
if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
return nullptr;
if (Instruction *I = commonCastTransforms(CI))
return I;
Value *Src = CI.getOperand(0);
Type *SrcTy = Src->getType(), *DestTy = CI.getType();
unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
unsigned DestBitSize = DestTy->getScalarSizeInBits();
if (isKnownNonNegative(Src, DL, 0, &AC, &CI, &DT))
return CastInst::Create(Instruction::ZExt, Src, DestTy);
if (shouldChangeType(SrcTy, DestTy) && canEvaluateSExtd(Src, DestTy)) {
LLVM_DEBUG(
dbgs() << "ICE: EvaluateInDifferentType converting expression type"
" to avoid sign extend: "
<< CI << '\n');
Value *Res = EvaluateInDifferentType(Src, DestTy, true);
assert(Res->getType() == DestTy);
if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize)
return replaceInstUsesWith(CI, Res);
Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
return BinaryOperator::CreateAShr(Builder.CreateShl(Res, ShAmt, "sext"),
ShAmt);
}
Value *X;
if (match(Src, m_Trunc(m_Value(X)))) {
unsigned XBitSize = X->getType()->getScalarSizeInBits();
if (ComputeNumSignBits(X, 0, &CI) > XBitSize - SrcBitSize)
return CastInst::CreateIntegerCast(X, DestTy, true);
if (Src->hasOneUse() && X->getType() == DestTy) {
Constant *ShAmt = ConstantInt::get(DestTy, DestBitSize - SrcBitSize);
return BinaryOperator::CreateAShr(Builder.CreateShl(X, ShAmt), ShAmt);
}
Value *Y;
if (Src->hasOneUse() &&
match(X, m_LShr(m_Value(Y),
m_SpecificIntAllowUndef(XBitSize - SrcBitSize)))) {
Value *Ashr = Builder.CreateAShr(Y, XBitSize - SrcBitSize);
return CastInst::CreateIntegerCast(Ashr, DestTy, true);
}
}
if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
return transformSExtICmp(ICI, CI);
Value *A = nullptr;
Constant *BA = nullptr, *CA = nullptr;
if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_Constant(BA)),
m_Constant(CA))) &&
BA->isElementWiseEqual(CA) && A->getType() == DestTy) {
Constant *WideCurrShAmt = ConstantExpr::getSExt(CA, DestTy);
Constant *NumLowbitsLeft = ConstantExpr::getSub(
ConstantInt::get(DestTy, SrcTy->getScalarSizeInBits()), WideCurrShAmt);
Constant *NewShAmt = ConstantExpr::getSub(
ConstantInt::get(DestTy, DestTy->getScalarSizeInBits()),
NumLowbitsLeft);
NewShAmt =
Constant::mergeUndefsWith(Constant::mergeUndefsWith(NewShAmt, BA), CA);
A = Builder.CreateShl(A, NewShAmt, CI.getName());
return BinaryOperator::CreateAShr(A, NewShAmt);
}
if (match(Src, m_OneUse(m_AShr(m_Trunc(m_Value(X)),
m_SpecificInt(SrcBitSize - 1))))) {
Type *XTy = X->getType();
unsigned XBitSize = XTy->getScalarSizeInBits();
Constant *ShlAmtC = ConstantInt::get(XTy, XBitSize - SrcBitSize);
Constant *AshrAmtC = ConstantInt::get(XTy, XBitSize - 1);
if (XTy == DestTy)
return BinaryOperator::CreateAShr(Builder.CreateShl(X, ShlAmtC),
AshrAmtC);
if (cast<BinaryOperator>(Src)->getOperand(0)->hasOneUse()) {
Value *Ashr = Builder.CreateAShr(Builder.CreateShl(X, ShlAmtC), AshrAmtC);
return CastInst::CreateIntegerCast(Ashr, DestTy, true);
}
}
if (match(Src, m_VScale(DL))) {
if (CI.getFunction() &&
CI.getFunction()->hasFnAttribute(Attribute::VScaleRange)) {
Attribute Attr = CI.getFunction()->getFnAttribute(Attribute::VScaleRange);
if (Optional<unsigned> MaxVScale = Attr.getVScaleRangeMax()) {
if (Log2_32(*MaxVScale) < (SrcBitSize - 1)) {
Value *VScale = Builder.CreateVScale(ConstantInt::get(DestTy, 1));
return replaceInstUsesWith(CI, VScale);
}
}
}
}
return nullptr;
}
static bool fitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
bool losesInfo;
APFloat F = CFP->getValueAPF();
(void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
return !losesInfo;
}
static Type *shrinkFPConstant(ConstantFP *CFP) {
if (CFP->getType() == Type::getPPC_FP128Ty(CFP->getContext()))
return nullptr; if (fitsInFPType(CFP, APFloat::IEEEhalf()))
return Type::getHalfTy(CFP->getContext());
if (fitsInFPType(CFP, APFloat::IEEEsingle()))
return Type::getFloatTy(CFP->getContext());
if (CFP->getType()->isDoubleTy())
return nullptr; if (fitsInFPType(CFP, APFloat::IEEEdouble()))
return Type::getDoubleTy(CFP->getContext());
return nullptr;
}
static Type *shrinkFPConstantVector(Value *V) {
auto *CV = dyn_cast<Constant>(V);
auto *CVVTy = dyn_cast<FixedVectorType>(V->getType());
if (!CV || !CVVTy)
return nullptr;
Type *MinType = nullptr;
unsigned NumElts = CVVTy->getNumElements();
for (unsigned i = 0; i != NumElts; ++i) {
auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
if (!CFP)
return nullptr;
Type *T = shrinkFPConstant(CFP);
if (!T)
return nullptr;
if (!MinType || T->getFPMantissaWidth() > MinType->getFPMantissaWidth())
MinType = T;
}
return FixedVectorType::get(MinType, NumElts);
}
static Type *getMinimumFPType(Value *V) {
if (auto *FPExt = dyn_cast<FPExtInst>(V))
return FPExt->getOperand(0)->getType();
if (auto *CFP = dyn_cast<ConstantFP>(V))
if (Type *T = shrinkFPConstant(CFP))
return T;
if (auto *FPCExt = dyn_cast<ConstantExpr>(V))
if (FPCExt->getOpcode() == Instruction::FPExt)
return FPCExt->getOperand(0)->getType();
if (Type *T = shrinkFPConstantVector(V))
return T;
return V->getType();
}
static bool isKnownExactCastIntToFP(CastInst &I, InstCombinerImpl &IC) {
CastInst::CastOps Opcode = I.getOpcode();
assert((Opcode == CastInst::SIToFP || Opcode == CastInst::UIToFP) &&
"Unexpected cast");
Value *Src = I.getOperand(0);
Type *SrcTy = Src->getType();
Type *FPTy = I.getType();
bool IsSigned = Opcode == Instruction::SIToFP;
int SrcSize = (int)SrcTy->getScalarSizeInBits() - IsSigned;
int DestNumSigBits = FPTy->getFPMantissaWidth();
if (SrcSize <= DestNumSigBits)
return true;
Value *F;
if (match(Src, m_FPToSI(m_Value(F))) || match(Src, m_FPToUI(m_Value(F)))) {
int SrcNumSigBits = F->getType()->getFPMantissaWidth();
if (!IsSigned && match(Src, m_FPToSI(m_Value())))
SrcNumSigBits++;
if (SrcNumSigBits > 0 && DestNumSigBits > 0 &&
SrcNumSigBits <= DestNumSigBits)
return true;
}
KnownBits SrcKnown = IC.computeKnownBits(Src, 0, &I);
int SigBits = (int)SrcTy->getScalarSizeInBits() -
SrcKnown.countMinLeadingZeros() -
SrcKnown.countMinTrailingZeros();
if (SigBits <= DestNumSigBits)
return true;
return false;
}
Instruction *InstCombinerImpl::visitFPTrunc(FPTruncInst &FPT) {
if (Instruction *I = commonCastTransforms(FPT))
return I;
Type *Ty = FPT.getType();
auto *BO = dyn_cast<BinaryOperator>(FPT.getOperand(0));
if (BO && BO->hasOneUse()) {
Type *LHSMinType = getMinimumFPType(BO->getOperand(0));
Type *RHSMinType = getMinimumFPType(BO->getOperand(1));
unsigned OpWidth = BO->getType()->getFPMantissaWidth();
unsigned LHSWidth = LHSMinType->getFPMantissaWidth();
unsigned RHSWidth = RHSMinType->getFPMantissaWidth();
unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
unsigned DstWidth = Ty->getFPMantissaWidth();
switch (BO->getOpcode()) {
default: break;
case Instruction::FAdd:
case Instruction::FSub:
if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty);
Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty);
Instruction *RI = BinaryOperator::Create(BO->getOpcode(), LHS, RHS);
RI->copyFastMathFlags(BO);
return RI;
}
break;
case Instruction::FMul:
if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty);
Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty);
return BinaryOperator::CreateFMulFMF(LHS, RHS, BO);
}
break;
case Instruction::FDiv:
if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty);
Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty);
return BinaryOperator::CreateFDivFMF(LHS, RHS, BO);
}
break;
case Instruction::FRem: {
if (SrcWidth == OpWidth)
break;
Value *LHS, *RHS;
if (LHSWidth == SrcWidth) {
LHS = Builder.CreateFPTrunc(BO->getOperand(0), LHSMinType);
RHS = Builder.CreateFPTrunc(BO->getOperand(1), LHSMinType);
} else {
LHS = Builder.CreateFPTrunc(BO->getOperand(0), RHSMinType);
RHS = Builder.CreateFPTrunc(BO->getOperand(1), RHSMinType);
}
Value *ExactResult = Builder.CreateFRemFMF(LHS, RHS, BO);
return CastInst::CreateFPCast(ExactResult, Ty);
}
}
}
Value *X;
Instruction *Op = dyn_cast<Instruction>(FPT.getOperand(0));
if (Op && Op->hasOneUse()) {
IRBuilder<>::FastMathFlagGuard FMFG(Builder);
if (isa<FPMathOperator>(Op))
Builder.setFastMathFlags(Op->getFastMathFlags());
if (match(Op, m_FNeg(m_Value(X)))) {
Value *InnerTrunc = Builder.CreateFPTrunc(X, Ty);
return UnaryOperator::CreateFNegFMF(InnerTrunc, Op);
}
Value *Cond, *X, *Y;
if (match(Op, m_Select(m_Value(Cond), m_FPExt(m_Value(X)), m_Value(Y))) &&
X->getType() == Ty) {
Value *NarrowY = Builder.CreateFPTrunc(Y, Ty);
Value *Sel = Builder.CreateSelect(Cond, X, NarrowY, "narrow.sel", Op);
return replaceInstUsesWith(FPT, Sel);
}
if (match(Op, m_Select(m_Value(Cond), m_Value(Y), m_FPExt(m_Value(X)))) &&
X->getType() == Ty) {
Value *NarrowY = Builder.CreateFPTrunc(Y, Ty);
Value *Sel = Builder.CreateSelect(Cond, NarrowY, X, "narrow.sel", Op);
return replaceInstUsesWith(FPT, Sel);
}
}
if (auto *II = dyn_cast<IntrinsicInst>(FPT.getOperand(0))) {
switch (II->getIntrinsicID()) {
default: break;
case Intrinsic::ceil:
case Intrinsic::fabs:
case Intrinsic::floor:
case Intrinsic::nearbyint:
case Intrinsic::rint:
case Intrinsic::round:
case Intrinsic::roundeven:
case Intrinsic::trunc: {
Value *Src = II->getArgOperand(0);
if (!Src->hasOneUse())
break;
if (II->getIntrinsicID() != Intrinsic::fabs) {
FPExtInst *FPExtSrc = dyn_cast<FPExtInst>(Src);
if (!FPExtSrc || FPExtSrc->getSrcTy() != Ty)
break;
}
Value *InnerTrunc = Builder.CreateFPTrunc(Src, Ty);
Function *Overload = Intrinsic::getDeclaration(FPT.getModule(),
II->getIntrinsicID(), Ty);
SmallVector<OperandBundleDef, 1> OpBundles;
II->getOperandBundlesAsDefs(OpBundles);
CallInst *NewCI =
CallInst::Create(Overload, {InnerTrunc}, OpBundles, II->getName());
NewCI->copyFastMathFlags(II);
return NewCI;
}
}
}
if (Instruction *I = shrinkInsertElt(FPT, Builder))
return I;
Value *Src = FPT.getOperand(0);
if (isa<SIToFPInst>(Src) || isa<UIToFPInst>(Src)) {
auto *FPCast = cast<CastInst>(Src);
if (isKnownExactCastIntToFP(*FPCast, *this))
return CastInst::Create(FPCast->getOpcode(), FPCast->getOperand(0), Ty);
}
return nullptr;
}
Instruction *InstCombinerImpl::visitFPExt(CastInst &FPExt) {
Type *Ty = FPExt.getType();
Value *Src = FPExt.getOperand(0);
if (isa<SIToFPInst>(Src) || isa<UIToFPInst>(Src)) {
auto *FPCast = cast<CastInst>(Src);
if (isKnownExactCastIntToFP(*FPCast, *this))
return CastInst::Create(FPCast->getOpcode(), FPCast->getOperand(0), Ty);
}
return commonCastTransforms(FPExt);
}
Instruction *InstCombinerImpl::foldItoFPtoI(CastInst &FI) {
if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0)))
return nullptr;
auto *OpI = cast<CastInst>(FI.getOperand(0));
Value *X = OpI->getOperand(0);
Type *XType = X->getType();
Type *DestType = FI.getType();
bool IsOutputSigned = isa<FPToSIInst>(FI);
if (!isKnownExactCastIntToFP(*OpI, *this)) {
int OutputSize = (int)DestType->getScalarSizeInBits();
if (OutputSize > OpI->getType()->getFPMantissaWidth())
return nullptr;
}
if (DestType->getScalarSizeInBits() > XType->getScalarSizeInBits()) {
bool IsInputSigned = isa<SIToFPInst>(OpI);
if (IsInputSigned && IsOutputSigned)
return new SExtInst(X, DestType);
return new ZExtInst(X, DestType);
}
if (DestType->getScalarSizeInBits() < XType->getScalarSizeInBits())
return new TruncInst(X, DestType);
assert(XType == DestType && "Unexpected types for int to FP to int casts");
return replaceInstUsesWith(FI, X);
}
Instruction *InstCombinerImpl::visitFPToUI(FPToUIInst &FI) {
if (Instruction *I = foldItoFPtoI(FI))
return I;
return commonCastTransforms(FI);
}
Instruction *InstCombinerImpl::visitFPToSI(FPToSIInst &FI) {
if (Instruction *I = foldItoFPtoI(FI))
return I;
return commonCastTransforms(FI);
}
Instruction *InstCombinerImpl::visitUIToFP(CastInst &CI) {
return commonCastTransforms(CI);
}
Instruction *InstCombinerImpl::visitSIToFP(CastInst &CI) {
return commonCastTransforms(CI);
}
Instruction *InstCombinerImpl::visitIntToPtr(IntToPtrInst &CI) {
unsigned AS = CI.getAddressSpace();
if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
DL.getPointerSizeInBits(AS)) {
Type *Ty = CI.getOperand(0)->getType()->getWithNewType(
DL.getIntPtrType(CI.getContext(), AS));
Value *P = Builder.CreateZExtOrTrunc(CI.getOperand(0), Ty);
return new IntToPtrInst(P, CI.getType());
}
if (Instruction *I = commonCastTransforms(CI))
return I;
return nullptr;
}
Instruction *InstCombinerImpl::commonPointerCastTransforms(CastInst &CI) {
Value *Src = CI.getOperand(0);
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
if (GEP->hasAllZeroIndices() &&
(!isa<AddrSpaceCastInst>(CI) ||
GEP->getType() == GEP->getPointerOperandType())) {
return replaceOperand(CI, 0, GEP->getOperand(0));
}
}
return commonCastTransforms(CI);
}
Instruction *InstCombinerImpl::visitPtrToInt(PtrToIntInst &CI) {
Value *SrcOp = CI.getPointerOperand();
Type *SrcTy = SrcOp->getType();
Type *Ty = CI.getType();
unsigned AS = CI.getPointerAddressSpace();
unsigned TySize = Ty->getScalarSizeInBits();
unsigned PtrSize = DL.getPointerSizeInBits(AS);
if (TySize != PtrSize) {
Type *IntPtrTy =
SrcTy->getWithNewType(DL.getIntPtrType(CI.getContext(), AS));
Value *P = Builder.CreatePtrToInt(SrcOp, IntPtrTy);
return CastInst::CreateIntegerCast(P, Ty, false);
}
if (auto *GEP = dyn_cast<GetElementPtrInst>(SrcOp)) {
if (GEP->hasOneUse() &&
isa<ConstantPointerNull>(GEP->getPointerOperand())) {
return replaceInstUsesWith(CI,
Builder.CreateIntCast(EmitGEPOffset(GEP), Ty,
false));
}
}
Value *Vec, *Scalar, *Index;
if (match(SrcOp, m_OneUse(m_InsertElt(m_IntToPtr(m_Value(Vec)),
m_Value(Scalar), m_Value(Index)))) &&
Vec->getType() == Ty) {
assert(Vec->getType()->getScalarSizeInBits() == PtrSize && "Wrong type");
Value *NewCast = Builder.CreatePtrToInt(Scalar, Ty->getScalarType());
return InsertElementInst::Create(Vec, NewCast, Index);
}
return commonPointerCastTransforms(CI);
}
static Instruction *
optimizeVectorResizeWithIntegerBitCasts(Value *InVal, VectorType *DestTy,
InstCombinerImpl &IC) {
VectorType *SrcTy = cast<VectorType>(InVal->getType());
if (SrcTy->getElementType() != DestTy->getElementType()) {
if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
DestTy->getElementType()->getPrimitiveSizeInBits())
return nullptr;
SrcTy =
FixedVectorType::get(DestTy->getElementType(),
cast<FixedVectorType>(SrcTy)->getNumElements());
InVal = IC.Builder.CreateBitCast(InVal, SrcTy);
}
bool IsBigEndian = IC.getDataLayout().isBigEndian();
unsigned SrcElts = cast<FixedVectorType>(SrcTy)->getNumElements();
unsigned DestElts = cast<FixedVectorType>(DestTy)->getNumElements();
assert(SrcElts != DestElts && "Element counts should be different.");
auto ShuffleMaskStorage = llvm::to_vector<16>(llvm::seq<int>(0, SrcElts));
ArrayRef<int> ShuffleMask;
Value *V2;
if (SrcElts > DestElts) {
V2 = PoisonValue::get(SrcTy);
ShuffleMask = ShuffleMaskStorage;
if (IsBigEndian)
ShuffleMask = ShuffleMask.take_back(DestElts);
else
ShuffleMask = ShuffleMask.take_front(DestElts);
} else {
V2 = Constant::getNullValue(SrcTy);
uint32_t NullElt = SrcElts;
unsigned DeltaElts = DestElts - SrcElts;
if (IsBigEndian)
ShuffleMaskStorage.insert(ShuffleMaskStorage.begin(), DeltaElts, NullElt);
else
ShuffleMaskStorage.append(DeltaElts, NullElt);
ShuffleMask = ShuffleMaskStorage;
}
return new ShuffleVectorInst(InVal, V2, ShuffleMask);
}
static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
return Value % Ty->getPrimitiveSizeInBits() == 0;
}
static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
return Value / Ty->getPrimitiveSizeInBits();
}
static bool collectInsertionElements(Value *V, unsigned Shift,
SmallVectorImpl<Value *> &Elements,
Type *VecEltTy, bool isBigEndian) {
assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
"Shift should be a multiple of the element type size");
if (isa<UndefValue>(V)) return true;
if (V->getType() == VecEltTy) {
if (Constant *C = dyn_cast<Constant>(V))
if (C->isNullValue())
return true;
unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
if (isBigEndian)
ElementIndex = Elements.size() - ElementIndex - 1;
if (Elements[ElementIndex])
return false;
Elements[ElementIndex] = V;
return true;
}
if (Constant *C = dyn_cast<Constant>(V)) {
unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
VecEltTy);
if (NumElts == 1)
return collectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
Shift, Elements, VecEltTy, isBigEndian);
if (!isa<IntegerType>(C->getType()))
C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
C->getType()->getPrimitiveSizeInBits()));
unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
for (unsigned i = 0; i != NumElts; ++i) {
unsigned ShiftI = Shift+i*ElementSize;
Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
ShiftI));
Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
if (!collectInsertionElements(Piece, ShiftI, Elements, VecEltTy,
isBigEndian))
return false;
}
return true;
}
if (!V->hasOneUse()) return false;
Instruction *I = dyn_cast<Instruction>(V);
if (!I) return false;
switch (I->getOpcode()) {
default: return false; case Instruction::BitCast:
if (I->getOperand(0)->getType()->isVectorTy())
return false;
return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
isBigEndian);
case Instruction::ZExt:
if (!isMultipleOfTypeSize(
I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
VecEltTy))
return false;
return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
isBigEndian);
case Instruction::Or:
return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
isBigEndian) &&
collectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy,
isBigEndian);
case Instruction::Shl: {
ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
if (!CI) return false;
Shift += CI->getZExtValue();
if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
isBigEndian);
}
}
}
static Value *optimizeIntegerToVectorInsertions(BitCastInst &CI,
InstCombinerImpl &IC) {
auto *DestVecTy = cast<FixedVectorType>(CI.getType());
Value *IntInput = CI.getOperand(0);
SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
if (!collectInsertionElements(IntInput, 0, Elements,
DestVecTy->getElementType(),
IC.getDataLayout().isBigEndian()))
return nullptr;
Value *Result = Constant::getNullValue(CI.getType());
for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
if (!Elements[i]) continue;
Result = IC.Builder.CreateInsertElement(Result, Elements[i],
IC.Builder.getInt32(i));
}
return Result;
}
static Instruction *canonicalizeBitCastExtElt(BitCastInst &BitCast,
InstCombinerImpl &IC) {
Value *VecOp, *Index;
if (!match(BitCast.getOperand(0),
m_OneUse(m_ExtractElt(m_Value(VecOp), m_Value(Index)))))
return nullptr;
Type *DestType = BitCast.getType();
VectorType *VecType = cast<VectorType>(VecOp->getType());
if (VectorType::isValidElementType(DestType)) {
auto *NewVecType = VectorType::get(DestType, VecType);
auto *NewBC = IC.Builder.CreateBitCast(VecOp, NewVecType, "bc");
return ExtractElementInst::Create(NewBC, Index);
}
auto *FixedVType = dyn_cast<FixedVectorType>(VecType);
if (DestType->isVectorTy() && FixedVType && FixedVType->getNumElements() == 1)
return CastInst::Create(Instruction::BitCast, VecOp, DestType);
return nullptr;
}
static Instruction *foldBitCastBitwiseLogic(BitCastInst &BitCast,
InstCombiner::BuilderTy &Builder) {
Type *DestTy = BitCast.getType();
BinaryOperator *BO;
if (!match(BitCast.getOperand(0), m_OneUse(m_BinOp(BO))) ||
!BO->isBitwiseLogicOp())
return nullptr;
if (!DestTy->isVectorTy() || !BO->getType()->isVectorTy())
return nullptr;
if (DestTy->isFPOrFPVectorTy()) {
Value *X, *Y;
if (match(BO->getOperand(0), m_OneUse(m_BitCast(m_Value(X)))) &&
match(BO->getOperand(1), m_OneUse(m_BitCast(m_Value(Y))))) {
if (X->getType()->isFPOrFPVectorTy() &&
Y->getType()->isIntOrIntVectorTy()) {
Value *CastedOp =
Builder.CreateBitCast(BO->getOperand(0), Y->getType());
Value *NewBO = Builder.CreateBinOp(BO->getOpcode(), CastedOp, Y);
return CastInst::CreateBitOrPointerCast(NewBO, DestTy);
}
if (X->getType()->isIntOrIntVectorTy() &&
Y->getType()->isFPOrFPVectorTy()) {
Value *CastedOp =
Builder.CreateBitCast(BO->getOperand(1), X->getType());
Value *NewBO = Builder.CreateBinOp(BO->getOpcode(), CastedOp, X);
return CastInst::CreateBitOrPointerCast(NewBO, DestTy);
}
}
return nullptr;
}
if (!DestTy->isIntOrIntVectorTy())
return nullptr;
Value *X;
if (match(BO->getOperand(0), m_OneUse(m_BitCast(m_Value(X)))) &&
X->getType() == DestTy && !isa<Constant>(X)) {
Value *CastedOp1 = Builder.CreateBitCast(BO->getOperand(1), DestTy);
return BinaryOperator::Create(BO->getOpcode(), X, CastedOp1);
}
if (match(BO->getOperand(1), m_OneUse(m_BitCast(m_Value(X)))) &&
X->getType() == DestTy && !isa<Constant>(X)) {
Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy);
return BinaryOperator::Create(BO->getOpcode(), CastedOp0, X);
}
Constant *C;
if (match(BO->getOperand(1), m_Constant(C))) {
Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy);
Value *CastedC = Builder.CreateBitCast(C, DestTy);
return BinaryOperator::Create(BO->getOpcode(), CastedOp0, CastedC);
}
return nullptr;
}
static Instruction *foldBitCastSelect(BitCastInst &BitCast,
InstCombiner::BuilderTy &Builder) {
Value *Cond, *TVal, *FVal;
if (!match(BitCast.getOperand(0),
m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
return nullptr;
Type *CondTy = Cond->getType();
Type *DestTy = BitCast.getType();
if (auto *CondVTy = dyn_cast<VectorType>(CondTy))
if (!DestTy->isVectorTy() ||
CondVTy->getElementCount() !=
cast<VectorType>(DestTy)->getElementCount())
return nullptr;
if (DestTy->isVectorTy() != TVal->getType()->isVectorTy())
return nullptr;
auto *Sel = cast<Instruction>(BitCast.getOperand(0));
Value *X;
if (match(TVal, m_OneUse(m_BitCast(m_Value(X)))) && X->getType() == DestTy &&
!isa<Constant>(X)) {
Value *CastedVal = Builder.CreateBitCast(FVal, DestTy);
return SelectInst::Create(Cond, X, CastedVal, "", nullptr, Sel);
}
if (match(FVal, m_OneUse(m_BitCast(m_Value(X)))) && X->getType() == DestTy &&
!isa<Constant>(X)) {
Value *CastedVal = Builder.CreateBitCast(TVal, DestTy);
return SelectInst::Create(Cond, CastedVal, X, "", nullptr, Sel);
}
return nullptr;
}
static bool hasStoreUsersOnly(CastInst &CI) {
for (User *U : CI.users()) {
if (!isa<StoreInst>(U))
return false;
}
return true;
}
Instruction *InstCombinerImpl::optimizeBitCastFromPhi(CastInst &CI,
PHINode *PN) {
if (hasStoreUsersOnly(CI))
return nullptr;
Value *Src = CI.getOperand(0);
Type *SrcTy = Src->getType(); Type *DestTy = CI.getType();
SmallVector<PHINode *, 4> PhiWorklist;
SmallSetVector<PHINode *, 4> OldPhiNodes;
PhiWorklist.push_back(PN);
OldPhiNodes.insert(PN);
while (!PhiWorklist.empty()) {
auto *OldPN = PhiWorklist.pop_back_val();
for (Value *IncValue : OldPN->incoming_values()) {
if (isa<Constant>(IncValue))
continue;
if (auto *LI = dyn_cast<LoadInst>(IncValue)) {
Value *Addr = LI->getOperand(0);
if (Addr == &CI || isa<LoadInst>(Addr))
return nullptr;
if (DestTy->isX86_AMXTy())
return nullptr;
if (LI->hasOneUse() && LI->isSimple())
continue;
return nullptr;
}
if (auto *PNode = dyn_cast<PHINode>(IncValue)) {
if (OldPhiNodes.insert(PNode))
PhiWorklist.push_back(PNode);
continue;
}
auto *BCI = dyn_cast<BitCastInst>(IncValue);
if (!BCI)
return nullptr;
Type *TyA = BCI->getOperand(0)->getType();
Type *TyB = BCI->getType();
if (TyA != DestTy || TyB != SrcTy)
return nullptr;
}
}
for (auto *OldPN : OldPhiNodes) {
for (User *V : OldPN->users()) {
if (auto *SI = dyn_cast<StoreInst>(V)) {
if (!SI->isSimple() || SI->getOperand(0) != OldPN)
return nullptr;
} else if (auto *BCI = dyn_cast<BitCastInst>(V)) {
Type *TyB = BCI->getOperand(0)->getType();
Type *TyA = BCI->getType();
if (TyA != DestTy || TyB != SrcTy)
return nullptr;
} else if (auto *PHI = dyn_cast<PHINode>(V)) {
if (!OldPhiNodes.contains(PHI))
return nullptr;
} else {
return nullptr;
}
}
}
SmallDenseMap<PHINode *, PHINode *> NewPNodes;
for (auto *OldPN : OldPhiNodes) {
Builder.SetInsertPoint(OldPN);
PHINode *NewPN = Builder.CreatePHI(DestTy, OldPN->getNumOperands());
NewPNodes[OldPN] = NewPN;
}
for (auto *OldPN : OldPhiNodes) {
PHINode *NewPN = NewPNodes[OldPN];
for (unsigned j = 0, e = OldPN->getNumOperands(); j != e; ++j) {
Value *V = OldPN->getOperand(j);
Value *NewV = nullptr;
if (auto *C = dyn_cast<Constant>(V)) {
NewV = ConstantExpr::getBitCast(C, DestTy);
} else if (auto *LI = dyn_cast<LoadInst>(V)) {
Builder.SetInsertPoint(LI);
NewV = combineLoadToNewType(*LI, DestTy);
replaceInstUsesWith(*LI, PoisonValue::get(LI->getType()));
eraseInstFromFunction(*LI);
} else if (auto *BCI = dyn_cast<BitCastInst>(V)) {
NewV = BCI->getOperand(0);
} else if (auto *PrevPN = dyn_cast<PHINode>(V)) {
NewV = NewPNodes[PrevPN];
}
assert(NewV);
NewPN->addIncoming(NewV, OldPN->getIncomingBlock(j));
}
}
Instruction *RetVal = nullptr;
for (auto *OldPN : OldPhiNodes) {
PHINode *NewPN = NewPNodes[OldPN];
for (User *V : make_early_inc_range(OldPN->users())) {
if (auto *SI = dyn_cast<StoreInst>(V)) {
assert(SI->isSimple() && SI->getOperand(0) == OldPN);
Builder.SetInsertPoint(SI);
auto *NewBC =
cast<BitCastInst>(Builder.CreateBitCast(NewPN, SrcTy));
SI->setOperand(0, NewBC);
Worklist.push(SI);
assert(hasStoreUsersOnly(*NewBC));
}
else if (auto *BCI = dyn_cast<BitCastInst>(V)) {
Type *TyB = BCI->getOperand(0)->getType();
Type *TyA = BCI->getType();
assert(TyA == DestTy && TyB == SrcTy);
(void) TyA;
(void) TyB;
Instruction *I = replaceInstUsesWith(*BCI, NewPN);
if (BCI == &CI)
RetVal = I;
} else if (auto *PHI = dyn_cast<PHINode>(V)) {
assert(OldPhiNodes.contains(PHI));
(void) PHI;
} else {
llvm_unreachable("all uses should be handled");
}
}
}
return RetVal;
}
static Instruction *convertBitCastToGEP(BitCastInst &CI, IRBuilderBase &Builder,
const DataLayout &DL) {
Value *Src = CI.getOperand(0);
PointerType *SrcPTy = cast<PointerType>(Src->getType());
PointerType *DstPTy = cast<PointerType>(CI.getType());
if (SrcPTy->isOpaque() || DstPTy->isOpaque())
return nullptr;
Type *DstElTy = DstPTy->getNonOpaquePointerElementType();
Type *SrcElTy = SrcPTy->getNonOpaquePointerElementType();
if (!SrcElTy->isSized())
return nullptr;
unsigned NumZeros = 0;
while (SrcElTy && SrcElTy != DstElTy) {
SrcElTy = GetElementPtrInst::getTypeAtIndex(SrcElTy, (uint64_t)0);
++NumZeros;
}
if (SrcElTy == DstElTy) {
SmallVector<Value *, 8> Idxs(NumZeros + 1, Builder.getInt32(0));
GetElementPtrInst *GEP = GetElementPtrInst::Create(
SrcPTy->getNonOpaquePointerElementType(), Src, Idxs);
bool CanBeNull, CanBeFreed;
if (Src->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed)) {
if (SrcPTy->getAddressSpace() == 0 || !CanBeNull)
GEP->setIsInBounds();
}
return GEP;
}
return nullptr;
}
Instruction *InstCombinerImpl::visitBitCast(BitCastInst &CI) {
Value *Src = CI.getOperand(0);
Type *SrcTy = Src->getType();
Type *DestTy = CI.getType();
if (DestTy == Src->getType())
return replaceInstUsesWith(CI, Src);
if (isa<PointerType>(SrcTy) && isa<PointerType>(DestTy)) {
if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
return V;
if (Instruction *I = convertBitCastToGEP(CI, Builder, DL))
return I;
}
if (FixedVectorType *DestVTy = dyn_cast<FixedVectorType>(DestTy)) {
if (DestVTy->getNumElements() == 1 && SrcTy->isX86_MMXTy()) {
Value *Elem = Builder.CreateBitCast(Src, DestVTy->getElementType());
return InsertElementInst::Create(PoisonValue::get(DestTy), Elem,
Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
}
if (isa<IntegerType>(SrcTy)) {
if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
CastInst *SrcCast = cast<CastInst>(Src);
if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
if (isa<VectorType>(BCIn->getOperand(0)->getType()))
if (Instruction *I = optimizeVectorResizeWithIntegerBitCasts(
BCIn->getOperand(0), cast<VectorType>(DestTy), *this))
return I;
}
if (Value *V = optimizeIntegerToVectorInsertions(CI, *this))
return replaceInstUsesWith(CI, V);
}
}
if (FixedVectorType *SrcVTy = dyn_cast<FixedVectorType>(SrcTy)) {
if (SrcVTy->getNumElements() == 1) {
if (!DestTy->isVectorTy()) {
Value *Elem =
Builder.CreateExtractElement(Src,
Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
return CastInst::Create(Instruction::BitCast, Elem, DestTy);
}
if (auto *InsElt = dyn_cast<InsertElementInst>(Src))
return new BitCastInst(InsElt->getOperand(1), DestTy);
}
unsigned BitWidth = DestTy->getScalarSizeInBits();
Value *X, *Y;
uint64_t IndexC;
if (match(Src, m_OneUse(m_InsertElt(m_OneUse(m_BitCast(m_Value(X))),
m_Value(Y), m_ConstantInt(IndexC)))) &&
DestTy->isIntegerTy() && X->getType() == DestTy &&
Y->getType()->isIntegerTy() && isDesirableIntType(BitWidth)) {
if (DL.isBigEndian())
IndexC = SrcVTy->getNumElements() - 1 - IndexC;
if (IndexC == 0) {
unsigned EltWidth = Y->getType()->getScalarSizeInBits();
APInt MaskC = APInt::getHighBitsSet(BitWidth, BitWidth - EltWidth);
Value *AndX = Builder.CreateAnd(X, MaskC);
Value *ZextY = Builder.CreateZExt(Y, DestTy);
return BinaryOperator::CreateOr(AndX, ZextY);
}
}
}
if (auto *Shuf = dyn_cast<ShuffleVectorInst>(Src)) {
Value *ShufOp0 = Shuf->getOperand(0);
Value *ShufOp1 = Shuf->getOperand(1);
auto ShufElts = cast<VectorType>(Shuf->getType())->getElementCount();
auto SrcVecElts = cast<VectorType>(ShufOp0->getType())->getElementCount();
if (Shuf->hasOneUse() && DestTy->isVectorTy() &&
cast<VectorType>(DestTy)->getElementCount() == ShufElts &&
ShufElts == SrcVecElts) {
BitCastInst *Tmp;
if (((Tmp = dyn_cast<BitCastInst>(ShufOp0)) &&
Tmp->getOperand(0)->getType() == DestTy) ||
((Tmp = dyn_cast<BitCastInst>(ShufOp1)) &&
Tmp->getOperand(0)->getType() == DestTy)) {
Value *LHS = Builder.CreateBitCast(ShufOp0, DestTy);
Value *RHS = Builder.CreateBitCast(ShufOp1, DestTy);
return new ShuffleVectorInst(LHS, RHS, Shuf->getShuffleMask());
}
}
if (DestTy->isIntegerTy() &&
DL.isLegalInteger(DestTy->getScalarSizeInBits()) &&
SrcTy->getScalarSizeInBits() == 8 &&
ShufElts.getKnownMinValue() % 2 == 0 && Shuf->hasOneUse() &&
Shuf->isReverse()) {
assert(ShufOp0->getType() == SrcTy && "Unexpected shuffle mask");
assert(match(ShufOp1, m_Undef()) && "Unexpected shuffle op");
Function *Bswap =
Intrinsic::getDeclaration(CI.getModule(), Intrinsic::bswap, DestTy);
Value *ScalarX = Builder.CreateBitCast(ShufOp0, DestTy);
return CallInst::Create(Bswap, { ScalarX });
}
}
if (PHINode *PN = dyn_cast<PHINode>(Src))
if (Instruction *I = optimizeBitCastFromPhi(CI, PN))
return I;
if (Instruction *I = canonicalizeBitCastExtElt(CI, *this))
return I;
if (Instruction *I = foldBitCastBitwiseLogic(CI, Builder))
return I;
if (Instruction *I = foldBitCastSelect(CI, Builder))
return I;
if (SrcTy->isPointerTy())
return commonPointerCastTransforms(CI);
return commonCastTransforms(CI);
}
Instruction *InstCombinerImpl::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
Value *Src = CI.getOperand(0);
PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType());
PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType());
if (!SrcTy->hasSameElementTypeAs(DestTy)) {
Type *MidTy =
PointerType::getWithSamePointeeType(DestTy, SrcTy->getAddressSpace());
if (VectorType *VT = dyn_cast<VectorType>(CI.getType()))
MidTy = VectorType::get(MidTy, VT->getElementCount());
Value *NewBitCast = Builder.CreateBitCast(Src, MidTy);
return new AddrSpaceCastInst(NewBitCast, CI.getType());
}
return commonPointerCastTransforms(CI);
}