44#define DEBUG_TYPE "instcombine"
50 "Number of aggregate reconstructions turned into reuse of the "
51 "original aggregate");
63 return CEI ||
C->getSplatValue();
102 SmallVector<Instruction *, 2> Extracts;
108 for (Instruction *U : PN->
users()) {
114 }
else if (!PHIUser) {
145 SmallDenseMap<BasicBlock *, Value *, 4> ScalarizedValues;
152 if (
Value *Existing = ScalarizedValues.
lookup(inBB)) {
159 if (PHIInVal == PHIUser) {
164 unsigned opId = (
B0->getOperand(0) == PN) ? 1 : 0;
167 B0->getOperand(opId)->getName() +
".Elt"),
171 Value *FirstOp = (
B0->getOperand(0) == PN) ? scalarPHI :
Op;
172 Value *SecondOp = (
B0->getOperand(0) == PN) ?
Op : scalarPHI;
174 B0->getOpcode(), FirstOp, SecondOp, B0),
191 ScalarizedValues[inBB] = ScalarVal;
195 for (
auto *
E : Extracts) {
211 ElementCount NumElts =
215 bool IsBigEndian =
DL.isBigEndian();
219 if (
X->getType()->isIntegerTy()) {
221 "Expected fixed vector type for bitcast from scalar integer");
228 unsigned ShiftAmountC = ExtIndexC * DestWidth;
229 if ((!ShiftAmountC ||
230 isDesirableIntType(
X->getType()->getPrimitiveSizeInBits())) &&
233 X =
Builder.CreateLShr(
X, ShiftAmountC,
"extelt.offset");
237 return new BitCastInst(
Trunc, DestTy);
239 return new TruncInst(
X, DestTy);
243 if (!
X->getType()->isVectorTy())
250 ElementCount NumSrcElts = SrcTy->getElementCount();
251 if (NumSrcElts == NumElts)
253 return new BitCastInst(Elt, DestTy);
256 "Src and Dst must be the same sort of vector type");
272 unsigned NarrowingRatio =
275 if (ExtIndexC / NarrowingRatio != InsIndexC) {
299 unsigned Chunk = ExtIndexC % NarrowingRatio;
301 Chunk = NarrowingRatio - 1 - Chunk;
306 bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy();
308 if (NeedSrcBitcast && NeedDestBitcast)
311 unsigned SrcWidth = SrcTy->getScalarSizeInBits();
312 unsigned ShAmt = Chunk * DestWidth;
318 if (NeedSrcBitcast || NeedDestBitcast)
321 if (NeedSrcBitcast) {
333 if (NeedDestBitcast) {
335 return new BitCastInst(
Builder.CreateTrunc(Scalar, DestIntTy), DestTy);
337 return new TruncInst(Scalar, DestTy);
346 APInt &UnionUsedElts) {
350 case Instruction::ExtractElement: {
354 if (EEIIndexC && EEIIndexC->
getValue().
ult(VWidth)) {
360 case Instruction::ShuffleVector: {
362 unsigned MaskNumElts =
367 if (MaskVal == -1u || MaskVal >= 2 * VWidth)
369 if (Shuffle->
getOperand(0) ==
V && (MaskVal < VWidth))
370 UnionUsedElts.
setBit(MaskVal);
372 ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth)))
373 UnionUsedElts.
setBit(MaskVal - VWidth);
391 APInt UnionUsedElts(VWidth, 0);
392 for (
const Use &U :
V->uses()) {
405 return UnionUsedElts;
427 if (!VecTy || !VecTy->getElementType()->isPointerTy())
430 unsigned NumElts = VecTy->getNumElements();
438 unsigned IdxWidth =
DL.getIndexTypeSizeInBits(VecTy->getElementType());
441 for (
unsigned I = 0;
I != NumElts; ++
I) {
455 else if (
Base != EltBase)
457 Offsets.push_back(
Offset);
461 APInt Stride = Offsets[1] - Offsets[0];
462 for (
unsigned I = 1;
I != NumElts; ++
I)
463 if (Offsets[
I] - Offsets[0] != Stride *
I)
469 Type *IdxTy =
DL.getIndexType(VecTy->getElementType());
471 Value *Ptr = Builder.CreatePtrAdd(
472 Base, Builder.CreateMul(Idx, ConstantInt::get(IdxTy, Stride)));
473 return Builder.CreatePtrAdd(Ptr, ConstantInt::get(IdxTy, Offsets[0]));
480 SQ.getWithInstruction(&EI)))
492 if (
SI->getCondition()->getType()->isIntegerTy() &&
506 bool HasKnownValidIndex =
false;
513 unsigned NumElts = EC.getKnownMinValue();
514 HasKnownValidIndex = IndexC->getValue().ult(NumElts);
520 if (IID == Intrinsic::stepvector && IndexC->getValue().ult(NumElts)) {
522 unsigned BitWidth = Ty->getIntegerBitWidth();
527 if (IndexC->getValue().getActiveBits() <=
BitWidth)
528 Idx = ConstantInt::get(Ty, IndexC->getValue().zextOrTrunc(
BitWidth));
537 if (!EC.isScalable() && IndexC->getValue().uge(NumElts))
546 if (
Instruction *ScalarPHI = scalarizePHI(EI, Phi))
571 (HasKnownValidIndex ||
602 uint64_t IdxVal = IndexC ? IndexC->getZExtValue() : 0;
603 if (IndexC && IdxVal < EC.getKnownMinValue() &&
GEP->hasOneUse()) {
614 return isa<VectorType>(V->getType());
616 if (VectorOps == 1) {
617 Value *NewPtr =
GEP->getPointerOperand();
619 NewPtr =
Builder.CreateExtractElement(NewPtr, IndexC);
622 for (
unsigned I = 1;
I !=
GEP->getNumOperands(); ++
I) {
631 GEP->getSourceElementType(), NewPtr, NewOps);
645 std::optional<int> SrcIdx;
647 if (SplatIndex != -1)
650 SrcIdx = SVI->getMaskValue(CI->getZExtValue());
660 if (*SrcIdx < (
int)LHSWidth)
661 Src = SVI->getOperand(0);
664 Src = SVI->getOperand(1);
668 Src, ConstantInt::get(Int64Ty, *SrcIdx,
false));
682 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast) &&
684 Value *EE =
Builder.CreateExtractElement(CI->getOperand(0), Index);
695 unsigned NumElts = EC.getKnownMinValue();
699 if (!EC.isScalable() && NumElts != 1) {
703 APInt PoisonElts(NumElts, 0);
704 APInt DemandedElts(NumElts, 0);
705 DemandedElts.
setBit(IndexC->getZExtValue());
714 APInt PoisonElts(NumElts, 0);
716 SrcVec, DemandedElts, PoisonElts, 0 ,
736 "Invalid CollectSingleShuffleElements");
740 Mask.assign(NumElts, -1);
745 for (
unsigned i = 0; i != NumElts; ++i)
751 for (
unsigned i = 0; i != NumElts; ++i)
752 Mask.push_back(i + NumElts);
758 Value *VecOp = IEI->getOperand(0);
759 Value *ScalarOp = IEI->getOperand(1);
760 Value *IdxOp = IEI->getOperand(2);
771 Mask[InsertedIdx] = -1;
776 unsigned ExtractedIdx =
778 unsigned NumLHSElts =
788 Mask[InsertedIdx % NumElts] = ExtractedIdx;
791 Mask[InsertedIdx % NumElts] = ExtractedIdx + NumLHSElts;
811 unsigned NumInsElts = InsVecType->getNumElements();
812 unsigned NumExtElts = ExtVecType->getNumElements();
815 if (InsVecType->getElementType() != ExtVecType->getElementType() ||
816 NumExtElts >= NumInsElts)
829 for (
unsigned i = 0; i < NumExtElts; ++i)
831 for (
unsigned i = NumExtElts; i < NumInsElts; ++i)
848 if (InsertionBlock != InsElt->
getParent())
866 WideVec->insertAfter(ExtVecOpInst->getIterator());
883 if (!OldExt || OldExt->
getParent() != WideVec->getParent())
909 assert(
V->getType()->isVectorTy() &&
"Invalid shuffle!");
913 Mask.assign(NumElts, -1);
914 return std::make_pair(
919 Mask.assign(NumElts, 0);
920 return std::make_pair(
V,
nullptr);
925 Value *VecOp = IEI->getOperand(0);
926 Value *ScalarOp = IEI->getOperand(1);
927 Value *IdxOp = IEI->getOperand(2);
931 unsigned ExtractedIdx =
937 if (EI->
getOperand(0) == PermittedRHS || PermittedRHS ==
nullptr) {
940 assert(LR.second ==
nullptr || LR.second ==
RHS);
942 if (LR.first->getType() !=
RHS->getType()) {
950 for (
unsigned i = 0; i < NumElts; ++i)
952 return std::make_pair(
V,
nullptr);
955 unsigned NumLHSElts =
957 Mask[InsertedIdx % NumElts] = NumLHSElts + ExtractedIdx;
958 return std::make_pair(LR.first,
RHS);
961 if (VecOp == PermittedRHS) {
964 unsigned NumLHSElts =
967 for (
unsigned i = 0; i != NumElts; ++i)
968 Mask.push_back(i == InsertedIdx ? ExtractedIdx : NumLHSElts + i);
969 return std::make_pair(EI->
getOperand(0), PermittedRHS);
977 return std::make_pair(EI->
getOperand(0), PermittedRHS);
983 for (
unsigned i = 0; i != NumElts; ++i)
985 return std::make_pair(
V,
nullptr);
1011 assert(NumAggElts > 0 &&
"Aggregate should have elements.");
1015 static constexpr auto NotFound = std::nullopt;
1016 static constexpr auto FoundMismatch =
nullptr;
1023 auto KnowAllElts = [&AggElts]() {
1031 static const int DepthLimit = 2 * NumAggElts;
1036 Depth < DepthLimit && CurrIVI && !KnowAllElts();
1039 auto *InsertedValue =
1047 if (Indices.
size() != 1)
1053 std::optional<Instruction *> &Elt = AggElts[Indices.
front()];
1054 Elt = Elt.value_or(InsertedValue);
1067 enum class AggregateDescription {
1083 auto Describe = [](std::optional<Value *> SourceAggregate) {
1084 if (SourceAggregate == NotFound)
1085 return AggregateDescription::NotFound;
1086 if (*SourceAggregate == FoundMismatch)
1087 return AggregateDescription::FoundMismatch;
1088 return AggregateDescription::Found;
1092 bool EltDefinedInUseBB =
false;
1099 auto FindSourceAggregate =
1100 [&](
Instruction *Elt,
unsigned EltIdx, std::optional<BasicBlock *> UseBB,
1101 std::optional<BasicBlock *> PredBB) -> std::optional<Value *> {
1103 if (UseBB && PredBB) {
1106 EltDefinedInUseBB =
true;
1115 Value *SourceAggregate = EVI->getAggregateOperand();
1118 if (SourceAggregate->
getType() != AggTy)
1119 return FoundMismatch;
1121 if (EVI->getNumIndices() != 1 || EltIdx != EVI->getIndices().front())
1122 return FoundMismatch;
1124 return SourceAggregate;
1130 auto FindCommonSourceAggregate =
1131 [&](std::optional<BasicBlock *> UseBB,
1132 std::optional<BasicBlock *> PredBB) -> std::optional<Value *> {
1133 std::optional<Value *> SourceAggregate;
1136 assert(Describe(SourceAggregate) != AggregateDescription::FoundMismatch &&
1137 "We don't store nullptr in SourceAggregate!");
1138 assert((Describe(SourceAggregate) == AggregateDescription::Found) ==
1140 "SourceAggregate should be valid after the first element,");
1145 std::optional<Value *> SourceAggregateForElement =
1146 FindSourceAggregate(*
I.value(),
I.index(), UseBB, PredBB);
1153 if (Describe(SourceAggregateForElement) != AggregateDescription::Found)
1154 return SourceAggregateForElement;
1158 switch (Describe(SourceAggregate)) {
1159 case AggregateDescription::NotFound:
1161 SourceAggregate = SourceAggregateForElement;
1163 case AggregateDescription::Found:
1166 if (*SourceAggregateForElement != *SourceAggregate)
1167 return FoundMismatch;
1169 case AggregateDescription::FoundMismatch:
1174 assert(Describe(SourceAggregate) == AggregateDescription::Found &&
1175 "Must be a valid Value");
1176 return *SourceAggregate;
1179 std::optional<Value *> SourceAggregate;
1182 SourceAggregate = FindCommonSourceAggregate(std::nullopt,
1184 if (Describe(SourceAggregate) != AggregateDescription::NotFound) {
1185 if (Describe(SourceAggregate) == AggregateDescription::FoundMismatch)
1187 ++NumAggregateReconstructionsSimplified;
1200 for (
const std::optional<Instruction *> &
I : AggElts) {
1224 static const int PredCountLimit = 64;
1231 if (Preds.
size() >= PredCountLimit)
1240 bool FoundSrcAgg =
false;
1242 std::pair<
decltype(SourceAggregates)
::iterator,
bool>
IV =
1251 SourceAggregate = FindCommonSourceAggregate(UseBB, Pred);
1252 if (Describe(SourceAggregate) == AggregateDescription::Found) {
1254 IV.first->second = *SourceAggregate;
1269 for (
auto &It : SourceAggregates) {
1270 if (Describe(It.second) == AggregateDescription::Found)
1274 if (EltDefinedInUseBB)
1282 if (UseBB != OrigBB)
1287 bool ConstAgg =
true;
1288 for (
auto Val : AggElts) {
1301 for (
auto &It : SourceAggregates) {
1302 if (Describe(It.second) == AggregateDescription::Found)
1306 Builder.SetInsertPoint(Pred->getTerminator());
1308 for (
auto [Idx, Val] :
enumerate(AggElts)) {
1310 V =
Builder.CreateInsertValue(V, Elt, Idx);
1322 Builder.SetInsertPoint(UseBB->getFirstNonPHIIt());
1326 PHI->addIncoming(SourceAggregates[Pred], Pred);
1328 ++NumAggregateReconstructionsSimplified;
1341 I.getAggregateOperand(),
I.getInsertedValueOperand(),
I.getIndices(),
1342 SQ.getWithInstruction(&
I)))
1345 bool IsRedundant =
false;
1354 while (V->hasOneUse() &&
Depth < 10) {
1357 if (!UserInsInst || U->getOperand(0) != V)
1359 if (UserInsInst->getIndices() == FirstIndices) {
1387 if (MaskSize != VecSize)
1392 for (
int i = 0; i != MaskSize; ++i) {
1394 if (Elt != -1 && Elt != i && Elt != i + VecSize)
1419 if (NumElements == 1)
1431 if (!Idx || CurrIE->
getOperand(1) != SplatVal)
1438 if (CurrIE != &InsElt &&
1439 (!CurrIE->
hasOneUse() && (NextIE !=
nullptr || !Idx->isZero())))
1442 ElementPresent[Idx->getZExtValue()] =
true;
1448 if (FirstIE == &InsElt)
1456 if (!ElementPresent.
all())
1469 for (
unsigned i = 0; i != NumElements; ++i)
1470 if (!ElementPresent[i])
1481 if (!Shuf || !Shuf->isZeroEltSplat())
1496 Value *Op0 = Shuf->getOperand(0);
1504 unsigned NumMaskElts =
1507 for (
unsigned i = 0; i != NumMaskElts; ++i)
1508 NewMask[i] = i == IdxC ? 0 : Shuf->getMaskValue(i);
1519 !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding()))
1535 Value *
X = Shuf->getOperand(0);
1543 unsigned NumMaskElts =
1547 for (
unsigned i = 0; i != NumMaskElts; ++i) {
1550 NewMask[i] = OldMask[i];
1551 }
else if (OldMask[i] == (
int)IdxC) {
1557 "Unexpected shuffle mask element for identity shuffle");
1577 if (!InsElt1 || !InsElt1->hasOneUse())
1588 Value *NewInsElt1 = Builder.CreateInsertElement(
X, ScalarC, IdxC2);
1601 if (!Inst || !Inst->hasOneUse())
1606 Constant *ShufConstVec, *InsEltScalar;
1630 unsigned NumElts = Mask.size();
1633 for (
unsigned I = 0;
I != NumElts; ++
I) {
1634 if (
I == InsEltIndex) {
1635 NewShufElts[
I] = InsEltScalar;
1636 NewMaskElts[
I] = InsEltIndex + NumElts;
1640 NewMaskElts[
I] = Mask[
I];
1644 if (!NewShufElts[
I])
1671 auto ValI = std::begin(Val);
1678 Mask[
I] = NumElts +
I;
1683 for (
unsigned I = 0;
I < NumElts; ++
I) {
1715 CastOpcode = Instruction::FPExt;
1717 CastOpcode = Instruction::SExt;
1719 CastOpcode = Instruction::ZExt;
1724 if (
X->getType()->getScalarType() !=
Y->getType())
1752 Value *Scalar0, *BaseVec;
1754 if (!VTy || (VTy->getNumElements() & 1) ||
1763 if (Index0 + 1 != Index1 || Index0 & 1)
1780 Type *SrcTy =
X->getType();
1781 unsigned ScalarWidth = SrcTy->getScalarSizeInBits();
1782 unsigned VecEltWidth = VTy->getScalarSizeInBits();
1783 if (ScalarWidth != VecEltWidth * 2 || ShAmt != VecEltWidth)
1788 Value *CastBaseVec = Builder.CreateBitCast(BaseVec, CastTy);
1792 uint64_t NewIndex = IsBigEndian ? Index1 / 2 : Index0 / 2;
1793 Value *NewInsert = Builder.CreateInsertElement(CastBaseVec,
X, NewIndex);
1798 Value *VecOp = IE.getOperand(0);
1799 Value *ScalarOp = IE.getOperand(1);
1800 Value *IdxOp = IE.getOperand(2);
1803 VecOp, ScalarOp, IdxOp,
SQ.getWithInstruction(&IE)))
1811 Value *BaseVec, *OtherScalar;
1812 uint64_t OtherIndexVal;
1816 !
isa<Constant>(OtherScalar) && OtherIndexVal > IndexC->getZExtValue()) {
1817 Value *NewIns =
Builder.CreateInsertElement(BaseVec, ScalarOp, IdxOp);
1819 Builder.getInt64(OtherIndexVal));
1837 Value *NewInsElt =
Builder.CreateInsertElement(NewUndef, ScalarSrc, IdxOp);
1852 Value *NewInsElt =
Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp);
1860 uint64_t InsertedIdx, ExtractedIdx;
1884 if (!Insert.hasOneUse())
1893 if (isShuffleRootCandidate(IE)) {
1904 if (LR.first != &IE && LR.second != &IE) {
1906 if (LR.second ==
nullptr)
1915 unsigned VWidth = VecTy->getNumElements();
1916 APInt PoisonElts(VWidth, 0);
1939 return IdentityShuf;
1953 unsigned Depth = 5) {
1960 if (!
I)
return false;
1963 if (!
I->hasOneUse())
1966 if (
Depth == 0)
return false;
1968 switch (
I->getOpcode()) {
1969 case Instruction::UDiv:
1970 case Instruction::SDiv:
1971 case Instruction::URem:
1972 case Instruction::SRem:
1979 case Instruction::Add:
1980 case Instruction::FAdd:
1981 case Instruction::Sub:
1982 case Instruction::FSub:
1983 case Instruction::Mul:
1984 case Instruction::FMul:
1985 case Instruction::FDiv:
1986 case Instruction::FRem:
1987 case Instruction::Shl:
1988 case Instruction::LShr:
1989 case Instruction::AShr:
1990 case Instruction::And:
1991 case Instruction::Or:
1992 case Instruction::Xor:
1993 case Instruction::ICmp:
1994 case Instruction::FCmp:
1995 case Instruction::Trunc:
1996 case Instruction::ZExt:
1997 case Instruction::SExt:
1998 case Instruction::FPToUI:
1999 case Instruction::FPToSI:
2000 case Instruction::UIToFP:
2001 case Instruction::SIToFP:
2002 case Instruction::FPTrunc:
2003 case Instruction::FPExt:
2004 case Instruction::GetElementPtr: {
2007 Type *ITy =
I->getType();
2011 for (
Value *Operand :
I->operands()) {
2017 case Instruction::InsertElement: {
2019 if (!CI)
return false;
2024 bool SeenOnce =
false;
2025 for (
int I : Mask) {
2026 if (
I == ElementNumber) {
2042 Builder.SetInsertPoint(
I);
2043 switch (
I->getOpcode()) {
2044 case Instruction::Add:
2045 case Instruction::FAdd:
2046 case Instruction::Sub:
2047 case Instruction::FSub:
2048 case Instruction::Mul:
2049 case Instruction::FMul:
2050 case Instruction::UDiv:
2051 case Instruction::SDiv:
2052 case Instruction::FDiv:
2053 case Instruction::URem:
2054 case Instruction::SRem:
2055 case Instruction::FRem:
2056 case Instruction::Shl:
2057 case Instruction::LShr:
2058 case Instruction::AShr:
2059 case Instruction::And:
2060 case Instruction::Or:
2061 case Instruction::Xor: {
2063 assert(NewOps.
size() == 2 &&
"binary operator with #ops != 2");
2065 NewOps[0], NewOps[1]);
2072 NewI->setIsExact(BO->
isExact());
2075 NewI->copyFastMathFlags(
I);
2079 case Instruction::ICmp: {
2080 assert(NewOps.
size() == 2 &&
"icmp with #ops != 2");
2082 NewOps[0], NewOps[1]);
2084 NewI->copyIRFlags(
I);
2087 case Instruction::FCmp:
2088 assert(NewOps.
size() == 2 &&
"fcmp with #ops != 2");
2089 return Builder.CreateFCmpFMF(
cast<FCmpInst>(
I)->getPredicate(), NewOps[0],
2091 case Instruction::Trunc:
2092 case Instruction::ZExt:
2093 case Instruction::SExt:
2094 case Instruction::FPToUI:
2095 case Instruction::FPToSI:
2096 case Instruction::UIToFP:
2097 case Instruction::SIToFP:
2098 case Instruction::FPTrunc:
2099 case Instruction::FPExt: {
2103 I->getType()->getScalarType(),
2105 assert(NewOps.
size() == 1 &&
"cast with #ops != 1");
2107 Builder.CreateCast(
cast<CastInst>(
I)->getOpcode(), NewOps[0], DestTy);
2109 NewI->copyIRFlags(
I);
2112 case Instruction::GetElementPtr: {
2113 Value *Ptr = NewOps[0];
2127 assert(
V->getType()->isVectorTy() &&
"can't reorder non-vector elements");
2128 Type *EltTy =
V->getType()->getScalarType();
2144 switch (
I->getOpcode()) {
2145 case Instruction::Add:
2146 case Instruction::FAdd:
2147 case Instruction::Sub:
2148 case Instruction::FSub:
2149 case Instruction::Mul:
2150 case Instruction::FMul:
2151 case Instruction::UDiv:
2152 case Instruction::SDiv:
2153 case Instruction::FDiv:
2154 case Instruction::URem:
2155 case Instruction::SRem:
2156 case Instruction::FRem:
2157 case Instruction::Shl:
2158 case Instruction::LShr:
2159 case Instruction::AShr:
2160 case Instruction::And:
2161 case Instruction::Or:
2162 case Instruction::Xor:
2163 case Instruction::ICmp:
2164 case Instruction::FCmp:
2165 case Instruction::Trunc:
2166 case Instruction::ZExt:
2167 case Instruction::SExt:
2168 case Instruction::FPToUI:
2169 case Instruction::FPToSI:
2170 case Instruction::UIToFP:
2171 case Instruction::SIToFP:
2172 case Instruction::FPTrunc:
2173 case Instruction::FPExt:
2174 case Instruction::Select:
2175 case Instruction::GetElementPtr: {
2180 for (
int i = 0, e =
I->getNumOperands(); i != e; ++i) {
2185 if (
I->getOperand(i)->getType()->isVectorTy())
2188 V =
I->getOperand(i);
2190 NeedsRebuild |= (
V !=
I->getOperand(i));
2196 case Instruction::InsertElement: {
2204 for (
int e = Mask.size(); Index != e; ++Index) {
2205 if (Mask[Index] == Element) {
2218 Builder.SetInsertPoint(
I);
2219 return Builder.CreateInsertElement(
V,
I->getOperand(1), Index);
2235 unsigned MaskElems = Mask.size();
2236 unsigned BegIdx = Mask.front();
2237 unsigned EndIdx = Mask.back();
2238 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
2240 for (
unsigned I = 0;
I != MaskElems; ++
I)
2241 if (
static_cast<unsigned>(Mask[
I]) != BegIdx +
I)
2266 case Instruction::Shl: {
2271 Instruction::Shl, ConstantInt::get(Ty, 1),
C,
DL);
2272 assert(ShlOne &&
"Constant folding of immediate constants failed");
2273 return {Instruction::Mul, BO0, ShlOne};
2277 case Instruction::Or: {
2280 return {Instruction::Add, BO0, BO1};
2283 case Instruction::Sub:
2298 assert(Shuf.
isSelect() &&
"Must have select-equivalent shuffle");
2303 unsigned NumElts = Mask.size();
2307 if (ShufOp && ShufOp->isSelect() &&
2308 (ShufOp->getOperand(0) == Op1 || ShufOp->getOperand(1) == Op1)) {
2314 if (!ShufOp || !ShufOp->isSelect() ||
2315 (ShufOp->getOperand(0) != Op0 && ShufOp->getOperand(1) != Op0))
2318 Value *
X = ShufOp->getOperand(0), *
Y = ShufOp->getOperand(1);
2320 ShufOp->getShuffleMask(Mask1);
2321 assert(Mask1.
size() == NumElts &&
"Vector size changed with select shuffle");
2334 for (
unsigned i = 0; i != NumElts; ++i)
2335 NewMask[i] = Mask[i] < (
signed)NumElts ? Mask[i] : Mask1[i];
2340 "Unexpected shuffle mask");
2346 assert(Shuf.
isSelect() &&
"Must have select-equivalent shuffle");
2369 Value *
X = Op0IsBinop ? Op1 : Op0;
2378 bool IsFloatingPointTy =
2391 bool MightCreatePoisonOrUB =
2394 if (MightCreatePoisonOrUB)
2435 Value *NewIns = Builder.CreateInsertElement(PoisonVec,
X, (
uint64_t)0);
2441 unsigned NumMaskElts =
2444 for (
unsigned i = 0; i != NumMaskElts; ++i)
2446 NewMask[i] = Mask[i];
2486 bool ConstantsAreOp1;
2489 ConstantsAreOp1 =
false;
2494 ConstantsAreOp1 =
true;
2501 bool DropNSW =
false;
2502 if (ConstantsAreOp1 && Opc0 != Opc1) {
2506 if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl)
2510 Opc0 = AltB0.Opcode;
2514 Opc1 = AltB1.Opcode;
2519 if (Opc0 != Opc1 || !
C0 || !
C1)
2532 bool MightCreatePoisonOrUB =
2535 if (MightCreatePoisonOrUB)
2549 if (!B0->hasOneUse() && !B1->hasOneUse())
2558 if (MightCreatePoisonOrUB && !ConstantsAreOp1)
2568 V =
Builder.CreateShuffleVector(
X,
Y, Mask);
2571 Value *NewBO = ConstantsAreOp1 ?
Builder.CreateBinOp(BOpc, V, NewC) :
2572 Builder.CreateBinOp(BOpc, NewC, V);
2580 NewI->copyIRFlags(B0);
2581 NewI->andIRFlags(B1);
2583 NewI->setHasNoSignedWrap(
false);
2585 NewI->dropPoisonGeneratingFlags();
2604 Type *SrcType =
X->getType();
2605 if (!SrcType->isVectorTy() || !SrcType->isIntOrIntVectorTy() ||
2612 "Expected a shuffle that decreases length");
2619 for (
unsigned i = 0, e = Mask.size(); i != e; ++i) {
2622 uint64_t LSBIndex = IsBigEndian ? (i + 1) * TruncRatio - 1 : i * TruncRatio;
2623 assert(LSBIndex <= INT32_MAX &&
"Overflowed 32-bits");
2624 if (Mask[i] != (
int)LSBIndex)
2650 unsigned NarrowNumElts =
2677 bool IsFNeg = S0->getOpcode() == Instruction::FNeg;
2686 S0->getOpcode() !=
S1->getOpcode() ||
2687 (!S0->hasOneUse() && !
S1->hasOneUse()))
2694 NewF = UnaryOperator::CreateFNeg(NewShuf);
2715 switch (CastOpcode) {
2716 case Instruction::SExt:
2717 case Instruction::ZExt:
2718 case Instruction::FPToSI:
2719 case Instruction::FPToUI:
2720 case Instruction::SIToFP:
2721 case Instruction::UIToFP:
2732 if (ShufTy->getElementCount().getKnownMinValue() >
2733 ShufOpTy->getElementCount().getKnownMinValue())
2740 auto *NewIns = Builder.CreateShuffleVector(Cast0->getOperand(0),
2748 if (!Cast1 || Cast0->getOpcode() != Cast1->getOpcode() ||
2749 Cast0->getSrcTy() != Cast1->getSrcTy())
2754 "Expected fixed vector operands for casts and binary shuffle");
2755 if (CastSrcTy->getPrimitiveSizeInBits() > ShufOpTy->getPrimitiveSizeInBits())
2759 if (!Cast0->hasOneUse() && !Cast1->hasOneUse())
2763 Value *
X = Cast0->getOperand(0);
2764 Value *
Y = Cast1->getOperand(0);
2779 X->getType()->getPrimitiveSizeInBits() ==
2807 assert(NumElts < Mask.size() &&
2808 "Identity with extract must have less elements than its inputs");
2810 for (
unsigned i = 0; i != NumElts; ++i) {
2812 int MaskElt = Mask[i];
2813 NewMask[i] = ExtractMaskElt ==
PoisonMaskElem ? ExtractMaskElt : MaskElt;
2826 int NumElts = Mask.size();
2852 if (NumElts != InpNumElts)
2856 auto isShufflingScalarIntoOp1 = [&](
Value *&Scalar,
ConstantInt *&IndexC) {
2864 int NewInsIndex = -1;
2865 for (
int i = 0; i != NumElts; ++i) {
2871 if (Mask[i] == NumElts + i)
2875 if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue())
2882 assert(NewInsIndex != -1 &&
"Did not fold shuffle with unused operand?");
2885 IndexC = ConstantInt::get(IndexC->getIntegerType(), NewInsIndex);
2894 if (isShufflingScalarIntoOp1(Scalar, IndexC))
2902 if (isShufflingScalarIntoOp1(Scalar, IndexC))
2914 if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() ||
2915 !Shuffle1 || !Shuffle1->isIdentityWithPadding())
2923 Value *
X = Shuffle0->getOperand(0);
2924 Value *
Y = Shuffle1->getOperand(0);
2925 if (
X->getType() !=
Y->getType() ||
2934 "Unexpected operand for identity shuffle");
2942 assert(WideElts > NarrowElts &&
"Unexpected types for identity with padding");
2946 for (
int i = 0, e = Mask.size(); i != e; ++i) {
2952 if (Mask[i] < WideElts) {
2953 if (Shuffle0->getMaskValue(Mask[i]) == -1)
2956 if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1)
2963 if (Mask[i] < WideElts) {
2964 assert(Mask[i] < NarrowElts &&
"Unexpected shuffle mask");
2965 NewMask[i] = Mask[i];
2967 assert(Mask[i] < (WideElts + NarrowElts) &&
"Unexpected shuffle mask");
2968 NewMask[i] = Mask[i] - (WideElts - NarrowElts);
2990 if (
X->getType() !=
Y->getType())
2999 NewBOI->copyIRFlags(BinOp);
3035 X->getType()->isVectorTy() &&
X->getType() ==
Y->getType() &&
3036 X->getType()->getScalarSizeInBits() ==
3038 (LHS->hasOneUse() || RHS->hasOneUse())) {
3053 X->getType()->isVectorTy() && VWidth == LHSWidth) {
3056 unsigned XNumElts = XType->getNumElements();
3062 ScaledMask, XType, ShufQuery))
3070 "Shuffle with 2 undef ops not simplified?");
3104 APInt PoisonElts(VWidth, 0);
3126 if (
SI->getCondition()->getType()->isIntegerTy() &&
3173 bool MadeChange =
false;
3176 unsigned MaskElems = Mask.size();
3178 unsigned VecBitWidth =
DL.getTypeSizeInBits(SrcTy);
3179 unsigned SrcElemBitWidth =
DL.getTypeSizeInBits(SrcTy->getElementType());
3180 assert(SrcElemBitWidth &&
"vector elements must have a bitwidth");
3181 unsigned SrcNumElems = SrcTy->getNumElements();
3187 if (BC->use_empty())
3190 if (BC->hasOneUse()) {
3192 if (BC2 && isEliminableCastPair(BC, BC2))
3198 unsigned BegIdx = Mask.front();
3199 Type *TgtTy = BC->getDestTy();
3200 unsigned TgtElemBitWidth =
DL.getTypeSizeInBits(TgtTy);
3201 if (!TgtElemBitWidth)
3203 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
3204 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
3205 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
3206 if (!VecBitWidthsEqual)
3211 if (!BegIsAligned) {
3215 for (
unsigned I = 0, E = MaskElems, Idx = BegIdx;
I != E; ++Idx, ++
I)
3216 ShuffleMask[
I] = Idx;
3217 V =
Builder.CreateShuffleVector(V, ShuffleMask,
3221 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
3222 assert(SrcElemsPerTgtElem);
3223 BegIdx /= SrcElemsPerTgtElem;
3224 auto [It, Inserted] = NewBCs.
try_emplace(CastSrcTy);
3226 It->second =
Builder.CreateBitCast(V, CastSrcTy, SVI.
getName() +
".bc");
3227 auto *Ext =
Builder.CreateExtractElement(It->second, BegIdx,
3284 LHSShuffle =
nullptr;
3287 RHSShuffle =
nullptr;
3288 if (!LHSShuffle && !RHSShuffle)
3289 return MadeChange ? &SVI :
nullptr;
3291 Value* LHSOp0 =
nullptr;
3292 Value* LHSOp1 =
nullptr;
3293 Value* RHSOp0 =
nullptr;
3294 unsigned LHSOp0Width = 0;
3295 unsigned RHSOp0Width = 0;
3305 Value* newLHS = LHS;
3306 Value* newRHS = RHS;
3314 else if (LHSOp0Width == LHSWidth) {
3319 if (RHSShuffle && RHSOp0Width == LHSWidth) {
3323 if (LHSOp0 == RHSOp0) {
3328 if (newLHS == LHS && newRHS == RHS)
3329 return MadeChange ? &SVI :
nullptr;
3335 if (RHSShuffle && newRHS != RHS)
3338 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
3344 for (
unsigned i = 0; i < VWidth; ++i) {
3349 }
else if (Mask[i] < (
int)LHSWidth) {
3354 if (newLHS != LHS) {
3355 eltMask = LHSMask[Mask[i]];
3371 else if (newRHS != RHS) {
3372 eltMask = RHSMask[Mask[i]-LHSWidth];
3375 if (eltMask >= (
int)RHSOp0Width) {
3377 "should have been check above");
3381 eltMask = Mask[i]-LHSWidth;
3389 if (eltMask >= 0 && newRHS !=
nullptr && newLHS != newRHS)
3390 eltMask += newLHSWidth;
3395 if (SplatElt >= 0 && SplatElt != eltMask)
3405 if (
isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
3411 return MadeChange ? &SVI :
nullptr;
3433 if (
DL.isBigEndian())
3448 auto isDeinterleaveShuffle =
3455 unsigned NumInputElements =
3461 NumInputElements) &&
3462 ShuffleMask.size() * 2 == NumInputElements)
3465 return {
nullptr, UINT_MAX};
3472 DIV = isDeinterleaveShuffle(SVI).first;
3478 if (!
all_of(DI->users(), [](User *Usr) ->
bool {
3479 auto *EV = dyn_cast<ExtractValueInst>(Usr);
3480 return EV && EV->getNumIndices() == 1;
3491 if (!InputVecTy->getElementCount().isKnownEven())
3497 for (
auto *Usr : DIV->
users()) {
3501 auto [
V,
Index] = isDeinterleaveShuffle(FieldI);
3506 if (FieldI->getParent() != SVI->
getParent())
3508 if (FieldI != SVI && FieldI->comesBefore(SVI))
3514 for (User *
Field : DI->users()) {
3516 unsigned FieldIdx = *FieldI->idx_begin();
3527 for (
auto [
Field, FieldIdx] : Fields) {
3528 for (User *FieldUsr :
Field->users()) {
3533 if (ZExt->getDestTy() != ZExt->getSrcTy()->getExtendedType())
3535 FieldReplacements.
push_back({ZExt, FieldIdx});
3540 Builder.SetInsertPoint(DI ? DI : SVI);
3549 unsigned InElementBitWidth = InElementTy->getBitWidth();
3552 Value *NewField1 =
Builder.CreateLShr(Bitcast, InElementBitWidth);
3554 for (
auto [
I, Idx] : FieldReplacements) {
3555 assert(Idx < 2 &&
"unsupported field index");
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file provides internal interfaces used to implement the InstCombine.
static Instruction * foldConstantInsEltIntoShuffle(InsertElementInst &InsElt)
insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex --> shufflevector X,...
static Value * evaluateInDifferentElementOrder(Value *V, ArrayRef< int > Mask, IRBuilderBase &Builder)
static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, SmallVectorImpl< int > &Mask)
If V is a shuffle of values that ONLY returns elements from either LHS or RHS, return the shuffle mas...
static ShuffleOps collectShuffleElements(Value *V, SmallVectorImpl< int > &Mask, Value *PermittedRHS, InstCombinerImpl &IC, bool &Rerun)
static APInt findDemandedEltsByAllUsers(Value *V)
Find union of elements of V demanded by all its users.
static Instruction * foldTruncInsEltPair(InsertElementInst &InsElt, bool IsBigEndian, InstCombiner::BuilderTy &Builder)
If we are inserting 2 halves of a value into adjacent elements of a vector, try to convert to a singl...
static Instruction * foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf, const SimplifyQuery &SQ)
static Instruction * foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf)
static Instruction * foldIdentityExtractShuffle(ShuffleVectorInst &Shuf)
Try to fold an extract subvector operation.
static bool findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr, APInt &UnionUsedElts)
Find elements of V demanded by UserInstr.
static Instruction * foldInsEltIntoSplat(InsertElementInst &InsElt)
Try to fold an insert element into an existing splat shuffle by changing the shuffle's mask to includ...
std::pair< Value *, Value * > ShuffleOps
We are building a shuffle to create V, which is a sequence of insertelement, extractelement pairs.
static Instruction * foldShuffleWithInsert(ShuffleVectorInst &Shuf, InstCombinerImpl &IC)
Try to replace a shuffle with an insertelement or try to replace a shuffle operand with the operand o...
static Instruction * canonicalizeInsertSplat(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder)
If we have an insert of a scalar to a non-zero element of an undefined vector and then shuffle that v...
static Instruction * foldTruncShuffle(ShuffleVectorInst &Shuf, bool IsBigEndian)
Convert a narrowing shuffle of a bitcasted vector into a vector truncate.
static bool replaceExtractElements(InsertElementInst *InsElt, ExtractElementInst *ExtElt, InstCombinerImpl &IC)
If we have insertion into a vector that is wider than the vector that we are extracting from,...
static bool cheapToScalarize(Value *V, Value *EI)
Return true if the value is cheaper to scalarize than it is to leave as a vector operation.
static Value * buildNew(Instruction *I, ArrayRef< Value * > NewOps, IRBuilderBase &Builder)
Rebuild a new instruction just like 'I' but with the new operands given.
static bool canEvaluateShuffled(Value *V, ArrayRef< int > Mask, unsigned Depth=5)
Return true if we can evaluate the specified expression tree if the vector elements were shuffled in ...
static Instruction * foldSelectShuffleOfSelectShuffle(ShuffleVectorInst &Shuf)
A select shuffle of a select shuffle with a shared operand can be reduced to a single select shuffle.
static Instruction * hoistInsEltConst(InsertElementInst &InsElt2, InstCombiner::BuilderTy &Builder)
If we have an insertelement instruction feeding into another insertelement and the 2nd is inserting a...
static Instruction * foldShuffleOfUnaryOps(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder)
Canonicalize FP negate/abs after shuffle.
static Instruction * foldCastShuffle(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder)
Canonicalize casts after shuffle.
static Instruction * narrowInsElt(InsertElementInst &InsElt, InstCombiner::BuilderTy &Builder)
If both the base vector and the inserted element are extended from the same type, do the insert eleme...
static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf)
static Instruction * foldInsSequenceIntoSplat(InsertElementInst &InsElt)
Turn a chain of inserts that splats a value into an insert + shuffle: insertelt(insertelt(insertelt(i...
static Instruction * foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt)
Try to fold an extract+insert element into an existing identity shuffle by changing the shuffle's mas...
static ConstantInt * getPreferredVectorIndex(ConstantInt *IndexC)
Given a constant index for a extractelement or insertelement instruction, return it with the canonica...
static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI, ArrayRef< int > Mask)
static Value * foldExtractOfStridedPointerVector(ExtractElementInst &EI, InstCombiner::BuilderTy &Builder, const DataLayout &DL)
Fold a variable extract from a vector of pointers that all point into the same object at a constant s...
static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL)
Binops may be transformed into binops with different opcodes and operands.
This file provides the interface for the instcombine pass implementation.
SmallVector< MachineOperand, 4 > Cond
static bool isSplat(Value *V)
Return true if V is a splat of a value (which is used when multiplying a matrix with a scalar).
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
This file implements the SmallBitVector class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SDValue narrowVectorSelect(SDNode *N, SelectionDAG &DAG, const SDLoc &DL, const X86Subtarget &Subtarget)
If both arms of a vector select are concatenated vectors, split the select, and concatenate the resul...
static const uint32_t IV[8]
Class for arbitrary precision integers.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
unsigned getActiveBits() const
Compute the number of active bits in the value.
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
bool ult(const APInt &RHS) const
Unsigned less than comparison.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
Get the first element.
size_t size() const
Get the array size.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
LLVM Basic Block Representation.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
BinaryOps getOpcode() const
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, const Twine &Name="", InsertPosition InsertBefore=nullptr)
This class represents a no-op cast from one type to another.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
This class is the base class for the comparison instructions.
static LLVM_ABI CmpInst * CreateWithCopiedFlags(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Instruction *FlagsSource, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate, the two operands and the instructio...
OtherOps getOpcode() const
Get the opcode casted to the right type.
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
This is the shared class of boolean and integer constants.
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const APInt & getValue() const
Return the constant as an APInt value reference.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
static DebugLoc getCompilerGenerated()
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setNoWrapFlags(GEPNoWrapFlags NW)
Set nowrap flags for GEP instruction.
Common base class shared among various IRBuilders.
This instruction inserts a single (scalar) element into a VectorType value.
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
VectorType * getType() const
Overload to return most specific vector type.
This instruction inserts a struct field of array element value into an aggregate value.
Instruction * foldExtractionOfVectorDeinterleave(ZExtInst &RootZExt)
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Value * SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &PoisonElts, unsigned Depth=0, bool AllowMultipleUsers=false) override
The specified value produces a vector with any number of elements.
Instruction * foldSelectShuffle(ShuffleVectorInst &Shuf)
Try to fold shuffles that are the equivalent of a vector select.
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * visitInsertValueInst(InsertValueInst &IV)
Try to find redundant insertvalue instructions, like the following ones: %0 = insertvalue { i8,...
Instruction * visitInsertElementInst(InsertElementInst &IE)
Instruction * visitExtractElementInst(ExtractElementInst &EI)
Instruction * simplifyBinOpSplats(ShuffleVectorInst &SVI)
Instruction * foldAggregateConstructionIntoAggregateReuse(InsertValueInst &OrigIVI)
Look for chain of insertvalue's that fully define an aggregate, and trace back the values inserted,...
Instruction * visitShuffleVectorInst(ShuffleVectorInst &SVI)
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
void addToWorklist(Instruction *I)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
static Constant * getSafeVectorConstantForBinop(BinaryOperator::BinaryOps Opcode, Constant *In, bool IsRHSConstant)
Some binary operators require special handling to avoid poison and undefined behavior.
const SimplifyQuery & getSimplifyQuery() const
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoInfs() const LLVM_READONLY
Determine whether the no-infs flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
Instruction * user_back()
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
bool isTerminator() const
iterator_range< user_iterator > users()
LLVM_ABI void setHasNoInfs(bool B)
Set or clear the no-infs flag on this instruction, which must be an operator which supports this flag...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
A wrapper class for inspecting calls to intrinsic functions.
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
In order to facilitate speculative execution, many instructions do not invoke immediate undefined beh...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
This instruction constructs a fixed permutation of two input vectors.
bool changesLength() const
Return true if this shuffle returns a vector with a different number of elements than its source vect...
int getMaskValue(unsigned Elt) const
Return the shuffle mask value of this instruction for the given element index.
static LLVM_ABI bool isSelectMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from its source vectors without lane crossings.
VectorType * getType() const
Overload to return most specific vector type.
bool increasesLength() const
Return true if this shuffle returns a vector with a greater number of elements than its source vector...
LLVM_ABI bool isIdentityWithExtract() const
Return true if this shuffle extracts the first N elements of exactly one source vector.
static LLVM_ABI bool isSingleSourceMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
bool isSelect() const
Return true if this shuffle chooses elements from its source vectors without lane crossings and all o...
static LLVM_ABI bool isDeInterleaveMaskOfFactor(ArrayRef< int > Mask, unsigned Factor, unsigned &Index)
Check if the mask is a DE-interleave mask of the given factor Factor like: <Index,...
static LLVM_ABI bool isIdentityMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector without lane crossin...
static void commuteShuffleMask(MutableArrayRef< int > Mask, unsigned InVecNumElts)
Change values in a shuffle permute mask assuming the two vector operands of length InVecNumElts have ...
LLVM_ABI void commute()
Swap the operands and adjust the mask to preserve the semantics of the instruction.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
bool all() const
Returns true if all bits are set.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
bool isVectorTy() const
True if this is an instance of VectorType.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isIntegerTy() const
True if this is an instance of IntegerType.
TypeID getTypeID() const
Return the type id for the type.
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static UnaryOperator * CreateWithCopiedFlags(UnaryOps Opc, Value *V, Instruction *CopyO, const Twine &Name="", InsertPosition InsertBefore=nullptr)
UnaryOps getOpcode() const
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI const Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const
Translate PHI node to its predecessor from the given basic block.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< user_iterator > users()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
static VectorType * getHalfElementsVectorType(VectorType *VTy)
This static method returns a VectorType with half as many elements as the input type and the same ele...
static VectorType * getExtendedElementVectorType(VectorType *VTy)
This static method is like getInteger except that the element types are twice as wide as the elements...
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Type * getElementType() const
This class represents zero extension of integer types.
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
const ParentTy * getParent() const
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
@ Bitcast
Perform the operation on a different, but equivalently sized type.
BinaryOpc_match< LHS, RHS, false > m_BinOp(unsigned Opcode, const LHS &L, const RHS &R)
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
auto m_Cmp()
Matches any compare instruction and ignore it.
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Constant()
Match an arbitrary Constant and ignore it.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
is_zero< false > m_ZeroForbidPoison()
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const DataLayout &DL, const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type and canonical index type.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_Deinterleave2(const Opnd &Op)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
auto m_FAbs(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
auto m_UnOp()
Match an arbitrary unary operation and ignore it.
auto m_Undef()
Match an arbitrary undef constant.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
RelativeUniformCounterPtr Values
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI llvm::SmallVector< int, 16 > createUnaryMask(ArrayRef< int > Mask, unsigned NumElts)
Given a shuffle mask for a binary shuffle, create the equivalent shuffle mask assuming both operands ...
LLVM_ABI Value * simplifyShuffleVectorInst(Value *Op0, Value *Op1, ArrayRef< int > Mask, Type *RetTy, const SimplifyQuery &Q)
Given operands for a ShuffleVectorInst, fold the result or return null.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI Value * simplifyInsertValueInst(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an InsertValueInst, fold the result or return null.
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
constexpr int PoisonMaskElem
LLVM_ABI Value * findScalarElement(Value *V, unsigned EltNo)
Given a vector and an element number, see if the scalar value is already around as a register,...
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
LLVM_ABI Value * simplifyInsertElementInst(Value *Vec, Value *Elt, Value *Idx, const SimplifyQuery &Q)
Given operands for an InsertElement, fold the result or return null.
constexpr unsigned BitWidth
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
bool pred_empty(const BasicBlock *BB)
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI Value * simplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &Q)
Given operands for an ExtractElementInst, fold the result or return null.
LLVM_ABI bool scaleShuffleMaskElts(unsigned NumDstElts, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Attempt to narrow/widen the Mask shuffle mask to the NumDstElts target width.
LLVM_ABI int getSplatIndex(ArrayRef< int > Mask)
If all non-negative Mask elements are the same value, return that value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
These are the ingredients in an alternate form binary operator as described below.
BinopElts(BinaryOperator::BinaryOps Opc=(BinaryOperator::BinaryOps) 0, Value *V0=nullptr, Value *V1=nullptr)
BinaryOperator::BinaryOps Opcode
A MapVector that performs no allocations if smaller than a certain size.