llvm.org GIT mirror llvm / 48fd38c
[STLExtras] Add distance() for ranges, pred_size(), and succ_size() This commit adds a wrapper for std::distance() which works with ranges. As it would be a common case to write `distance(predecessors(BB))`, this also introduces `pred_size()` and `succ_size()` helpers to make that easier to write. Differential Revision: https://reviews.llvm.org/D46668 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@332057 91177308-0d34-0410-b5e6-96231b3b80d8 Vedant Kumar 2 years ago
24 changed file(s) with 55 addition(s) and 53 deletion(s). Raw diff Collapse all Expand all
10251025 C.erase(remove_if(C, P), C.end());
10261026 }
10271027
1028 /// Wrapper function around std::distance which works with ranges.
1029 template
1030 auto distance(R &&Range)
1031 -> decltype(std::distance(Range.begin(), Range.end())) {
1032 return std::distance(Range.begin(), Range.end());
1033 }
1034
10281035 //===----------------------------------------------------------------------===//
10291036 // Extra additions to
10301037 //===----------------------------------------------------------------------===//
106106 inline bool pred_empty(const BasicBlock *BB) {
107107 return pred_begin(BB) == pred_end(BB);
108108 }
109 inline unsigned pred_size(const BasicBlock *BB) {
110 return std::distance(pred_begin(BB), pred_end(BB));
111 }
109112 inline pred_range predecessors(BasicBlock *BB) {
110113 return pred_range(pred_begin(BB), pred_end(BB));
111114 }
139142 inline bool succ_empty(const BasicBlock *BB) {
140143 return succ_begin(BB) == succ_end(BB);
141144 }
145 inline unsigned succ_size(const BasicBlock *BB) {
146 return std::distance(succ_begin(BB), succ_end(BB));
147 }
142148 inline succ_range successors(BasicBlock *BB) {
143149 return succ_range(succ_begin(BB), succ_end(BB));
144150 }
872872 if (I != Probs.end())
873873 return I->second;
874874
875 return {1,
876 static_cast(std::distance(succ_begin(Src), succ_end(Src)))};
875 return {1, static_cast(succ_size(Src))};
877876 }
878877
879878 BranchProbability
12711271 // the removal hasn't changed the structure at all. This is an important
12721272 // special case and we can directly exit the entire routine more
12731273 // efficiently as soon as we discover it.
1274 if (std::distance(RefSCCNodes.begin(), RefSCCNodes.end()) ==
1275 NumRefSCCNodes) {
1274 if (distance(RefSCCNodes) == NumRefSCCNodes) {
12761275 // Clear out the low link field as we won't need it.
12771276 for (Node *N : RefSCCNodes)
12781277 N->LowLink = -1;
17381737 }
17391738
17401739 static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C) {
1741 ptrdiff_t Size = std::distance(C.begin(), C.end());
1740 ptrdiff_t Size = distance(C);
17421741 OS << " SCC with " << Size << " functions:\n";
17431742
17441743 for (LazyCallGraph::Node &N : C)
17461745 }
17471746
17481747 static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C) {
1749 ptrdiff_t Size = std::distance(C.begin(), C.end());
1748 ptrdiff_t Size = distance(C);
17501749 OS << " RefSCC with " << Size << " call SCCs:\n";
17511750
17521751 for (LazyCallGraph::SCC &InnerC : C)
416416 // If a terminator has more then two successors, for example SwitchInst,
417417 // then it is possible that there are multiple edges from current block
418418 // to one exit block.
419 if (std::distance(succ_begin(BB), succ_end(BB)) <= 2) {
419 if (succ_size(BB) <= 2) {
420420 ExitBlocks.push_back(Successor);
421421 continue;
422422 }
67556755 if (NumUses < 2)
67566756 return Error(Loc, "value only has one use");
67576757 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6758 return Error(Loc, "wrong number of indexes, expected " +
6759 Twine(std::distance(V->use_begin(), V->use_end())));
6758 return Error(Loc,
6759 "wrong number of indexes, expected " + Twine(V->getNumUses()));
67606760
67616761 V->sortUseList([&](const Use &L, const Use &R) {
67626762 return Order.lookup(&L) < Order.lookup(&R);
488488 V->print(errs());
489489 errs() << '\n';
490490
491 OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
491 OS << " Uses(" << V->getNumUses() << "):";
492492 for (const Use &U : V->uses()) {
493493 if (&U != &*V->use_begin())
494494 OS << ",";
30933093 Instruction *CurrentI = cast(CurrentValue);
30943094 bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
30953095
3096 unsigned PredCount =
3097 std::distance(pred_begin(CurrentBlock), pred_end(CurrentBlock));
3096 unsigned PredCount = pred_size(CurrentBlock);
30983097 // if Current Value is not defined in this basic block we are interested
30993098 // in values in predecessors.
31003099 if (!IsDefinedInThisBB) {
596596 unsigned DefReg = NoRegister;
597597 if (NumDefs != 0) {
598598 DefReg = MI->defs().begin()->getReg();
599 assert(std::distance(MI->defs().begin(), MI->defs().end()) == 1 &&
600 "expected exactly one def!");
599 assert(distance(MI->defs()) == 1 && "expected exactly one def!");
601600 }
602601
603602 FaultMaps::FaultKind FK;
16991699 if (!BPI) {
17001700 // If BPI is not available, set the default probability as 1 / N, where N is
17011701 // the number of successors.
1702 auto SuccSize = std::max(
1703 std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1);
1702 auto SuccSize = std::max(succ_size(SrcBB), 1);
17041703 return BranchProbability(1, SuccSize);
17051704 }
17061705 return BPI->getEdgeProbability(SrcBB, DstBB);
166166 return false;
167167 }
168168
169 unsigned Value::getNumUses() const {
170 return (unsigned)std::distance(use_begin(), use_end());
171 }
169 unsigned Value::getNumUses() const { return (unsigned)distance(uses()); }
172170
173171 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
174172 ST = nullptr;
253253 const PPCSubtarget *ST =
254254 TM ? TM->getSubtargetImpl(*Header->getParent()) : nullptr;
255255
256 unsigned HeaderLoopPredCount =
257 std::distance(pred_begin(Header), pred_end(Header));
256 unsigned HeaderLoopPredCount = pred_size(Header);
258257
259258 // Collect buckets of comparable addresses used by loads and stores.
260259 SmallVector Buckets;
402402
403403 auto IsSingleEntry = [](SmallVectorImpl &BlockList) {
404404 BasicBlock *Dom = BlockList.front();
405 return BlockList.size() > 1 &&
406 std::distance(pred_begin(Dom), pred_end(Dom)) == 1;
405 return BlockList.size() > 1 && pred_size(Dom) == 1;
407406 };
408407
409408 auto IsSingleExit =
555554 return is_contained(successors(BB), Succ);
556555 };
557556
558 auto SuccSize = [](BasicBlock *BB) {
559 return std::distance(succ_begin(BB), succ_end(BB));
560 };
561
562557 auto IsReturnBlock = [](BasicBlock *BB) {
563558 TerminatorInst *TI = BB->getTerminator();
564559 return isa(TI);
595590 if (OutliningInfo->GetNumInlinedBlocks() >= MaxNumInlineBlocks)
596591 break;
597592
598 if (SuccSize(CurrEntry) != 2)
593 if (succ_size(CurrEntry) != 2)
599594 break;
600595
601596 BasicBlock *Succ1 = *succ_begin(CurrEntry);
669664 // peeling off dominating blocks from the outlining region:
670665 while (OutliningInfo->GetNumInlinedBlocks() < MaxNumInlineBlocks) {
671666 BasicBlock *Cand = OutliningInfo->NonReturnBlock;
672 if (SuccSize(Cand) != 2)
667 if (succ_size(Cand) != 2)
673668 break;
674669
675670 if (HasNonEntryPred(Cand))
577577
578578 // Returns true when the values are flowing out to each edge.
579579 bool valueAnticipable(CHIArgs C, TerminatorInst *TI) const {
580 if (TI->getNumSuccessors() > (unsigned)std::distance(C.begin(), C.end()))
580 if (TI->getNumSuccessors() > (unsigned)distance(C))
581581 return false; // Not enough args in this CHI.
582582
583583 for (auto CHI : C) {
944944 unsigned MinSucc = 0;
945945 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
946946 // Compute the successor with the minimum number of predecessors.
947 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
947 unsigned MinNumPreds = pred_size(TestBB);
948948 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
949949 TestBB = BBTerm->getSuccessor(i);
950 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
950 unsigned NumPreds = pred_size(TestBB);
951951 if (NumPreds < MinNumPreds) {
952952 MinSucc = i;
953953 MinNumPreds = NumPreds;
16471647 // not thread. By doing so, we do not need to duplicate the current block and
16481648 // also miss potential opportunities in case we dont/cant duplicate.
16491649 if (OnlyDest && OnlyDest != MultipleDestSentinel) {
1650 if (PredWithKnownDest ==
1651 (size_t)std::distance(pred_begin(BB), pred_end(BB))) {
1650 if (PredWithKnownDest == (size_t)pred_size(BB)) {
16521651 bool SeenFirstBranchToOnlyDest = false;
16531652 std::vector Updates;
16541653 Updates.reserve(BB->getTerminator()->getNumSuccessors() - 1);
284284 return false; // No. More than 2 predecessors.
285285
286286 // #Instructions in Succ1 for Compile Time Control
287 int Size1 = std::distance(Pred1->instructionsWithoutDebug().begin(),
288 Pred1->instructionsWithoutDebug().end());
287 int Size1 = distance(Pred1->instructionsWithoutDebug());
289288 int NStores = 0;
290289
291290 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
965965 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
966966 if (isa(I)) {
967967 BasicBlock *BB = I->getParent();
968 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
968 int NumPreds = pred_size(BB);
969969 assert(NumPreds > 0 && "how did we reach here");
970970 std::string Name = suffixed_name_or(I, ".base", "base_phi");
971971 return PHINode::Create(I->getType(), NumPreds, Name, I);
18101810
18111811 SmallVector Uses;
18121812 // PERF: trade a linear scan for repeated reallocation
1813 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1813 Uses.reserve(Def->getNumUses());
18141814 for (User *U : Def->users()) {
18151815 if (!isa(U)) {
18161816 // If the def has a ConstantExpr use, then the def is either a
537537 // phi nodes will have invalid entries. Update the PHI nodes in this
538538 // case.
539539 PHINode *PN = cast(NewBB->begin());
540 NumPreds = std::distance(pred_begin(NewBB), pred_end(NewBB));
540 NumPreds = pred_size(NewBB);
541541 if (NumPreds != PN->getNumIncomingValues()) {
542542 assert(NumPreds < PN->getNumIncomingValues());
543543 // Count how many times each predecessor comes to this block.
668668 // dominator edges will be redirected to DestBB.
669669 std::vector Updates;
670670 if (DDT && !ReplaceEntryBB) {
671 Updates.reserve(1 +
672 (2 * std::distance(pred_begin(PredBB), pred_end(PredBB))));
671 Updates.reserve(1 + (2 * pred_size(PredBB)));
673672 Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
674673 for (auto I = pred_begin(PredBB), E = pred_end(PredBB); I != E; ++I) {
675674 Updates.push_back({DominatorTree::Delete, *I, PredBB});
974973
975974 std::vector Updates;
976975 if (DDT) {
977 Updates.reserve(1 + (2 * std::distance(pred_begin(BB), pred_end(BB))));
976 Updates.reserve(1 + (2 * pred_size(BB)));
978977 Updates.push_back({DominatorTree::Delete, BB, Succ});
979978 // All predecessors of BB will be moved to Succ.
980979 for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
294294 unsigned getNumPreds(const BasicBlock *BB) {
295295 unsigned &NP = BBNumPreds[BB];
296296 if (NP == 0)
297 NP = std::distance(pred_begin(BB), pred_end(BB)) + 1;
297 NP = pred_size(BB) + 1;
298298 return NP - 1;
299299 }
300300
687687 if (SwitchInst *SI = dyn_cast(TI)) {
688688 // Do not permit merging of large switch instructions into their
689689 // predecessors unless there is only one predecessor.
690 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
691 pred_end(SI->getParent())) <=
692 128)
690 if (SI->getNumSuccessors() * pred_size(SI->getParent()) <= 128)
693691 CV = SI->getCondition();
694692 } else if (BranchInst *BI = dyn_cast(TI))
695693 if (BI->isConditional() && BI->getCondition()->hasOneUse())
28702868 if (!AlternativeV)
28712869 break;
28722870
2873 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2871 assert(pred_size(Succ) == 2);
28742872 auto PredI = pred_begin(Succ);
28752873 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
28762874 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
57515749 // backedge, so we can eliminate BB.
57525750 bool NeedCanonicalLoop =
57535751 Options.NeedCanonicalLoop &&
5754 (LoopHeaders && std::distance(pred_begin(BB), pred_end(BB)) > 1 &&
5752 (LoopHeaders && pred_size(BB) > 1 &&
57555753 (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
57565754 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
57575755 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
355355 "One successor of a basic block does not lead to the other.");
356356 assert(InterimSucc->getSinglePredecessor() &&
357357 "Interim successor has more than one predecessor.");
358 assert(std::distance(pred_begin(PostDomSucc), pred_end(PostDomSucc)) == 2 &&
358 assert(pred_size(PostDomSucc) == 2 &&
359359 "PostDom successor has more than two predecessors.");
360360 DT->addNewBlock(InterimSucc, BB);
361361 DT->addNewBlock(PostDomSucc, BB);
364364 EXPECT_TRUE(all_of(ascending, [](unsigned n) { return (n & 0x01) == 0; }));
365365 }
366366
367 TEST(RangeTest, Distance) {
368 std::vector v1;
369 std::vector v2{1, 2, 3};
370
371 EXPECT_EQ(std::distance(v1.begin(), v1.end()), distance(v1));
372 EXPECT_EQ(std::distance(v2.begin(), v2.end()), distance(v2));
373 }
374
367375 } // anonymous namespace
7272 auto isPhi = [](Instruction &I) { return isa(&I); };
7373 auto Phis = make_filter_range(*BB, isPhi);
7474 auto ReversedPhis = reverse(make_filter_range(*BB, isPhi));
75 EXPECT_EQ(std::distance(Phis.begin(), Phis.end()), 3);
75 EXPECT_EQ(distance(Phis), 3);
7676 EXPECT_EQ(&*Phis.begin(), P1);
77 EXPECT_EQ(std::distance(ReversedPhis.begin(), ReversedPhis.end()), 3);
77 EXPECT_EQ(distance(ReversedPhis), 3);
7878 EXPECT_EQ(&*ReversedPhis.begin(), P3);
7979
8080 // And iterate a const range.
8686 }
8787
8888 #define CHECK_ITERATORS(Range1, Range2) \
89 EXPECT_EQ(std::distance(Range1.begin(), Range1.end()), \
90 std::distance(Range2.begin(), Range2.end())); \
89 EXPECT_EQ(distance(Range1), distance(Range2)); \
9190 for (auto Pair : zip(Range1, Range2)) \
9291 EXPECT_EQ(&std::get<0>(Pair), std::get<1>(Pair));
9392