51 using namespace slpvectorizer;
53 #define SV_NAME "slp-vectorizer"
54 #define DEBUG_TYPE "SLP"
56 STATISTIC(NumVectorInstructions,
"Number of vector instructions generated");
60 cl::desc(
"Only vectorize if you gain more than this "
65 cl::desc(
"Attempt to vectorize horizontal reductions"));
70 "Attempt to vectorize horizontal reductions feeding into a store"));
74 cl::desc(
"Attempt to vectorize for this register size in bits"));
82 cl::desc(
"Limit the size of the SLP scheduling region per block"));
86 cl::desc(
"Attempt to vectorize for this register size in bits"));
90 cl::desc(
"Limit the recursion depth when building a vectorizable tree"));
94 cl::desc(
"Only vectorize small trees if they are fully vectorizable"));
98 cl::desc(
"Display the SLP trees with Graphviz"));
132 for (
int i = 1, e = VL.
size(); i < e; i++) {
146 if (!isa<Constant>(i))
153 for (
unsigned i = 1, e = VL.
size(); i < e; ++i)
163 case Instruction::FAdd:
164 return Instruction::FSub;
165 case Instruction::FSub:
166 return Instruction::FAdd;
168 return Instruction::Sub;
169 case Instruction::Sub:
185 return Op == Instruction::FAdd || Op == Instruction::FSub ||
196 for (
int i = 1, e = VL.
size(); i < e; i++) {
201 return Instruction::ShuffleVector;
211 for (
int i = 1, e = VL.
size(); i < e; i++) {
225 Type *Ty = VL[0]->getType();
226 for (
int i = 1, e = VL.
size(); i < e; i++)
235 assert(Opcode == Instruction::ExtractElement ||
236 Opcode == Instruction::ExtractValue);
237 if (Opcode == Instruction::ExtractElement) {
254 LoadInst *LI = cast<LoadInst>(UserInst);
262 CallInst *CI = cast<CallInst>(UserInst);
278 if (
LoadInst *LI = dyn_cast<LoadInst>(I))
285 if (
LoadInst *LI = dyn_cast<LoadInst>(I))
286 return LI->isSimple();
288 return SI->isSimple();
290 return !
MI->isVolatile();
295 namespace slpvectorizer {
310 : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0),
F(Func),
311 SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC), DB(DB),
312 DL(DL), ORE(ORE), Builder(Se->getContext()) {
323 MaxVecRegSize = TTI->getRegisterBitWidth(
true);
328 MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
333 Value *vectorizeTree();
337 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
356 ExtraValueToDebugLocsMap &ExternallyUsedValues,
361 VectorizableTree.clear();
362 ScalarToTreeEntry.clear();
364 ExternalUses.clear();
365 NumLoadsWantToKeepOrder = 0;
366 NumLoadsWantToChangeOrder = 0;
367 for (
auto &Iter : BlocksSchedules) {
368 BlockScheduling *BS = Iter.second.get();
377 void optimizeGatherSequence();
381 return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
389 unsigned getVectorElementSize(
Value *V);
397 return MaxVecRegSize;
402 return MinVecRegSize;
412 bool isTreeTinyAndNotFullyVectorizable();
420 int getEntryCost(TreeEntry *
E);
430 Value *vectorizeTree(TreeEntry *
E);
441 int getGatherCost(
Type *Ty);
457 bool isFullyVectorizableTinyTree();
470 TreeEntry(std::vector<TreeEntry> &Container)
471 : Scalars(), VectorizedValue(nullptr), NeedToGather(0),
472 Container(Container) {}
476 assert(VL.
size() == Scalars.size() &&
"Invalid size");
484 Value *VectorizedValue;
495 std::vector<TreeEntry> &Container;
506 int idx = VectorizableTree.size() - 1;
507 TreeEntry *
Last = &VectorizableTree[idx];
508 Last->Scalars.insert(Last->Scalars.begin(), VL.
begin(), VL.
end());
509 Last->NeedToGather = !Vectorized;
511 for (
int i = 0, e = VL.
size(); i != e; ++i) {
512 assert(!getTreeEntry(VL[i]) &&
"Scalar already in tree!");
513 ScalarToTreeEntry[VL[i]] = idx;
516 MustGather.insert(VL.
begin(), VL.
end());
519 if (UserTreeIdx >= 0)
520 Last->UserTreeIndices.push_back(UserTreeIdx);
527 std::vector<TreeEntry> VectorizableTree;
529 TreeEntry *getTreeEntry(
Value *V) {
530 auto I = ScalarToTreeEntry.find(V);
531 if (
I != ScalarToTreeEntry.end())
532 return &VectorizableTree[
I->second];
536 const TreeEntry *getTreeEntry(
Value *V)
const {
537 auto I = ScalarToTreeEntry.find(V);
538 if (
I != ScalarToTreeEntry.end())
539 return &VectorizableTree[
I->second];
550 struct ExternalUser {
570 AliasCacheKey key = std::make_pair(Inst1, Inst2);
579 aliased = AA->alias(Loc1, Loc2);
586 typedef std::pair<Instruction *, Instruction *> AliasCacheKey;
601 DeletedInstructions.emplace_back(I);
612 UserList ExternalUses;
626 struct ScheduleData {
630 enum { InvalidDeps = -1 };
633 : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
634 NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
635 Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
636 UnscheduledDepsInBundle(InvalidDeps), IsScheduled(
false) {}
638 void init(
int BlockSchedulingRegionID) {
639 FirstInBundle =
this;
640 NextInBundle =
nullptr;
641 NextLoadStore =
nullptr;
643 SchedulingRegionID = BlockSchedulingRegionID;
644 UnscheduledDepsInBundle = UnscheduledDeps;
649 bool hasValidDependencies()
const {
return Dependencies != InvalidDeps; }
653 bool isSchedulingEntity()
const {
return FirstInBundle ==
this; }
657 bool isPartOfBundle()
const {
658 return NextInBundle !=
nullptr || FirstInBundle !=
this;
663 bool isReady()
const {
664 assert(isSchedulingEntity() &&
665 "can't consider non-scheduling entity for ready list");
666 return UnscheduledDepsInBundle == 0 && !IsScheduled;
671 int incrementUnscheduledDeps(
int Incr) {
672 UnscheduledDeps += Incr;
673 return FirstInBundle->UnscheduledDepsInBundle += Incr;
678 void resetUnscheduledDeps() {
679 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
683 void clearDependencies() {
684 Dependencies = InvalidDeps;
685 resetUnscheduledDeps();
686 MemoryDependencies.clear();
690 if (!isSchedulingEntity()) {
692 }
else if (NextInBundle) {
694 ScheduleData *SD = NextInBundle;
696 os <<
';' << *SD->Inst;
697 SD = SD->NextInBundle;
709 ScheduleData *FirstInBundle;
713 ScheduleData *NextInBundle;
717 ScheduleData *NextLoadStore;
725 int SchedulingRegionID;
728 int SchedulingPriority;
745 int UnscheduledDepsInBundle;
754 const BoUpSLP::ScheduleData &SD) {
764 struct BlockScheduling {
767 : BB(BB), ChunkSize(BB->
size()), ChunkPos(ChunkSize),
768 ScheduleStart(
nullptr), ScheduleEnd(
nullptr),
769 FirstLoadStoreInRegion(
nullptr), LastLoadStoreInRegion(
nullptr),
770 ScheduleRegionSize(0),
774 SchedulingRegionID(1) {}
778 ScheduleStart =
nullptr;
779 ScheduleEnd =
nullptr;
780 FirstLoadStoreInRegion =
nullptr;
781 LastLoadStoreInRegion =
nullptr;
785 ScheduleRegionSizeLimit -= ScheduleRegionSize;
788 ScheduleRegionSize = 0;
792 ++SchedulingRegionID;
795 ScheduleData *getScheduleData(
Value *V) {
796 ScheduleData *SD = ScheduleDataMap[V];
797 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
802 bool isInSchedulingRegion(ScheduleData *SD) {
803 return SD->SchedulingRegionID == SchedulingRegionID;
808 template <
typename ReadyListType>
809 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
810 SD->IsScheduled =
true;
811 DEBUG(
dbgs() <<
"SLP: schedule " << *SD <<
"\n");
813 ScheduleData *BundleMember = SD;
814 while (BundleMember) {
816 for (
Use &U : BundleMember->Inst->operands()) {
817 ScheduleData *OpDef = getScheduleData(U.get());
818 if (OpDef && OpDef->hasValidDependencies() &&
819 OpDef->incrementUnscheduledDeps(-1) == 0) {
822 ScheduleData *DepBundle = OpDef->FirstInBundle;
823 assert(!DepBundle->IsScheduled &&
824 "already scheduled bundle gets ready");
825 ReadyList.insert(DepBundle);
826 DEBUG(
dbgs() <<
"SLP: gets ready (def): " << *DepBundle <<
"\n");
830 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
831 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
834 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
835 assert(!DepBundle->IsScheduled &&
836 "already scheduled bundle gets ready");
837 ReadyList.insert(DepBundle);
838 DEBUG(
dbgs() <<
"SLP: gets ready (mem): " << *DepBundle <<
"\n");
841 BundleMember = BundleMember->NextInBundle;
846 template <
typename ReadyListType>
847 void initialFillReadyList(ReadyListType &ReadyList) {
848 for (
auto *I = ScheduleStart; I != ScheduleEnd; I = I->
getNextNode()) {
849 ScheduleData *SD = getScheduleData(I);
850 if (SD->isSchedulingEntity() && SD->isReady()) {
851 ReadyList.insert(SD);
852 DEBUG(
dbgs() <<
"SLP: initially in ready list: " << *I <<
"\n");
867 bool extendSchedulingRegion(
Value *V);
872 ScheduleData *PrevLoadStore,
873 ScheduleData *NextLoadStore);
877 void calculateDependencies(ScheduleData *SD,
bool InsertInReadyList,
881 void resetSchedule();
886 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
901 void insert(ScheduleData *SD) { push_back(SD); }
905 ReadyList ReadyInsts;
915 ScheduleData *FirstLoadStoreInRegion;
919 ScheduleData *LastLoadStoreInRegion;
922 int ScheduleRegionSize;
925 int ScheduleRegionSizeLimit;
929 int SchedulingRegionID;
937 void scheduleBlock(BlockScheduling *BS);
943 int NumLoadsWantToKeepOrder;
946 int NumLoadsWantToChangeOrder;
961 unsigned MaxVecRegSize;
962 unsigned MinVecRegSize;
983 struct ChildIteratorType
985 SmallVector<int, 1>::iterator> {
990 std::vector<TreeEntry> &VT)
999 return {N->UserTreeIndices.begin(), N->Container};
1002 return {N->UserTreeIndices.end(), N->Container};
1010 return nodes_iterator(R->VectorizableTree.begin());
1013 return nodes_iterator(R->VectorizableTree.end());
1016 static unsigned size(
BoUpSLP *R) {
return R->VectorizableTree.size(); }
1027 if (
isSplat(Entry->Scalars)) {
1028 OS <<
"<splat> " << *Entry->Scalars[0];
1031 for (
auto V : Entry->Scalars) {
1034 R->ExternalUses.
begin(), R->ExternalUses.
end(),
1035 [&](
const BoUpSLP::ExternalUser &EU) {
return EU.Scalar == V; }))
1044 if (Entry->NeedToGather)
1055 buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
1061 UserIgnoreList = UserIgnoreLst;
1064 buildTree_rec(Roots, 0, -1);
1067 for (TreeEntry &EIdx : VectorizableTree) {
1068 TreeEntry *Entry = &EIdx;
1071 if (Entry->NeedToGather)
1075 for (
int Lane = 0,
LE = Entry->Scalars.size(); Lane !=
LE; ++Lane) {
1079 auto ExtI = ExternallyUsedValues.
find(Scalar);
1080 if (ExtI != ExternallyUsedValues.
end()) {
1081 DEBUG(
dbgs() <<
"SLP: Need to extract: Extra arg from lane " <<
1082 Lane <<
" from " << *Scalar <<
".\n");
1087 DEBUG(
dbgs() <<
"SLP: Checking user:" << *U <<
".\n");
1094 if (TreeEntry *UseEntry = getTreeEntry(U)) {
1095 Value *UseScalar = UseEntry->Scalars[0];
1099 if (UseScalar != U ||
1101 DEBUG(
dbgs() <<
"SLP: \tInternal user will be removed:" << *U
1103 assert(!UseEntry->NeedToGather &&
"Bad state");
1112 DEBUG(
dbgs() <<
"SLP: Need to extract:" << *U <<
" from lane " <<
1113 Lane <<
" from " << *Scalar <<
".\n");
1114 ExternalUses.
push_back(ExternalUser(Scalar, U, Lane));
1122 bool isAltShuffle =
false;
1126 DEBUG(
dbgs() <<
"SLP: Gathering due to max recursion depth.\n");
1127 newTreeEntry(VL,
false, UserTreeIdx);
1132 if (VL[0]->
getType()->isVectorTy()) {
1133 DEBUG(
dbgs() <<
"SLP: Gathering due to vector type.\n");
1134 newTreeEntry(VL,
false, UserTreeIdx);
1139 if (
SI->getValueOperand()->getType()->isVectorTy()) {
1140 DEBUG(
dbgs() <<
"SLP: Gathering due to store vector type.\n");
1141 newTreeEntry(VL,
false, UserTreeIdx);
1148 if (Opcode == Instruction::ShuffleVector) {
1151 if (Op != Instruction::ShuffleVector)
1152 isAltShuffle =
true;
1157 DEBUG(
dbgs() <<
"SLP: Gathering due to C,S,B,O. \n");
1158 newTreeEntry(VL,
false, UserTreeIdx);
1166 for (
unsigned i = 0, e = VL.
size(); i != e; ++i) {
1167 if (EphValues.count(VL[i])) {
1168 DEBUG(
dbgs() <<
"SLP: The instruction (" << *VL[i] <<
1169 ") is ephemeral.\n");
1170 newTreeEntry(VL,
false, UserTreeIdx);
1176 if (TreeEntry *
E = getTreeEntry(VL[0])) {
1177 for (
unsigned i = 0, e = VL.
size(); i != e; ++i) {
1178 DEBUG(
dbgs() <<
"SLP: \tChecking bundle: " << *VL[i] <<
".\n");
1179 if (
E->Scalars[i] != VL[i]) {
1180 DEBUG(
dbgs() <<
"SLP: Gathering due to partial overlap.\n");
1181 newTreeEntry(VL,
false, UserTreeIdx);
1187 E->UserTreeIndices.push_back(UserTreeIdx);
1188 DEBUG(
dbgs() <<
"SLP: Perfect diamond merge at " << *VL[0] <<
".\n");
1193 for (
unsigned i = 0, e = VL.
size(); i != e; ++i) {
1194 if (ScalarToTreeEntry.count(VL[i])) {
1195 DEBUG(
dbgs() <<
"SLP: The instruction (" << *VL[i] <<
1196 ") is already in tree.\n");
1197 newTreeEntry(VL,
false, UserTreeIdx);
1204 for (
unsigned i = 0, e = VL.
size(); i != e; ++i) {
1205 if (MustGather.
count(VL[i])) {
1206 DEBUG(
dbgs() <<
"SLP: Gathering due to gathered scalar.\n");
1207 newTreeEntry(VL,
false, UserTreeIdx);
1220 DEBUG(
dbgs() <<
"SLP: bundle in unreachable block.\n");
1221 newTreeEntry(VL,
false, UserTreeIdx);
1226 for (
unsigned i = 0, e = VL.
size(); i < e; ++i)
1227 for (
unsigned j = i+1; j < e; ++j)
1228 if (VL[i] == VL[j]) {
1229 DEBUG(
dbgs() <<
"SLP: Scalar used twice in bundle.\n");
1230 newTreeEntry(VL,
false, UserTreeIdx);
1234 auto &BSRef = BlocksSchedules[BB];
1236 BSRef = llvm::make_unique<BlockScheduling>(BB);
1238 BlockScheduling &BS = *BSRef.get();
1240 if (!BS.tryScheduleBundle(VL,
this, VL0)) {
1241 DEBUG(
dbgs() <<
"SLP: We are not able to schedule this bundle!\n");
1242 assert((!BS.getScheduleData(VL[0]) ||
1243 !BS.getScheduleData(VL[0])->isPartOfBundle()) &&
1244 "tryScheduleBundle should cancelScheduling on failure");
1245 newTreeEntry(VL,
false, UserTreeIdx);
1248 DEBUG(
dbgs() <<
"SLP: We are able to schedule this bundle.\n");
1251 case Instruction::PHI: {
1255 for (
unsigned j = 0; j < VL.
size(); ++j)
1260 DEBUG(
dbgs() <<
"SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1261 BS.cancelScheduling(VL, VL0);
1262 newTreeEntry(VL,
false, UserTreeIdx);
1267 newTreeEntry(VL,
true, UserTreeIdx);
1268 DEBUG(
dbgs() <<
"SLP: added a vector of PHINodes.\n");
1274 Operands.
push_back(cast<PHINode>(j)->getIncomingValueForBlock(
1277 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1281 case Instruction::ExtractValue:
1282 case Instruction::ExtractElement: {
1283 bool Reuse = canReuseExtract(VL, Opcode);
1285 DEBUG(
dbgs() <<
"SLP: Reusing extract sequence.\n");
1287 BS.cancelScheduling(VL, VL0);
1289 newTreeEntry(VL, Reuse, UserTreeIdx);
1300 Type *ScalarTy = VL[0]->getType();
1304 BS.cancelScheduling(VL, VL0);
1305 newTreeEntry(VL,
false, UserTreeIdx);
1306 DEBUG(
dbgs() <<
"SLP: Gathering loads of non-packed type.\n");
1312 for (
unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1315 BS.cancelScheduling(VL, VL0);
1316 newTreeEntry(VL,
false, UserTreeIdx);
1317 DEBUG(
dbgs() <<
"SLP: Gathering non-simple loads.\n");
1325 bool Consecutive =
true;
1326 bool ReverseConsecutive =
true;
1327 for (
unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1329 Consecutive =
false;
1332 ReverseConsecutive =
false;
1337 ++NumLoadsWantToKeepOrder;
1338 newTreeEntry(VL,
true, UserTreeIdx);
1339 DEBUG(
dbgs() <<
"SLP: added a vector of loads.\n");
1345 if (ReverseConsecutive)
1346 for (
unsigned i = VL.size() - 1; i > 0; --i)
1348 ReverseConsecutive =
false;
1352 BS.cancelScheduling(VL, VL0);
1353 newTreeEntry(VL,
false, UserTreeIdx);
1355 if (ReverseConsecutive) {
1356 ++NumLoadsWantToChangeOrder;
1357 DEBUG(
dbgs() <<
"SLP: Gathering reversed loads.\n");
1359 DEBUG(
dbgs() <<
"SLP: Gathering non-consecutive loads.\n");
1363 case Instruction::ZExt:
1364 case Instruction::SExt:
1365 case Instruction::FPToUI:
1366 case Instruction::FPToSI:
1367 case Instruction::FPExt:
1368 case Instruction::PtrToInt:
1369 case Instruction::IntToPtr:
1370 case Instruction::SIToFP:
1371 case Instruction::UIToFP:
1372 case Instruction::Trunc:
1373 case Instruction::FPTrunc:
1374 case Instruction::BitCast: {
1376 for (
unsigned i = 0; i < VL.size(); ++i) {
1377 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1379 BS.cancelScheduling(VL, VL0);
1380 newTreeEntry(VL,
false, UserTreeIdx);
1381 DEBUG(
dbgs() <<
"SLP: Gathering casts with different src types.\n");
1385 newTreeEntry(VL,
true, UserTreeIdx);
1386 DEBUG(
dbgs() <<
"SLP: added a vector of casts.\n");
1392 Operands.
push_back(cast<Instruction>(j)->getOperand(i));
1394 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1398 case Instruction::ICmp:
1399 case Instruction::FCmp: {
1402 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1403 for (
unsigned i = 1, e = VL.size(); i < e; ++i) {
1404 CmpInst *Cmp = cast<CmpInst>(VL[i]);
1407 BS.cancelScheduling(VL, VL0);
1408 newTreeEntry(VL,
false, UserTreeIdx);
1409 DEBUG(
dbgs() <<
"SLP: Gathering cmp with different predicate.\n");
1414 newTreeEntry(VL,
true, UserTreeIdx);
1415 DEBUG(
dbgs() <<
"SLP: added a vector of compares.\n");
1421 Operands.
push_back(cast<Instruction>(j)->getOperand(i));
1423 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1429 case Instruction::FAdd:
1430 case Instruction::Sub:
1431 case Instruction::FSub:
1432 case Instruction::Mul:
1433 case Instruction::FMul:
1434 case Instruction::UDiv:
1435 case Instruction::SDiv:
1436 case Instruction::FDiv:
1437 case Instruction::URem:
1438 case Instruction::SRem:
1439 case Instruction::FRem:
1440 case Instruction::Shl:
1441 case Instruction::LShr:
1442 case Instruction::AShr:
1443 case Instruction::And:
1444 case Instruction::Or:
1445 case Instruction::Xor: {
1446 newTreeEntry(VL,
true, UserTreeIdx);
1447 DEBUG(
dbgs() <<
"SLP: added a vector of bin op.\n");
1453 reorderInputsAccordingToOpcode(VL, Left, Right);
1454 buildTree_rec(Left, Depth + 1, UserTreeIdx);
1455 buildTree_rec(Right, Depth + 1, UserTreeIdx);
1463 Operands.
push_back(cast<Instruction>(j)->getOperand(i));
1465 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1469 case Instruction::GetElementPtr: {
1471 for (
unsigned j = 0; j < VL.size(); ++j) {
1472 if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1473 DEBUG(
dbgs() <<
"SLP: not-vectorizable GEP (nested indexes).\n");
1474 BS.cancelScheduling(VL, VL0);
1475 newTreeEntry(VL,
false, UserTreeIdx);
1482 Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1483 for (
unsigned j = 0; j < VL.size(); ++j) {
1484 Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1486 DEBUG(
dbgs() <<
"SLP: not-vectorizable GEP (different types).\n");
1487 BS.cancelScheduling(VL, VL0);
1488 newTreeEntry(VL,
false, UserTreeIdx);
1494 for (
unsigned j = 0; j < VL.size(); ++j) {
1495 auto Op = cast<Instruction>(VL[j])->getOperand(1);
1496 if (!isa<ConstantInt>(Op)) {
1498 dbgs() <<
"SLP: not-vectorizable GEP (non-constant indexes).\n");
1499 BS.cancelScheduling(VL, VL0);
1500 newTreeEntry(VL,
false, UserTreeIdx);
1505 newTreeEntry(VL,
true, UserTreeIdx);
1506 DEBUG(
dbgs() <<
"SLP: added a vector of GEPs.\n");
1507 for (
unsigned i = 0, e = 2; i < e; ++i) {
1511 Operands.
push_back(cast<Instruction>(j)->getOperand(i));
1513 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1519 for (
unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1521 BS.cancelScheduling(VL, VL0);
1522 newTreeEntry(VL,
false, UserTreeIdx);
1523 DEBUG(
dbgs() <<
"SLP: Non-consecutive store.\n");
1527 newTreeEntry(VL,
true, UserTreeIdx);
1528 DEBUG(
dbgs() <<
"SLP: added a vector of stores.\n");
1532 Operands.
push_back(cast<Instruction>(j)->getOperand(0));
1534 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1539 CallInst *CI = cast<CallInst>(VL[0]);
1544 BS.cancelScheduling(VL, VL0);
1545 newTreeEntry(VL,
false, UserTreeIdx);
1546 DEBUG(
dbgs() <<
"SLP: Non-vectorizable call.\n");
1550 Value *A1I =
nullptr;
1553 for (
unsigned i = 1, e = VL.size(); i != e; ++i) {
1558 BS.cancelScheduling(VL, VL0);
1559 newTreeEntry(VL,
false, UserTreeIdx);
1560 DEBUG(
dbgs() <<
"SLP: mismatched calls:" << *CI <<
"!=" << *VL[i]
1569 BS.cancelScheduling(VL, VL0);
1570 newTreeEntry(VL,
false, UserTreeIdx);
1571 DEBUG(
dbgs() <<
"SLP: mismatched arguments in call:" << *CI
1572 <<
" argument "<< A1I<<
"!=" << A1J
1582 BS.cancelScheduling(VL, VL0);
1583 newTreeEntry(VL,
false, UserTreeIdx);
1584 DEBUG(
dbgs() <<
"SLP: mismatched bundle operands in calls:" << *CI <<
"!="
1590 newTreeEntry(VL,
true, UserTreeIdx);
1594 for (
Value *j : VL) {
1598 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1602 case Instruction::ShuffleVector: {
1605 if (!isAltShuffle) {
1606 BS.cancelScheduling(VL, VL0);
1607 newTreeEntry(VL,
false, UserTreeIdx);
1608 DEBUG(
dbgs() <<
"SLP: ShuffleVector are not vectorized.\n");
1611 newTreeEntry(VL,
true, UserTreeIdx);
1612 DEBUG(
dbgs() <<
"SLP: added a ShuffleVector op.\n");
1615 if (isa<BinaryOperator>(VL0)) {
1617 reorderAltShuffleOperands(VL, Left, Right);
1618 buildTree_rec(Left, Depth + 1, UserTreeIdx);
1619 buildTree_rec(Right, Depth + 1, UserTreeIdx);
1627 Operands.
push_back(cast<Instruction>(j)->getOperand(i));
1629 buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1634 BS.cancelScheduling(VL, VL0);
1635 newTreeEntry(VL,
false, UserTreeIdx);
1636 DEBUG(
dbgs() <<
"SLP: Gathering unknown instruction.\n");
1646 N =
ST->getNumElements();
1647 EltTy = *
ST->element_begin();
1649 N = cast<ArrayType>(
T)->getNumElements();
1650 EltTy = cast<ArrayType>(
T)->getElementType();
1659 for (
const auto *Ty :
ST->elements())
1667 assert(Opcode == Instruction::ExtractElement ||
1668 Opcode == Instruction::ExtractValue);
1678 if (Opcode == Instruction::ExtractValue) {
1688 NElts = Vec->getType()->getVectorNumElements();
1691 if (NElts != VL.
size())
1698 for (
unsigned i = 1, e = VL.
size(); i < e; ++i) {
1709 int BoUpSLP::getEntryCost(TreeEntry *E) {
1712 Type *ScalarTy = VL[0]->getType();
1714 ScalarTy =
SI->getValueOperand()->getType();
1715 else if (
CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
1721 if (MinBWs.count(VL[0]))
1725 if (E->NeedToGather) {
1731 return getGatherCost(E->Scalars);
1737 case Instruction::PHI: {
1740 case Instruction::ExtractValue:
1741 case Instruction::ExtractElement: {
1742 if (canReuseExtract(VL, Opcode)) {
1744 for (
unsigned i = 0, e = VL.
size(); i < e; ++i) {
1751 return ScalarToTreeEntry.count(U) > 0;
1759 return getGatherCost(VecTy);
1761 case Instruction::ZExt:
1762 case Instruction::SExt:
1763 case Instruction::FPToUI:
1764 case Instruction::FPToSI:
1765 case Instruction::FPExt:
1766 case Instruction::PtrToInt:
1767 case Instruction::IntToPtr:
1768 case Instruction::SIToFP:
1769 case Instruction::UIToFP:
1770 case Instruction::Trunc:
1771 case Instruction::FPTrunc:
1772 case Instruction::BitCast: {
1781 return VecCost - ScalarCost;
1783 case Instruction::FCmp:
1784 case Instruction::ICmp:
1791 return VecCost - ScalarCost;
1794 case Instruction::FAdd:
1795 case Instruction::Sub:
1796 case Instruction::FSub:
1797 case Instruction::Mul:
1798 case Instruction::FMul:
1799 case Instruction::UDiv:
1800 case Instruction::SDiv:
1801 case Instruction::FDiv:
1802 case Instruction::URem:
1803 case Instruction::SRem:
1804 case Instruction::FRem:
1805 case Instruction::Shl:
1806 case Instruction::LShr:
1807 case Instruction::AShr:
1808 case Instruction::And:
1809 case Instruction::Or:
1810 case Instruction::Xor: {
1828 for (
unsigned i = 0; i < VL.
size(); ++i) {
1854 Op1VP, Op2VP, Operands);
1855 return VecCost - ScalarCost;
1857 case Instruction::GetElementPtr: {
1869 return VecCost - ScalarCost;
1877 VecTy, alignment, 0, VL0);
1878 return VecLdCost - ScalarLdCost;
1886 VecTy, alignment, 0, VL0);
1887 return VecStCost - ScalarStCost;
1890 CallInst *CI = cast<CallInst>(VL0);
1899 if (
auto *FPMO = dyn_cast<FPMathOperator>(CI))
1900 FMF = FPMO->getFastMathFlags();
1909 DEBUG(
dbgs() <<
"SLP: Call cost "<< VecCallCost - ScalarCallCost
1910 <<
" (" << VecCallCost <<
"-" << ScalarCallCost <<
")"
1911 <<
" for " << *CI <<
"\n");
1913 return VecCallCost - ScalarCallCost;
1915 case Instruction::ShuffleVector: {
1922 for (
Value *i : VL) {
1939 return VecCost - ScalarCost;
1946 bool BoUpSLP::isFullyVectorizableTinyTree() {
1947 DEBUG(
dbgs() <<
"SLP: Check whether the tree with height " <<
1948 VectorizableTree.size() <<
" is fully vectorizable .\n");
1951 if (VectorizableTree.size() == 1 && !VectorizableTree[0].NeedToGather)
1954 if (VectorizableTree.size() != 2)
1958 if (!VectorizableTree[0].NeedToGather &&
1960 isSplat(VectorizableTree[1].Scalars)))
1964 if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1979 if (isFullyVectorizableTinyTree())
1982 assert(VectorizableTree.empty()
1983 ? ExternalUses.
empty()
1984 :
true &&
"We shouldn't have any external users");
1996 unsigned BundleWidth = VectorizableTree.front().Scalars.size();
2002 for (
const auto &
N : VectorizableTree) {
2013 LiveValues.
erase(PrevInst);
2014 for (
auto &J : PrevInst->
operands()) {
2015 if (isa<Instruction>(&*J) && getTreeEntry(&*J))
2016 LiveValues.
insert(cast<Instruction>(&*J));
2020 dbgs() <<
"SLP: #LV: " << LiveValues.
size();
2021 for (
auto *
X : LiveValues)
2022 dbgs() <<
" " <<
X->getName();
2023 dbgs() <<
", Looking at ";
2031 while (InstIt != PrevInstIt) {
2037 if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
2039 for (
auto *II : LiveValues)
2055 DEBUG(
dbgs() <<
"SLP: Calculating cost for tree of size " <<
2056 VectorizableTree.size() <<
".\n");
2058 unsigned BundleWidth = VectorizableTree[0].Scalars.size();
2060 for (TreeEntry &TE : VectorizableTree) {
2061 int C = getEntryCost(&TE);
2062 DEBUG(
dbgs() <<
"SLP: Adding cost " << C <<
" for bundle that starts with "
2063 << *TE.Scalars[0] <<
".\n");
2068 int ExtractCost = 0;
2069 for (ExternalUser &EU : ExternalUses) {
2071 if (!ExtractCostCalculated.
insert(EU.Scalar).second)
2077 if (EphValues.count(EU.User))
2084 auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2085 if (MinBWs.count(ScalarRoot)) {
2088 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
2099 Cost += SpillCost + ExtractCost;
2104 OS <<
"SLP: Spill Cost = " << SpillCost <<
".\n"
2105 <<
"SLP: Extract Cost = " << ExtractCost <<
".\n"
2106 <<
"SLP: Total Cost = " << Cost <<
".\n";
2111 ViewGraph(
this,
"SLP" +
F->getName(),
false, Str);
2116 int BoUpSLP::getGatherCost(
Type *Ty) {
2118 for (
unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
2125 Type *ScalarTy = VL[0]->getType();
2127 ScalarTy =
SI->getValueOperand()->getType();
2130 return getGatherCost(VecTy);
2146 for (
Value *i : VL) {
2147 Left.
push_back(cast<Instruction>(i)->getOperand(0));
2148 Right.
push_back(cast<Instruction>(i)->getOperand(1));
2153 for (
unsigned j = 0; j < VL.size() - 1; ++j) {
2154 if (
LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2155 if (
LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2161 }
else if (VL2->isCommutative() &&
2169 if (
LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2170 if (
LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2176 }
else if (VL2->isCommutative() &&
2196 bool AllSameOpcodeLeft,
2197 bool AllSameOpcodeRight,
bool SplatLeft,
2203 if (VRight == Right[i - 1])
2206 if (VLeft == Right[i - 1]) {
2210 if (SplatLeft && VLeft == Left[i - 1])
2217 if (VLeft == Left[i - 1])
2220 if (VRight == Left[i - 1])
2229 if (AllSameOpcodeRight) {
2230 unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
2231 if (IRight && RightPrevOpcode == IRight->getOpcode())
2234 if (ILeft && RightPrevOpcode == ILeft->
getOpcode()) {
2239 if (AllSameOpcodeLeft && ILeft &&
2246 if (AllSameOpcodeLeft) {
2247 unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
2248 if (ILeft && LeftPrevOpcode == ILeft->
getOpcode())
2250 if (IRight && LeftPrevOpcode == IRight->getOpcode())
2263 auto VLeft = cast<Instruction>(VL[0])->getOperand(0);
2264 auto VRight = cast<Instruction>(VL[0])->getOperand(1);
2265 if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
2273 bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
2274 bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
2276 bool SplatLeft =
true;
2277 bool SplatRight =
true;
2279 for (
unsigned i = 1, e = VL.
size(); i != e; ++i) {
2285 AllSameOpcodeRight, SplatLeft, SplatRight)) {
2293 SplatRight = SplatRight && (Right[i - 1] == Right[i]);
2294 SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
2295 AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
2296 (cast<Instruction>(Left[i - 1])->getOpcode() ==
2297 cast<Instruction>(Left[i])->getOpcode());
2298 AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
2299 (cast<Instruction>(Right[i - 1])->getOpcode() ==
2300 cast<Instruction>(Right[i])->getOpcode());
2304 if (SplatRight || SplatLeft)
2322 for (
unsigned j = 0; j < VL.
size() - 1; ++j) {
2323 if (
LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2324 if (
LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2331 if (
LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2332 if (
LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2347 auto *Front = cast<Instruction>(VL.
front());
2348 auto *BB = Front->getParent();
2350 return cast<Instruction>(V)->
getParent() == BB;
2360 if (BlocksSchedules.count(BB)) {
2361 auto *Bundle = BlocksSchedules[BB]->getScheduleData(VL.
back());
2362 if (Bundle && Bundle->isPartOfBundle())
2363 for (; Bundle; Bundle = Bundle->NextInBundle)
2364 LastInst = Bundle->Inst;
2388 if (Bundle.erase(&I))
2406 if (
Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2407 GatherSeq.insert(Insrt);
2408 CSEBlocks.insert(Insrt->getParent());
2411 if (TreeEntry *E = getTreeEntry(VL[i])) {
2414 for (
unsigned Lane = 0,
LE = VL.
size(); Lane !=
LE; ++Lane) {
2416 if (E->Scalars[Lane] == VL[i]) {
2421 assert(FoundLane >= 0 &&
"Could not find the correct lane");
2422 ExternalUses.
push_back(ExternalUser(VL[i], Insrt, FoundLane));
2431 if (
const TreeEntry *En = getTreeEntry(OpValue)) {
2432 if (En->isSame(VL) && En->VectorizedValue)
2433 return En->VectorizedValue;
2439 if (TreeEntry *E = getTreeEntry(VL[0]))
2443 Type *ScalarTy = VL[0]->getType();
2445 ScalarTy =
SI->getValueOperand()->getType();
2448 return Gather(VL, VecTy);
2454 if (E->VectorizedValue) {
2455 DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *E->Scalars[0] <<
".\n");
2456 return E->VectorizedValue;
2459 Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
2462 ScalarTy =
SI->getValueOperand()->getType();
2465 if (E->NeedToGather) {
2466 setInsertPointAfterBundle(E->Scalars);
2467 auto *V = Gather(E->Scalars, VecTy);
2468 E->VectorizedValue = V;
2475 case Instruction::PHI: {
2480 E->VectorizedValue = NewPhi;
2490 if (!VisitedBBs.
insert(IBB).second) {
2496 for (
Value *V : E->Scalars)
2497 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB));
2506 "Invalid number of incoming values");
2510 case Instruction::ExtractElement: {
2511 if (canReuseExtract(E->Scalars, Instruction::ExtractElement)) {
2513 E->VectorizedValue = V;
2516 setInsertPointAfterBundle(E->Scalars);
2517 auto *V = Gather(E->Scalars, VecTy);
2518 E->VectorizedValue = V;
2521 case Instruction::ExtractValue: {
2522 if (canReuseExtract(E->Scalars, Instruction::ExtractValue)) {
2528 E->VectorizedValue = V;
2531 setInsertPointAfterBundle(E->Scalars);
2532 auto *V = Gather(E->Scalars, VecTy);
2533 E->VectorizedValue = V;
2536 case Instruction::ZExt:
2537 case Instruction::SExt:
2538 case Instruction::FPToUI:
2539 case Instruction::FPToSI:
2540 case Instruction::FPExt:
2541 case Instruction::PtrToInt:
2542 case Instruction::IntToPtr:
2543 case Instruction::SIToFP:
2544 case Instruction::UIToFP:
2545 case Instruction::Trunc:
2546 case Instruction::FPTrunc:
2547 case Instruction::BitCast: {
2549 for (
Value *V : E->Scalars)
2550 INVL.
push_back(cast<Instruction>(V)->getOperand(0));
2552 setInsertPointAfterBundle(E->Scalars);
2556 if (
Value *V = alreadyVectorized(E->Scalars, VL0))
2561 E->VectorizedValue = V;
2562 ++NumVectorInstructions;
2565 case Instruction::FCmp:
2566 case Instruction::ICmp: {
2568 for (
Value *V : E->Scalars) {
2569 LHSV.
push_back(cast<Instruction>(V)->getOperand(0));
2570 RHSV.push_back(cast<Instruction>(V)->getOperand(1));
2573 setInsertPointAfterBundle(E->Scalars);
2578 if (
Value *V = alreadyVectorized(E->Scalars, VL0))
2583 if (Opcode == Instruction::FCmp)
2588 E->VectorizedValue = V;
2590 ++NumVectorInstructions;
2595 for (
Value *V : E->Scalars) {
2596 CondVec.
push_back(cast<Instruction>(V)->getOperand(0));
2597 TrueVec.push_back(cast<Instruction>(V)->getOperand(1));
2598 FalseVec.push_back(cast<Instruction>(V)->getOperand(2));
2601 setInsertPointAfterBundle(E->Scalars);
2607 if (
Value *V = alreadyVectorized(E->Scalars, VL0))
2611 E->VectorizedValue = V;
2612 ++NumVectorInstructions;
2616 case Instruction::FAdd:
2617 case Instruction::Sub:
2618 case Instruction::FSub:
2619 case Instruction::Mul:
2620 case Instruction::FMul:
2621 case Instruction::UDiv:
2622 case Instruction::SDiv:
2623 case Instruction::FDiv:
2624 case Instruction::URem:
2625 case Instruction::SRem:
2626 case Instruction::FRem:
2627 case Instruction::Shl:
2628 case Instruction::LShr:
2629 case Instruction::AShr:
2630 case Instruction::And:
2631 case Instruction::Or:
2632 case Instruction::Xor: {
2635 reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
2637 for (
Value *V : E->Scalars) {
2638 LHSVL.push_back(cast<Instruction>(V)->getOperand(0));
2639 RHSVL.push_back(cast<Instruction>(V)->getOperand(1));
2642 setInsertPointAfterBundle(E->Scalars);
2647 if (
Value *V = alreadyVectorized(E->Scalars, VL0))
2652 E->VectorizedValue = V;
2654 ++NumVectorInstructions;
2664 setInsertPointAfterBundle(E->Scalars);
2666 LoadInst *LI = cast<LoadInst>(VL0);
2677 if (getTreeEntry(PO))
2678 ExternalUses.
push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
2686 E->VectorizedValue = LI;
2687 ++NumVectorInstructions;
2696 for (
Value *V : E->Scalars)
2697 ValueOp.
push_back(cast<StoreInst>(V)->getValueOperand());
2699 setInsertPointAfterBundle(E->Scalars);
2710 if (getTreeEntry(PO))
2711 ExternalUses.
push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
2717 E->VectorizedValue = S;
2718 ++NumVectorInstructions;
2721 case Instruction::GetElementPtr: {
2722 setInsertPointAfterBundle(E->Scalars);
2725 for (
Value *V : E->Scalars)
2726 Op0VL.
push_back(cast<GetElementPtrInst>(V)->getOperand(0));
2730 std::vector<Value *> OpVecs;
2731 for (
int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2734 for (
Value *V : E->Scalars)
2735 OpVL.
push_back(cast<GetElementPtrInst>(V)->getOperand(j));
2738 OpVecs.push_back(OpVec);
2742 cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
2743 E->VectorizedValue = V;
2744 ++NumVectorInstructions;
2752 CallInst *CI = cast<CallInst>(VL0);
2753 setInsertPointAfterBundle(E->Scalars);
2756 Value *ScalarArg =
nullptr;
2760 std::vector<Value *> OpVecs;
2766 CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2771 for (
Value *V : E->Scalars) {
2777 DEBUG(
dbgs() <<
"SLP: OpVec[" << j <<
"]: " << *OpVec <<
"\n");
2778 OpVecs.push_back(OpVec);
2792 if (ScalarArg && getTreeEntry(ScalarArg))
2793 ExternalUses.
push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
2795 E->VectorizedValue = V;
2797 ++NumVectorInstructions;
2800 case Instruction::ShuffleVector: {
2802 assert(isa<BinaryOperator>(VL0) &&
"Invalid Shuffle Vector Operand");
2803 reorderAltShuffleOperands(E->Scalars, LHSVL, RHSVL);
2804 setInsertPointAfterBundle(E->Scalars);
2809 if (
Value *V = alreadyVectorized(E->Scalars, VL0))
2817 Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2825 unsigned e = E->Scalars.size();
2827 for (
unsigned i = 0; i < e; ++i) {
2830 OddScalars.push_back(E->Scalars[i]);
2833 EvenScalars.push_back(E->Scalars[i]);
2842 E->VectorizedValue = V;
2843 ++NumVectorInstructions;
2864 for (
auto &BSIter : BlocksSchedules) {
2865 scheduleBlock(BSIter.second.get());
2874 auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2875 if (MinBWs.count(ScalarRoot)) {
2876 if (
auto *I = dyn_cast<Instruction>(VectorRoot))
2878 auto BundleWidth = VectorizableTree[0].Scalars.size();
2881 auto *Trunc = Builder.
CreateTrunc(VectorRoot, VecTy);
2882 VectorizableTree[0].VectorizedValue = Trunc;
2885 DEBUG(
dbgs() <<
"SLP: Extracting " << ExternalUses.
size() <<
" values .\n");
2889 auto extend = [&](
Value *ScalarRoot,
Value *Ex,
Type *ScalarType) {
2890 if (!MinBWs.count(ScalarRoot))
2892 if (MinBWs[ScalarRoot].
second)
2898 for (
const auto &ExternalUse : ExternalUses) {
2906 TreeEntry *E = getTreeEntry(Scalar);
2907 assert(E &&
"Invalid scalar");
2908 assert(!E->NeedToGather &&
"Extracting from a gather list");
2910 Value *Vec = E->VectorizedValue;
2911 assert(Vec &&
"Can't find vectorizable value");
2919 "Scalar with nullptr as an external user must be registered in "
2920 "ExternallyUsedValues map");
2921 if (
auto *VecI = dyn_cast<Instruction>(Vec)) {
2923 std::next(VecI->getIterator()));
2928 Ex = extend(ScalarRoot, Ex, Scalar->
getType());
2929 CSEBlocks.insert(cast<Instruction>(Scalar)->
getParent());
2930 auto &Locs = ExternallyUsedValues[
Scalar];
2931 ExternallyUsedValues.
insert({Ex, Locs});
2932 ExternallyUsedValues.
erase(Scalar);
2938 if (
auto *VecI = dyn_cast<Instruction>(Vec)) {
2939 if (
PHINode *PH = dyn_cast<PHINode>(User)) {
2944 if (isa<CatchSwitchInst>(IncomingTerminator)) {
2946 std::next(VecI->getIterator()));
2951 Ex = extend(ScalarRoot, Ex, Scalar->
getType());
2959 Ex = extend(ScalarRoot, Ex, Scalar->
getType());
2960 CSEBlocks.insert(cast<Instruction>(User)->
getParent());
2966 Ex = extend(ScalarRoot, Ex, Scalar->
getType());
2967 CSEBlocks.insert(&
F->getEntryBlock());
2971 DEBUG(
dbgs() <<
"SLP: Replaced:" << *User <<
".\n");
2975 for (TreeEntry &EIdx : VectorizableTree) {
2976 TreeEntry *Entry = &EIdx;
2979 for (
int Lane = 0,
LE = Entry->Scalars.size(); Lane !=
LE; ++Lane) {
2982 if (Entry->NeedToGather)
2985 assert(Entry->VectorizedValue &&
"Can't find vectorizable value");
2991 DEBUG(
dbgs() <<
"SLP: \tvalidating user:" << *U <<
".\n");
2993 assert((getTreeEntry(U) ||
2996 "Replacing out-of-tree value with undef");
3002 DEBUG(
dbgs() <<
"SLP: \tErasing scalar:" << *Scalar <<
".\n");
3003 eraseInstruction(cast<Instruction>(Scalar));
3009 return VectorizableTree[0].VectorizedValue;
3013 DEBUG(
dbgs() <<
"SLP: Optimizing " << GatherSeq.size()
3014 <<
" gather sequences instructions.\n");
3037 if (CurrVec && L->
contains(CurrVec))
3039 if (NewElem && L->
contains(NewElem))
3048 CSEWorkList.
reserve(CSEBlocks.size());
3057 std::stable_sort(CSEWorkList.
begin(), CSEWorkList.
end(),
3066 for (
auto I = CSEWorkList.
begin(), E = CSEWorkList.
end(); I !=
E; ++
I) {
3068 "Worklist not sorted properly!");
3073 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(
In))
3082 eraseInstruction(In);
3089 Visited.push_back(In);
3101 if (isa<PHINode>(OpValue))
3106 ScheduleData *PrevInBundle =
nullptr;
3107 ScheduleData *Bundle =
nullptr;
3108 bool ReSchedule =
false;
3109 DEBUG(
dbgs() <<
"SLP: bundle: " << *OpValue <<
"\n");
3113 for (
Value *V : VL) {
3114 if (!extendSchedulingRegion(V))
3118 for (
Value *V : VL) {
3119 ScheduleData *BundleMember = getScheduleData(V);
3121 "no ScheduleData for bundle member (maybe not in same basic block)");
3122 if (BundleMember->IsScheduled) {
3126 DEBUG(
dbgs() <<
"SLP: reset schedule because " << *BundleMember
3127 <<
" was already scheduled\n");
3130 assert(BundleMember->isSchedulingEntity() &&
3131 "bundle member already part of other bundle");
3133 PrevInBundle->NextInBundle = BundleMember;
3135 Bundle = BundleMember;
3137 BundleMember->UnscheduledDepsInBundle = 0;
3138 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
3141 BundleMember->FirstInBundle = Bundle;
3142 PrevInBundle = BundleMember;
3144 if (ScheduleEnd != OldScheduleEnd) {
3150 for (
auto *I = ScheduleStart; I != ScheduleEnd; I = I->
getNextNode()) {
3151 ScheduleData *SD = getScheduleData(I);
3152 SD->clearDependencies();
3158 initialFillReadyList(ReadyInsts);
3161 DEBUG(
dbgs() <<
"SLP: try schedule bundle " << *Bundle <<
" in block "
3162 << BB->getName() <<
"\n");
3164 calculateDependencies(Bundle,
true, SLP);
3170 while (!Bundle->isReady() && !ReadyInsts.empty()) {
3172 ScheduleData *pickedSD = ReadyInsts.back();
3173 ReadyInsts.pop_back();
3175 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
3176 schedule(pickedSD, ReadyInsts);
3179 if (!Bundle->isReady()) {
3180 cancelScheduling(VL, OpValue);
3188 if (isa<PHINode>(OpValue))
3191 ScheduleData *Bundle = getScheduleData(OpValue);
3192 DEBUG(
dbgs() <<
"SLP: cancel scheduling of " << *Bundle <<
"\n");
3193 assert(!Bundle->IsScheduled &&
3194 "Can't cancel bundle which is already scheduled");
3195 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
3196 "tried to unbundle something which is not a bundle");
3199 ScheduleData *BundleMember = Bundle;
3200 while (BundleMember) {
3201 assert(BundleMember->FirstInBundle == Bundle &&
"corrupt bundle links");
3202 BundleMember->FirstInBundle = BundleMember;
3203 ScheduleData *Next = BundleMember->NextInBundle;
3204 BundleMember->NextInBundle =
nullptr;
3205 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
3206 if (BundleMember->UnscheduledDepsInBundle == 0) {
3207 ReadyInsts.insert(BundleMember);
3209 BundleMember = Next;
3213 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(
Value *V) {
3214 if (getScheduleData(V))
3217 assert(I &&
"bundle member must be an instruction");
3218 assert(!isa<PHINode>(I) &&
"phi nodes don't need to be scheduled");
3219 if (!ScheduleStart) {
3221 initScheduleData(I, I->
getNextNode(),
nullptr,
nullptr);
3224 assert(ScheduleEnd &&
"tried to vectorize a TerminatorInst?");
3225 DEBUG(
dbgs() <<
"SLP: initialize schedule region to " << *I <<
"\n");
3236 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
3237 DEBUG(
dbgs() <<
"SLP: exceeded schedule region size limit\n");
3241 if (UpIter != UpperEnd) {
3242 if (&*UpIter == I) {
3243 initScheduleData(I, ScheduleStart,
nullptr, FirstLoadStoreInRegion);
3245 DEBUG(
dbgs() <<
"SLP: extend schedule region start to " << *I <<
"\n");
3250 if (DownIter != LowerEnd) {
3251 if (&*DownIter == I) {
3252 initScheduleData(ScheduleEnd, I->
getNextNode(), LastLoadStoreInRegion,
3255 assert(ScheduleEnd &&
"tried to vectorize a TerminatorInst?");
3256 DEBUG(
dbgs() <<
"SLP: extend schedule region end to " << *I <<
"\n");
3261 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
3262 "instruction not found in block");
3267 void BoUpSLP::BlockScheduling::initScheduleData(
Instruction *FromI,
3269 ScheduleData *PrevLoadStore,
3270 ScheduleData *NextLoadStore) {
3271 ScheduleData *CurrentLoadStore = PrevLoadStore;
3273 ScheduleData *SD = ScheduleDataMap[
I];
3276 if (ChunkPos >= ChunkSize) {
3277 ScheduleDataChunks.push_back(
3281 SD = &(ScheduleDataChunks.back()[ChunkPos++]);
3282 ScheduleDataMap[
I] = SD;
3285 assert(!isInSchedulingRegion(SD) &&
3286 "new ScheduleData already in scheduling region");
3287 SD->init(SchedulingRegionID);
3291 if (CurrentLoadStore) {
3292 CurrentLoadStore->NextLoadStore = SD;
3294 FirstLoadStoreInRegion = SD;
3296 CurrentLoadStore = SD;
3299 if (NextLoadStore) {
3300 if (CurrentLoadStore)
3301 CurrentLoadStore->NextLoadStore = NextLoadStore;
3303 LastLoadStoreInRegion = CurrentLoadStore;
3307 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
3308 bool InsertInReadyList,
3310 assert(SD->isSchedulingEntity());
3315 while (!WorkList.empty()) {
3316 ScheduleData *SD = WorkList.back();
3317 WorkList.pop_back();
3319 ScheduleData *BundleMember = SD;
3320 while (BundleMember) {
3321 assert(isInSchedulingRegion(BundleMember));
3322 if (!BundleMember->hasValidDependencies()) {
3324 DEBUG(
dbgs() <<
"SLP: update deps of " << *BundleMember <<
"\n");
3325 BundleMember->Dependencies = 0;
3326 BundleMember->resetUnscheduledDeps();
3329 for (
User *U : BundleMember->Inst->users()) {
3330 if (isa<Instruction>(U)) {
3331 ScheduleData *UseSD = getScheduleData(U);
3332 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
3333 BundleMember->Dependencies++;
3334 ScheduleData *DestBundle = UseSD->FirstInBundle;
3335 if (!DestBundle->IsScheduled)
3336 BundleMember->incrementUnscheduledDeps(1);
3337 if (!DestBundle->hasValidDependencies())
3338 WorkList.push_back(DestBundle);
3344 BundleMember->Dependencies++;
3345 BundleMember->incrementUnscheduledDeps(1);
3350 ScheduleData *DepDest = BundleMember->NextLoadStore;
3354 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
3355 unsigned numAliased = 0;
3356 unsigned DistToSrc = 1;
3359 assert(isInSchedulingRegion(DepDest));
3369 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
3371 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
3378 DepDest->MemoryDependencies.push_back(BundleMember);
3379 BundleMember->Dependencies++;
3380 ScheduleData *DestBundle = DepDest->FirstInBundle;
3381 if (!DestBundle->IsScheduled) {
3382 BundleMember->incrementUnscheduledDeps(1);
3384 if (!DestBundle->hasValidDependencies()) {
3385 WorkList.push_back(DestBundle);
3388 DepDest = DepDest->NextLoadStore;
3409 BundleMember = BundleMember->NextInBundle;
3411 if (InsertInReadyList && SD->isReady()) {
3412 ReadyInsts.push_back(SD);
3413 DEBUG(
dbgs() <<
"SLP: gets ready on update: " << *SD->Inst <<
"\n");
3418 void BoUpSLP::BlockScheduling::resetSchedule() {
3420 "tried to reset schedule on block which has not been scheduled");
3422 ScheduleData *SD = getScheduleData(I);
3423 assert(isInSchedulingRegion(SD));
3424 SD->IsScheduled =
false;
3425 SD->resetUnscheduledDeps();
3430 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
3432 if (!BS->ScheduleStart)
3435 DEBUG(
dbgs() <<
"SLP: schedule block " << BS->BB->getName() <<
"\n");
3437 BS->resetSchedule();
3442 struct ScheduleDataCompare {
3443 bool operator()(ScheduleData *SD1, ScheduleData *SD2)
const {
3444 return SD2->SchedulingPriority < SD1->SchedulingPriority;
3447 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
3452 int NumToSchedule = 0;
3453 for (
auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
3455 ScheduleData *SD = BS->getScheduleData(I);
3457 SD->isPartOfBundle() == (getTreeEntry(SD->Inst) !=
nullptr) &&
3458 "scheduler and vectorizer have different opinion on what is a bundle");
3459 SD->FirstInBundle->SchedulingPriority = Idx++;
3460 if (SD->isSchedulingEntity()) {
3461 BS->calculateDependencies(SD,
false,
this);
3465 BS->initialFillReadyList(ReadyInsts);
3470 while (!ReadyInsts.empty()) {
3471 ScheduleData *picked = *ReadyInsts.begin();
3472 ReadyInsts.erase(ReadyInsts.begin());
3476 ScheduleData *BundleMember = picked;
3477 while (BundleMember) {
3479 if (LastScheduledInst->
getNextNode() != pickedInst) {
3480 BS->BB->getInstList().remove(pickedInst);
3481 BS->BB->getInstList().insert(LastScheduledInst->
getIterator(),
3484 LastScheduledInst = pickedInst;
3485 BundleMember = BundleMember->NextInBundle;
3488 BS->schedule(picked, ReadyInsts);
3491 assert(NumToSchedule == 0 &&
"could not schedule all instructions");
3494 BS->ScheduleStart =
nullptr;
3500 if (
auto *
Store = dyn_cast<StoreInst>(V))
3509 if (
auto *I = dyn_cast<Instruction>(V))
3515 auto FoundUnknownInst =
false;
3516 while (!Worklist.
empty() && !FoundUnknownInst) {
3523 if (isa<VectorType>(Ty))
3524 FoundUnknownInst =
true;
3528 else if (isa<LoadInst>(I))
3534 else if (isa<PHINode>(I) || isa<CastInst>(
I) || isa<GetElementPtrInst>(I) ||
3535 isa<CmpInst>(
I) || isa<SelectInst>(I) || isa<BinaryOperator>(
I)) {
3537 if (
auto *J = dyn_cast<Instruction>(U.get()))
3538 if (!Visited.
count(J))
3544 FoundUnknownInst =
true;
3549 if (!MaxWidth || FoundUnknownInst)
3564 if (isa<Constant>(V)) {
3579 case Instruction::Trunc:
3581 case Instruction::ZExt:
3582 case Instruction::SExt:
3588 case Instruction::Sub:
3589 case Instruction::Mul:
3590 case Instruction::And:
3591 case Instruction::Or:
3592 case Instruction::Xor:
3609 case Instruction::PHI: {
3630 if (ExternalUses.
empty())
3634 auto &TreeRoot = VectorizableTree[0].Scalars;
3646 for (
auto &EU : ExternalUses)
3647 if (!Expr.erase(EU.Scalar))
3655 for (
auto &Entry : VectorizableTree)
3656 Expr.
insert(Entry.Scalars.begin(), Entry.Scalars.end());
3660 for (
auto *Root : TreeRoot)
3661 if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
3669 for (
auto *Root : TreeRoot)
3676 auto MaxBitWidth = 8u;
3680 for (
auto *Root : TreeRoot) {
3682 MaxBitWidth = std::max<unsigned>(
3683 Mask.getBitWidth() -
Mask.countLeadingZeros(), MaxBitWidth);
3689 bool IsKnownPositive =
true;
3705 IsKnownPositive =
all_of(TreeRoot, [&](
Value *R) {
3712 for (
auto *
Scalar : ToDemote) {
3715 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
3733 if (!IsKnownPositive)
3743 if (MaxBitWidth >= TreeRootIT->getBitWidth())
3749 while (!Roots.
empty())
3753 for (
auto *
Scalar : ToDemote)
3754 MinBWs[
Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
3770 bool doInitialization(
Module &M)
override {
3774 bool runOnFunction(
Function &F)
override {
3775 if (skipFunction(F))
3778 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3779 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3780 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
3781 auto *TLI = TLIP ? &TLIP->getTLI() :
nullptr;
3782 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3783 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3784 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3785 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3786 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
3787 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().
getORE();
3789 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
3822 bool Changed =
runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
3851 bool Changed =
false;
3866 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
3873 collectSeedInstructions(BB);
3876 if (!Stores.empty()) {
3877 DEBUG(
dbgs() <<
"SLP: Found stores for " << Stores.size()
3878 <<
" underlying objects.\n");
3879 Changed |= vectorizeStoreChains(R);
3883 Changed |= vectorizeChainsInBlock(BB, R);
3888 if (!GEPs.empty()) {
3889 DEBUG(
dbgs() <<
"SLP: Found GEPs for " << GEPs.size()
3890 <<
" underlying objects.\n");
3891 Changed |= vectorizeGEPIndices(BB, R);
3896 R.optimizeGatherSequence();
3910 unsigned SliceSize) {
3911 VL = VL.
slice(SliceBegin, SliceSize);
3912 VH = VH.
slice(SliceBegin, SliceSize);
3917 unsigned VecRegSize) {
3918 unsigned ChainLen = Chain.
size();
3919 DEBUG(
dbgs() <<
"SLP: Analyzing a store chain of length " << ChainLen
3922 unsigned VF = VecRegSize / Sz;
3930 bool Changed =
false;
3932 for (
unsigned i = 0, e = ChainLen; i < e; ++i) {
3940 DEBUG(
dbgs() <<
"SLP: Analyzing " << VF <<
" stores at offset " << i
3952 DEBUG(
dbgs() <<
"SLP: Found cost=" << Cost <<
" for VF=" << VF <<
"\n");
3954 DEBUG(
dbgs() <<
"SLP: Decided to vectorize cost=" << Cost <<
"\n");
3955 using namespace ore;
3957 cast<StoreInst>(Chain[i]))
3958 <<
"Stores SLP vectorized with cost " <<
NV(
"Cost", Cost)
3959 <<
" and with tree size "
3981 bool Changed =
false;
3986 for (
unsigned i = 0, e = Stores.
size(); i < e; ++i) {
3993 for (j = i + 1; j < e; ++j)
3995 for (j = i; j > 0; --j)
3998 for (
auto &k : IndexQueue) {
4002 ConsecutiveChain[Stores[i]] = Stores[k];
4011 if (Tails.
count(*it))
4020 if (VectorizedStores.
count(I))
4024 I = ConsecutiveChain[
I];
4031 if (vectorizeStoreChain(Operands, R,
Size)) {
4043 void SLPVectorizerPass::collectSeedInstructions(
BasicBlock *BB) {
4056 if (
auto *SI = dyn_cast<StoreInst>(&I)) {
4067 else if (
auto *
GEP = dyn_cast<GetElementPtrInst>(&I)) {
4068 auto Idx =
GEP->idx_begin()->get();
4069 if (
GEP->getNumIndices() > 1 || isa<Constant>(Idx))
4073 if (
GEP->getType()->isVectorTy())
4084 return tryToVectorizeList(VL, R, None,
true);
4089 bool AllowReorder) {
4093 DEBUG(
dbgs() <<
"SLP: Trying to vectorize a list of length = " << VL.
size()
4109 for (
Value *V : VL) {
4114 if (!Inst || Inst->
getOpcode() != Opcode0)
4118 bool Changed =
false;
4123 unsigned NextInst = 0, MaxInst = VL.
size();
4124 for (
unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
4132 for (
unsigned I = NextInst; I < MaxInst; ++
I) {
4133 unsigned OpsWidth = 0;
4135 if (I + VF > MaxInst)
4136 OpsWidth = MaxInst -
I;
4147 DEBUG(
dbgs() <<
"SLP: Analyzing " << OpsWidth <<
" operations "
4152 if (!BuildVector.
empty())
4153 BuildVectorSlice = BuildVector.
slice(I, OpsWidth);
4164 Value *ReorderedOps[] = {Ops[1], Ops[0]};
4174 DEBUG(
dbgs() <<
"SLP: Vectorizing list at cost:" << Cost <<
".\n");
4176 cast<Instruction>(Ops[0]))
4177 <<
"SLP vectorized with cost " <<
ore::NV(
"Cost", Cost)
4178 <<
" and with tree size "
4187 if (!BuildVectorSlice.
empty()) {
4191 Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.
back());
4192 unsigned VecIdx = 0;
4193 for (
auto &V : BuildVectorSlice) {
4197 assert(isa<InsertElementInst>(I) || isa<InsertValueInst>(I));
4200 VectorizedRoot, Builder.
getInt32(VecIdx++)));
4201 I->setOperand(1, Extract);
4202 I->removeFromParent();
4203 I->insertAfter(Extract);
4227 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() !=
P)
4231 if (tryToVectorizePair(Op0, Op1, R))
4237 if (B && B->hasOneUse()) {
4240 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
4242 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
4250 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
4252 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
4269 bool IsPairwise,
bool IsLeft,
4271 assert((IsPairwise || !IsLeft) &&
"Don't support a <0,1,undef,...> mask");
4278 for (
unsigned i = 0; i != NumEltsToRdx; ++i)
4279 ShuffleMask[i] = Builder.
getInt32(2 * i + !IsLeft);
4282 for (
unsigned i = 0; i != NumEltsToRdx; ++i)
4283 ShuffleMask[i] = Builder.
getInt32(NumEltsToRdx + i);
4316 class HorizontalReduction {
4327 unsigned ReducedValueOpcode = 0;
4330 bool IsPairwiseReduction =
false;
4334 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
4336 if (ExtraArgs.count(ParentStackElem.first)) {
4337 ExtraArgs[ParentStackElem.first] =
nullptr;
4344 ParentStackElem.second = ParentStackElem.first->
getNumOperands();
4348 ExtraArgs[ParentStackElem.first] = ExtraArg;
4353 HorizontalReduction() =
default;
4358 "Thi phi needs to use the binary operator");
4381 ReducedValueOpcode = 0;
4386 ReductionOpcode != Instruction::FAdd) ||
4394 while (!Stack.
empty()) {
4396 unsigned EdgeToVist = Stack.
back().second++;
4397 bool IsReducedValue = TreeN->
getOpcode() != ReductionOpcode;
4400 if (EdgeToVist == 2 || IsReducedValue) {
4402 ReducedVals.push_back(TreeN);
4404 auto I = ExtraArgs.find(TreeN);
4405 if (I != ExtraArgs.end() && !I->second) {
4407 if (Stack.
size() <= 1) {
4415 markExtraArg(Stack[Stack.
size() - 2], TreeN);
4416 ExtraArgs.erase(TreeN);
4418 ReductionOps.push_back(TreeN);
4433 if (I && (!ReducedValueOpcode || I->getOpcode() == ReducedValueOpcode ||
4434 I->getOpcode() == ReductionOpcode)) {
4438 markExtraArg(Stack.
back(),
I);
4444 if (!I->hasOneUse() && I !=
B) {
4446 markExtraArg(Stack.
back(),
I);
4450 if (I->getOpcode() == ReductionOpcode) {
4452 if (!I->isAssociative()) {
4454 markExtraArg(Stack.
back(),
I);
4457 }
else if (ReducedValueOpcode &&
4458 ReducedValueOpcode != I->getOpcode()) {
4462 markExtraArg(Stack.
back(),
I);
4464 }
else if (!ReducedValueOpcode)
4472 markExtraArg(Stack.
back(), NextV);
4480 if (ReducedVals.empty())
4486 unsigned NumReducedVals = ReducedVals.size();
4487 if (NumReducedVals < 4)
4492 Value *VectorizedTree =
nullptr;
4496 Builder.setFastMathFlags(Unsafe);
4502 for (
auto &Pair : ExtraArgs)
4503 ExternallyUsedValues[Pair.second].push_back(Pair.first);
4504 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
4506 V.
buildTree(VL, ExternallyUsedValues, ReductionOps);
4509 V.
buildTree(Reversed, ExternallyUsedValues, ReductionOps);
4518 V.
getTreeCost() + getReductionCost(TTI, ReducedVals[i], ReduxWidth);
4522 DEBUG(
dbgs() <<
"SLP: Vectorizing horizontal reduction at cost:" << Cost
4524 auto *I0 = cast<Instruction>(VL[0]);
4527 <<
"Vectorized horizontal reduction with cost "
4528 <<
ore::NV(
"Cost", Cost) <<
" and with tree size "
4532 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
4536 Value *ReducedSubTree =
4537 emitReduction(VectorizedRoot, Builder, ReduxWidth, ReductionOps, TTI);
4538 if (VectorizedTree) {
4539 Builder.SetCurrentDebugLocation(Loc);
4540 VectorizedTree = Builder.CreateBinOp(ReductionOpcode, VectorizedTree,
4541 ReducedSubTree,
"bin.rdx");
4544 VectorizedTree = ReducedSubTree;
4549 if (VectorizedTree) {
4551 for (; i < NumReducedVals; ++i) {
4552 auto *I = cast<Instruction>(ReducedVals[i]);
4553 Builder.SetCurrentDebugLocation(I->getDebugLoc());
4555 Builder.CreateBinOp(ReductionOpcode, VectorizedTree, I);
4558 for (
auto &Pair : ExternallyUsedValues) {
4559 assert(!Pair.second.empty() &&
4560 "At least one DebugLoc must be inserted");
4562 for (
auto *I : Pair.second) {
4563 Builder.SetCurrentDebugLocation(I->getDebugLoc());
4564 VectorizedTree = Builder.CreateBinOp(ReductionOpcode, VectorizedTree,
4565 Pair.first,
"bin.extra");
4570 ReductionRoot->replaceAllUsesWith(VectorizedTree);
4572 return VectorizedTree !=
nullptr;
4575 unsigned numReductionValues()
const {
4576 return ReducedVals.size();
4582 unsigned ReduxWidth) {
4587 int SplittingRdxCost = TTI->
getReductionCost(ReductionOpcode, VecTy,
false);
4589 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
4590 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
4592 int ScalarReduxCost =
4596 DEBUG(
dbgs() <<
"SLP: Adding cost " << VecReduxCost - ScalarReduxCost
4597 <<
" for reduction that starts with " << *FirstReducedVal
4599 << (IsPairwiseReduction ?
"pairwise" :
"splitting")
4600 <<
" reduction)\n");
4602 return VecReduxCost - ScalarReduxCost;
4609 assert(VectorizedValue &&
"Need to have a vectorized tree node");
4611 "We only handle power-of-two reductions for now");
4613 if (!IsPairwiseReduction)
4615 Builder, TTI, ReductionOpcode, VectorizedValue,
4618 Value *TmpVec = VectorizedValue;
4619 for (
unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
4631 Builder.
CreateBinOp(ReductionOpcode, LeftShuf, RightShuf,
"bin.rdx");
4652 if (!isa<UndefValue>(FirstInsertElem->
getOperand(0)))
4689 if (isa<UndefValue>(V))
4716 auto DominatedReduxValue = [&](
Value *R) {
4718 dyn_cast<Instruction>(R) &&
4722 Value *Rdx =
nullptr;
4731 if (Rdx && DominatedReduxValue(Rdx))
4750 if (Rdx && DominatedReduxValue(Rdx))
4791 while (!Stack.
empty()) {
4798 if (!Inst || isa<PHINode>(Inst))
4800 if (
auto *BI = dyn_cast<BinaryOperator>(Inst)) {
4801 HorizontalReduction HorRdx;
4802 if (HorRdx.matchAssociativeReduction(P, BI)) {
4803 if (HorRdx.tryToReduce(R, TTI)) {
4826 if (Vectorize(dyn_cast<BinaryOperator>(Inst), R)) {
4839 bool SLPVectorizerPass::vectorizeRootInstruction(
PHINode *P,
Value *V,
4848 if (!isa<BinaryOperator>(I))
4853 return tryToVectorize(BI, R);
4858 bool Changed =
false;
4862 bool HaveVectorizedPhiNodes =
true;
4863 while (HaveVectorizedPhiNodes) {
4864 HaveVectorizedPhiNodes =
false;
4873 if (!VisitedInstrs.
count(P))
4887 while (SameTypeIt != E &&
4888 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
4889 VisitedInstrs.
insert(*SameTypeIt);
4894 unsigned NumElts = (SameTypeIt - IncIt);
4895 DEBUG(
errs() <<
"SLP: Trying to vectorize starting at PHIs (" << NumElts <<
")\n");
4900 bool AllowReorder = NumElts == 2;
4901 if (NumElts > 1 && tryToVectorizeList(
makeArrayRef(IncIt, NumElts), R,
4902 None, AllowReorder)) {
4904 HaveVectorizedPhiNodes =
true;
4914 VisitedInstrs.
clear();
4918 if (!VisitedInstrs.
insert(&*it).second)
4921 if (isa<DbgInfoIntrinsic>(it))
4925 if (
PHINode *P = dyn_cast<PHINode>(it)) {
4942 if (
StoreInst *SI = dyn_cast<StoreInst>(it)) {
4955 if (
ReturnInst *RI = dyn_cast<ReturnInst>(it)) {
4956 if (RI->getNumOperands() != 0) {
4958 if (vectorizeRootInstruction(
nullptr, RI->getOperand(0), BB, R, TTI)) {
4968 if (
CmpInst *CI = dyn_cast<CmpInst>(it)) {
4978 for (
int I = 0; I < 2; ++
I) {
4979 if (vectorizeRootInstruction(
nullptr, CI->
getOperand(I), BB, R, TTI)) {
5001 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
5012 if (
StoreInst *SI = dyn_cast<StoreInst>(it)) {
5014 const DataLayout &DL = BB->getModule()->getDataLayout();
5021 DEBUG(
dbgs() <<
"SLP: store of array mappable to vector: " << *SI <<
"\n");
5022 if (tryToVectorizeList(BuildVectorOpds, R, BuildVector,
false)) {
5037 auto Changed =
false;
5038 for (
auto &Entry : GEPs) {
5042 if (Entry.second.size() < 2)
5045 DEBUG(
dbgs() <<
"SLP: Analyzing a getelementptr list of length "
5046 << Entry.second.size() <<
".\n");
5050 for (
unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
5051 auto Len = std::min<unsigned>(BE - BI, 16);
5064 Candidates.
remove(
nullptr);
5071 for (
int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++
I) {
5072 auto *GEPI = cast<GetElementPtrInst>(GEPList[
I]);
5073 if (!Candidates.count(GEPI))
5075 auto *SCEVI = SE->
getSCEV(GEPList[I]);
5076 for (
int J = I + 1; J < E && Candidates.size() > 1; ++J) {
5077 auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
5078 auto *SCEVJ = SE->
getSCEV(GEPList[J]);
5079 if (isa<SCEVConstant>(SE->
getMinusSCEV(SCEVI, SCEVJ))) {
5080 Candidates.remove(GEPList[I]);
5081 Candidates.remove(GEPList[J]);
5082 }
else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
5083 Candidates.remove(GEPList[J]);
5090 if (Candidates.size() < 2)
5097 auto BundleIndex = 0u;
5098 for (
auto *V : Candidates) {
5099 auto *
GEP = cast<GetElementPtrInst>(V);
5100 auto *GEPIdx =
GEP->idx_begin()->get();
5101 assert(
GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
5102 Bundle[BundleIndex++] = GEPIdx;
5114 Changed |= tryToVectorizeList(Bundle, R);
5120 bool SLPVectorizerPass::vectorizeStoreChains(
BoUpSLP &R) {
5121 bool Changed =
false;
5123 for (StoreListMap::iterator it = Stores.
begin(), e = Stores.
end(); it != e;
5125 if (it->second.size() < 2)
5128 DEBUG(
dbgs() <<
"SLP: Analyzing a store chain of length "
5129 << it->second.size() <<
".\n");
5135 for (
unsigned CI = 0, CE = it->second.size(); CI <
CE; CI+=16) {
5136 unsigned Len = std::min<unsigned>(CE - CI, 16);
5137 Changed |= vectorizeStores(
makeArrayRef(&it->second[CI], Len), R);
Legacy wrapper pass to provide the GlobalsAAResult object.
Pass interface - Implemented by all 'passes'.
static unsigned getSameOpcode(ArrayRef< Value * > VL)
static cl::opt< bool > ViewSLPTree("view-slp-tree", cl::Hidden, cl::desc("Display the SLP trees with Graphviz"))
Return a value (possibly void), from a function.
Value * getValueOperand()
static std::string getNodeAttributes(const TreeEntry *Entry, const BoUpSLP *)
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
static bool canCombineAsAltInst(unsigned Op)
This class is the base class for the comparison instructions.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
SmallPtrSet< Value *, 16 > ValueSet
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Value * getAggregateOperand()
DiagnosticInfoOptimizationBase::Argument NV
void dropAllReferences()
Drop all references to operands.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
STATISTIC(NumFunctions,"Total number of functions")
OptimizationRemarkEmitter * getORE()
This is the interface for a simple mod/ref and alias analysis over globals.
static bool allSameBlock(ArrayRef< Value * > VL)
A Module instance is used to store all the information related to an LLVM module. ...
bool hasNUses(unsigned N) const
Return true if this Value has exactly N users.
const T & front() const
front - Get the first element.
static Value * getReductionValue(const DominatorTree *DT, PHINode *P, BasicBlock *ParentBB, LoopInfo *LI)
Try and get a reduction value from a phi node.
unsigned getNumOperands() const
static bool tryToVectorizeHorReductionOrInstOperands(PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, TargetTransformInfo *TTI, const function_ref< bool(BinaryOperator *, BoUpSLP &)> Vectorize)
Attempt to reduce a horizontal reduction.
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)
The main scalar evolution driver.
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
ilist_iterator< OptionsT,!IsReverse, IsConst > getReverse() const
Get a reverse iterator to the same node.
This class represents a function call, abstracting a target machine's calling convention.
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...
An efficient, type-erasing, non-owning reference to a callable.
static const unsigned MaxMemDepDistance
A cache of .assume calls within a function.
Analysis pass providing the TargetTransformInfo.
static cl::opt< int > SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden, cl::desc("Only vectorize if you gain more than this ""number "))
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...
static bool findBuildVector(InsertElementInst *FirstInsertElem, SmallVectorImpl< Value * > &BuildVector, SmallVectorImpl< Value * > &BuildVectorOpds)
Recognize construction of vectors like ra = insertelement <4 x float> undef, float s0...
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
reverse_iterator rbegin()
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
DOTGraphTraits(bool isSimple=false)
void reserve(size_type N)
iterator end()
Get an iterator to the end of the SetVector.
uint64_t getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
StringRef getName() const
Return a constant reference to the value's name.
Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
iterator begin()
Instruction iterator methods.
SmallVector< Instruction *, 16 > InstrList
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
static nodes_iterator nodes_end(BoUpSLP *R)
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...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
static uint32_t getAlignment(const MCSectionCOFF &Sec)
bool isNonNegative() const
Returns true if this value is known to be non-negative.
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"))
This class represents the LLVM 'select' instruction.
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
This is the base class for all instructions that perform data casts.
const APInt & getValue() const
Return the constant as an APInt value reference.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Class to represent struct types.
bool isTreeTinyAndNotFullyVectorizable()
A Use represents the edge between a Value definition and its users.
Value * vectorizeTree()
Vectorize the tree that starts with the elements in VL.
Value * createSimpleTargetReduction(IRBuilder<> &B, const TargetTransformInfo *TTI, unsigned Opcode, Value *Src, TargetTransformInfo::ReductionFlags Flags=TargetTransformInfo::ReductionFlags(), ArrayRef< Value * > RedOps=ArrayRef< Value * >())
Create a target reduction of the given vector.
static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter)
unsigned getNumArgOperands() const
Return the number of call arguments.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
static Constant * get(ArrayRef< Constant * > V)
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)
Windows NT (Windows on ARM)
static const unsigned AliasedCheckLimit
Analysis pass that exposes the LoopInfo for a function.
static bool allConstant(ArrayRef< Value * > VL)
bool remove(const value_type &X)
Remove an item from the set vector.
static bool shouldReorderOperands(int i, Instruction &I, SmallVectorImpl< Value * > &Left, SmallVectorImpl< Value * > &Right, bool AllSameOpcodeLeft, bool AllSameOpcodeRight, bool SplatLeft, bool SplatRight)
LLVM_NODISCARD bool empty() const
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
static ChildIteratorType child_end(NodeRef N)
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
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()))
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
bool insert(const value_type &X)
Insert a new element into the SetVector.
static unsigned isAltInst(ArrayRef< Value * > VL)
const T & getValue() const LLVM_LVALUE_FUNCTION
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
void ClearInsertionPoint()
Clear the insertion point: created instructions will not be inserted into a block.
iterator begin()
Get an iterator to the beginning of the SetVector.
void insert(ScheduleData *SD)
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
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...
Value * getInsertedValueOperand()
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
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.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
iterator find(const KeyT &Key)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
size_t size() const
size - Get the array size.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Class to represent pointers.
static bool collectValuesToDemote(Value *V, SmallPtrSetImpl< Value * > &Expr, SmallVectorImpl< Value * > &ToDemote, SmallVectorImpl< Value * > &Roots)
bool mayReadOrWriteMemory() const
Return true if this instruction may read or write memory.
unsigned getTreeSize() const
void optimizeGatherSequence()
Perform LICM and CSE on the newly generated gather sequences.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
static ChildIteratorType child_begin(NodeRef N)
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
Value * CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
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.
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Function Alias Analysis false
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...
unsigned getAlignment() const
Return the alignment of the access that is being performed.
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.
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"))
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
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...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
SmallVector< Value *, 8 > ValueList
CRTP base class for adapting an iterator to a different type.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
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.
A manager for alias analyses.
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::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
unsigned getVectorElementSize(Value *V)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
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.)
static bool findBuildAggregate(InsertValueInst *IV, SmallVectorImpl< Value * > &BuildVector, SmallVectorImpl< Value * > &BuildVectorOpds)
Like findBuildVector, but looks backwards for construction of aggregate.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
void buildTree(ArrayRef< Value * > Roots, ArrayRef< Value * > UserIgnoreLst=None)
Construct a vectorizable tree that starts at Roots, ignoring users for the purpose of scheduling and ...
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
Analysis pass providing a never-invalidated alias analysis result.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
uint64_t getNumElements() const
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
Value * getPointerOperand()
bool isCommutative() const
Return true if the instruction is commutative:
iterator_range< po_iterator< T > > post_order(const T &G)
self_iterator getIterator()
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.
Predicate getPredicate() const
Return the predicate for this instruction.
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
bool empty() const
empty - Check if the array is empty.
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
void setAlignment(unsigned Align)
unsigned getMinVecRegSize() const
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.
static wasm::ValType getType(const TargetRegisterClass *RC)
const Value * getTrueValue() const
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
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...
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
const T & back() const
back - Get the last element.
void dump() const
Support for debugging, callable in GDB: V->dump()
ChildIteratorType(SmallVector< int, 1 >::iterator W, std::vector< TreeEntry > &VT)
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
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.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Representation for a specific memory location.
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.
BinaryOps getOpcode() const
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
typename vector_type::const_iterator iterator
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
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...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Value * CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx, const Twine &Name="")
Provides information about what library functions are available for the current target.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
static bool matchExtractIndex(Instruction *E, unsigned Idx, unsigned Opcode)
User(Type *ty, unsigned vty, Use *, unsigned NumOps)
unsigned getBundleOperandsStartIndex() const
Return the index of the first bundle operand in the Use array.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
LLVM_NODISCARD T pop_back_val()
SmallVector< StoreInst *, 8 > StoreList
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="")
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
const BasicBlock & getEntryBlock() const
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
bool hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, unsigned ScalarOpdIdx)
Identifies if the intrinsic has a scalar operand.
APInt getDemandedBits(Instruction *I)
Return the bits demanded from instruction I.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
BoUpSLP::TreeEntry TreeEntry
Value * CreateGEP(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Class to represent vector types.
size_type count(const KeyT &Key) const
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...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
iterator_range< user_iterator > users()
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
InstListType::iterator iterator
Instruction iterators...
Represents analyses that only rely on functions' control flow.
static void clear(coro::Shape &Shape)
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.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
llvm_unreachable("Unknown RegBank!")
Analysis pass that exposes the ScalarEvolution for a function.
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
static unsigned size(BoUpSLP *R)
bool isX86_FP80Ty() const
Return true if this is x86 long double.
void emplace_back(ArgTypes &&...Args)
void initializeSLPVectorizerPass(PassRegistry &)
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
MapVector< Value *, SmallVector< Instruction *, 2 > > ExtraValueToDebugLocsMap
Represents a single loop in the control flow graph.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
void preserveSet()
Mark an analysis set as preserved.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
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.
CallInst * CreateCall(Value *Callee, ArrayRef< Value * > Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
iterator_range< value_op_iterator > operand_values()
friend raw_ostream & operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD)
unsigned getMaxVecRegSize() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
std::vector< TreeEntry > & VectorizableTree
void preserve()
Mark an analysis as preserved.
bool shouldReorder() const
static cl::opt< bool > ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden, cl::desc("Attempt to vectorize horizontal reductions"))
unsigned getBundleOperandsEndIndex() const
Return the index of the last bundle operand in the Use array.
static bool isSplat(ArrayRef< Value * > VL)
Pass * createSLPVectorizerPass()
unsigned canMapToVector(Type *T, const DataLayout &DL) const
Check if ArrayType or StructType is isomorphic to some VectorType.
Analysis pass providing the TargetLibraryInfo.
iterator_range< op_iterator > arg_operands()
Iteration adapter for range-for loops.
static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA)
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
static NodeRef getEntryNode(BoUpSLP &R)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
static const char lv_name[]
static bool PhiTypeSorterFunc(Value *V, Value *V2)
LoadInst * CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name)
A raw_ostream that writes to an std::string.
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)
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
A vector that has set insertion semantics.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
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 moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
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.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
TreeEntry * NodeRef
NodeRef has to be a pointer per the GraphWriter.
const Value * getFalseValue() const
Convenience struct for specifying and reasoning about fast-math flags.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
void deleteTree()
Clear the internal data structures that are created by 'buildTree'.
void computeMinimumValueSizes()
Compute the minimum type sizes required to represent the entries in a vectorizable tree...
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...
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)...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
op_range incoming_values()
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"))
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 bool isOdd(unsigned Value)
true if the Value is odd, false otherwise.
const BasicBlock * getParent() const
BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li, DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB, const DataLayout *DL, OptimizationRemarkEmitter *ORE)
pointer_iterator< std::vector< TreeEntry >::iterator > nodes_iterator
For the node iterator we just need to turn the TreeEntry iterator into a TreeEntry* iterator so that ...
Instruction * propagateMetadata(Instruction *I, ArrayRef< Value * > VL)
Specifically, let Kinds = [MD_tbaa, MD_alias_scope, MD_noalias, MD_fpmath, MD_nontemporal].
bool isVoidTy() const
Return true if this is 'void'.
This instruction inserts a struct field of array element value into an aggregate value.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
BoUpSLP::TreeEntry TreeEntry
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.
static bool allSameType(ArrayRef< Value * > VL)
static unsigned getAltOpcode(unsigned Op)