100 using namespace llvm;
104 #define SV_NAME "slp-vectorizer" 105 #define DEBUG_TYPE "SLP" 107 STATISTIC(NumVectorInstructions,
"Number of vector instructions generated");
111 cl::desc(
"Only vectorize if you gain more than this " 116 cl::desc(
"Attempt to vectorize horizontal reductions"));
121 "Attempt to vectorize horizontal reductions feeding into a store"));
125 cl::desc(
"Attempt to vectorize for this register size in bits"));
133 cl::desc(
"Limit the size of the SLP scheduling region per block"));
137 cl::desc(
"Attempt to vectorize for this register size in bits"));
141 cl::desc(
"Limit the recursion depth when building a vectorizable tree"));
145 cl::desc(
"Only vectorize small trees if they are fully vectorizable"));
149 cl::desc(
"Display the SLP trees with Graphviz"));
183 for (
int i = 1, e = VL.
size(); i < e; i++) {
197 if (!isa<Constant>(i))
204 for (
unsigned i = 1, e = VL.
size(); i < e; ++i)
253 auto *EI0 = cast<ExtractElementInst>(VL[0]);
254 unsigned Size = EI0->getVectorOperandType()->getVectorNumElements();
255 Value *Vec1 =
nullptr;
256 Value *Vec2 =
nullptr;
257 enum ShuffleMode { Unknown,
Select, Permute };
258 ShuffleMode CommonShuffleMode = Unknown;
259 for (
unsigned I = 0,
E = VL.
size();
I <
E; ++
I) {
260 auto *EI = cast<ExtractElementInst>(VL[
I]);
261 auto *Vec = EI->getVectorOperand();
263 if (Vec->getType()->getVectorNumElements() !=
Size)
269 if (Idx->getValue().uge(Size))
271 unsigned IntIdx = Idx->getValue().getZExtValue();
273 if (isa<UndefValue>(Vec))
277 if (!Vec1 || Vec1 == Vec)
279 else if (!Vec2 || Vec2 == Vec)
283 if (CommonShuffleMode == Permute)
288 CommonShuffleMode = Permute;
291 CommonShuffleMode =
Select;
294 if (CommonShuffleMode ==
Select && Vec2)
305 struct InstructionsState {
307 Value *OpValue =
nullptr;
314 unsigned getOpcode()
const {
318 unsigned getAltOpcode()
const {
323 bool isAltShuffle()
const {
return getOpcode() != getAltOpcode(); }
327 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
330 InstructionsState() =
delete;
332 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
342 if (
I && S.isOpcodeOrAlt(
I))
351 unsigned BaseIndex = 0) {
354 return InstructionsState(VL[BaseIndex],
nullptr,
nullptr);
356 bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
357 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
358 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
359 unsigned AltOpcode = Opcode;
360 unsigned AltIndex = BaseIndex;
364 for (
int Cnt = 0,
E = VL.
size(); Cnt <
E; Cnt++) {
365 unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
366 if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
367 if (InstOpcode == Opcode || InstOpcode == AltOpcode)
369 if (Opcode == AltOpcode) {
370 AltOpcode = InstOpcode;
374 }
else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
375 Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
376 Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
378 if (InstOpcode == Opcode || InstOpcode == AltOpcode)
380 if (Opcode == AltOpcode) {
381 AltOpcode = InstOpcode;
386 }
else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
388 return InstructionsState(VL[BaseIndex],
nullptr,
nullptr);
391 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
392 cast<Instruction>(VL[AltIndex]));
398 Type *Ty = VL[0]->getType();
399 for (
int i = 1, e = VL.
size(); i < e; i++)
409 assert((Opcode == Instruction::ExtractElement ||
410 Opcode == Instruction::ExtractValue) &&
411 "Expected extractelement or extractvalue instruction.");
412 if (Opcode == Instruction::ExtractElement) {
416 return CI->getZExtValue();
431 LoadInst *LI = cast<LoadInst>(UserInst);
439 CallInst *CI = cast<CallInst>(UserInst);
455 if (
LoadInst *LI = dyn_cast<LoadInst>(I))
462 if (
LoadInst *LI = dyn_cast<LoadInst>(I))
463 return LI->isSimple();
465 return SI->isSimple();
467 return !
MI->isVolatile();
489 :
F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
490 DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
501 MaxVecRegSize = TTI->getRegisterBitWidth(
true);
506 MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
511 Value *vectorizeTree();
541 VectorizableTree.clear();
542 ScalarToTreeEntry.clear();
544 ExternalUses.clear();
545 NumOpsWantToKeepOrder.clear();
546 NumOpsWantToKeepOriginalOrder = 0;
547 for (
auto &Iter : BlocksSchedules) {
548 BlockScheduling *BS = Iter.second.get();
557 void optimizeGatherSequence();
561 auto I = std::max_element(
562 NumOpsWantToKeepOrder.begin(), NumOpsWantToKeepOrder.end(),
563 [](
const decltype(NumOpsWantToKeepOrder)::value_type &D1,
564 const decltype(NumOpsWantToKeepOrder)::value_type &D2) {
565 return D1.second < D2.second;
567 if (
I == NumOpsWantToKeepOrder.end() ||
568 I->getSecond() <= NumOpsWantToKeepOriginalOrder)
579 unsigned getVectorElementSize(
Value *V);
587 return MaxVecRegSize;
592 return MinVecRegSize;
602 bool isTreeTinyAndNotFullyVectorizable();
613 int getEntryCost(TreeEntry *
E);
627 Value *vectorizeTree(TreeEntry *E);
644 const InstructionsState &S);
651 bool isFullyVectorizableTinyTree();
655 void reorderAltShuffleOperands(
const InstructionsState &S,
666 TreeEntry(std::vector<TreeEntry> &Container) : Container(Container) {}
670 if (VL.
size() == Scalars.size())
672 return VL.
size() == ReuseShuffleIndices.size() &&
674 VL.
begin(), VL.
end(), ReuseShuffleIndices.begin(),
675 [
this](
Value *V,
unsigned Idx) {
return V == Scalars[Idx]; });
682 Value *VectorizedValue =
nullptr;
685 bool NeedToGather =
false;
699 std::vector<TreeEntry> &Container;
711 int idx = VectorizableTree.size() - 1;
712 TreeEntry *Last = &VectorizableTree[idx];
713 Last->Scalars.insert(Last->Scalars.begin(), VL.
begin(), VL.
end());
714 Last->NeedToGather = !Vectorized;
715 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
716 ReuseShuffleIndices.end());
717 Last->ReorderIndices = ReorderIndices;
719 for (
int i = 0, e = VL.
size(); i != e; ++i) {
720 assert(!getTreeEntry(VL[i]) &&
"Scalar already in tree!");
721 ScalarToTreeEntry[VL[i]] = idx;
724 MustGather.insert(VL.
begin(), VL.
end());
727 if (UserTreeIdx >= 0)
728 Last->UserTreeIndices.push_back(UserTreeIdx);
734 std::vector<TreeEntry> VectorizableTree;
736 TreeEntry *getTreeEntry(
Value *V) {
737 auto I = ScalarToTreeEntry.find(V);
738 if (I != ScalarToTreeEntry.end())
739 return &VectorizableTree[I->second];
750 struct ExternalUser {
772 AliasCacheKey key = std::make_pair(Inst1, Inst2);
781 aliased = AA->alias(Loc1, Loc2);
788 using AliasCacheKey = std::pair<Instruction *, Instruction *>;
803 DeletedInstructions.emplace_back(I);
829 struct ScheduleData {
832 enum { InvalidDeps = -1 };
834 ScheduleData() =
default;
836 void init(
int BlockSchedulingRegionID,
Value *OpVal) {
837 FirstInBundle =
this;
838 NextInBundle =
nullptr;
839 NextLoadStore =
nullptr;
841 SchedulingRegionID = BlockSchedulingRegionID;
842 UnscheduledDepsInBundle = UnscheduledDeps;
848 bool hasValidDependencies()
const {
return Dependencies != InvalidDeps; }
852 bool isSchedulingEntity()
const {
return FirstInBundle ==
this; }
856 bool isPartOfBundle()
const {
857 return NextInBundle !=
nullptr || FirstInBundle !=
this;
862 bool isReady()
const {
863 assert(isSchedulingEntity() &&
864 "can't consider non-scheduling entity for ready list");
865 return UnscheduledDepsInBundle == 0 && !IsScheduled;
870 int incrementUnscheduledDeps(
int Incr) {
871 UnscheduledDeps += Incr;
872 return FirstInBundle->UnscheduledDepsInBundle += Incr;
877 void resetUnscheduledDeps() {
878 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
882 void clearDependencies() {
883 Dependencies = InvalidDeps;
884 resetUnscheduledDeps();
885 MemoryDependencies.clear();
889 if (!isSchedulingEntity()) {
891 }
else if (NextInBundle) {
893 ScheduleData *SD = NextInBundle;
895 os <<
';' << *SD->Inst;
896 SD = SD->NextInBundle;
908 ScheduleData *FirstInBundle =
nullptr;
912 ScheduleData *NextInBundle =
nullptr;
916 ScheduleData *NextLoadStore =
nullptr;
924 int SchedulingRegionID = 0;
927 int SchedulingPriority = 0;
933 int Dependencies = InvalidDeps;
939 int UnscheduledDeps = InvalidDeps;
943 int UnscheduledDepsInBundle = InvalidDeps;
947 bool IsScheduled =
false;
950 Value *OpValue =
nullptr;
955 const BoUpSLP::ScheduleData &SD) {
965 struct BlockScheduling {
967 : BB(BB), ChunkSize(BB->
size()), ChunkPos(ChunkSize) {}
971 ScheduleStart =
nullptr;
972 ScheduleEnd =
nullptr;
973 FirstLoadStoreInRegion =
nullptr;
974 LastLoadStoreInRegion =
nullptr;
978 ScheduleRegionSizeLimit -= ScheduleRegionSize;
979 if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
981 ScheduleRegionSize = 0;
985 ++SchedulingRegionID;
988 ScheduleData *getScheduleData(
Value *V) {
989 ScheduleData *SD = ScheduleDataMap[V];
990 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
997 return getScheduleData(V);
998 auto I = ExtraScheduleDataMap.find(V);
999 if (I != ExtraScheduleDataMap.end()) {
1000 ScheduleData *SD = I->second[
Key];
1001 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
1007 bool isInSchedulingRegion(ScheduleData *SD) {
1008 return SD->SchedulingRegionID == SchedulingRegionID;
1013 template <
typename ReadyListType>
1014 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
1015 SD->IsScheduled =
true;
1018 ScheduleData *BundleMember = SD;
1019 while (BundleMember) {
1020 if (BundleMember->Inst != BundleMember->OpValue) {
1021 BundleMember = BundleMember->NextInBundle;
1025 for (
Use &U : BundleMember->Inst->operands()) {
1029 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
1030 if (OpDef && OpDef->hasValidDependencies() &&
1031 OpDef->incrementUnscheduledDeps(-1) == 0) {
1035 ScheduleData *DepBundle = OpDef->FirstInBundle;
1036 assert(!DepBundle->IsScheduled &&
1037 "already scheduled bundle gets ready");
1038 ReadyList.insert(DepBundle);
1040 <<
"SLP: gets ready (def): " << *DepBundle <<
"\n");
1045 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
1046 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
1049 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
1050 assert(!DepBundle->IsScheduled &&
1051 "already scheduled bundle gets ready");
1052 ReadyList.insert(DepBundle);
1054 <<
"SLP: gets ready (mem): " << *DepBundle <<
"\n");
1057 BundleMember = BundleMember->NextInBundle;
1061 void doForAllOpcodes(
Value *V,
1063 if (ScheduleData *SD = getScheduleData(V))
1065 auto I = ExtraScheduleDataMap.find(V);
1066 if (I != ExtraScheduleDataMap.end())
1067 for (
auto &
P : I->second)
1068 if (
P.second->SchedulingRegionID == SchedulingRegionID)
1073 template <
typename ReadyListType>
1074 void initialFillReadyList(ReadyListType &ReadyList) {
1075 for (
auto *I = ScheduleStart; I != ScheduleEnd; I = I->
getNextNode()) {
1076 doForAllOpcodes(I, [&](ScheduleData *SD) {
1077 if (SD->isSchedulingEntity() && SD->isReady()) {
1078 ReadyList.insert(SD);
1080 <<
"SLP: initially in ready list: " << *I <<
"\n");
1090 const InstructionsState &S);
1096 ScheduleData *allocateScheduleDataChunks();
1100 bool extendSchedulingRegion(
Value *V,
const InstructionsState &S);
1105 ScheduleData *PrevLoadStore,
1106 ScheduleData *NextLoadStore);
1110 void calculateDependencies(ScheduleData *SD,
bool InsertInReadyList,
1114 void resetSchedule();
1119 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
1135 ExtraScheduleDataMap;
1138 void insert(ScheduleData *SD) { push_back(SD); }
1142 ReadyList ReadyInsts;
1152 ScheduleData *FirstLoadStoreInRegion =
nullptr;
1156 ScheduleData *LastLoadStoreInRegion =
nullptr;
1159 int ScheduleRegionSize = 0;
1168 int SchedulingRegionID = 1;
1176 void scheduleBlock(BlockScheduling *BS);
1184 struct OrdersTypeDenseMapInfo {
1197 static unsigned getHashValue(
const OrdersType &V) {
1212 unsigned NumOpsWantToKeepOriginalOrder = 0;
1227 unsigned MaxVecRegSize;
1228 unsigned MinVecRegSize;
1251 struct ChildIteratorType
1253 SmallVector<int, 1>::iterator> {
1257 std::vector<TreeEntry> &VT)
1266 return {N->UserTreeIndices.begin(), N->Container};
1270 return {N->UserTreeIndices.end(), N->Container};
1285 static unsigned size(BoUpSLP *R) {
return R->VectorizableTree.size(); }
1296 if (
isSplat(Entry->Scalars)) {
1297 OS <<
"<splat> " << *Entry->Scalars[0];
1300 for (
auto V : Entry->Scalars) {
1303 R->ExternalUses.begin(), R->ExternalUses.end(),
1304 [&](
const BoUpSLP::ExternalUser &EU) {
return EU.Scalar == V; }))
1313 if (Entry->NeedToGather)
1323 ExtraValueToDebugLocsMap ExternallyUsedValues;
1324 buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
1328 ExtraValueToDebugLocsMap &ExternallyUsedValues,
1331 UserIgnoreList = UserIgnoreLst;
1334 buildTree_rec(Roots, 0, -1);
1337 for (
TreeEntry &EIdx : VectorizableTree) {
1341 if (Entry->NeedToGather)
1345 for (
int Lane = 0,
LE = Entry->Scalars.size(); Lane !=
LE; ++Lane) {
1347 int FoundLane = Lane;
1348 if (!Entry->ReuseShuffleIndices.empty()) {
1350 std::distance(Entry->ReuseShuffleIndices.begin(),
1351 llvm::find(Entry->ReuseShuffleIndices, FoundLane));
1355 auto ExtI = ExternallyUsedValues.find(Scalar);
1356 if (ExtI != ExternallyUsedValues.end()) {
1357 LLVM_DEBUG(
dbgs() <<
"SLP: Need to extract: Extra arg from lane " 1358 << Lane <<
" from " << *Scalar <<
".\n");
1359 ExternalUses.emplace_back(Scalar,
nullptr, FoundLane);
1369 if (
TreeEntry *UseEntry = getTreeEntry(U)) {
1370 Value *UseScalar = UseEntry->Scalars[0];
1374 if (UseScalar != U ||
1376 LLVM_DEBUG(
dbgs() <<
"SLP: \tInternal user will be removed:" << *U
1378 assert(!UseEntry->NeedToGather &&
"Bad state");
1387 LLVM_DEBUG(
dbgs() <<
"SLP: Need to extract:" << *U <<
" from lane " 1388 << Lane <<
" from " << *Scalar <<
".\n");
1389 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
1401 LLVM_DEBUG(
dbgs() <<
"SLP: Gathering due to max recursion depth.\n");
1402 newTreeEntry(VL,
false, UserTreeIdx);
1407 if (S.OpValue->getType()->isVectorTy()) {
1409 newTreeEntry(VL,
false, UserTreeIdx);
1413 if (
StoreInst *
SI = dyn_cast<StoreInst>(S.OpValue))
1414 if (
SI->getValueOperand()->getType()->isVectorTy()) {
1415 LLVM_DEBUG(
dbgs() <<
"SLP: Gathering due to store vector type.\n");
1416 newTreeEntry(VL,
false, UserTreeIdx);
1423 newTreeEntry(VL,
false, UserTreeIdx);
1431 for (
unsigned i = 0, e = VL.
size(); i != e; ++i) {
1432 if (EphValues.count(VL[i])) {
1434 <<
") is ephemeral.\n");
1435 newTreeEntry(VL,
false, UserTreeIdx);
1441 if (
TreeEntry *
E = getTreeEntry(S.OpValue)) {
1442 LLVM_DEBUG(
dbgs() <<
"SLP: \tChecking bundle: " << *S.OpValue <<
".\n");
1443 if (!
E->isSame(VL)) {
1444 LLVM_DEBUG(
dbgs() <<
"SLP: Gathering due to partial overlap.\n");
1445 newTreeEntry(VL,
false, UserTreeIdx);
1450 E->UserTreeIndices.push_back(UserTreeIdx);
1451 LLVM_DEBUG(
dbgs() <<
"SLP: Perfect diamond merge at " << *S.OpValue
1457 for (
unsigned i = 0, e = VL.
size(); i != e; ++i) {
1461 if (getTreeEntry(
I)) {
1463 <<
") is already in tree.\n");
1464 newTreeEntry(VL,
false, UserTreeIdx);
1471 for (
unsigned i = 0, e = VL.
size(); i != e; ++i) {
1472 if (MustGather.count(VL[i])) {
1473 LLVM_DEBUG(
dbgs() <<
"SLP: Gathering due to gathered scalar.\n");
1474 newTreeEntry(VL,
false, UserTreeIdx);
1481 auto *VL0 = cast<Instruction>(S.OpValue);
1484 if (!DT->isReachableFromEntry(BB)) {
1488 newTreeEntry(VL,
false, UserTreeIdx);
1496 for (
Value *V : VL) {
1502 if (UniqueValues.
size() == VL.size()) {
1503 ReuseShuffleIndicies.
clear();
1508 newTreeEntry(VL,
false, UserTreeIdx);
1514 auto &BSRef = BlocksSchedules[BB];
1516 BSRef = llvm::make_unique<BlockScheduling>(BB);
1518 BlockScheduling &BS = *BSRef.get();
1520 if (!BS.tryScheduleBundle(VL,
this, S)) {
1521 LLVM_DEBUG(
dbgs() <<
"SLP: We are not able to schedule this bundle!\n");
1522 assert((!BS.getScheduleData(VL0) ||
1523 !BS.getScheduleData(VL0)->isPartOfBundle()) &&
1524 "tryScheduleBundle should cancelScheduling on failure");
1525 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1528 LLVM_DEBUG(
dbgs() <<
"SLP: We are able to schedule this bundle.\n");
1530 unsigned ShuffleOrOp = S.isAltShuffle() ?
1531 (
unsigned) Instruction::ShuffleVector : S.getOpcode();
1532 switch (ShuffleOrOp) {
1533 case Instruction::PHI: {
1537 for (
unsigned j = 0; j < VL.size(); ++j)
1544 <<
"SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1545 BS.cancelScheduling(VL, VL0);
1546 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1551 newTreeEntry(VL,
true, UserTreeIdx, ReuseShuffleIndicies);
1558 Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock(
1561 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1565 case Instruction::ExtractValue:
1566 case Instruction::ExtractElement: {
1567 OrdersType CurrentOrder;
1568 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
1570 LLVM_DEBUG(
dbgs() <<
"SLP: Reusing or shuffling extract sequence.\n");
1571 ++NumOpsWantToKeepOriginalOrder;
1572 newTreeEntry(VL,
true, UserTreeIdx,
1573 ReuseShuffleIndicies);
1576 if (!CurrentOrder.empty()) {
1578 dbgs() <<
"SLP: Reusing or shuffling of reordered extract sequence " 1580 for (
unsigned Idx : CurrentOrder)
1581 dbgs() <<
" " << Idx;
1586 auto StoredCurrentOrderAndNum =
1587 NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
1588 ++StoredCurrentOrderAndNum->getSecond();
1589 newTreeEntry(VL,
true, UserTreeIdx, ReuseShuffleIndicies,
1590 StoredCurrentOrderAndNum->getFirst());
1594 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1595 BS.cancelScheduling(VL, VL0);
1605 Type *ScalarTy = VL0->getType();
1607 if (DL->getTypeSizeInBits(ScalarTy) !=
1608 DL->getTypeAllocSizeInBits(ScalarTy)) {
1609 BS.cancelScheduling(VL, VL0);
1610 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1611 LLVM_DEBUG(
dbgs() <<
"SLP: Gathering loads of non-packed type.\n");
1618 auto POIter = PointerOps.
begin();
1619 for (
Value *V : VL) {
1620 auto *L = cast<LoadInst>(V);
1621 if (!L->isSimple()) {
1622 BS.cancelScheduling(VL, VL0);
1623 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1627 *POIter = L->getPointerOperand();
1631 OrdersType CurrentOrder;
1636 if (CurrentOrder.empty()) {
1637 Ptr0 = PointerOps.front();
1638 PtrN = PointerOps.back();
1640 Ptr0 = PointerOps[CurrentOrder.front()];
1641 PtrN = PointerOps[CurrentOrder.back()];
1643 const SCEV *Scev0 = SE->getSCEV(Ptr0);
1644 const SCEV *ScevN = SE->getSCEV(PtrN);
1647 uint64_t
Size = DL->getTypeAllocSize(ScalarTy);
1649 if (Diff && Diff->getAPInt().getZExtValue() == (VL.size() - 1) * Size) {
1650 if (CurrentOrder.empty()) {
1652 ++NumOpsWantToKeepOriginalOrder;
1653 newTreeEntry(VL,
true, UserTreeIdx,
1654 ReuseShuffleIndicies);
1658 auto I = NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
1660 newTreeEntry(VL,
true, UserTreeIdx,
1661 ReuseShuffleIndicies,
I->getFirst());
1669 BS.cancelScheduling(VL, VL0);
1670 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1673 case Instruction::ZExt:
1674 case Instruction::SExt:
1675 case Instruction::FPToUI:
1676 case Instruction::FPToSI:
1677 case Instruction::FPExt:
1678 case Instruction::PtrToInt:
1679 case Instruction::IntToPtr:
1680 case Instruction::SIToFP:
1681 case Instruction::UIToFP:
1682 case Instruction::Trunc:
1683 case Instruction::FPTrunc:
1684 case Instruction::BitCast: {
1685 Type *SrcTy = VL0->getOperand(0)->getType();
1686 for (
unsigned i = 0; i < VL.size(); ++i) {
1687 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1689 BS.cancelScheduling(VL, VL0);
1690 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1692 <<
"SLP: Gathering casts with different src types.\n");
1696 newTreeEntry(VL,
true, UserTreeIdx, ReuseShuffleIndicies);
1699 for (
unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1703 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1705 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1709 case Instruction::ICmp:
1710 case Instruction::FCmp: {
1713 Type *ComparedTy = VL0->getOperand(0)->getType();
1714 for (
unsigned i = 1, e = VL.size(); i < e; ++i) {
1715 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1718 BS.cancelScheduling(VL, VL0);
1719 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1721 <<
"SLP: Gathering cmp with different predicate.\n");
1726 newTreeEntry(VL,
true, UserTreeIdx, ReuseShuffleIndicies);
1729 for (
unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1733 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1735 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1741 case Instruction::FAdd:
1742 case Instruction::Sub:
1743 case Instruction::FSub:
1744 case Instruction::Mul:
1745 case Instruction::FMul:
1746 case Instruction::UDiv:
1747 case Instruction::SDiv:
1748 case Instruction::FDiv:
1749 case Instruction::URem:
1750 case Instruction::SRem:
1751 case Instruction::FRem:
1752 case Instruction::Shl:
1753 case Instruction::LShr:
1754 case Instruction::AShr:
1755 case Instruction::And:
1756 case Instruction::Or:
1757 case Instruction::Xor:
1758 newTreeEntry(VL,
true, UserTreeIdx, ReuseShuffleIndicies);
1763 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1765 reorderInputsAccordingToOpcode(S.getOpcode(), VL, Left, Right);
1766 buildTree_rec(Left, Depth + 1, UserTreeIdx);
1767 buildTree_rec(Right, Depth + 1, UserTreeIdx);
1771 for (
unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1775 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1777 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1781 case Instruction::GetElementPtr: {
1783 for (
unsigned j = 0; j < VL.size(); ++j) {
1784 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1785 LLVM_DEBUG(
dbgs() <<
"SLP: not-vectorizable GEP (nested indexes).\n");
1786 BS.cancelScheduling(VL, VL0);
1787 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1794 Type *Ty0 = VL0->getOperand(0)->getType();
1795 for (
unsigned j = 0; j < VL.size(); ++j) {
1796 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1799 <<
"SLP: not-vectorizable GEP (different types).\n");
1800 BS.cancelScheduling(VL, VL0);
1801 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1807 for (
unsigned j = 0; j < VL.size(); ++j) {
1808 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1809 if (!isa<ConstantInt>(
Op)) {
1811 <<
"SLP: not-vectorizable GEP (non-constant indexes).\n");
1812 BS.cancelScheduling(VL, VL0);
1813 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1818 newTreeEntry(VL,
true, UserTreeIdx, ReuseShuffleIndicies);
1820 for (
unsigned i = 0, e = 2; i < e; ++i) {
1824 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1826 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1832 for (
unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1834 BS.cancelScheduling(VL, VL0);
1835 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1840 newTreeEntry(VL,
true, UserTreeIdx, ReuseShuffleIndicies);
1845 Operands.push_back(cast<Instruction>(j)->getOperand(0));
1847 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1852 CallInst *CI = cast<CallInst>(VL0);
1857 BS.cancelScheduling(VL, VL0);
1858 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1863 Value *A1I =
nullptr;
1866 for (
unsigned i = 1, e = VL.size(); i != e; ++i) {
1871 BS.cancelScheduling(VL, VL0);
1872 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1873 LLVM_DEBUG(
dbgs() <<
"SLP: mismatched calls:" << *CI <<
"!=" << *VL[i]
1882 BS.cancelScheduling(VL, VL0);
1883 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1885 <<
" argument " << A1I <<
"!=" << A1J <<
"\n");
1894 BS.cancelScheduling(VL, VL0);
1895 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1897 << *CI <<
"!=" << *VL[i] <<
'\n');
1902 newTreeEntry(VL,
true, UserTreeIdx, ReuseShuffleIndicies);
1906 for (
Value *j : VL) {
1910 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1914 case Instruction::ShuffleVector:
1917 if (!S.isAltShuffle()) {
1918 BS.cancelScheduling(VL, VL0);
1919 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1920 LLVM_DEBUG(
dbgs() <<
"SLP: ShuffleVector are not vectorized.\n");
1923 newTreeEntry(VL,
true, UserTreeIdx, ReuseShuffleIndicies);
1927 if (isa<BinaryOperator>(VL0)) {
1929 reorderAltShuffleOperands(S, VL, Left, Right);
1930 buildTree_rec(Left, Depth + 1, UserTreeIdx);
1931 buildTree_rec(Right, Depth + 1, UserTreeIdx);
1935 for (
unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1939 Operands.push_back(cast<Instruction>(j)->getOperand(i));
1941 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1946 BS.cancelScheduling(VL, VL0);
1947 newTreeEntry(VL,
false, UserTreeIdx, ReuseShuffleIndicies);
1958 N =
ST->getNumElements();
1959 EltTy = *
ST->element_begin();
1961 N = cast<ArrayType>(
T)->getNumElements();
1962 EltTy = cast<ArrayType>(
T)->getElementType();
1971 for (
const auto *Ty :
ST->elements())
1982 E0->
getOpcode() == Instruction::ExtractValue);
1988 CurrentOrder.
clear();
1992 if (E0->
getOpcode() == Instruction::ExtractValue) {
1994 NElts = canMapToVector(Vec->getType(), DL);
2002 NElts = Vec->getType()->getVectorNumElements();
2005 if (NElts != VL.
size())
2009 bool ShouldKeepOrder =
true;
2010 unsigned E = VL.
size();
2016 CurrentOrder.
assign(E, E + 1);
2018 for (; I <
E; ++
I) {
2019 auto *Inst = cast<Instruction>(VL[
I]);
2020 if (Inst->getOperand(0) != Vec)
2025 const unsigned ExtIdx = *Idx;
2027 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1)
2029 ShouldKeepOrder =
false;
2030 CurrentOrder[ExtIdx] =
I;
2032 if (CurrentOrder[I] != E + 1)
2034 CurrentOrder[
I] =
I;
2038 CurrentOrder.
clear();
2042 return ShouldKeepOrder;
2045 bool BoUpSLP::areAllUsersVectorized(
Instruction *
I)
const {
2048 return ScalarToTreeEntry.count(U) > 0;
2052 int BoUpSLP::getEntryCost(TreeEntry *
E) {
2055 Type *ScalarTy = VL[0]->getType();
2057 ScalarTy =
SI->getValueOperand()->getType();
2058 else if (
CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
2059 ScalarTy = CI->getOperand(0)->getType();
2064 if (MinBWs.count(VL[0]))
2068 unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size();
2069 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
2070 int ReuseShuffleCost = 0;
2071 if (NeedToShuffleReuses) {
2075 if (E->NeedToGather) {
2079 return ReuseShuffleCost +
2082 if (
getSameOpcode(VL).getOpcode() == Instruction::ExtractElement &&
2086 int Cost = TTI->getShuffleCost(ShuffleKind.
getValue(), VecTy);
2087 for (
auto *V : VL) {
2092 if (areAllUsersVectorized(cast<Instruction>(V)) &&
2093 !ScalarToTreeEntry.count(V)) {
2094 auto *IO = cast<ConstantInt>(
2095 cast<ExtractElementInst>(V)->getIndexOperand());
2096 Cost -= TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
2097 IO->getZExtValue());
2100 return ReuseShuffleCost + Cost;
2103 return ReuseShuffleCost + getGatherCost(VL);
2108 unsigned ShuffleOrOp = S.isAltShuffle() ?
2109 (
unsigned) Instruction::ShuffleVector : S.getOpcode();
2110 switch (ShuffleOrOp) {
2111 case Instruction::PHI:
2114 case Instruction::ExtractValue:
2115 case Instruction::ExtractElement:
2116 if (NeedToShuffleReuses) {
2118 for (
unsigned I : E->ReuseShuffleIndices) {
2119 if (ShuffleOrOp == Instruction::ExtractElement) {
2120 auto *IO = cast<ConstantInt>(
2121 cast<ExtractElementInst>(VL[
I])->getIndexOperand());
2122 Idx = IO->getZExtValue();
2123 ReuseShuffleCost -= TTI->getVectorInstrCost(
2124 Instruction::ExtractElement, VecTy, Idx);
2126 ReuseShuffleCost -= TTI->getVectorInstrCost(
2127 Instruction::ExtractElement, VecTy, Idx);
2131 Idx = ReuseShuffleNumbers;
2132 for (
Value *V : VL) {
2133 if (ShuffleOrOp == Instruction::ExtractElement) {
2134 auto *IO = cast<ConstantInt>(
2135 cast<ExtractElementInst>(V)->getIndexOperand());
2136 Idx = IO->getZExtValue();
2141 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, Idx);
2144 if (!E->NeedToGather) {
2145 int DeadCost = ReuseShuffleCost;
2146 if (!E->ReorderIndices.empty()) {
2148 DeadCost += TTI->getShuffleCost(
2151 for (
unsigned i = 0, e = VL.
size(); i < e; ++i) {
2156 if (areAllUsersVectorized(E)) {
2160 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2162 [](
User *U) {
return isa<GetElementPtrInst>(U); })) {
2165 DeadCost -= TTI->getExtractWithExtendCost(
2168 DeadCost += TTI->getCastInstrCost(
2174 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
2179 return ReuseShuffleCost + getGatherCost(VL);
2181 case Instruction::ZExt:
2182 case Instruction::SExt:
2183 case Instruction::FPToUI:
2184 case Instruction::FPToSI:
2185 case Instruction::FPExt:
2186 case Instruction::PtrToInt:
2187 case Instruction::IntToPtr:
2188 case Instruction::SIToFP:
2189 case Instruction::UIToFP:
2190 case Instruction::Trunc:
2191 case Instruction::FPTrunc:
2192 case Instruction::BitCast: {
2193 Type *SrcTy = VL0->getOperand(0)->getType();
2195 TTI->getCastInstrCost(S.getOpcode(), ScalarTy, SrcTy, VL0);
2196 if (NeedToShuffleReuses) {
2197 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
2201 int ScalarCost = VL.
size() * ScalarEltCost;
2206 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
2207 VecCost = ReuseShuffleCost +
2208 TTI->getCastInstrCost(S.getOpcode(), VecTy, SrcVecTy, VL0);
2210 return VecCost - ScalarCost;
2212 case Instruction::FCmp:
2213 case Instruction::ICmp:
2216 int ScalarEltCost = TTI->getCmpSelInstrCost(S.getOpcode(), ScalarTy,
2218 if (NeedToShuffleReuses) {
2219 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
2223 int VecCost = TTI->getCmpSelInstrCost(S.getOpcode(), VecTy, MaskTy, VL0);
2224 return ReuseShuffleCost + VecCost - ScalarCost;
2227 case Instruction::FAdd:
2228 case Instruction::Sub:
2229 case Instruction::FSub:
2230 case Instruction::Mul:
2231 case Instruction::FMul:
2232 case Instruction::UDiv:
2233 case Instruction::SDiv:
2234 case Instruction::FDiv:
2235 case Instruction::URem:
2236 case Instruction::SRem:
2237 case Instruction::FRem:
2238 case Instruction::Shl:
2239 case Instruction::LShr:
2240 case Instruction::AShr:
2241 case Instruction::And:
2242 case Instruction::Or:
2243 case Instruction::Xor: {
2261 for (
unsigned i = 0, e = VL.
size(); i < e; ++i) {
2270 !CInt->getValue().isPowerOf2())
2281 int ScalarEltCost = TTI->getArithmeticInstrCost(
2282 S.getOpcode(), ScalarTy, Op1VK, Op2VK, Op1VP, Op2VP, Operands);
2283 if (NeedToShuffleReuses) {
2284 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
2287 int VecCost = TTI->getArithmeticInstrCost(S.getOpcode(), VecTy, Op1VK,
2288 Op2VK, Op1VP, Op2VP, Operands);
2289 return ReuseShuffleCost + VecCost - ScalarCost;
2291 case Instruction::GetElementPtr: {
2299 if (NeedToShuffleReuses) {
2300 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
2305 return ReuseShuffleCost + VecCost - ScalarCost;
2309 unsigned alignment = cast<LoadInst>(VL0)->
getAlignment();
2312 if (NeedToShuffleReuses) {
2313 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
2318 if (!E->ReorderIndices.empty()) {
2320 VecLdCost += TTI->getShuffleCost(
2323 return ReuseShuffleCost + VecLdCost - ScalarLdCost;
2327 unsigned alignment = cast<StoreInst>(VL0)->
getAlignment();
2330 if (NeedToShuffleReuses) {
2331 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
2336 return ReuseShuffleCost + VecStCost - ScalarStCost;
2339 CallInst *CI = cast<CallInst>(VL0);
2348 if (
auto *FPMO = dyn_cast<FPMathOperator>(CI))
2349 FMF = FPMO->getFastMathFlags();
2352 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
2353 if (NeedToShuffleReuses) {
2354 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
2359 int VecCallCost = TTI->getIntrinsicInstrCost(ID, CI->
getType(),
Args, FMF,
2362 LLVM_DEBUG(
dbgs() <<
"SLP: Call cost " << VecCallCost - ScalarCallCost
2363 <<
" (" << VecCallCost <<
"-" << ScalarCallCost <<
")" 2364 <<
" for " << *CI <<
"\n");
2366 return ReuseShuffleCost + VecCallCost - ScalarCallCost;
2368 case Instruction::ShuffleVector: {
2369 assert(S.isAltShuffle() &&
2374 "Invalid Shuffle Vector Operand");
2376 if (NeedToShuffleReuses) {
2377 for (
unsigned Idx : E->ReuseShuffleIndices) {
2379 ReuseShuffleCost -= TTI->getInstructionCost(
2382 for (
Value *V : VL) {
2384 ReuseShuffleCost += TTI->getInstructionCost(
2388 for (
Value *i : VL) {
2390 assert(S.isOpcodeOrAlt(I) &&
"Unexpected main/alternate opcode");
2391 ScalarCost += TTI->getInstructionCost(
2398 VecCost = TTI->getArithmeticInstrCost(S.getOpcode(), VecTy);
2399 VecCost += TTI->getArithmeticInstrCost(S.getAltOpcode(), VecTy);
2401 Type *Src0SclTy = S.MainOp->getOperand(0)->getType();
2402 Type *Src1SclTy = S.AltOp->getOperand(0)->getType();
2405 VecCost = TTI->getCastInstrCost(S.getOpcode(), VecTy, Src0Ty);
2406 VecCost += TTI->getCastInstrCost(S.getAltOpcode(), VecTy, Src1Ty);
2409 return ReuseShuffleCost + VecCost - ScalarCost;
2416 bool BoUpSLP::isFullyVectorizableTinyTree() {
2418 << VectorizableTree.size() <<
" is fully vectorizable .\n");
2421 if (VectorizableTree.size() == 1 && !VectorizableTree[0].NeedToGather)
2424 if (VectorizableTree.size() != 2)
2428 if (!VectorizableTree[0].NeedToGather &&
2430 isSplat(VectorizableTree[1].Scalars)))
2434 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
2440 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() {
2448 if (isFullyVectorizableTinyTree())
2451 assert(VectorizableTree.empty()
2452 ? ExternalUses.empty()
2453 :
true &&
"We shouldn't have any external users");
2460 int BoUpSLP::getSpillCost() {
2465 unsigned BundleWidth = VectorizableTree.front().Scalars.size();
2471 for (
const auto &
N : VectorizableTree) {
2482 LiveValues.
erase(PrevInst);
2483 for (
auto &J : PrevInst->
operands()) {
2484 if (isa<Instruction>(&*J) && getTreeEntry(&*J))
2485 LiveValues.
insert(cast<Instruction>(&*J));
2489 dbgs() <<
"SLP: #LV: " << LiveValues.
size();
2490 for (
auto *
X : LiveValues)
2491 dbgs() <<
" " <<
X->getName();
2492 dbgs() <<
", Looking at ";
2500 while (InstIt != PrevInstIt) {
2507 if ((isa<CallInst>(&*PrevInstIt) &&
2508 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
2509 &*PrevInstIt != PrevInst) {
2511 for (
auto *II : LiveValues)
2513 Cost += TTI->getCostOfKeepingLiveOverCall(V);
2525 int BoUpSLP::getTreeCost() {
2528 << VectorizableTree.size() <<
".\n");
2530 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
2532 for (
unsigned I = 0, E = VectorizableTree.size(); I <
E; ++
I) {
2533 TreeEntry &TE = VectorizableTree[
I];
2547 if (TE.NeedToGather &&
2548 std::any_of(std::next(VectorizableTree.begin(), I + 1),
2549 VectorizableTree.end(), [TE](TreeEntry &Entry) {
2550 return Entry.NeedToGather && Entry.isSame(TE.Scalars);
2554 int C = getEntryCost(&TE);
2556 <<
" for bundle that starts with " << *TE.Scalars[0]
2562 int ExtractCost = 0;
2563 for (ExternalUser &EU : ExternalUses) {
2565 if (!ExtractCostCalculated.
insert(EU.Scalar).second)
2571 if (EphValues.count(EU.User))
2578 auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2579 if (MinBWs.count(ScalarRoot)) {
2582 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
2584 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
2588 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
2592 int SpillCost = getSpillCost();
2593 Cost += SpillCost + ExtractCost;
2598 OS <<
"SLP: Spill Cost = " << SpillCost <<
".\n" 2599 <<
"SLP: Extract Cost = " << ExtractCost <<
".\n" 2600 <<
"SLP: Total Cost = " << Cost <<
".\n";
2605 ViewGraph(
this,
"SLP" +
F->getName(),
false, Str);
2610 int BoUpSLP::getGatherCost(
Type *Ty,
2613 for (
unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
2614 if (!ShuffledIndices.
count(i))
2615 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
2616 if (!ShuffledIndices.
empty())
2623 Type *ScalarTy = VL[0]->getType();
2625 ScalarTy =
SI->getValueOperand()->getType();
2633 for (
unsigned I = VL.
size(); I > 0; --
I) {
2634 unsigned Idx = I - 1;
2635 if (!UniqueElements.
insert(VL[Idx]).second)
2636 ShuffledElements.insert(Idx);
2638 return getGatherCost(VecTy, ShuffledElements);
2650 void BoUpSLP::reorderAltShuffleOperands(
const InstructionsState &S,
2655 for (
Value *V : VL) {
2656 auto *I = cast<Instruction>(V);
2657 assert(S.isOpcodeOrAlt(I) &&
"Incorrect instruction in vector");
2664 for (
unsigned j = 0; j < VL.size() - 1; ++j) {
2665 if (
LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2666 if (
LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2672 }
else if (VL2->isCommutative() &&
2680 if (
LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2681 if (
LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2687 }
else if (VL2->isCommutative() &&
2707 bool SplatLeft,
bool SplatRight,
Value *&VLeft,
Value *&VRight) {
2712 if (VRight == Right[i - 1])
2715 if (VLeft == Right[i - 1]) {
2719 if (SplatLeft && VLeft == Left[i - 1])
2726 if (VLeft == Left[i - 1])
2729 if (VRight == Left[i - 1])
2738 if (AllSameOpcodeRight) {
2739 unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
2740 if (IRight && RightPrevOpcode == IRight->getOpcode())
2743 if (ILeft && RightPrevOpcode == ILeft->
getOpcode()) {
2748 if (AllSameOpcodeLeft && ILeft &&
2755 if (AllSameOpcodeLeft) {
2756 unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
2757 if (ILeft && LeftPrevOpcode == ILeft->
getOpcode())
2759 if (IRight && LeftPrevOpcode == IRight->getOpcode())
2765 void BoUpSLP::reorderInputsAccordingToOpcode(
unsigned Opcode,
2772 auto *I = cast<Instruction>(VL[0]);
2775 if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
2783 bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
2784 bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
2786 bool SplatLeft =
true;
2787 bool SplatRight =
true;
2789 for (
unsigned i = 1, e = VL.
size(); i != e; ++i) {
2793 "Can only process commutative instruction");
2799 AllSameOpcodeRight, SplatLeft, SplatRight, VLeft,
2808 SplatRight = SplatRight && (Right[i - 1] == Right[i]);
2809 SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
2810 AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
2811 (cast<Instruction>(Left[i - 1])->getOpcode() ==
2812 cast<Instruction>(Left[i])->getOpcode());
2813 AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
2814 (cast<Instruction>(Right[i - 1])->getOpcode() ==
2815 cast<Instruction>(Right[i])->getOpcode());
2819 if (SplatRight || SplatLeft)
2837 for (
unsigned j = 0, e = VL.
size() - 1; j < e; ++j) {
2838 if (
LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2839 if (
LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2846 if (
LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2847 if (
LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2859 const InstructionsState &S) {
2862 auto *Front = cast<Instruction>(S.OpValue);
2863 auto *BB = Front->getParent();
2865 auto *I = cast<Instruction>(V);
2866 return !S.isOpcodeOrAlt(I) || I->
getParent() == BB;
2876 if (BlocksSchedules.count(BB)) {
2878 BlocksSchedules[BB]->getScheduleData(
isOneOf(S, VL.
back()));
2879 if (Bundle && Bundle->isPartOfBundle())
2880 for (; Bundle; Bundle = Bundle->NextInBundle)
2881 if (Bundle->OpValue == Bundle->Inst)
2882 LastInst = Bundle->Inst;
2906 if (Bundle.erase(&I) && S.isOpcodeOrAlt(&I))
2915 Builder.SetInsertPoint(BB, ++LastInst->
getIterator());
2916 Builder.SetCurrentDebugLocation(Front->getDebugLoc());
2923 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2924 if (
Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2925 GatherSeq.insert(Insrt);
2926 CSEBlocks.insert(Insrt->getParent());
2929 if (TreeEntry *E = getTreeEntry(VL[i])) {
2932 for (
unsigned Lane = 0,
LE = E->Scalars.size(); Lane !=
LE; ++Lane) {
2934 if (E->Scalars[Lane] == VL[i]) {
2939 assert(FoundLane >= 0 &&
"Could not find the correct lane");
2940 if (!E->ReuseShuffleIndices.empty()) {
2942 std::distance(E->ReuseShuffleIndices.begin(),
2943 llvm::find(E->ReuseShuffleIndices, FoundLane));
2945 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2955 if (S.getOpcode()) {
2956 if (TreeEntry *E = getTreeEntry(S.OpValue)) {
2957 if (E->isSame(VL)) {
2958 Value *V = vectorizeTree(E);
2959 if (VL.
size() == E->Scalars.size() && !E->ReuseShuffleIndices.empty()) {
2961 if (
auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
2962 V = SV->getOperand(0);
2967 for(
unsigned Idx : E->ReuseShuffleIndices)
2968 if (UsedIdxs.
insert(Idx).second)
2979 Type *ScalarTy = S.OpValue->getType();
2980 if (
StoreInst *
SI = dyn_cast<StoreInst>(S.OpValue))
2981 ScalarTy =
SI->getValueOperand()->getType();
2986 if (VL.
size() > 2) {
2988 for (
Value *V : VL) {
2991 if (Res.second || isa<Constant>(V))
2996 if (UniqueValues.
size() == VL.size() || UniqueValues.
size() <= 1 ||
2998 ReuseShuffleIndicies.
clear();
3004 Value *V = Gather(VL, VecTy);
3005 if (!ReuseShuffleIndicies.
empty()) {
3007 ReuseShuffleIndicies,
"shuffle");
3008 if (
auto *I = dyn_cast<Instruction>(V)) {
3009 GatherSeq.insert(I);
3019 const unsigned E = Indices.
size();
3021 for (
unsigned I = 0; I <
E; ++
I)
3022 Mask[Indices[I]] = I;
3025 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
3028 if (E->VectorizedValue) {
3029 LLVM_DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *E->Scalars[0] <<
".\n");
3030 return E->VectorizedValue;
3037 ScalarTy =
SI->getValueOperand()->getType();
3040 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
3042 if (E->NeedToGather) {
3043 setInsertPointAfterBundle(E->Scalars, S);
3044 auto *V = Gather(E->Scalars, VecTy);
3045 if (NeedToShuffleReuses) {
3047 E->ReuseShuffleIndices,
"shuffle");
3048 if (
auto *I = dyn_cast<Instruction>(V)) {
3049 GatherSeq.insert(I);
3053 E->VectorizedValue = V;
3057 unsigned ShuffleOrOp = S.isAltShuffle() ?
3058 (
unsigned) Instruction::ShuffleVector : S.getOpcode();
3059 switch (ShuffleOrOp) {
3060 case Instruction::PHI: {
3063 Builder.SetCurrentDebugLocation(PH->
getDebugLoc());
3066 if (NeedToShuffleReuses) {
3068 E->ReuseShuffleIndices,
"shuffle");
3070 E->VectorizedValue = V;
3080 if (!VisitedBBs.
insert(IBB).second) {
3086 for (
Value *V : E->Scalars)
3087 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB));
3090 Builder.SetCurrentDebugLocation(PH->
getDebugLoc());
3091 Value *Vec = vectorizeTree(Operands);
3096 "Invalid number of incoming values");
3100 case Instruction::ExtractElement: {
3101 if (!E->NeedToGather) {
3103 if (!E->ReorderIndices.empty()) {
3106 Builder.SetInsertPoint(VL0);
3110 if (NeedToShuffleReuses) {
3112 if (E->ReorderIndices.empty())
3113 Builder.SetInsertPoint(VL0);
3115 E->ReuseShuffleIndices,
"shuffle");
3117 E->VectorizedValue = V;
3120 setInsertPointAfterBundle(E->Scalars, S);
3121 auto *V = Gather(E->Scalars, VecTy);
3122 if (NeedToShuffleReuses) {
3124 E->ReuseShuffleIndices,
"shuffle");
3125 if (
auto *I = dyn_cast<Instruction>(V)) {
3126 GatherSeq.insert(I);
3130 E->VectorizedValue = V;
3133 case Instruction::ExtractValue: {
3134 if (!E->NeedToGather) {
3136 Builder.SetInsertPoint(LI);
3141 if (!E->ReorderIndices.empty()) {
3144 NewV = Builder.CreateShuffleVector(NewV,
UndefValue::get(VecTy), Mask,
3147 if (NeedToShuffleReuses) {
3149 NewV = Builder.CreateShuffleVector(
3152 E->VectorizedValue = NewV;
3155 setInsertPointAfterBundle(E->Scalars, S);
3156 auto *V = Gather(E->Scalars, VecTy);
3157 if (NeedToShuffleReuses) {
3159 E->ReuseShuffleIndices,
"shuffle");
3160 if (
auto *I = dyn_cast<Instruction>(V)) {
3161 GatherSeq.insert(I);
3165 E->VectorizedValue = V;
3168 case Instruction::ZExt:
3169 case Instruction::SExt:
3170 case Instruction::FPToUI:
3171 case Instruction::FPToSI:
3172 case Instruction::FPExt:
3173 case Instruction::PtrToInt:
3174 case Instruction::IntToPtr:
3175 case Instruction::SIToFP:
3176 case Instruction::UIToFP:
3177 case Instruction::Trunc:
3178 case Instruction::FPTrunc:
3179 case Instruction::BitCast: {
3181 for (
Value *V : E->Scalars)
3182 INVL.push_back(cast<Instruction>(V)->getOperand(0));
3184 setInsertPointAfterBundle(E->Scalars, S);
3186 Value *InVec = vectorizeTree(INVL);
3188 if (E->VectorizedValue) {
3189 LLVM_DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *VL0 <<
".\n");
3190 return E->VectorizedValue;
3195 if (NeedToShuffleReuses) {
3197 E->ReuseShuffleIndices,
"shuffle");
3199 E->VectorizedValue = V;
3200 ++NumVectorInstructions;
3203 case Instruction::FCmp:
3204 case Instruction::ICmp: {
3205 ValueList LHSV, RHSV;
3206 for (
Value *V : E->Scalars) {
3207 LHSV.push_back(cast<Instruction>(V)->getOperand(0));
3208 RHSV.push_back(cast<Instruction>(V)->getOperand(1));
3211 setInsertPointAfterBundle(E->Scalars, S);
3213 Value *L = vectorizeTree(LHSV);
3214 Value *
R = vectorizeTree(RHSV);
3216 if (E->VectorizedValue) {
3217 LLVM_DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *VL0 <<
".\n");
3218 return E->VectorizedValue;
3223 if (S.getOpcode() == Instruction::FCmp)
3224 V = Builder.CreateFCmp(P0, L, R);
3226 V = Builder.CreateICmp(P0, L, R);
3229 if (NeedToShuffleReuses) {
3231 E->ReuseShuffleIndices,
"shuffle");
3233 E->VectorizedValue = V;
3234 ++NumVectorInstructions;
3238 ValueList TrueVec, FalseVec, CondVec;
3239 for (
Value *V : E->Scalars) {
3240 CondVec.push_back(cast<Instruction>(V)->getOperand(0));
3241 TrueVec.push_back(cast<Instruction>(V)->getOperand(1));
3242 FalseVec.push_back(cast<Instruction>(V)->getOperand(2));
3245 setInsertPointAfterBundle(E->Scalars, S);
3247 Value *Cond = vectorizeTree(CondVec);
3248 Value *True = vectorizeTree(TrueVec);
3249 Value *False = vectorizeTree(FalseVec);
3251 if (E->VectorizedValue) {
3252 LLVM_DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *VL0 <<
".\n");
3253 return E->VectorizedValue;
3256 Value *V = Builder.CreateSelect(Cond, True, False);
3257 if (NeedToShuffleReuses) {
3259 E->ReuseShuffleIndices,
"shuffle");
3261 E->VectorizedValue = V;
3262 ++NumVectorInstructions;
3266 case Instruction::FAdd:
3267 case Instruction::Sub:
3268 case Instruction::FSub:
3269 case Instruction::Mul:
3270 case Instruction::FMul:
3271 case Instruction::UDiv:
3272 case Instruction::SDiv:
3273 case Instruction::FDiv:
3274 case Instruction::URem:
3275 case Instruction::SRem:
3276 case Instruction::FRem:
3277 case Instruction::Shl:
3278 case Instruction::LShr:
3279 case Instruction::AShr:
3280 case Instruction::And:
3281 case Instruction::Or:
3282 case Instruction::Xor: {
3283 ValueList LHSVL, RHSVL;
3285 reorderInputsAccordingToOpcode(S.getOpcode(), E->Scalars, LHSVL,
3288 for (
Value *V : E->Scalars) {
3289 auto *I = cast<Instruction>(V);
3294 setInsertPointAfterBundle(E->Scalars, S);
3296 Value *LHS = vectorizeTree(LHSVL);
3297 Value *RHS = vectorizeTree(RHSVL);
3299 if (E->VectorizedValue) {
3300 LLVM_DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *VL0 <<
".\n");
3301 return E->VectorizedValue;
3304 Value *V = Builder.CreateBinOp(
3305 static_cast<Instruction::BinaryOps>(S.getOpcode()), LHS, RHS);
3307 if (
auto *I = dyn_cast<Instruction>(V))
3310 if (NeedToShuffleReuses) {
3312 E->ReuseShuffleIndices,
"shuffle");
3314 E->VectorizedValue = V;
3315 ++NumVectorInstructions;
3322 bool IsReorder = !E->ReorderIndices.empty();
3325 VL0 = cast<Instruction>(S.OpValue);
3327 setInsertPointAfterBundle(E->Scalars, S);
3329 LoadInst *LI = cast<LoadInst>(VL0);
3340 if (getTreeEntry(PO))
3341 ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
3344 LI = Builder.CreateLoad(VecPtr);
3346 Alignment = DL->getABITypeAlignment(ScalarLoadTy);
3354 Mask,
"reorder_shuffle");
3356 if (NeedToShuffleReuses) {
3359 E->ReuseShuffleIndices,
"shuffle");
3361 E->VectorizedValue = V;
3362 ++NumVectorInstructions;
3370 ValueList ScalarStoreValues;
3371 for (
Value *V : E->Scalars)
3372 ScalarStoreValues.push_back(cast<StoreInst>(V)->getValueOperand());
3374 setInsertPointAfterBundle(E->Scalars, S);
3376 Value *VecValue = vectorizeTree(ScalarStoreValues);
3379 StoreInst *
ST = Builder.CreateStore(VecValue, VecPtr);
3384 if (getTreeEntry(ScalarPtr))
3385 ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
3392 if (NeedToShuffleReuses) {
3394 E->ReuseShuffleIndices,
"shuffle");
3396 E->VectorizedValue = V;
3397 ++NumVectorInstructions;
3400 case Instruction::GetElementPtr: {
3401 setInsertPointAfterBundle(E->Scalars, S);
3404 for (
Value *V : E->Scalars)
3405 Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0));
3407 Value *Op0 = vectorizeTree(Op0VL);
3409 std::vector<Value *> OpVecs;
3410 for (
int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
3413 for (
Value *V : E->Scalars)
3414 OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j));
3416 Value *OpVec = vectorizeTree(OpVL);
3417 OpVecs.push_back(OpVec);
3420 Value *V = Builder.CreateGEP(
3421 cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
3425 if (NeedToShuffleReuses) {
3427 E->ReuseShuffleIndices,
"shuffle");
3429 E->VectorizedValue = V;
3430 ++NumVectorInstructions;
3435 CallInst *CI = cast<CallInst>(VL0);
3436 setInsertPointAfterBundle(E->Scalars, S);
3439 Value *ScalarArg =
nullptr;
3443 std::vector<Value *> OpVecs;
3449 CallInst *CEI = cast<CallInst>(VL0);
3454 for (
Value *V : E->Scalars) {
3459 Value *OpVec = vectorizeTree(OpVL);
3460 LLVM_DEBUG(
dbgs() <<
"SLP: OpVec[" << j <<
"]: " << *OpVec <<
"\n");
3461 OpVecs.push_back(OpVec);
3470 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
3475 if (ScalarArg && getTreeEntry(ScalarArg))
3476 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
3479 if (NeedToShuffleReuses) {
3481 E->ReuseShuffleIndices,
"shuffle");
3483 E->VectorizedValue = V;
3484 ++NumVectorInstructions;
3487 case Instruction::ShuffleVector: {
3488 ValueList LHSVL, RHSVL;
3489 assert(S.isAltShuffle() &&
3494 "Invalid Shuffle Vector Operand");
3498 reorderAltShuffleOperands(S, E->Scalars, LHSVL, RHSVL);
3499 setInsertPointAfterBundle(E->Scalars, S);
3500 LHS = vectorizeTree(LHSVL);
3501 RHS = vectorizeTree(RHSVL);
3504 for (
Value *V : E->Scalars)
3505 INVL.push_back(cast<Instruction>(V)->getOperand(0));
3506 setInsertPointAfterBundle(E->Scalars, S);
3507 LHS = vectorizeTree(INVL);
3510 if (E->VectorizedValue) {
3511 LLVM_DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *VL0 <<
".\n");
3512 return E->VectorizedValue;
3517 V0 = Builder.CreateBinOp(
3518 static_cast<Instruction::BinaryOps>(S.getOpcode()), LHS, RHS);
3519 V1 = Builder.CreateBinOp(
3520 static_cast<Instruction::BinaryOps>(S.getAltOpcode()), LHS, RHS);
3522 V0 = Builder.CreateCast(
3523 static_cast<Instruction::CastOps>(S.getOpcode()), LHS, VecTy);
3524 V1 = Builder.CreateCast(
3525 static_cast<Instruction::CastOps>(S.getAltOpcode()), LHS, VecTy);
3531 ValueList OpScalars, AltScalars;
3532 unsigned e = E->Scalars.size();
3534 for (
unsigned i = 0; i < e; ++i) {
3535 auto *OpInst = cast<Instruction>(E->Scalars[i]);
3536 assert(S.isOpcodeOrAlt(OpInst) &&
"Unexpected main/alternate opcode");
3537 if (OpInst->getOpcode() == S.getAltOpcode()) {
3538 Mask[i] = Builder.getInt32(e + i);
3541 Mask[i] = Builder.getInt32(i);
3550 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
3553 if (NeedToShuffleReuses) {
3555 E->ReuseShuffleIndices,
"shuffle");
3557 E->VectorizedValue = V;
3558 ++NumVectorInstructions;
3570 return vectorizeTree(ExternallyUsedValues);
3576 for (
auto &BSIter : BlocksSchedules) {
3577 scheduleBlock(BSIter.second.get());
3580 Builder.SetInsertPoint(&
F->getEntryBlock().front());
3581 auto *VectorRoot = vectorizeTree(&VectorizableTree[0]);
3586 auto *ScalarRoot = VectorizableTree[0].Scalars[0];
3587 if (MinBWs.count(ScalarRoot)) {
3588 if (
auto *I = dyn_cast<Instruction>(VectorRoot))
3590 auto BundleWidth = VectorizableTree[0].Scalars.size();
3593 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
3594 VectorizableTree[0].VectorizedValue = Trunc;
3602 auto extend = [&](
Value *ScalarRoot,
Value *Ex,
Type *ScalarType) {
3603 if (!MinBWs.count(ScalarRoot))
3605 if (MinBWs[ScalarRoot].
second)
3606 return Builder.CreateSExt(Ex, ScalarType);
3607 return Builder.CreateZExt(Ex, ScalarType);
3611 for (
const auto &ExternalUse : ExternalUses) {
3619 TreeEntry *E = getTreeEntry(Scalar);
3620 assert(E &&
"Invalid scalar");
3621 assert(!E->NeedToGather &&
"Extracting from a gather list");
3623 Value *Vec = E->VectorizedValue;
3624 assert(Vec &&
"Can't find vectorizable value");
3626 Value *Lane = Builder.getInt32(ExternalUse.Lane);
3632 "Scalar with nullptr as an external user must be registered in " 3633 "ExternallyUsedValues map");
3634 if (
auto *VecI = dyn_cast<Instruction>(Vec)) {
3635 Builder.SetInsertPoint(VecI->getParent(),
3636 std::next(VecI->getIterator()));
3638 Builder.SetInsertPoint(&
F->getEntryBlock().front());
3640 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3641 Ex = extend(ScalarRoot, Ex, Scalar->
getType());
3642 CSEBlocks.insert(cast<Instruction>(Scalar)->
getParent());
3643 auto &Locs = ExternallyUsedValues[
Scalar];
3644 ExternallyUsedValues.
insert({Ex, Locs});
3645 ExternallyUsedValues.
erase(Scalar);
3651 if (
auto *VecI = dyn_cast<Instruction>(Vec)) {
3652 if (
PHINode *PH = dyn_cast<PHINode>(User)) {
3653 for (
int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
3654 if (PH->getIncomingValue(i) ==
Scalar) {
3656 PH->getIncomingBlock(i)->getTerminator();
3657 if (isa<CatchSwitchInst>(IncomingTerminator)) {
3658 Builder.SetInsertPoint(VecI->getParent(),
3659 std::next(VecI->getIterator()));
3661 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
3663 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3664 Ex = extend(ScalarRoot, Ex, Scalar->
getType());
3665 CSEBlocks.insert(PH->getIncomingBlock(i));
3666 PH->setOperand(i, Ex);
3670 Builder.SetInsertPoint(cast<Instruction>(User));
3671 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3672 Ex = extend(ScalarRoot, Ex, Scalar->
getType());
3673 CSEBlocks.insert(cast<Instruction>(User)->
getParent());
3677 Builder.SetInsertPoint(&
F->getEntryBlock().front());
3678 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3679 Ex = extend(ScalarRoot, Ex, Scalar->
getType());
3680 CSEBlocks.insert(&
F->getEntryBlock());
3688 for (TreeEntry &EIdx : VectorizableTree) {
3689 TreeEntry *Entry = &EIdx;
3692 if (Entry->NeedToGather)
3695 assert(Entry->VectorizedValue &&
"Can't find vectorizable value");
3698 for (
int Lane = 0,
LE = Entry->Scalars.size(); Lane !=
LE; ++Lane) {
3709 "Replacing out-of-tree value with undef");
3715 LLVM_DEBUG(
dbgs() <<
"SLP: \tErasing scalar:" << *Scalar <<
".\n");
3716 eraseInstruction(cast<Instruction>(Scalar));
3720 Builder.ClearInsertionPoint();
3722 return VectorizableTree[0].VectorizedValue;
3725 void BoUpSLP::optimizeGatherSequence() {
3727 <<
" gather sequences instructions.\n");
3730 if (!isa<InsertElementInst>(I) && !isa<ShuffleVectorInst>(
I))
3759 CSEWorkList.
reserve(CSEBlocks.size());
3762 assert(DT->isReachableFromEntry(
N));
3768 std::stable_sort(CSEWorkList.
begin(), CSEWorkList.
end(),
3770 return DT->properlyDominates(A,
B);
3777 for (
auto I = CSEWorkList.
begin(), E = CSEWorkList.
end(); I !=
E; ++
I) {
3778 assert((I == CSEWorkList.
begin() || !DT->dominates(*I, *std::prev(I))) &&
3779 "Worklist not sorted properly!");
3784 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(
In))
3791 DT->dominates(v->getParent(), In->
getParent())) {
3793 eraseInstruction(In);
3800 Visited.push_back(In);
3812 const InstructionsState &S) {
3813 if (isa<PHINode>(S.OpValue))
3818 ScheduleData *PrevInBundle =
nullptr;
3819 ScheduleData *Bundle =
nullptr;
3820 bool ReSchedule =
false;
3825 for (
Value *V : VL) {
3826 if (!extendSchedulingRegion(V, S))
3830 for (
Value *V : VL) {
3831 ScheduleData *BundleMember = getScheduleData(V);
3833 "no ScheduleData for bundle member (maybe not in same basic block)");
3834 if (BundleMember->IsScheduled) {
3838 LLVM_DEBUG(
dbgs() <<
"SLP: reset schedule because " << *BundleMember
3839 <<
" was already scheduled\n");
3842 assert(BundleMember->isSchedulingEntity() &&
3843 "bundle member already part of other bundle");
3845 PrevInBundle->NextInBundle = BundleMember;
3847 Bundle = BundleMember;
3849 BundleMember->UnscheduledDepsInBundle = 0;
3850 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
3853 BundleMember->FirstInBundle = Bundle;
3854 PrevInBundle = BundleMember;
3856 if (ScheduleEnd != OldScheduleEnd) {
3862 for (
auto *I = ScheduleStart; I != ScheduleEnd; I = I->
getNextNode()) {
3863 doForAllOpcodes(I, [](ScheduleData *SD) {
3864 SD->clearDependencies();
3871 initialFillReadyList(ReadyInsts);
3874 LLVM_DEBUG(
dbgs() <<
"SLP: try schedule bundle " << *Bundle <<
" in block " 3875 << BB->getName() <<
"\n");
3877 calculateDependencies(Bundle,
true, SLP);
3883 while (!Bundle->isReady() && !ReadyInsts.empty()) {
3885 ScheduleData *pickedSD = ReadyInsts.back();
3886 ReadyInsts.pop_back();
3888 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
3889 schedule(pickedSD, ReadyInsts);
3892 if (!Bundle->isReady()) {
3893 cancelScheduling(VL, S.OpValue);
3901 if (isa<PHINode>(OpValue))
3904 ScheduleData *Bundle = getScheduleData(OpValue);
3905 LLVM_DEBUG(
dbgs() <<
"SLP: cancel scheduling of " << *Bundle <<
"\n");
3906 assert(!Bundle->IsScheduled &&
3907 "Can't cancel bundle which is already scheduled");
3908 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
3909 "tried to unbundle something which is not a bundle");
3912 ScheduleData *BundleMember = Bundle;
3913 while (BundleMember) {
3914 assert(BundleMember->FirstInBundle == Bundle &&
"corrupt bundle links");
3915 BundleMember->FirstInBundle = BundleMember;
3916 ScheduleData *Next = BundleMember->NextInBundle;
3917 BundleMember->NextInBundle =
nullptr;
3918 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
3919 if (BundleMember->UnscheduledDepsInBundle == 0) {
3920 ReadyInsts.insert(BundleMember);
3922 BundleMember = Next;
3926 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
3928 if (ChunkPos >= ChunkSize) {
3932 return &(ScheduleDataChunks.back()[ChunkPos++]);
3935 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(
Value *V,
3936 const InstructionsState &S) {
3937 if (getScheduleData(V,
isOneOf(S, V)))
3940 assert(I &&
"bundle member must be an instruction");
3941 assert(!isa<PHINode>(I) &&
"phi nodes don't need to be scheduled");
3942 auto &&CheckSheduleForI = [
this, &S](
Instruction *
I) ->
bool {
3943 ScheduleData *ISD = getScheduleData(I);
3946 assert(isInSchedulingRegion(ISD) &&
3947 "ScheduleData not in scheduling region");
3948 ScheduleData *SD = allocateScheduleDataChunks();
3950 SD->init(SchedulingRegionID, S.OpValue);
3951 ExtraScheduleDataMap[
I][S.OpValue] = SD;
3954 if (CheckSheduleForI(I))
3956 if (!ScheduleStart) {
3958 initScheduleData(I, I->
getNextNode(),
nullptr,
nullptr);
3962 CheckSheduleForI(I);
3963 assert(ScheduleEnd &&
"tried to vectorize a TerminatorInst?");
3964 LLVM_DEBUG(
dbgs() <<
"SLP: initialize schedule region to " << *I <<
"\n");
3975 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
3976 LLVM_DEBUG(
dbgs() <<
"SLP: exceeded schedule region size limit\n");
3980 if (UpIter != UpperEnd) {
3981 if (&*UpIter == I) {
3982 initScheduleData(I, ScheduleStart,
nullptr, FirstLoadStoreInRegion);
3985 CheckSheduleForI(I);
3986 LLVM_DEBUG(
dbgs() <<
"SLP: extend schedule region start to " << *I
3992 if (DownIter != LowerEnd) {
3993 if (&*DownIter == I) {
3994 initScheduleData(ScheduleEnd, I->
getNextNode(), LastLoadStoreInRegion,
3998 CheckSheduleForI(I);
3999 assert(ScheduleEnd &&
"tried to vectorize a TerminatorInst?");
4006 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
4007 "instruction not found in block");
4012 void BoUpSLP::BlockScheduling::initScheduleData(
Instruction *FromI,
4014 ScheduleData *PrevLoadStore,
4015 ScheduleData *NextLoadStore) {
4016 ScheduleData *CurrentLoadStore = PrevLoadStore;
4018 ScheduleData *SD = ScheduleDataMap[
I];
4020 SD = allocateScheduleDataChunks();
4021 ScheduleDataMap[
I] = SD;
4024 assert(!isInSchedulingRegion(SD) &&
4025 "new ScheduleData already in scheduling region");
4026 SD->init(SchedulingRegionID, I);
4029 (!isa<IntrinsicInst>(
I) ||
4030 cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect)) {
4032 if (CurrentLoadStore) {
4033 CurrentLoadStore->NextLoadStore = SD;
4035 FirstLoadStoreInRegion = SD;
4037 CurrentLoadStore = SD;
4040 if (NextLoadStore) {
4041 if (CurrentLoadStore)
4042 CurrentLoadStore->NextLoadStore = NextLoadStore;
4044 LastLoadStoreInRegion = CurrentLoadStore;
4048 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
4049 bool InsertInReadyList,
4051 assert(SD->isSchedulingEntity());
4056 while (!WorkList.empty()) {
4057 ScheduleData *SD = WorkList.back();
4058 WorkList.pop_back();
4060 ScheduleData *BundleMember = SD;
4061 while (BundleMember) {
4062 assert(isInSchedulingRegion(BundleMember));
4063 if (!BundleMember->hasValidDependencies()) {
4067 BundleMember->Dependencies = 0;
4068 BundleMember->resetUnscheduledDeps();
4071 if (BundleMember->OpValue != BundleMember->Inst) {
4072 ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
4073 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
4074 BundleMember->Dependencies++;
4075 ScheduleData *DestBundle = UseSD->FirstInBundle;
4076 if (!DestBundle->IsScheduled)
4077 BundleMember->incrementUnscheduledDeps(1);
4078 if (!DestBundle->hasValidDependencies())
4079 WorkList.push_back(DestBundle);
4082 for (
User *U : BundleMember->Inst->users()) {
4083 if (isa<Instruction>(U)) {
4084 ScheduleData *UseSD = getScheduleData(U);
4085 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
4086 BundleMember->Dependencies++;
4087 ScheduleData *DestBundle = UseSD->FirstInBundle;
4088 if (!DestBundle->IsScheduled)
4089 BundleMember->incrementUnscheduledDeps(1);
4090 if (!DestBundle->hasValidDependencies())
4091 WorkList.push_back(DestBundle);
4097 BundleMember->Dependencies++;
4098 BundleMember->incrementUnscheduledDeps(1);
4104 ScheduleData *DepDest = BundleMember->NextLoadStore;
4108 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
4109 unsigned numAliased = 0;
4110 unsigned DistToSrc = 1;
4113 assert(isInSchedulingRegion(DepDest));
4122 if (DistToSrc >= MaxMemDepDistance ||
4123 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
4124 (numAliased >= AliasedCheckLimit ||
4125 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
4132 DepDest->MemoryDependencies.push_back(BundleMember);
4133 BundleMember->Dependencies++;
4134 ScheduleData *DestBundle = DepDest->FirstInBundle;
4135 if (!DestBundle->IsScheduled) {
4136 BundleMember->incrementUnscheduledDeps(1);
4138 if (!DestBundle->hasValidDependencies()) {
4139 WorkList.push_back(DestBundle);
4142 DepDest = DepDest->NextLoadStore;
4157 if (DistToSrc >= 2 * MaxMemDepDistance)
4163 BundleMember = BundleMember->NextInBundle;
4165 if (InsertInReadyList && SD->isReady()) {
4166 ReadyInsts.push_back(SD);
4173 void BoUpSLP::BlockScheduling::resetSchedule() {
4175 "tried to reset schedule on block which has not been scheduled");
4177 doForAllOpcodes(I, [&](ScheduleData *SD) {
4178 assert(isInSchedulingRegion(SD) &&
4179 "ScheduleData not in scheduling region");
4180 SD->IsScheduled =
false;
4181 SD->resetUnscheduledDeps();
4187 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
4188 if (!BS->ScheduleStart)
4191 LLVM_DEBUG(
dbgs() <<
"SLP: schedule block " << BS->BB->getName() <<
"\n");
4193 BS->resetSchedule();
4198 struct ScheduleDataCompare {
4199 bool operator()(ScheduleData *SD1, ScheduleData *SD2)
const {
4200 return SD2->SchedulingPriority < SD1->SchedulingPriority;
4203 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
4208 int NumToSchedule = 0;
4209 for (
auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
4211 BS->doForAllOpcodes(I, [
this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
4212 assert(SD->isPartOfBundle() ==
4213 (getTreeEntry(SD->Inst) !=
nullptr) &&
4214 "scheduler and vectorizer bundle mismatch");
4215 SD->FirstInBundle->SchedulingPriority = Idx++;
4216 if (SD->isSchedulingEntity()) {
4217 BS->calculateDependencies(SD,
false,
this);
4222 BS->initialFillReadyList(ReadyInsts);
4227 while (!ReadyInsts.empty()) {
4228 ScheduleData *picked = *ReadyInsts.begin();
4229 ReadyInsts.erase(ReadyInsts.begin());
4233 ScheduleData *BundleMember = picked;
4234 while (BundleMember) {
4236 if (LastScheduledInst->
getNextNode() != pickedInst) {
4237 BS->BB->getInstList().remove(pickedInst);
4238 BS->BB->getInstList().insert(LastScheduledInst->
getIterator(),
4241 LastScheduledInst = pickedInst;
4242 BundleMember = BundleMember->NextInBundle;
4245 BS->schedule(picked, ReadyInsts);
4248 assert(NumToSchedule == 0 &&
"could not schedule all instructions");
4251 BS->ScheduleStart =
nullptr;
4254 unsigned BoUpSLP::getVectorElementSize(
Value *V) {
4257 if (
auto *
Store = dyn_cast<StoreInst>(V))
4258 return DL->getTypeSizeInBits(
Store->getValueOperand()->getType());
4266 if (
auto *I = dyn_cast<Instruction>(V))
4272 auto FoundUnknownInst =
false;
4273 while (!Worklist.
empty() && !FoundUnknownInst) {
4280 if (isa<VectorType>(Ty))
4281 FoundUnknownInst =
true;
4285 else if (isa<LoadInst>(I))
4286 MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
4291 else if (isa<PHINode>(I) || isa<CastInst>(
I) || isa<GetElementPtrInst>(I) ||
4292 isa<CmpInst>(
I) || isa<SelectInst>(I) || isa<BinaryOperator>(
I)) {
4294 if (
auto *J = dyn_cast<Instruction>(U.get()))
4295 if (!Visited.
count(J))
4301 FoundUnknownInst =
true;
4306 if (!MaxWidth || FoundUnknownInst)
4307 return DL->getTypeSizeInBits(V->
getType());
4320 if (isa<Constant>(V)) {
4335 case Instruction::Trunc:
4338 case Instruction::ZExt:
4339 case Instruction::SExt:
4345 case Instruction::Sub:
4346 case Instruction::Mul:
4347 case Instruction::And:
4348 case Instruction::Or:
4349 case Instruction::Xor:
4366 case Instruction::PHI: {
4387 if (ExternalUses.empty())
4391 auto &TreeRoot = VectorizableTree[0].Scalars;
4403 for (
auto &EU : ExternalUses)
4404 if (!Expr.erase(EU.Scalar))
4412 for (
auto &Entry : VectorizableTree)
4413 Expr.
insert(Entry.Scalars.begin(), Entry.Scalars.end());
4417 for (
auto *Root : TreeRoot)
4418 if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
4426 for (
auto *Root : TreeRoot)
4433 auto MaxBitWidth = 8u;
4437 for (
auto *Root : TreeRoot) {
4438 auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
4439 MaxBitWidth = std::max<unsigned>(
4440 Mask.getBitWidth() -
Mask.countLeadingZeros(), MaxBitWidth);
4446 bool IsKnownPositive =
true;
4457 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
4460 return isa<GetElementPtrInst>(R->
user_back());
4473 for (
auto *
Scalar : ToDemote) {
4475 auto NumTypeBits = DL->getTypeSizeInBits(
Scalar->getType());
4476 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
4494 if (!IsKnownPositive)
4504 if (MaxBitWidth >= TreeRootIT->getBitWidth())
4510 while (!Roots.
empty())
4514 for (
auto *
Scalar : ToDemote)
4515 MinBWs[
Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
4531 bool doInitialization(
Module &M)
override {
4536 if (skipFunction(F))
4539 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4540 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
4541 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
4542 auto *TLI = TLIP ? &TLIP->getTLI() :
nullptr;
4543 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4544 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4545 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4546 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4547 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
4548 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
4550 return Impl.
runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4584 bool Changed =
runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4613 bool Changed =
false;
4617 if (!TTI->getNumberOfRegisters(
true))
4628 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
4635 collectSeedInstructions(BB);
4638 if (!Stores.empty()) {
4640 <<
" underlying objects.\n");
4641 Changed |= vectorizeStoreChains(R);
4645 Changed |= vectorizeChainsInBlock(BB, R);
4650 if (!GEPs.empty()) {
4652 <<
" underlying objects.\n");
4653 Changed |= vectorizeGEPIndices(BB, R);
4658 R.optimizeGatherSequence();
4672 unsigned SliceSize) {
4673 VL = VL.
slice(SliceBegin, SliceSize);
4674 VH = VH.
slice(SliceBegin, SliceSize);
4678 bool SLPVectorizerPass::vectorizeStoreChain(
ArrayRef<Value *> Chain, BoUpSLP &R,
4679 unsigned VecRegSize) {
4680 const unsigned ChainLen = Chain.
size();
4681 LLVM_DEBUG(
dbgs() <<
"SLP: Analyzing a store chain of length " << ChainLen
4683 const unsigned Sz = R.getVectorElementSize(Chain[0]);
4684 const unsigned VF = VecRegSize / Sz;
4692 bool Changed =
false;
4694 for (
unsigned i = 0, e = ChainLen; i + VF <= e; ++i) {
4700 LLVM_DEBUG(
dbgs() <<
"SLP: Analyzing " << VF <<
" stores at offset " << i
4704 R.buildTree(Operands);
4705 if (R.isTreeTinyAndNotFullyVectorizable())
4708 R.computeMinimumValueSizes();
4710 int Cost = R.getTreeCost();
4712 LLVM_DEBUG(
dbgs() <<
"SLP: Found cost=" << Cost <<
" for VF=" << VF
4715 LLVM_DEBUG(
dbgs() <<
"SLP: Decided to vectorize cost=" << Cost <<
"\n");
4717 using namespace ore;
4720 cast<StoreInst>(Chain[i]))
4721 <<
"Stores SLP vectorized with cost " <<
NV(
"Cost", Cost)
4722 <<
" and with tree size " 4723 <<
NV(
"TreeSize", R.getTreeSize()));
4744 BoUpSLP::ValueSet VectorizedStores;
4745 bool Changed =
false;
4750 unsigned E = Stores.
size();
4751 IndexQueue.
resize(E - 1);
4752 for (
unsigned I = E; I > 0; --
I) {
4753 unsigned Idx = I - 1;
4760 for (
unsigned J = 0; J < E - 1; ++J, ++
Offset) {
4761 if (Idx >= Offset) {
4762 IndexQueue[Cnt] = Idx -
Offset;
4765 if (Idx + Offset < E) {
4766 IndexQueue[Cnt] = Idx +
Offset;
4771 for (
auto K : IndexQueue) {
4773 Tails.
insert(Stores[Idx]);
4775 ConsecutiveChain[Stores[K]] = Stores[Idx];
4788 BoUpSLP::ValueList Operands;
4791 while ((Tails.
count(I) || Heads.
count(I)) && !VectorizedStores.count(I)) {
4792 Operands.push_back(I);
4794 I = ConsecutiveChain[
I];
4799 for (
unsigned Size = R.getMaxVecRegSize();
Size >= R.getMinVecRegSize();
4801 if (vectorizeStoreChain(Operands, R,
Size)) {
4803 VectorizedStores.
insert(Operands.begin(), Operands.end());
4813 void SLPVectorizerPass::collectSeedInstructions(
BasicBlock *BB) {
4824 if (
auto *
SI = dyn_cast<StoreInst>(&I)) {
4825 if (!
SI->isSimple())
4835 else if (
auto *
GEP = dyn_cast<GetElementPtrInst>(&I)) {
4836 auto Idx =
GEP->idx_begin()->get();
4837 if (
GEP->getNumIndices() > 1 || isa<Constant>(Idx))
4841 if (
GEP->getType()->isVectorTy())
4848 bool SLPVectorizerPass::tryToVectorizePair(
Value *A,
Value *
B, BoUpSLP &R) {
4851 Value *VL[] = { A, B };
4852 return tryToVectorizeList(VL, R, 0,
true);
4856 int UserCost,
bool AllowReorder) {
4860 LLVM_DEBUG(
dbgs() <<
"SLP: Trying to vectorize a list of length = " 4861 << VL.
size() <<
".\n");
4870 unsigned Sz = R.getVectorElementSize(I0);
4871 unsigned MinVF =
std::max(2U, R.getMinVecRegSize() / Sz);
4874 R.getORE()->emit([&]() {
4876 <<
"Cannot SLP vectorize list: vectorization factor " 4877 <<
"less than 2 is not supported";
4882 for (
Value *V : VL) {
4887 R.getORE()->emit([&]() {
4888 std::string type_str;
4892 <<
"Cannot SLP vectorize list: type " 4893 << rso.
str() +
" is unsupported by vectorizer";
4899 bool Changed =
false;
4900 bool CandidateFound =
false;
4906 unsigned NextInst = 0, MaxInst = VL.
size();
4907 for (
unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
4913 if (TTI->getNumberOfParts(VecTy) == VF)
4915 for (
unsigned I = NextInst; I < MaxInst; ++
I) {
4916 unsigned OpsWidth = 0;
4918 if (I + VF > MaxInst)
4919 OpsWidth = MaxInst -
I;
4930 LLVM_DEBUG(
dbgs() <<
"SLP: Analyzing " << OpsWidth <<
" operations " 4937 if (AllowReorder && Order) {
4944 Value *ReorderedOps[] = {Ops[1], Ops[0]};
4945 R.buildTree(ReorderedOps,
None);
4947 if (R.isTreeTinyAndNotFullyVectorizable())
4950 R.computeMinimumValueSizes();
4951 int Cost = R.getTreeCost() - UserCost;
4952 CandidateFound =
true;
4953 MinCost = std::min(MinCost, Cost);
4956 LLVM_DEBUG(
dbgs() <<
"SLP: Vectorizing list at cost:" << Cost <<
".\n");
4958 cast<Instruction>(Ops[0]))
4959 <<
"SLP vectorized with cost " <<
ore::NV(
"Cost", Cost)
4960 <<
" and with tree size " 4961 <<
ore::NV(
"TreeSize", R.getTreeSize()));
4972 if (!Changed && CandidateFound) {
4973 R.getORE()->emit([&]() {
4975 <<
"List vectorization was possible but not beneficial with cost " 4976 <<
ore::NV(
"Cost", MinCost) <<
" >= " 4979 }
else if (!Changed) {
4980 R.getORE()->emit([&]() {
4982 <<
"Cannot SLP vectorize list: vectorization was impossible" 4983 <<
" with available vectorization factors";
4989 bool SLPVectorizerPass::tryToVectorize(
Instruction *I, BoUpSLP &R) {
4993 if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
5001 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() !=
P)
5005 if (tryToVectorizePair(Op0, Op1, R))
5011 if (B && B->hasOneUse()) {
5014 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
5016 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
5024 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
5026 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
5043 bool IsPairwise,
bool IsLeft,
5045 assert((IsPairwise || !IsLeft) &&
"Don't support a <0,1,undef,...> mask");
5052 for (
unsigned i = 0; i != NumEltsToRdx; ++i)
5053 ShuffleMask[i] = Builder.
getInt32(2 * i + !IsLeft);
5056 for (
unsigned i = 0; i != NumEltsToRdx; ++i)
5057 ShuffleMask[i] = Builder.
getInt32(NumEltsToRdx + i);
5091 class HorizontalReduction {
5094 ReductionOpsListType ReductionOps;
5110 class OperationData {
5112 unsigned Opcode = 0;
5115 Value *LHS =
nullptr;
5118 Value *RHS =
nullptr;
5127 bool isVectorizable()
const {
5128 return LHS && RHS &&
5130 ((Kind == RK_Arithmetic &&
5132 ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
5133 (Kind == RK_Min || Kind == RK_Max)) ||
5134 (Opcode == Instruction::ICmp &&
5135 (Kind == RK_UMin || Kind == RK_UMax)));
5140 assert(isVectorizable() &&
5141 "Expected add|fadd or min/max reduction operation.");
5148 Cmp = Opcode == Instruction::ICmp ? Builder.
CreateICmpSLT(LHS, RHS)
5152 Cmp = Opcode == Instruction::ICmp ? Builder.
CreateICmpSGT(LHS, RHS)
5156 assert(Opcode == Instruction::ICmp &&
"Expected integer types.");
5160 assert(Opcode == Instruction::ICmp &&
"Expected integer types.");
5170 explicit OperationData() =
default;
5174 explicit OperationData(
Value *V) {
5175 if (
auto *I = dyn_cast<Instruction>(V))
5183 : Opcode(Opcode), LHS(LHS), RHS(RHS),
Kind(Kind), NoNaN(NoNaN) {
5184 assert(Kind != RK_None &&
"One of the reduction operations is expected.");
5187 explicit operator bool()
const {
return Opcode; }
5190 unsigned getFirstOperandIndex()
const {
5191 assert(!!*
this &&
"The opcode is not set.");
5206 unsigned getNumberOfOperands()
const {
5207 assert(Kind != RK_None && !!*
this && LHS && RHS &&
5208 "Expected reduction operation.");
5225 assert(Kind != RK_None && !!*
this && LHS && RHS &&
5226 "Expected reduction operation.");
5239 auto *Cmp = cast<Instruction>(cast<SelectInst>(
I)->getCondition());
5240 return I->
getParent() == P && Cmp && Cmp->getParent() ==
P;
5248 bool hasRequiredNumberOfUses(
Instruction *I,
bool IsReductionOp)
const {
5249 assert(Kind != RK_None && !!*
this && LHS && RHS &&
5250 "Expected reduction operation.");
5260 cast<SelectInst>(
I)->getCondition()->hasOneUse());
5268 void initReductionOps(ReductionOpsListType &ReductionOps) {
5269 assert(Kind != RK_None && !!*
this && LHS && RHS &&
5270 "Expected reduction operation.");
5273 ReductionOps.assign(1, ReductionOpsType());
5279 ReductionOps.assign(2, ReductionOpsType());
5286 void addReductionOps(
Instruction *I, ReductionOpsListType &ReductionOps) {
5287 assert(Kind != RK_None && !!*
this && LHS && RHS &&
5288 "Expected reduction operation.");
5291 ReductionOps[0].emplace_back(I);
5297 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
5298 ReductionOps[1].emplace_back(I);
5307 assert(Kind != RK_None && *
this && LHS && RHS &&
5308 "Expected reduction operation.");
5314 return Opcode == Instruction::ICmp ||
5315 cast<Instruction>(I->
getOperand(0))->isFast();
5318 assert(Opcode == Instruction::ICmp &&
5319 "Only integer compare operation is expected.");
5335 assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) &&
5336 "One of the comparing operations is incorrect.");
5337 return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode);
5339 bool operator!=(
const OperationData &OD) {
return !(*
this == OD); }
5349 unsigned getOpcode()
const {
5350 assert(isVectorizable() &&
"Expected vectorizable operation.");
5356 Value *getLHS()
const {
return LHS; }
5357 Value *getRHS()
const {
return RHS; }
5358 Type *getConditionType()
const {
5376 const ReductionOpsListType &ReductionOps)
const {
5377 assert(isVectorizable() &&
5378 "Expected add|fadd or min/max reduction operation.");
5379 auto *
Op = createOp(Builder, Name);
5388 if (
auto *
SI = dyn_cast<SelectInst>(
Op))
5401 assert(isVectorizable() &&
5402 "Expected add|fadd or min/max reduction operation.");
5403 auto *
Op = createOp(Builder, Name);
5412 if (
auto *
SI = dyn_cast<SelectInst>(
Op)) {
5414 cast<SelectInst>(
I)->getCondition());
5426 Flags.
NoNaN = NoNaN;
5431 Flags.
IsSigned = Opcode == Instruction::ICmp;
5435 Flags.
IsSigned = Opcode == Instruction::ICmp;
5456 OperationData ReductionData;
5459 OperationData ReducedValueData;
5463 bool IsPairwiseReduction =
false;
5467 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
5469 if (ExtraArgs.
count(ParentStackElem.first)) {
5470 ExtraArgs[ParentStackElem.first] =
nullptr;
5477 ParentStackElem.second = ParentStackElem.first->getNumOperands();
5481 ExtraArgs[ParentStackElem.first] = ExtraArg;
5485 static OperationData getOperationData(
Value *V) {
5487 return OperationData();
5492 return OperationData(cast<BinaryOperator>(V)->getOpcode(), LHS, RHS,
5495 if (
auto *
Select = dyn_cast<SelectInst>(V)) {
5498 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
5500 return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
5503 return OperationData(
5504 Instruction::FCmp, LHS, RHS, RK_Min,
5505 cast<Instruction>(
Select->getCondition())->hasNoNaNs());
5507 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
5509 return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
5512 return OperationData(
5513 Instruction::FCmp, LHS, RHS, RK_Max,
5514 cast<Instruction>(
Select->getCondition())->hasNoNaNs());
5531 LHS =
Select->getTrueValue();
5532 RHS =
Select->getFalseValue();
5537 if (!isa<ExtractElementInst>(RHS) ||
5539 return OperationData(V);
5541 if (!isa<ExtractElementInst>(LHS) ||
5543 return OperationData(V);
5545 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
5546 return OperationData(V);
5550 return OperationData(V);
5554 return OperationData(V);
5558 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
5562 return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
5568 return OperationData(Instruction::FCmp, LHS, RHS, RK_Min,
5569 cast<Instruction>(Cond)->hasNoNaNs());
5573 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
5577 return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
5583 return OperationData(Instruction::FCmp, LHS, RHS, RK_Max,
5584 cast<Instruction>(Cond)->hasNoNaNs());
5588 return OperationData(V);
5592 HorizontalReduction() =
default;
5597 "Thi phi needs to use the binary operator");
5599 ReductionData = getOperationData(B);
5605 if (ReductionData.getLHS() == Phi) {
5608 ReductionData = getOperationData(B);
5609 }
else if (ReductionData.getRHS() == Phi) {
5612 ReductionData = getOperationData(B);
5616 if (!ReductionData.isVectorizable(B))
5625 ReducedValueData.clear();
5631 Stack.
push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
5632 ReductionData.initReductionOps(ReductionOps);
5633 while (!Stack.
empty()) {
5635 unsigned EdgeToVist = Stack.
back().second++;
5636 OperationData OpData = getOperationData(TreeN);
5637 bool IsReducedValue = OpData != ReductionData;
5640 if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
5644 auto I = ExtraArgs.
find(TreeN);
5645 if (I != ExtraArgs.
end() && !I->second) {
5647 if (Stack.
size() <= 1) {
5655 markExtraArg(Stack[Stack.
size() - 2], TreeN);
5656 ExtraArgs.
erase(TreeN);
5658 ReductionData.addReductionOps(TreeN, ReductionOps);
5669 OpData = getOperationData(I);
5674 if (I && (!ReducedValueData || OpData == ReducedValueData ||
5675 OpData == ReductionData)) {
5676 const bool IsReductionOperation = OpData == ReductionData;
5678 if (!ReductionData.hasSameParent(I, B->
getParent(),
5679 IsReductionOperation)) {
5681 markExtraArg(Stack.
back(),
I);
5687 if (!ReductionData.hasRequiredNumberOfUses(I,
5688 OpData == ReductionData) &&
5691 markExtraArg(Stack.
back(),
I);
5695 if (IsReductionOperation) {
5697 if (!OpData.isAssociative(I)) {
5699 markExtraArg(Stack.
back(),
I);
5702 }
else if (ReducedValueData &&
5703 ReducedValueData != OpData) {
5707 markExtraArg(Stack.
back(),
I);
5709 }
else if (!ReducedValueData)
5710 ReducedValueData = OpData;
5712 Stack.
push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
5717 markExtraArg(Stack.
back(), NextV);
5725 if (ReducedVals.
empty())
5731 unsigned NumReducedVals = ReducedVals.
size();
5732 if (NumReducedVals < 4)
5737 Value *VectorizedTree =
nullptr;
5744 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
5747 for (
auto &Pair : ExtraArgs)
5748 ExternallyUsedValues[Pair.second].push_back(Pair.first);
5750 for (
auto &V : ReductionOps)
5751 IgnoreList.
append(V.begin(), V.end());
5752 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
5754 V.buildTree(VL, ExternallyUsedValues, IgnoreList);
5757 if (Order && Order->size() == VL.
size()) {
5761 [VL](
const unsigned Idx) {
return VL[Idx]; });
5762 V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList);
5764 if (V.isTreeTinyAndNotFullyVectorizable())
5767 V.computeMinimumValueSizes();
5770 int TreeCost = V.getTreeCost();
5771 int ReductionCost = getReductionCost(TTI, ReducedVals[i], ReduxWidth);
5772 int Cost = TreeCost + ReductionCost;
5774 V.getORE()->emit([&]() {
5776 SV_NAME,
"HorSLPNotBeneficial", cast<Instruction>(VL[0]))
5777 <<
"Vectorizing horizontal reduction is possible" 5778 <<
"but not beneficial with cost " 5779 <<
ore::NV(
"Cost", Cost) <<
" and threshold " 5785 LLVM_DEBUG(
dbgs() <<
"SLP: Vectorizing horizontal reduction at cost:" 5786 << Cost <<
". (HorRdx)\n");
5787 V.getORE()->emit([&]() {
5789 SV_NAME,
"VectorizedHorizontalReduction", cast<Instruction>(VL[0]))
5790 <<
"Vectorized horizontal reduction with cost " 5791 <<
ore::NV(
"Cost", Cost) <<
" and with tree size " 5792 <<
ore::NV(
"TreeSize", V.getTreeSize());
5796 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
5797 Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
5800 Value *ReducedSubTree =
5801 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
5802 if (VectorizedTree) {
5804 OperationData VectReductionData(ReductionData.getOpcode(),
5805 VectorizedTree, ReducedSubTree,
5806 ReductionData.getKind());
5808 VectReductionData.createOp(Builder,
"op.rdx", ReductionOps);
5810 VectorizedTree = ReducedSubTree;
5815 if (VectorizedTree) {
5817 for (; i < NumReducedVals; ++i) {
5818 auto *I = cast<Instruction>(ReducedVals[i]);
5820 OperationData VectReductionData(ReductionData.getOpcode(),
5822 ReductionData.getKind());
5823 VectorizedTree = VectReductionData.createOp(Builder,
"", ReductionOps);
5825 for (
auto &Pair : ExternallyUsedValues) {
5826 assert(!Pair.second.empty() &&
5827 "At least one DebugLoc must be inserted");
5829 for (
auto *I : Pair.second) {
5831 OperationData VectReductionData(ReductionData.getOpcode(),
5832 VectorizedTree, Pair.first,
5833 ReductionData.getKind());
5834 VectorizedTree = VectReductionData.createOp(Builder,
"op.extra", I);
5840 return VectorizedTree !=
nullptr;
5843 unsigned numReductionValues()
const {
5844 return ReducedVals.
size();
5850 unsigned ReduxWidth) {
5854 int PairwiseRdxCost;
5855 int SplittingRdxCost;
5856 switch (ReductionData.getKind()) {
5870 bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
5871 ReductionData.getKind() == RK_UMax;
5884 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
5885 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
5887 int ScalarReduxCost;
5888 switch (ReductionData.getKind()) {
5905 ScalarReduxCost *= (ReduxWidth - 1);
5907 LLVM_DEBUG(
dbgs() <<
"SLP: Adding cost " << VecReduxCost - ScalarReduxCost
5908 <<
" for reduction that starts with " << *FirstReducedVal
5910 << (IsPairwiseReduction ?
"pairwise" :
"splitting")
5911 <<
" reduction)\n");
5913 return VecReduxCost - ScalarReduxCost;
5919 assert(VectorizedValue &&
"Need to have a vectorized tree node");
5921 "We only handle power-of-two reductions for now");
5923 if (!IsPairwiseReduction)
5925 Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
5926 ReductionData.getFlags(), ReductionOps.back());
5928 Value *TmpVec = VectorizedValue;
5929 for (
unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
5940 OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf,
5941 RightShuf, ReductionData.getKind());
5942 TmpVec = VectReductionData.createOp(Builder,
"op.rdx", ReductionOps);
5967 if (
auto *CI = dyn_cast<ConstantInt>(LastInsertElem->
getOperand(2))) {
5970 CI->getZExtValue());
5974 if (isa<UndefValue>(V))
5977 if (!LastInsertElem || !LastInsertElem->
hasOneUse())
5993 if (isa<UndefValue>(V))
6019 auto DominatedReduxValue = [&](
Value *R) {
6020 return isa<Instruction>(R) &&
6024 Value *Rdx =
nullptr;
6033 if (Rdx && DominatedReduxValue(Rdx))
6052 if (Rdx && DominatedReduxValue(Rdx))
6079 if (Root->
getParent() != BB || isa<PHINode>(Root))
6093 while (!Stack.empty()) {
6096 std::tie(V, Level) = Stack.pop_back_val();
6105 HorizontalReduction HorRdx;
6106 if (HorRdx.matchAssociativeReduction(P, Inst)) {
6107 if (HorRdx.tryToReduce(R, TTI)) {
6130 if (Vectorize(Inst, R)) {
6139 for (
auto *
Op : Inst->operand_values())
6140 if (VisitedInstrs.
insert(
Op).second)
6141 if (
auto *I = dyn_cast<Instruction>(
Op))
6142 if (!isa<PHINode>(I) && I->
getParent() == BB)
6143 Stack.emplace_back(
Op, Level);
6148 bool SLPVectorizerPass::vectorizeRootInstruction(
PHINode *P,
Value *V,
6157 if (!isa<BinaryOperator>(I))
6160 auto &&ExtraVectorization = [
this](
Instruction *
I, BoUpSLP &R) ->
bool {
6161 return tryToVectorize(I, R);
6164 ExtraVectorization);
6167 bool SLPVectorizerPass::vectorizeInsertValueInst(
InsertValueInst *IVI,
6170 if (!R.canMapToVector(IVI->
getType(), DL))
6177 LLVM_DEBUG(
dbgs() <<
"SLP: array mappable to vector: " << *IVI <<
"\n");
6180 return tryToVectorizeList(BuildVectorOpds, R);
6189 [](
Value *V) {
return isa<ExtractElementInst>(V); }) &&
6195 return tryToVectorizeList(BuildVectorOpds, R, UserCost);
6203 bool OpsChanged =
false;
6204 for (
int Idx = 0; Idx < 2; ++Idx) {
6206 vectorizeRootInstruction(
nullptr, CI->
getOperand(Idx), BB, R, TTI);
6211 bool SLPVectorizerPass::vectorizeSimpleInstructions(
6213 bool OpsChanged =
false;
6214 for (
auto &VH :
reverse(Instructions)) {
6215 auto *I = dyn_cast_or_null<Instruction>(VH);
6218 if (
auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
6219 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
6220 else if (
auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
6221 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
6222 else if (
auto *CI = dyn_cast<CmpInst>(I))
6223 OpsChanged |= vectorizeCmpInst(CI, BB, R);
6225 Instructions.
clear();
6229 bool SLPVectorizerPass::vectorizeChainsInBlock(
BasicBlock *BB, BoUpSLP &R) {
6230 bool Changed =
false;
6234 bool HaveVectorizedPhiNodes =
true;
6235 while (HaveVectorizedPhiNodes) {
6236 HaveVectorizedPhiNodes =
false;
6245 if (!VisitedInstrs.
count(P))
6259 while (SameTypeIt != E &&
6260 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
6261 VisitedInstrs.
insert(*SameTypeIt);
6266 unsigned NumElts = (SameTypeIt - IncIt);
6267 LLVM_DEBUG(
dbgs() <<
"SLP: Trying to vectorize starting at PHIs (" 6268 << NumElts <<
")\n");
6273 bool AllowReorder = NumElts == 2;
6274 if (NumElts > 1 && tryToVectorizeList(
makeArrayRef(IncIt, NumElts), R,
6277 HaveVectorizedPhiNodes =
true;
6287 VisitedInstrs.
clear();
6293 if (!VisitedInstrs.
insert(&*it).second) {
6294 if (it->use_empty() && KeyNodes.
count(&*it) > 0 &&
6295 vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
6305 if (isa<DbgInfoIntrinsic>(it))
6309 if (
PHINode *P = dyn_cast<PHINode>(it)) {
6328 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
6329 isa<InvokeInst>(it))) {
6331 bool OpsChanged =
false;
6333 for (
auto *V : it->operand_values()) {
6335 OpsChanged |= vectorizeRootInstruction(
nullptr, V, BB, R, TTI);
6341 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
6352 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
6353 isa<InsertValueInst>(it))
6354 PostProcessInstructions.
push_back(&*it);
6360 bool SLPVectorizerPass::vectorizeGEPIndices(
BasicBlock *BB, BoUpSLP &R) {
6361 auto Changed =
false;
6362 for (
auto &Entry : GEPs) {
6365 if (Entry.second.size() < 2)
6368 LLVM_DEBUG(
dbgs() <<
"SLP: Analyzing a getelementptr list of length " 6369 << Entry.second.size() <<
".\n");
6373 for (
unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
6374 auto Len = std::min<unsigned>(BE - BI, 16);
6387 Candidates.
remove(
nullptr);
6394 for (
int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++
I) {
6395 auto *GEPI = cast<GetElementPtrInst>(GEPList[
I]);
6396 if (!Candidates.count(GEPI))
6398 auto *SCEVI = SE->getSCEV(GEPList[I]);
6399 for (
int J = I + 1; J < E && Candidates.size() > 1; ++J) {
6400 auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
6401 auto *SCEVJ = SE->getSCEV(GEPList[J]);
6402 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
6403 Candidates.remove(GEPList[I]);
6404 Candidates.remove(GEPList[J]);
6405 }
else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
6406 Candidates.remove(GEPList[J]);
6413 if (Candidates.size() < 2)
6420 auto BundleIndex = 0u;
6421 for (
auto *V : Candidates) {
6422 auto *
GEP = cast<GetElementPtrInst>(V);
6423 auto *GEPIdx =
GEP->idx_begin()->get();
6424 assert(
GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
6425 Bundle[BundleIndex++] = GEPIdx;
6437 Changed |= tryToVectorizeList(Bundle, R);
6443 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
6444 bool Changed =
false;
6446 for (StoreListMap::iterator it = Stores.
begin(), e = Stores.
end(); it != e;
6448 if (it->second.size() < 2)
6452 << it->second.size() <<
".\n");
6458 for (
unsigned CI = 0, CE = it->second.size(); CI < CE; CI += 16) {
6459 unsigned Len = std::min<unsigned>(CE - CI, 16);
6460 Changed |= vectorizeStores(
makeArrayRef(&it->second[CI], Len), R);
Legacy wrapper pass to provide the GlobalsAAResult object.
MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty > m_UMin(const LHS &L, const RHS &R)
Pass interface - Implemented by all 'passes'.
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value *> &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop)...
bool hasOperandBundles() const
Return true if this User has any operand bundles.
static cl::opt< bool > ViewSLPTree("view-slp-tree", cl::Hidden, cl::desc("Display the SLP trees with Graphviz"))
Value * getValueOperand()
static std::string getNodeAttributes(const TreeEntry *Entry, const BoUpSLP *)
static cl::opt< int > SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden, cl::desc("Only vectorize if you gain more than this " "number "))
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static IntegerType * getInt1Ty(LLVMContext &C)
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static bool allConstant(ArrayRef< Value *> VL)
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
MapVector< Instruction *, uint64_t > computeMinimumValueSizes(ArrayRef< BasicBlock *> Blocks, DemandedBits &DB, const TargetTransformInfo *TTI=nullptr)
Compute a map of integer instructions to their minimum legal type size.
const T & back() const
back - Get the last element.
Value * getAggregateOperand()
void setFast(bool B=true)
DiagnosticInfoOptimizationBase::Argument NV
void dropAllReferences()
Drop all references to operands.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
OptimizationRemarkEmitter * getORE()
Compute iterated dominance frontiers using a linear time algorithm.
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
This is the interface for a simple mod/ref and alias analysis over globals.
A Module instance is used to store all the information related to an LLVM module. ...
static InstructionsState getSameOpcode(ArrayRef< Value *> VL, unsigned BaseIndex=0)
static Value * getReductionValue(const DominatorTree *DT, PHINode *P, BasicBlock *ParentBB, LoopInfo *LI)
Try and get a reduction value from a phi node.
static cl::opt< int > MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden, cl::desc("Attempt to vectorize for this register size in bits"))
static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, TargetLibraryInfo *TLI)
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
Instruction * propagateMetadata(Instruction *I, ArrayRef< Value *> VL)
Specifically, let Kinds = [MD_tbaa, MD_alias_scope, MD_noalias, MD_fpmath, MD_nontemporal].
The main scalar evolution driver.
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
This class represents a function call, abstracting a target machine's calling convention.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
An immutable pass that tracks lazily created AssumptionCache objects.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
const Value * getTrueValue() const
An efficient, type-erasing, non-owning reference to a callable.
static const unsigned MaxMemDepDistance
A cache of @llvm.assume calls within a function.
Analysis pass providing the TargetTransformInfo.
0 1 0 0 True if ordered and less than
static bool collectValuesToDemote(Value *V, SmallPtrSetImpl< Value *> &Expr, SmallVectorImpl< Value *> &ToDemote, SmallVectorImpl< Value *> &Roots)
Value * createSimpleTargetReduction(IRBuilder<> &B, const TargetTransformInfo *TTI, unsigned Opcode, Value *Src, TargetTransformInfo::ReductionFlags Flags=TargetTransformInfo::ReductionFlags(), ArrayRef< Value *> RedOps=None)
Create a target reduction of the given vector.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
This class implements a map that also provides access to all stored values in a deterministic order...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
reverse_iterator rbegin()
MaxMin_match< FCmpInst, LHS, RHS, ufmax_pred_ty > m_UnordFMax(const LHS &L, const RHS &R)
Match an 'unordered' floating point maximum function.
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&... args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
DOTGraphTraits(bool isSimple=false)
This defines the Use class.
void reserve(size_type N)
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
iterator begin()
Instruction iterator methods.
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
static nodes_iterator nodes_end(BoUpSLP *R)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
void dump() const
Support for debugging, callable in GDB: V->dump()
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
static uint32_t getAlignment(const MCSectionCOFF &Sec)
static cl::opt< unsigned > RecursionMaxDepth("slp-recursion-max-depth", cl::init(12), cl::Hidden, cl::desc("Limit the recursion depth when building a vectorizable tree"))
static void inversePermutation(ArrayRef< unsigned > Indices, SmallVectorImpl< unsigned > &Mask)
static Optional< TargetTransformInfo::ShuffleKind > isShuffle(ArrayRef< Value *> VL)
Checks if the vector of instructions can be represented as a shuffle, like: x0 = extractelement <4 x ...
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static bool findBuildAggregate(InsertValueInst *IV, SmallVectorImpl< Value *> &BuildVectorOpds)
Like findBuildVector, but looks for construction of aggregate.
This is the base class for all instructions that perform data casts.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
unsigned getTreeSize() const
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
An analysis that produces DemandedBits for a function.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
0 1 0 1 True if ordered and less than or equal
This file contains the simple types necessary to represent the attributes associated with functions a...
static bool shouldReorderOperands(int i, unsigned Opcode, Instruction &I, ArrayRef< Value *> Left, ArrayRef< Value *> Right, bool AllSameOpcodeLeft, bool AllSameOpcodeRight, bool SplatLeft, bool SplatRight, Value *&VLeft, Value *&VRight)
MaxMin_match< FCmpInst, LHS, RHS, ufmin_pred_ty > m_UnordFMin(const LHS &L, const RHS &R)
Match an 'unordered' floating point minimum function.
static const unsigned AliasedCheckLimit
Analysis pass that exposes the LoopInfo for a function.
Value * CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name="")
uint64_t getNumElements() const
static cl::opt< bool > ShouldStartVectorizeHorAtStore("slp-vectorize-hor-store", cl::init(false), cl::Hidden, cl::desc("Attempt to vectorize horizontal reductions feeding into a store"))
std::vector< TreeEntry > & VectorizableTree
bool remove(const value_type &X)
Remove an item from the set vector.
void assign(size_type NumElts, const T &Elt)
static ChildIteratorType child_end(NodeRef N)
static bool allSameBlock(ArrayRef< Value *> VL)
static bool isSimple(Instruction *I)
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
static bool isEqual(const Function &Caller, const Function &Callee)
Value * CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name="")
TreeEntry * NodeRef
NodeRef has to be a pointer per the GraphWriter.
BoUpSLP::TreeEntry TreeEntry
const T & getValue() const LLVM_LVALUE_FUNCTION
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
MaxMin_match< FCmpInst, LHS, RHS, ofmin_pred_ty > m_OrdFMin(const LHS &L, const RHS &R)
Match an 'ordered' floating point minimum function.
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > m_SMin(const LHS &L, const RHS &R)
void insert(ScheduleData *SD)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Value * getInsertedValueOperand()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
static Value * createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx, bool IsPairwise, bool IsLeft, IRBuilder<> &Builder)
Generate a shuffle mask to be used in a reduction tree.
An instruction for storing to memory.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator find(const KeyT &Key)
VectorType * getType() const
Overload to return most specific vector type.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Value * getOperand(unsigned i) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Class to represent pointers.
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
static ChildIteratorType child_begin(NodeRef N)
unsigned getMinVecRegSize() const
static bool findBuildVector(InsertElementInst *LastInsertElem, TargetTransformInfo *TTI, SmallVectorImpl< Value *> &BuildVectorOpds, int &UserCost)
Recognize construction of vectors like ra = insertelement <4 x float> undef, float s0...
bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, ScalarEvolution &SE, bool CheckType=true)
Returns true if the memory operations A and B are consecutive.
bool isVoidTy() const
Return true if this is 'void'.
const BasicBlock & getEntryBlock() const
static bool runOnFunction(Function &F, bool PostInlining)
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R)
initializer< Ty > init(const Ty &Val)
This instruction inserts a single (scalar) element into a VectorType value.
static const int MinScheduleRegionSize
If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling regions to be handled...
typename GraphType::UnknownGraphTypeError NodeRef
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty > m_UMax(const LHS &L, const RHS &R)
bool hasNUses(unsigned N) const
Return true if this Value has exactly N users.
BoUpSLP::TreeEntry TreeEntry
unsigned getBundleOperandsStartIndex() const
Return the index of the first bundle operand in the Use array.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
static bool tryToVectorizeHorReductionOrInstOperands(PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, TargetTransformInfo *TTI, const function_ref< bool(Instruction *, BoUpSLP &)> Vectorize)
Attempt to reduce a horizontal reduction.
CRTP base class for adapting an iterator to a different type.
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
A manager for alias analyses.
std::pair< iterator, bool > insert(const ValueT &V)
Value * CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
User::op_iterator op_begin()
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
Represent the analysis usage information of a pass.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Analysis pass providing a never-invalidated alias analysis result.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
FunctionPass class - This class is used to implement most global optimizations.
Value * getPointerOperand()
iterator_range< po_iterator< T > > post_order(const T &G)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Class to represent integer types.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
void setAlignment(unsigned Align)
Used in the streaming interface as the general argument type.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
iterator_range< User::op_iterator > arg_operands()
Iteration adapter for range-for loops.
static Optional< unsigned > getExtractIndex(Instruction *E)
static wasm::ValType getType(const TargetRegisterClass *RC)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
1 1 0 1 True if unordered, less than, or equal
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
bool hasIdenticalOperandBundleSchema(const OperandBundleUser< InstrTy, OpIteratorTy > &Other) const
Return true if Other has the same sequence of operand bundle tags with the same number of operands on...
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void propagateIRFlags(Value *I, ArrayRef< Value *> VL, Value *OpValue=nullptr)
Get the intersection (logical and) of all of the potential IR flags of each scalar operation (VL) tha...
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
static Value * isOneOf(const InstructionsState &S, Value *Op)
Chooses the correct key for scheduling data.
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
const Value * Ptr
The address of the start of the location.
Representation for a specific memory location.
Value * CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
0 0 1 0 True if ordered and greater than
A function analysis which provides an AssumptionCache.
static cl::opt< int > MinVectorRegSizeOption("slp-min-reg-size", cl::init(128), cl::Hidden, cl::desc("Attempt to vectorize for this register size in bits"))
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
This is the shared class of boolean and integer constants.
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Return the number of times the sign bit of the register is replicated into the other bits...
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
1 1 0 0 True if unordered or less than
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Provides information about what library functions are available for the current target.
size_type count(const KeyT &Key) const
User(Type *ty, unsigned vty, Use *, unsigned NumOps)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
LLVM_NODISCARD T pop_back_val()
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
static nodes_iterator nodes_begin(BoUpSLP *R)
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Optional< ArrayRef< unsigned > > bestOrder() const
void setPreservesCFG()
This function should be called by the pass, iff they do not:
bool hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, unsigned ScalarOpdIdx)
Identifies if the intrinsic has a scalar operand.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
bool isCommutative() const
Return true if the instruction is commutative:
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Implements a dense probed hash-table based set with some number of buckets stored inline...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Class to represent vector types.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
static bool allSameType(ArrayRef< Value *> VL)
iterator_range< user_iterator > users()
unsigned getBundleOperandsEndIndex() const
Return the index of the last bundle operand in the Use array.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
unsigned getMaxVecRegSize() const
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...
Represents analyses that only rely on functions' control flow.
static void clear(coro::Shape &Shape)
iterator insert(iterator I, T &&Elt)
const Value * getFalseValue() const
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
static cl::opt< int > ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden, cl::desc("Limit the size of the SLP scheduling region per block"))
Limits the size of scheduling regions in a block.
bool isX86_FP80Ty() const
Return true if this is x86 long double.
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
Analysis pass that exposes the ScalarEvolution for a function.
bool operator!=(uint64_t V1, const APInt &V2)
Predicate getPredicate() const
Return the predicate for this instruction.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
static unsigned size(BoUpSLP *R)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
void initializeSLPVectorizerPass(PassRegistry &)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
void emplace_back(ArgTypes &&... Args)
This class represents an analyzed expression in the program.
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
LLVM_NODISCARD bool empty() const
unsigned getNumArgOperands() const
Return the number of call arguments.
unsigned greater or equal
Represents a single loop in the control flow graph.
This file provides utility analysis objects describing memory locations.
void preserveSet()
Mark an analysis set as preserved.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
bool runImpl(Function &F, ScalarEvolution *SE_, TargetTransformInfo *TTI_, TargetLibraryInfo *TLI_, AliasAnalysis *AA_, LoopInfo *LI_, DominatorTree *DT_, AssumptionCache *AC_, DemandedBits *DB_, OptimizationRemarkEmitter *ORE_)
static bool isValidElementType(Type *Ty)
Predicate for the element types that the SLP vectorizer supports.
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty > m_SMax(const LHS &L, const RHS &R)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
friend raw_ostream & operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
ilist_iterator< OptionsT, !IsReverse, IsConst > getReverse() const
Get a reverse iterator to the same node.
void preserve()
Mark an analysis as preserved.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
static cl::opt< bool > ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden, cl::desc("Attempt to vectorize horizontal reductions"))
1 0 1 0 True if unordered or greater than
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Pass * createSLPVectorizerPass()
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
ChildIteratorType(SmallVector< int, 1 >::iterator W, std::vector< TreeEntry > &VT)
Analysis pass providing the TargetLibraryInfo.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA)
static NodeRef getEntryNode(BoUpSLP &R)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
static const char lv_name[]
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
static bool PhiTypeSorterFunc(Value *V, Value *V2)
A raw_ostream that writes to an std::string.
MaxMin_match< FCmpInst, LHS, RHS, ofmax_pred_ty > m_OrdFMax(const LHS &L, const RHS &R)
Match an 'ordered' floating point maximum function.
uint64_t PowerOf2Floor(uint64_t A)
Returns the power of two which is less than or equal to the given value.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
void setAlignment(unsigned Align)
1 0 1 1 True if unordered, greater than, or equal
A vector that has set insertion semantics.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
static bool hasValueBeenRAUWed(ArrayRef< Value *> VL, ArrayRef< WeakTrackingVH > VH, unsigned SliceBegin, unsigned SliceSize)
Check that the Values in the slice in VL array are still existent in the WeakTrackingVH array...
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
static const Function * getParent(const Value *V)
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
This class implements an extremely fast bulk output stream that can only output to a stream...
DefaultDOTGraphTraits - This class provides the default implementations of all of the DOTGraphTraits ...
The legacy pass manager's analysis pass to compute loop information.
bool hasOneUse() const
Return true if there is exactly one user of this value.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Convenience struct for specifying and reasoning about fast-math flags.
bool isNonNegative() const
Returns true if this value is known to be non-negative.
A container for analyses that lazily runs them and caches their results.
static bool isSplat(ArrayRef< Value *> VL)
Legacy analysis pass which computes a DominatorTree.
void deleteTree()
Clear the internal data structures that are created by 'buildTree'.
bool operator==(uint64_t V1, const APInt &V2)
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
This header defines various interfaces for pass management in LLVM.
static bool isAssociative(const COFFSection &Section)
op_range incoming_values()
0 0 1 1 True if ordered and greater than or equal
Bottom Up SLP Vectorizer.
static cl::opt< unsigned > MinTreeSize("slp-min-tree-size", cl::init(3), cl::Hidden, cl::desc("Only vectorize small trees if they are fully vectorizable"))
bool sortPtrAccesses(ArrayRef< Value *> VL, const DataLayout &DL, ScalarEvolution &SE, SmallVectorImpl< unsigned > &SortedIndices)
Attempt to sort the pointers in VL and return the sorted indices in SortedIndices, if reordering is required.
Value * getPointerOperand()
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
static Constant * get(ArrayRef< Constant *> V)
BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li, DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB, const DataLayout *DL, OptimizationRemarkEmitter *ORE)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
bool empty() const
empty - Check if the array is empty.
const BasicBlock * getParent() const
This class represents a constant integer value.
This instruction inserts a struct field of array element value into an aggregate value.
bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
bool mayReadOrWriteMemory() const
Return true if this instruction may read or write memory.