Skip to content

Add llvm::min/max_element and use it in llvm/ and mlir/ directories. #84678

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions llvm/include/llvm/ADT/STLExtras.h
Original file line number Diff line number Diff line change
Expand Up @@ -1971,6 +1971,22 @@ auto upper_bound(R &&Range, T &&Value, Compare C) {
std::forward<T>(Value), C);
}

template <typename R> auto min_element(R &&Range) {
return std::min_element(adl_begin(Range), adl_end(Range));
}

template <typename R, typename Compare> auto min_element(R &&Range, Compare C) {
return std::min_element(adl_begin(Range), adl_end(Range), C);
}

template <typename R> auto max_element(R &&Range) {
return std::max_element(adl_begin(Range), adl_end(Range));
}

template <typename R, typename Compare> auto max_element(R &&Range, Compare C) {
return std::max_element(adl_begin(Range), adl_end(Range), C);
}

template <typename R>
void stable_sort(R &&Range) {
std::stable_sort(adl_begin(Range), adl_end(Range));
Expand Down
6 changes: 2 additions & 4 deletions llvm/include/llvm/CodeGen/RegAllocPBQP.h
Original file line number Diff line number Diff line change
Expand Up @@ -462,10 +462,8 @@ class RegAllocSolverImpl {
NodeStack.push_back(NId);
G.disconnectAllNeighborsFromNode(NId);
} else if (!NotProvablyAllocatableNodes.empty()) {
NodeSet::iterator NItr =
std::min_element(NotProvablyAllocatableNodes.begin(),
NotProvablyAllocatableNodes.end(),
SpillCostComparator(G));
NodeSet::iterator NItr = llvm::min_element(NotProvablyAllocatableNodes,
SpillCostComparator(G));
NodeId NId = *NItr;
NotProvablyAllocatableNodes.erase(NItr);
NodeStack.push_back(NId);
Expand Down
7 changes: 3 additions & 4 deletions llvm/lib/Analysis/ScalarEvolution.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10839,10 +10839,9 @@ bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
#endif

const Loop *MDL =
*std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
[&](const Loop *L1, const Loop *L2) {
return DT.properlyDominates(L1->getHeader(), L2->getHeader());
});
*llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
return DT.properlyDominates(L1->getHeader(), L2->getHeader());
});

// Get init and post increment value for LHS.
auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
Expand Down
3 changes: 1 addition & 2 deletions llvm/lib/DebugInfo/PDB/Native/PDBFile.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,7 @@ uint32_t PDBFile::getNumStreams() const {
}

uint32_t PDBFile::getMaxStreamSize() const {
return *std::max_element(ContainerLayout.StreamSizes.begin(),
ContainerLayout.StreamSizes.end());
return *llvm::max_element(ContainerLayout.StreamSizes);
}

uint32_t PDBFile::getStreamByteSize(uint32_t StreamIndex) const {
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/IR/DataLayout.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -898,7 +898,7 @@ Type *DataLayout::getSmallestLegalIntType(LLVMContext &C, unsigned Width) const
}

unsigned DataLayout::getLargestLegalIntTypeSizeInBits() const {
auto Max = std::max_element(LegalIntWidths.begin(), LegalIntWidths.end());
auto Max = llvm::max_element(LegalIntWidths);
return Max != LegalIntWidths.end() ? *Max : 0;
}

Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/ObjCopy/MachO/MachOWriter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ size_t MachOWriter::totalSize() const {
}

if (!Ends.empty())
return *std::max_element(Ends.begin(), Ends.end());
return *llvm::max_element(Ends);

// Otherwise, we have only Mach header and load commands.
return headerSize() + loadCommandsSize();
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/ProfileData/GCOV.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -703,7 +703,7 @@ void Context::collectFunction(GCOVFunction &f, Summary &summary) {
for (const GCOVBlock &b : f.blocksRange()) {
if (b.lines.empty())
continue;
uint32_t maxLineNum = *std::max_element(b.lines.begin(), b.lines.end());
uint32_t maxLineNum = *llvm::max_element(b.lines);
if (maxLineNum >= si.lines.size())
si.lines.resize(maxLineNum + 1);
for (uint32_t lineNum : b.lines) {
Expand Down
4 changes: 2 additions & 2 deletions llvm/lib/Target/AArch64/SVEIntrinsicOpts.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,8 @@ bool SVEIntrinsicOpts::coalescePTrueIntrinsicCalls(
return false;

// Find the ptrue with the most lanes.
auto *MostEncompassingPTrue = *std::max_element(
PTrues.begin(), PTrues.end(), [](auto *PTrue1, auto *PTrue2) {
auto *MostEncompassingPTrue =
*llvm::max_element(PTrues, [](auto *PTrue1, auto *PTrue2) {
auto *PTrue1VTy = cast<ScalableVectorType>(PTrue1->getType());
auto *PTrue2VTy = cast<ScalableVectorType>(PTrue2->getType());
return PTrue1VTy->getElementCount().getKnownMinValue() <
Expand Down
10 changes: 5 additions & 5 deletions llvm/lib/Target/AMDGPU/GCNILPSched.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -313,11 +313,11 @@ GCNILPScheduler::schedule(ArrayRef<const SUnit*> BotRoots,
Schedule.reserve(SUnits.size());
while (true) {
if (AvailQueue.empty() && !PendingQueue.empty()) {
auto EarliestSU = std::min_element(
PendingQueue.begin(), PendingQueue.end(),
[=](const Candidate& C1, const Candidate& C2) {
return C1.SU->getHeight() < C2.SU->getHeight();
})->SU;
auto EarliestSU =
llvm::min_element(PendingQueue, [=](const Candidate &C1,
const Candidate &C2) {
return C1.SU->getHeight() < C2.SU->getHeight();
})->SU;
advanceToCycle(std::max(CurCycle + 1, EarliestSU->getHeight()));
}
if (AvailQueue.empty())
Expand Down
5 changes: 2 additions & 3 deletions llvm/lib/Target/AMDGPU/SIFixSGPRCopies.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -973,9 +973,8 @@ bool SIFixSGPRCopies::needToBeConvertedToVALU(V2SCopyInfo *Info) {
Info->Score = 0;
return true;
}
Info->Siblings = SiblingPenalty[*std::max_element(
Info->SChain.begin(), Info->SChain.end(),
[&](MachineInstr *A, MachineInstr *B) -> bool {
Info->Siblings = SiblingPenalty[*llvm::max_element(
Info->SChain, [&](MachineInstr *A, MachineInstr *B) -> bool {
return SiblingPenalty[A].size() < SiblingPenalty[B].size();
})];
Info->Siblings.remove_if([&](unsigned ID) { return ID == Info->ID; });
Expand Down
6 changes: 2 additions & 4 deletions llvm/lib/Target/AMDGPU/SIMachineScheduler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -904,10 +904,8 @@ void SIScheduleBlockCreator::colorEndsAccordingToDependencies() {
CurrentTopDownReservedDependencyColoring.size() == DAGSize);
// If there is no reserved block at all, do nothing. We don't want
// everything in one block.
if (*std::max_element(CurrentBottomUpReservedDependencyColoring.begin(),
CurrentBottomUpReservedDependencyColoring.end()) == 0 &&
*std::max_element(CurrentTopDownReservedDependencyColoring.begin(),
CurrentTopDownReservedDependencyColoring.end()) == 0)
if (*llvm::max_element(CurrentBottomUpReservedDependencyColoring) == 0 &&
*llvm::max_element(CurrentTopDownReservedDependencyColoring) == 0)
return;

for (unsigned SUNum : DAG->BottomUpIndex2SU) {
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/Target/Hexagon/HexagonCommonGEP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,7 @@ void HexagonCommonGEP::common() {
using ProjMap = std::map<const NodeSet *, GepNode *>;
ProjMap PM;
for (const NodeSet &S : EqRel) {
GepNode *Min = *std::min_element(S.begin(), S.end(), NodeOrder);
GepNode *Min = *llvm::min_element(S, NodeOrder);
std::pair<ProjMap::iterator,bool> Ins = PM.insert(std::make_pair(&S, Min));
(void)Ins;
assert(Ins.second && "Cannot add minimal element");
Expand Down
9 changes: 4 additions & 5 deletions llvm/lib/Target/Hexagon/HexagonConstExtenders.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1388,11 +1388,10 @@ void HCE::assignInits(const ExtRoot &ER, unsigned Begin, unsigned End,
break;

// Find the best candidate with respect to the number of extenders covered.
auto BestIt = std::max_element(Counts.begin(), Counts.end(),
[](const CMap::value_type &A, const CMap::value_type &B) {
return A.second < B.second ||
(A.second == B.second && A < B);
});
auto BestIt = llvm::max_element(
Counts, [](const CMap::value_type &A, const CMap::value_type &B) {
return A.second < B.second || (A.second == B.second && A < B);
});
int32_t Best = BestIt->first;
ExtValue BestV(ER, Best);
for (RangeTree::Node *N : Tree.nodesWith(Best)) {
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/Target/Hexagon/HexagonGenInsert.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1314,7 +1314,7 @@ void HexagonGenInsert::selectCandidates() {
// element found is adequate, we will put it back on the list, other-
// wise the list will remain empty, and the entry for this register
// will be removed (i.e. this register will not be replaced by insert).
IFListType::iterator MinI = std::min_element(LL.begin(), LL.end(), IFO);
IFListType::iterator MinI = llvm::min_element(LL, IFO);
assert(MinI != LL.end());
IFRecordWithRegSet M = *MinI;
LL.clear();
Expand Down
6 changes: 3 additions & 3 deletions llvm/lib/Target/Hexagon/HexagonVectorCombine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1411,9 +1411,9 @@ auto AlignVectors::realignGroup(const MoveGroup &Move) const -> bool {
// Return the element with the maximum alignment from Range,
// where GetValue obtains the value to compare from an element.
auto getMaxOf = [](auto Range, auto GetValue) {
return *std::max_element(
Range.begin(), Range.end(),
[&GetValue](auto &A, auto &B) { return GetValue(A) < GetValue(B); });
return *llvm::max_element(Range, [&GetValue](auto &A, auto &B) {
return GetValue(A) < GetValue(B);
});
};

const AddrList &BaseInfos = AddrGroups.at(Move.Base);
Expand Down
3 changes: 1 addition & 2 deletions llvm/lib/Transforms/Scalar/GVNSink.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -655,8 +655,7 @@ GVNSink::analyzeInstructionForSinking(LockstepReverseIterator &LRI,
return std::nullopt;
VNums[N]++;
}
unsigned VNumToSink =
std::max_element(VNums.begin(), VNums.end(), llvm::less_second())->first;
unsigned VNumToSink = llvm::max_element(VNums, llvm::less_second())->first;

if (VNums[VNumToSink] == 1)
// Can't sink anything!
Expand Down
8 changes: 3 additions & 5 deletions llvm/lib/Transforms/Scalar/JumpThreading.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1488,7 +1488,7 @@ findMostPopularDest(BasicBlock *BB,

// Populate DestPopularity with the successors in the order they appear in the
// successor list. This way, we ensure determinism by iterating it in the
// same order in std::max_element below. We map nullptr to 0 so that we can
// same order in llvm::max_element below. We map nullptr to 0 so that we can
// return nullptr when PredToDestList contains nullptr only.
DestPopularity[nullptr] = 0;
for (auto *SuccBB : successors(BB))
Expand All @@ -1499,8 +1499,7 @@ findMostPopularDest(BasicBlock *BB,
DestPopularity[PredToDest.second]++;

// Find the most popular dest.
auto MostPopular = std::max_element(
DestPopularity.begin(), DestPopularity.end(), llvm::less_second());
auto MostPopular = llvm::max_element(DestPopularity, llvm::less_second());

// Okay, we have finally picked the most popular destination.
return MostPopular->first;
Expand Down Expand Up @@ -2553,8 +2552,7 @@ void JumpThreadingPass::updateBlockFreqAndEdgeWeight(BasicBlock *PredBB,
BBSuccFreq.push_back(SuccFreq.getFrequency());
}

uint64_t MaxBBSuccFreq =
*std::max_element(BBSuccFreq.begin(), BBSuccFreq.end());
uint64_t MaxBBSuccFreq = *llvm::max_element(BBSuccFreq);

SmallVector<BranchProbability, 4> BBSuccProbs;
if (MaxBBSuccFreq == 0)
Expand Down
23 changes: 12 additions & 11 deletions llvm/lib/Transforms/Scalar/LoopLoadElimination.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -349,19 +349,20 @@ class LoadEliminationForLoop {
// ld0.

LoadInst *LastLoad =
std::max_element(Candidates.begin(), Candidates.end(),
[&](const StoreToLoadForwardingCandidate &A,
const StoreToLoadForwardingCandidate &B) {
return getInstrIndex(A.Load) < getInstrIndex(B.Load);
})
llvm::max_element(Candidates,
[&](const StoreToLoadForwardingCandidate &A,
const StoreToLoadForwardingCandidate &B) {
return getInstrIndex(A.Load) <
getInstrIndex(B.Load);
})
->Load;
StoreInst *FirstStore =
std::min_element(Candidates.begin(), Candidates.end(),
[&](const StoreToLoadForwardingCandidate &A,
const StoreToLoadForwardingCandidate &B) {
return getInstrIndex(A.Store) <
getInstrIndex(B.Store);
})
llvm::min_element(Candidates,
[&](const StoreToLoadForwardingCandidate &A,
const StoreToLoadForwardingCandidate &B) {
return getInstrIndex(A.Store) <
getInstrIndex(B.Store);
})
->Store;

// We're looking for stores after the first forwarding store until the end
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/Transforms/Utils/SimplifyCFG.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1084,7 +1084,7 @@ static void GetBranchWeights(Instruction *TI,

/// Keep halving the weights until all can fit in uint32_t.
static void FitWeights(MutableArrayRef<uint64_t> Weights) {
uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
uint64_t Max = *llvm::max_element(Weights);
if (Max > UINT_MAX) {
unsigned Offset = 32 - llvm::countl_zero(Max);
for (uint64_t &I : Weights)
Expand Down
9 changes: 4 additions & 5 deletions llvm/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -892,7 +892,7 @@ bool Vectorizer::vectorizeChain(Chain &C) {
// Loads get hoisted to the location of the first load in the chain. We may
// also need to hoist the (transitive) operands of the loads.
Builder.SetInsertPoint(
std::min_element(C.begin(), C.end(), [](const auto &A, const auto &B) {
llvm::min_element(C, [](const auto &A, const auto &B) {
return A.Inst->comesBefore(B.Inst);
})->Inst);

Expand Down Expand Up @@ -944,10 +944,9 @@ bool Vectorizer::vectorizeChain(Chain &C) {
reorder(VecInst);
} else {
// Stores get sunk to the location of the last store in the chain.
Builder.SetInsertPoint(
std::max_element(C.begin(), C.end(), [](auto &A, auto &B) {
return A.Inst->comesBefore(B.Inst);
})->Inst);
Builder.SetInsertPoint(llvm::max_element(C, [](auto &A, auto &B) {
return A.Inst->comesBefore(B.Inst);
})->Inst);

// Build the vector to store.
Value *Vec = PoisonValue::get(VecTy);
Expand Down
9 changes: 4 additions & 5 deletions llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10172,11 +10172,10 @@ BoUpSLP::isGatherShuffledSingleRegisterEntry(
// No 2 source vectors with the same vector factor - just choose 2 with max
// index.
if (Entries.empty()) {
Entries.push_back(
*std::max_element(UsedTEs.front().begin(), UsedTEs.front().end(),
[](const TreeEntry *TE1, const TreeEntry *TE2) {
return TE1->Idx < TE2->Idx;
}));
Entries.push_back(*llvm::max_element(
UsedTEs.front(), [](const TreeEntry *TE1, const TreeEntry *TE2) {
return TE1->Idx < TE2->Idx;
}));
Entries.push_back(SecondEntries.front());
VF = std::max(Entries.front()->getVectorFactor(),
Entries.back()->getVectorFactor());
Expand Down
4 changes: 2 additions & 2 deletions llvm/tools/llvm-exegesis/lib/LatencyBenchmarkRunner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@ static double computeVariance(const SmallVector<int64_t, 4> &Values) {
static int64_t findMin(const SmallVector<int64_t, 4> &Values) {
if (Values.empty())
return 0;
return *std::min_element(Values.begin(), Values.end());
return *llvm::min_element(Values);
}

static int64_t findMax(const SmallVector<int64_t, 4> &Values) {
if (Values.empty())
return 0;
return *std::max_element(Values.begin(), Values.end());
return *llvm::max_element(Values);
}

static int64_t findMean(const SmallVector<int64_t, 4> &Values) {
Expand Down
7 changes: 4 additions & 3 deletions llvm/tools/llvm-mca/Views/BottleneckAnalysis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -270,9 +270,10 @@ void DependencyGraph::getCriticalSequence(
// To obtain the sequence of critical edges, we simply follow the chain of
// critical predecessors starting from node N (field
// DGNode::CriticalPredecessor).
const auto It = std::max_element(
Nodes.begin(), Nodes.end(),
[](const DGNode &Lhs, const DGNode &Rhs) { return Lhs.Cost < Rhs.Cost; });
const auto It =
llvm::max_element(Nodes, [](const DGNode &Lhs, const DGNode &Rhs) {
return Lhs.Cost < Rhs.Cost;
});
unsigned IID = std::distance(Nodes.begin(), It);
Seq.resize(Nodes[IID].Depth);
for (const DependencyEdge *&DE : llvm::reverse(Seq)) {
Expand Down
3 changes: 1 addition & 2 deletions llvm/tools/llvm-mca/Views/SchedulerStatistics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,7 @@ void SchedulerStatistics::printSchedulerStats(raw_ostream &OS) const {
OS << "[# issued], [# cycles]\n";

bool HasColors = OS.has_colors();
const auto It =
std::max_element(IssueWidthPerCycle.begin(), IssueWidthPerCycle.end());
const auto It = llvm::max_element(IssueWidthPerCycle);
for (const std::pair<const unsigned, unsigned> &Entry : IssueWidthPerCycle) {
unsigned NumIssued = Entry.first;
if (NumIssued == It->first && HasColors)
Expand Down
9 changes: 4 additions & 5 deletions llvm/tools/llvm-pdbutil/DumpOutputStyle.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1070,8 +1070,7 @@ Error DumpOutputStyle::dumpStringTableFromPdb() {
if (IS->name_ids().empty())
P.formatLine("Empty");
else {
auto MaxID =
std::max_element(IS->name_ids().begin(), IS->name_ids().end());
auto MaxID = llvm::max_element(IS->name_ids(), IS->name_ids());
uint32_t Digits = NumDigits(*MaxID);

P.formatLine("{0} | {1}", fmt_align("ID", AlignStyle::Right, Digits),
Expand Down Expand Up @@ -1836,9 +1835,9 @@ Error DumpOutputStyle::dumpSectionContribs() {
class Visitor : public ISectionContribVisitor {
public:
Visitor(LinePrinter &P, ArrayRef<std::string> Names) : P(P), Names(Names) {
auto Max = std::max_element(
Names.begin(), Names.end(),
[](StringRef S1, StringRef S2) { return S1.size() < S2.size(); });
auto Max = llvm::max_element(Names, [](StringRef S1, StringRef S2) {
return S1.size() < S2.size();
});
MaxNameLen = (Max == Names.end() ? 0 : Max->size());
}
void visit(const SectionContrib &SC) override {
Expand Down
6 changes: 3 additions & 3 deletions llvm/tools/llvm-pdbutil/MinimalTypeDumper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ Error MinimalTypeDumpVisitor::visitKnownRecord(CVType &CVR,
if (Indices.empty())
return Error::success();

auto Max = std::max_element(Indices.begin(), Indices.end());
auto Max = llvm::max_element(Indices);
uint32_t W = NumDigits(Max->getIndex()) + 2;

for (auto I : Indices)
Expand All @@ -323,7 +323,7 @@ Error MinimalTypeDumpVisitor::visitKnownRecord(CVType &CVR,
if (Indices.empty())
return Error::success();

auto Max = std::max_element(Indices.begin(), Indices.end());
auto Max = llvm::max_element(Indices);
uint32_t W = NumDigits(Max->getIndex()) + 2;

for (auto I : Indices)
Expand Down Expand Up @@ -493,7 +493,7 @@ Error MinimalTypeDumpVisitor::visitKnownRecord(CVType &CVR,
if (Indices.empty())
return Error::success();

auto Max = std::max_element(Indices.begin(), Indices.end());
auto Max = llvm::max_element(Indices);
uint32_t W = NumDigits(Max->getIndex()) + 2;

for (auto I : Indices)
Expand Down
Loading