Use llvm::sort instead of std::sort where possible

llvm::sort is beneficial even when we use the iterator-based overload,
since it can optionally shuffle the elements (to detect
non-determinism). However llvm::sort is not usable everywhere, for
example, in compiler-rt.

Reviewed By: nhaehnle

Differential Revision: https://reviews.llvm.org/D130406
This commit is contained in:
Dmitri Gribenko 2022-07-23 15:14:14 +02:00
parent e82880e6b8
commit aba43035bd
31 changed files with 127 additions and 120 deletions

View File

@ -7,7 +7,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
#include "IncludeFixerContext.h" #include "IncludeFixerContext.h"
#include <algorithm> #include "llvm/ADT/STLExtras.h"
namespace clang { namespace clang {
namespace include_fixer { namespace include_fixer {
@ -84,11 +84,11 @@ IncludeFixerContext::IncludeFixerContext(
// QuerySymbolInfos may contain replicated elements. Because CorrectTypo // QuerySymbolInfos may contain replicated elements. Because CorrectTypo
// callback doesn't always work as we expected. In somecases, it will be // callback doesn't always work as we expected. In somecases, it will be
// triggered at the same position or unidentified symbol multiple times. // triggered at the same position or unidentified symbol multiple times.
std::sort(QuerySymbolInfos.begin(), QuerySymbolInfos.end(), llvm::sort(QuerySymbolInfos,
[&](const QuerySymbolInfo &A, const QuerySymbolInfo &B) { [&](const QuerySymbolInfo &A, const QuerySymbolInfo &B) {
return std::make_pair(A.Range.getOffset(), A.Range.getLength()) < return std::make_pair(A.Range.getOffset(), A.Range.getLength()) <
std::make_pair(B.Range.getOffset(), B.Range.getLength()); std::make_pair(B.Range.getOffset(), B.Range.getLength());
}); });
QuerySymbolInfos.erase( QuerySymbolInfos.erase(
std::unique(QuerySymbolInfos.begin(), QuerySymbolInfos.end(), std::unique(QuerySymbolInfos.begin(), QuerySymbolInfos.end(),
[](const QuerySymbolInfo &A, const QuerySymbolInfo &B) { [](const QuerySymbolInfo &A, const QuerySymbolInfo &B) {

View File

@ -21,8 +21,8 @@
#include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h" #include "clang/Lex/Lexer.h"
#include "clang/Tooling/Refactoring.h" #include "clang/Tooling/Refactoring.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h" #include "llvm/ADT/SetVector.h"
#include <algorithm>
#include <string> #include <string>
namespace clang { namespace clang {
@ -206,8 +206,7 @@ static void reorderFieldsInConstructor(
return NewFieldsPositions[LHS->getMember()->getFieldIndex()] < return NewFieldsPositions[LHS->getMember()->getFieldIndex()] <
NewFieldsPositions[RHS->getMember()->getFieldIndex()]; NewFieldsPositions[RHS->getMember()->getFieldIndex()];
}; };
std::sort(std::begin(NewWrittenInitializersOrder), llvm::sort(NewWrittenInitializersOrder, ByFieldNewPosition);
std::end(NewWrittenInitializersOrder), ByFieldNewPosition);
assert(OldWrittenInitializersOrder.size() == assert(OldWrittenInitializersOrder.size() ==
NewWrittenInitializersOrder.size()); NewWrittenInitializersOrder.size());
for (unsigned i = 0, e = NewWrittenInitializersOrder.size(); i < e; ++i) for (unsigned i = 0, e = NewWrittenInitializersOrder.size(); i < e; ++i)

View File

@ -14,6 +14,7 @@
#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Analysis/CFG.h" #include "clang/Analysis/CFG.h"
#include "clang/Lex/Lexer.h" #include "clang/Lex/Lexer.h"
#include "llvm/ADT/STLExtras.h"
#include "../utils/ExprSequence.h" #include "../utils/ExprSequence.h"
@ -228,10 +229,9 @@ void UseAfterMoveFinder::getUsesAndReinits(
} }
// Sort the uses by their occurrence in the source code. // Sort the uses by their occurrence in the source code.
std::sort(Uses->begin(), Uses->end(), llvm::sort(*Uses, [](const DeclRefExpr *D1, const DeclRefExpr *D2) {
[](const DeclRefExpr *D1, const DeclRefExpr *D2) { return D1->getExprLoc() < D2->getExprLoc();
return D1->getExprLoc() < D2->getExprLoc(); });
});
} }
bool isStandardSmartPointer(const ValueDecl *VD) { bool isStandardSmartPointer(const ValueDecl *VD) {

View File

@ -10,6 +10,7 @@
#include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/PPCallbacks.h" #include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Preprocessor.h" #include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/STLExtras.h"
#include <map> #include <map>
@ -125,20 +126,20 @@ void IncludeOrderPPCallbacks::EndOfMainFile() {
// Sort the includes. We first sort by priority, then lexicographically. // Sort the includes. We first sort by priority, then lexicographically.
for (unsigned BI = 0, BE = Blocks.size() - 1; BI != BE; ++BI) for (unsigned BI = 0, BE = Blocks.size() - 1; BI != BE; ++BI)
std::sort(IncludeIndices.begin() + Blocks[BI], llvm::sort(IncludeIndices.begin() + Blocks[BI],
IncludeIndices.begin() + Blocks[BI + 1], IncludeIndices.begin() + Blocks[BI + 1],
[&FileDirectives](unsigned LHSI, unsigned RHSI) { [&FileDirectives](unsigned LHSI, unsigned RHSI) {
IncludeDirective &LHS = FileDirectives[LHSI]; IncludeDirective &LHS = FileDirectives[LHSI];
IncludeDirective &RHS = FileDirectives[RHSI]; IncludeDirective &RHS = FileDirectives[RHSI];
int PriorityLHS = int PriorityLHS = getPriority(LHS.Filename, LHS.IsAngled,
getPriority(LHS.Filename, LHS.IsAngled, LHS.IsMainModule); LHS.IsMainModule);
int PriorityRHS = int PriorityRHS = getPriority(RHS.Filename, RHS.IsAngled,
getPriority(RHS.Filename, RHS.IsAngled, RHS.IsMainModule); RHS.IsMainModule);
return std::tie(PriorityLHS, LHS.Filename) < return std::tie(PriorityLHS, LHS.Filename) <
std::tie(PriorityRHS, RHS.Filename); std::tie(PriorityRHS, RHS.Filename);
}); });
// Emit a warning for each block and fixits for all changes within that // Emit a warning for each block and fixits for all changes within that
// block. // block.

View File

@ -5,13 +5,13 @@
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringExtras.h"
#include "llvm/Support/ConvertUTF.h" #include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace llvm; using namespace llvm;
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
@ -54,7 +54,7 @@ int main(int argc, char *argv[]) {
Entries.emplace_back(CodePoint, To); Entries.emplace_back(CodePoint, To);
} }
std::sort(Entries.begin(), Entries.end()); llvm::sort(Entries);
unsigned LargestValue = unsigned LargestValue =
std::max_element(Entries.begin(), Entries.end(), std::max_element(Entries.begin(), Entries.end(),

View File

@ -9,8 +9,8 @@
#include "InconsistentDeclarationParameterNameCheck.h" #include "InconsistentDeclarationParameterNameCheck.h"
#include "clang/AST/ASTContext.h" #include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/ASTMatchers/ASTMatchFinder.h"
#include "llvm/ADT/STLExtras.h"
#include <algorithm>
#include <functional> #include <functional>
using namespace clang::ast_matchers; using namespace clang::ast_matchers;
@ -158,12 +158,12 @@ findInconsistentDeclarations(const FunctionDecl *OriginalDeclaration,
// Sort in order of appearance in translation unit to generate clear // Sort in order of appearance in translation unit to generate clear
// diagnostics. // diagnostics.
std::sort(InconsistentDeclarations.begin(), InconsistentDeclarations.end(), llvm::sort(InconsistentDeclarations,
[&SM](const InconsistentDeclarationInfo &Info1, [&SM](const InconsistentDeclarationInfo &Info1,
const InconsistentDeclarationInfo &Info2) { const InconsistentDeclarationInfo &Info2) {
return SM.isBeforeInTranslationUnit(Info1.DeclarationLocation, return SM.isBeforeInTranslationUnit(Info1.DeclarationLocation,
Info2.DeclarationLocation); Info2.DeclarationLocation);
}); });
return InconsistentDeclarations; return InconsistentDeclarations;
} }

View File

@ -35,6 +35,7 @@
#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/None.h" #include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h" #include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h" #include "llvm/ADT/StringSet.h"
@ -475,7 +476,7 @@ collectAccessibleScopes(Sema &Sem, const DeclarationNameInfo &Typo, Scope *S,
Sem.LookupVisibleDecls(S, LookupKind, Collector, Sem.LookupVisibleDecls(S, LookupKind, Collector,
/*IncludeGlobalScope=*/false, /*IncludeGlobalScope=*/false,
/*LoadExternal=*/false); /*LoadExternal=*/false);
std::sort(Scopes.begin(), Scopes.end()); llvm::sort(Scopes);
Scopes.erase(std::unique(Scopes.begin(), Scopes.end()), Scopes.end()); Scopes.erase(std::unique(Scopes.begin(), Scopes.end()), Scopes.end());
return Scopes; return Scopes;
} }

View File

@ -10,6 +10,7 @@
#include "clang-pseudo/grammar/LRGraph.h" #include "clang-pseudo/grammar/LRGraph.h"
#include "clang-pseudo/grammar/LRTable.h" #include "clang-pseudo/grammar/LRTable.h"
#include "clang/Basic/TokenKinds.h" #include "clang/Basic/TokenKinds.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallSet.h"
#include <cstdint> #include <cstdint>
@ -60,8 +61,8 @@ LRTable LRTable::Builder::build() && {
continue; continue;
Table.Reduces.insert(Table.Reduces.end(), It->second.begin(), Table.Reduces.insert(Table.Reduces.end(), It->second.begin(),
It->second.end()); It->second.end());
std::sort(Table.Reduces.begin() + Table.ReduceOffset.back(), llvm::sort(Table.Reduces.begin() + Table.ReduceOffset.back(),
Table.Reduces.end()); Table.Reduces.end());
} }
Table.ReduceOffset.push_back(Table.Reduces.size()); Table.ReduceOffset.push_back(Table.Reduces.size());

View File

@ -35,7 +35,7 @@
#include "llvm/IR/Type.h" #include "llvm/IR/Type.h"
#include "llvm/Support/MathExtras.h" #include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
#include <algorithm> // std::sort #include <algorithm>
using namespace clang; using namespace clang;
using namespace CodeGen; using namespace CodeGen;

View File

@ -12,6 +12,7 @@
#include "clang/Tooling/Transformer/RangeSelector.h" #include "clang/Tooling/Transformer/RangeSelector.h"
#include "clang/Tooling/Transformer/RewriteRule.h" #include "clang/Tooling/Transformer/RewriteRule.h"
#include "clang/Tooling/Transformer/Stencil.h" #include "clang/Tooling/Transformer/Stencil.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Errc.h" #include "llvm/Support/Errc.h"
#include "llvm/Support/Error.h" #include "llvm/Support/Error.h"
#include "gmock/gmock.h" #include "gmock/gmock.h"
@ -1617,10 +1618,9 @@ TEST_F(TransformerTest, MultipleFiles) {
"clang-tool", std::make_shared<PCHContainerOperations>(), "clang-tool", std::make_shared<PCHContainerOperations>(),
{{"input.h", Header}})); {{"input.h", Header}}));
std::sort(Changes.begin(), Changes.end(), llvm::sort(Changes, [](const AtomicChange &L, const AtomicChange &R) {
[](const AtomicChange &L, const AtomicChange &R) { return L.getFilePath() < R.getFilePath();
return L.getFilePath() < R.getFilePath(); });
});
ASSERT_EQ(Changes[0].getFilePath(), "./input.h"); ASSERT_EQ(Changes[0].getFilePath(), "./input.h");
EXPECT_THAT(Changes[0].getInsertedHeaders(), IsEmpty()); EXPECT_THAT(Changes[0].getInsertedHeaders(), IsEmpty());

View File

@ -13,6 +13,7 @@
#include "Symbols.h" #include "Symbols.h"
#include "Writer.h" #include "Writer.h"
#include "llvm/ADT/Twine.h" #include "llvm/ADT/Twine.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/BinaryFormat/COFF.h" #include "llvm/BinaryFormat/COFF.h"
#include "llvm/Object/COFF.h" #include "llvm/Object/COFF.h"
#include "llvm/Support/Debug.h" #include "llvm/Support/Debug.h"
@ -815,7 +816,7 @@ void RVATableChunk::writeTo(uint8_t *buf) const {
size_t cnt = 0; size_t cnt = 0;
for (const ChunkAndOffset &co : syms) for (const ChunkAndOffset &co : syms)
begin[cnt++] = co.inputChunk->getRVA() + co.offset; begin[cnt++] = co.inputChunk->getRVA() + co.offset;
std::sort(begin, begin + cnt); llvm::sort(begin, begin + cnt);
assert(std::unique(begin, begin + cnt) == begin + cnt && assert(std::unique(begin, begin + cnt) == begin + cnt &&
"RVA tables should be de-duplicated"); "RVA tables should be de-duplicated");
} }

View File

@ -21,6 +21,7 @@
#include "COFFLinkerContext.h" #include "COFFLinkerContext.h"
#include "Chunks.h" #include "Chunks.h"
#include "SymbolTable.h" #include "SymbolTable.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Object/COFF.h" #include "llvm/Object/COFF.h"
#include "llvm/Support/Endian.h" #include "llvm/Support/Endian.h"
#include "llvm/Support/Path.h" #include "llvm/Support/Path.h"
@ -150,10 +151,9 @@ binImports(const std::vector<DefinedImportData *> &imports) {
for (auto &kv : m) { for (auto &kv : m) {
// Sort symbols by name for each group. // Sort symbols by name for each group.
std::vector<DefinedImportData *> &syms = kv.second; std::vector<DefinedImportData *> &syms = kv.second;
std::sort(syms.begin(), syms.end(), llvm::sort(syms, [](DefinedImportData *a, DefinedImportData *b) {
[](DefinedImportData *a, DefinedImportData *b) { return a->getName() < b->getName();
return a->getName() < b->getName(); });
});
v.push_back(std::move(syms)); v.push_back(std::move(syms));
} }
return v; return v;

View File

@ -18,6 +18,7 @@
#include "lld/Common/ErrorHandler.h" #include "lld/Common/ErrorHandler.h"
#include "lld/Common/Memory.h" #include "lld/Common/Memory.h"
#include "llvm/ADT/Optional.h" #include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/StringSwitch.h"
#include "llvm/BinaryFormat/COFF.h" #include "llvm/BinaryFormat/COFF.h"
#include "llvm/Object/COFF.h" #include "llvm/Object/COFF.h"
@ -694,10 +695,9 @@ void fixupExports() {
config->exports = std::move(v); config->exports = std::move(v);
// Sort by name. // Sort by name.
std::sort(config->exports.begin(), config->exports.end(), llvm::sort(config->exports, [](const Export &a, const Export &b) {
[](const Export &a, const Export &b) { return a.exportName < b.exportName;
return a.exportName < b.exportName; });
});
} }
void assignExportOrdinals() { void assignExportOrdinals() {

View File

@ -29,6 +29,7 @@
#include "lld/Common/DWARF.h" #include "lld/Common/DWARF.h"
#include "lld/Common/Strings.h" #include "lld/Common/Strings.h"
#include "lld/Common/Version.h" #include "lld/Common/Version.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetOperations.h" #include "llvm/ADT/SetOperations.h"
#include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringExtras.h"
#include "llvm/BinaryFormat/Dwarf.h" #include "llvm/BinaryFormat/Dwarf.h"
@ -1703,7 +1704,7 @@ void RelocationBaseSection::computeRels() {
parallelSort(relocs.begin(), nonRelative, parallelSort(relocs.begin(), nonRelative,
[&](auto &a, auto &b) { return a.r_offset < b.r_offset; }); [&](auto &a, auto &b) { return a.r_offset < b.r_offset; });
// Non-relative relocations are few, so don't bother with parallelSort. // Non-relative relocations are few, so don't bother with parallelSort.
std::sort(nonRelative, relocs.end(), [&](auto &a, auto &b) { llvm::sort(nonRelative, relocs.end(), [&](auto &a, auto &b) {
return std::tie(a.r_sym, a.r_offset) < std::tie(b.r_sym, b.r_offset); return std::tie(a.r_sym, a.r_offset) < std::tie(b.r_sym, b.r_offset);
}); });
} }
@ -2039,7 +2040,7 @@ template <class ELFT> bool RelrSection<ELFT>::updateAllocSize() {
std::unique_ptr<uint64_t[]> offsets(new uint64_t[relocs.size()]); std::unique_ptr<uint64_t[]> offsets(new uint64_t[relocs.size()]);
for (auto it : llvm::enumerate(relocs)) for (auto it : llvm::enumerate(relocs))
offsets[it.index()] = it.value().getOffset(); offsets[it.index()] = it.value().getOffset();
std::sort(offsets.get(), offsets.get() + relocs.size()); llvm::sort(offsets.get(), offsets.get() + relocs.size());
// For each leading relocation, find following ones that can be folded // For each leading relocation, find following ones that can be folded
// as a bitmap and fold them. // as a bitmap and fold them.

View File

@ -802,7 +802,7 @@ void ValueEnumerator::organizeMetadata() {
// - by function, then // - by function, then
// - by isa<MDString> // - by isa<MDString>
// and then sort by the original/current ID. Since the IDs are guaranteed to // and then sort by the original/current ID. Since the IDs are guaranteed to
// be unique, the result of std::sort will be deterministic. There's no need // be unique, the result of llvm::sort will be deterministic. There's no need
// for std::stable_sort. // for std::stable_sort.
llvm::sort(Order, [this](MDIndex LHS, MDIndex RHS) { llvm::sort(Order, [this](MDIndex LHS, MDIndex RHS) {
return std::make_tuple(LHS.F, getMetadataTypeOrder(LHS.get(MDs)), LHS.ID) < return std::make_tuple(LHS.F, getMetadataTypeOrder(LHS.get(MDs)), LHS.ID) <

View File

@ -3709,10 +3709,9 @@ Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl(
for (auto &PHI : CreatedPHIs) for (auto &PHI : CreatedPHIs)
SortedPHIs.push_back(PHI); SortedPHIs.push_back(PHI);
std::sort( llvm::sort(SortedPHIs, [&](LDVSSAPhi *A, LDVSSAPhi *B) {
SortedPHIs.begin(), SortedPHIs.end(), [&](LDVSSAPhi *A, LDVSSAPhi *B) { return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB];
return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB]; });
});
for (auto &PHI : SortedPHIs) { for (auto &PHI : SortedPHIs) {
ValueIDNum ThisBlockValueNum = ValueIDNum ThisBlockValueNum =

View File

@ -7,6 +7,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
#include "llvm/MC/MCPseudoProbe.h" #include "llvm/MC/MCPseudoProbe.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h" #include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h" #include "llvm/MC/MCExpr.h"
@ -519,7 +520,7 @@ void MCPseudoProbeDecoder::printProbesForAllAddresses(raw_ostream &OS) {
std::vector<uint64_t> Addresses; std::vector<uint64_t> Addresses;
for (auto Entry : Address2ProbesMap) for (auto Entry : Address2ProbesMap)
Addresses.push_back(Entry.first); Addresses.push_back(Entry.first);
std::sort(Addresses.begin(), Addresses.end()); llvm::sort(Addresses);
for (auto K : Addresses) { for (auto K : Addresses) {
OS << "Address:\t"; OS << "Address:\t";
OS << K; OS << K;

View File

@ -13,6 +13,7 @@
#include "DXILBitcodeWriter.h" #include "DXILBitcodeWriter.h"
#include "DXILValueEnumerator.h" #include "DXILValueEnumerator.h"
#include "PointerTypeAnalysis.h" #include "PointerTypeAnalysis.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Triple.h" #include "llvm/ADT/Triple.h"
#include "llvm/Bitcode/BitcodeCommon.h" #include "llvm/Bitcode/BitcodeCommon.h"
#include "llvm/Bitcode/BitcodeReader.h" #include "llvm/Bitcode/BitcodeReader.h"
@ -2580,10 +2581,9 @@ void DXILBitcodeWriter::writeFunctionLevelValueSymbolTable(
SortedTable.push_back(VI.second->getValueName()); SortedTable.push_back(VI.second->getValueName());
} }
// The keys are unique, so there shouldn't be stability issues. // The keys are unique, so there shouldn't be stability issues.
std::sort(SortedTable.begin(), SortedTable.end(), llvm::sort(SortedTable, [](const ValueName *A, const ValueName *B) {
[](const ValueName *A, const ValueName *B) { return A->first() < B->first();
return A->first() < B->first(); });
});
for (const ValueName *SI : SortedTable) { for (const ValueName *SI : SortedTable) {
auto &Name = *SI; auto &Name = *SI;

View File

@ -809,7 +809,7 @@ void ValueEnumerator::organizeMetadata() {
// - by function, then // - by function, then
// - by isa<MDString> // - by isa<MDString>
// and then sort by the original/current ID. Since the IDs are guaranteed to // and then sort by the original/current ID. Since the IDs are guaranteed to
// be unique, the result of std::sort will be deterministic. There's no need // be unique, the result of llvm::sort will be deterministic. There's no need
// for std::stable_sort. // for std::stable_sort.
llvm::sort(Order, [this](MDIndex LHS, MDIndex RHS) { llvm::sort(Order, [this](MDIndex LHS, MDIndex RHS) {
return std::make_tuple(LHS.F, getMetadataTypeOrder(LHS.get(MDs)), LHS.ID) < return std::make_tuple(LHS.F, getMetadataTypeOrder(LHS.get(MDs)), LHS.ID) <

View File

@ -27,7 +27,7 @@
#include "llvm/IR/Function.h" #include "llvm/IR/Function.h"
#include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ErrorHandling.h"
#include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetOptions.h"
#include <algorithm> // std::sort #include <algorithm>
using namespace llvm; using namespace llvm;

View File

@ -11,6 +11,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
#include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/STLExtras.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include <string> #include <string>
@ -78,7 +79,7 @@ TEST(SmallSetTest, IteratorInt) {
std::vector<int> V(s1.begin(), s1.end()); std::vector<int> V(s1.begin(), s1.end());
// Make sure the elements are in the expected order. // Make sure the elements are in the expected order.
std::sort(V.begin(), V.end()); llvm::sort(V);
for (int i = 0; i < 3; i++) for (int i = 0; i < 3; i++)
EXPECT_EQ(i, V[i]); EXPECT_EQ(i, V[i]);
@ -89,7 +90,7 @@ TEST(SmallSetTest, IteratorInt) {
V.assign(s1.begin(), s1.end()); V.assign(s1.begin(), s1.end());
// Make sure the elements are in the expected order. // Make sure the elements are in the expected order.
std::sort(V.begin(), V.end()); llvm::sort(V);
for (int i = 0; i < 6; i++) for (int i = 0; i < 6; i++)
EXPECT_EQ(i, V[i]); EXPECT_EQ(i, V[i]);
} }
@ -104,7 +105,7 @@ TEST(SmallSetTest, IteratorString) {
s1.insert("str 1"); s1.insert("str 1");
std::vector<std::string> V(s1.begin(), s1.end()); std::vector<std::string> V(s1.begin(), s1.end());
std::sort(V.begin(), V.end()); llvm::sort(V);
EXPECT_EQ(2u, s1.size()); EXPECT_EQ(2u, s1.size());
EXPECT_EQ("str 1", V[0]); EXPECT_EQ("str 1", V[0]);
EXPECT_EQ("str 2", V[1]); EXPECT_EQ("str 2", V[1]);
@ -115,7 +116,7 @@ TEST(SmallSetTest, IteratorString) {
V.assign(s1.begin(), s1.end()); V.assign(s1.begin(), s1.end());
// Make sure the elements are in the expected order. // Make sure the elements are in the expected order.
std::sort(V.begin(), V.end()); llvm::sort(V);
EXPECT_EQ(4u, s1.size()); EXPECT_EQ(4u, s1.size());
EXPECT_EQ("str 0", V[0]); EXPECT_EQ("str 0", V[0]);
EXPECT_EQ("str 1", V[1]); EXPECT_EQ("str 1", V[1]);

View File

@ -6,6 +6,7 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/CodeGen/MIRParser/MIRParser.h" #include "llvm/CodeGen/MIRParser/MIRParser.h"
#include "llvm/CodeGen/MIRPrinter.h" #include "llvm/CodeGen/MIRPrinter.h"
#include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFunction.h"
@ -271,8 +272,8 @@ body: |
for (auto &MD : MDList) for (auto &MD : MDList)
Collected.push_back(MD.second); Collected.push_back(MD.second);
std::sort(Generated.begin(), Generated.end()); llvm::sort(Generated);
std::sort(Collected.begin(), Collected.end()); llvm::sort(Collected);
EXPECT_EQ(Collected, Generated); EXPECT_EQ(Collected, Generated);
// FileCheck the output from MIR printer. // FileCheck the output from MIR printer.
@ -421,8 +422,8 @@ body: |
for (auto &MD : MDList) for (auto &MD : MDList)
Collected.push_back(MD.second); Collected.push_back(MD.second);
std::sort(Generated.begin(), Generated.end()); llvm::sort(Generated);
std::sort(Collected.begin(), Collected.end()); llvm::sort(Collected);
EXPECT_EQ(Collected, Generated); EXPECT_EQ(Collected, Generated);
// FileCheck the output from MIR printer. // FileCheck the output from MIR printer.
@ -520,8 +521,8 @@ body: |
for (auto &MD : MDList) for (auto &MD : MDList)
Collected.push_back(MD.second); Collected.push_back(MD.second);
std::sort(Generated.begin(), Generated.end()); llvm::sort(Generated);
std::sort(Collected.begin(), Collected.end()); llvm::sort(Collected);
EXPECT_EQ(Collected, Generated); EXPECT_EQ(Collected, Generated);
// FileCheck the output from MIR printer. // FileCheck the output from MIR printer.

View File

@ -7,6 +7,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
#include "llvm/Support/Alignment.h" #include "llvm/Support/Alignment.h"
#include "llvm/ADT/STLExtras.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include <vector> #include <vector>
@ -179,7 +180,7 @@ TEST(AlignmentTest, offsetToAlignment) {
TEST(AlignmentTest, AlignComparisons) { TEST(AlignmentTest, AlignComparisons) {
std::vector<uint64_t> ValidAlignments = getValidAlignments(); std::vector<uint64_t> ValidAlignments = getValidAlignments();
std::sort(ValidAlignments.begin(), ValidAlignments.end()); llvm::sort(ValidAlignments);
for (size_t I = 1; I < ValidAlignments.size(); ++I) { for (size_t I = 1; I < ValidAlignments.size(); ++I) {
assert(I >= 1); assert(I >= 1);
const Align A(ValidAlignments[I - 1]); const Align A(ValidAlignments[I - 1]);

View File

@ -122,15 +122,14 @@ static std::string buildCategoryStr(StringSet<> &Cetegorys) {
static void emitDXILEnums(std::vector<DXILOperationData> &DXILOps, static void emitDXILEnums(std::vector<DXILOperationData> &DXILOps,
raw_ostream &OS) { raw_ostream &OS) {
// Sort by Category + OpName. // Sort by Category + OpName.
std::sort(DXILOps.begin(), DXILOps.end(), llvm::sort(DXILOps, [](DXILOperationData &A, DXILOperationData &B) {
[](DXILOperationData &A, DXILOperationData &B) { // Group by Category first.
// Group by Category first. if (A.Category == B.Category)
if (A.Category == B.Category) // Inside same Category, order by OpName.
// Inside same Category, order by OpName. return A.DXILOp < B.DXILOp;
return A.DXILOp < B.DXILOp; else
else return A.Category < B.Category;
return A.Category < B.Category; });
});
OS << "// Enumeration for operations specified by DXIL\n"; OS << "// Enumeration for operations specified by DXIL\n";
OS << "enum class OpCode : unsigned {\n"; OS << "enum class OpCode : unsigned {\n";
@ -160,20 +159,19 @@ static void emitDXILEnums(std::vector<DXILOperationData> &DXILOps,
std::make_pair(It.getKey().str(), buildCategoryStr(It.second))); std::make_pair(It.getKey().str(), buildCategoryStr(It.second)));
} }
// Sort by Category + ClassName. // Sort by Category + ClassName.
std::sort(ClassVec.begin(), ClassVec.end(), llvm::sort(ClassVec, [](std::pair<std::string, std::string> &A,
[](std::pair<std::string, std::string> &A, std::pair<std::string, std::string> &B) {
std::pair<std::string, std::string> &B) { StringRef ClassA = A.first;
StringRef ClassA = A.first; StringRef CategoryA = A.second;
StringRef CategoryA = A.second; StringRef ClassB = B.first;
StringRef ClassB = B.first; StringRef CategoryB = B.second;
StringRef CategoryB = B.second; // Group by Category first.
// Group by Category first. if (CategoryA == CategoryB)
if (CategoryA == CategoryB) // Inside same Category, order by ClassName.
// Inside same Category, order by ClassName. return ClassA < ClassB;
return ClassA < ClassB; else
else return CategoryA < CategoryB;
return CategoryA < CategoryB; });
});
OS << "// Groups for DXIL operations with equivalent function templates\n"; OS << "// Groups for DXIL operations with equivalent function templates\n";
OS << "enum class OpCodeClass : unsigned {\n"; OS << "enum class OpCodeClass : unsigned {\n";
@ -266,10 +264,9 @@ static std::string getDXILOpClassName(StringRef DXILOpClass) {
static void emitDXILOperationTable(std::vector<DXILOperationData> &DXILOps, static void emitDXILOperationTable(std::vector<DXILOperationData> &DXILOps,
raw_ostream &OS) { raw_ostream &OS) {
// Sort by DXILOpID. // Sort by DXILOpID.
std::sort(DXILOps.begin(), DXILOps.end(), llvm::sort(DXILOps, [](DXILOperationData &A, DXILOperationData &B) {
[](DXILOperationData &A, DXILOperationData &B) { return A.DXILOpID < B.DXILOpID;
return A.DXILOpID < B.DXILOpID; });
});
// Collect Names. // Collect Names.
SequenceToOffsetTable<std::string> OpClassStrings; SequenceToOffsetTable<std::string> OpClassStrings;

View File

@ -681,7 +681,7 @@ void GenerateFlangClausesParser(const DirectiveLanguage &DirLang,
std::vector<Record *> Clauses = DirLang.getClauses(); std::vector<Record *> Clauses = DirLang.getClauses();
// Sort clauses in reverse alphabetical order so with clauses with same // Sort clauses in reverse alphabetical order so with clauses with same
// beginning, the longer option is tried before. // beginning, the longer option is tried before.
std::sort(Clauses.begin(), Clauses.end(), compareClauseName); llvm::sort(Clauses, compareClauseName);
IfDefScope Scope("GEN_FLANG_CLAUSES_PARSER", OS); IfDefScope Scope("GEN_FLANG_CLAUSES_PARSER", OS);
OS << "\n"; OS << "\n";
unsigned index = 0; unsigned index = 0;

View File

@ -15,6 +15,7 @@
#include "CodeGenIntrinsics.h" #include "CodeGenIntrinsics.h"
#include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringExtras.h"
#include "llvm/TableGen/Error.h" #include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h" #include "llvm/TableGen/Record.h"
@ -650,8 +651,9 @@ void SearchableTableEmitter::collectTableEntries(
SearchIndex Idx; SearchIndex Idx;
std::copy(Table.Fields.begin(), Table.Fields.end(), std::copy(Table.Fields.begin(), Table.Fields.end(),
std::back_inserter(Idx.Fields)); std::back_inserter(Idx.Fields));
std::sort(Table.Entries.begin(), Table.Entries.end(), llvm::sort(Table.Entries, [&](Record *LHS, Record *RHS) {
[&](Record *LHS, Record *RHS) { return compareBy(LHS, RHS, Idx); }); return compareBy(LHS, RHS, Idx);
});
} }
void SearchableTableEmitter::run(raw_ostream &OS) { void SearchableTableEmitter::run(raw_ostream &OS) {

View File

@ -121,8 +121,9 @@ public:
std::pair<std::string, std::vector<uint8_t>> serialize() { std::pair<std::string, std::vector<uint8_t>> serialize() {
std::set<std::string> Names = this->getNameFragments(); std::set<std::string> Names = this->getNameFragments();
std::vector<std::string> Sorted(Names.begin(), Names.end()); std::vector<std::string> Sorted(Names.begin(), Names.end());
std::sort(Sorted.begin(), Sorted.end(), llvm::sort(Sorted, [](const auto &a, const auto &b) {
[](const auto &a, const auto &b) { return a.size() > b.size(); }); return a.size() > b.size();
});
std::string Dict(Letters.begin(), Letters.end()); std::string Dict(Letters.begin(), Letters.end());
Dict.reserve(50000); Dict.reserve(50000);
for (const std::string &Name : Sorted) { for (const std::string &Name : Sorted) {

View File

@ -15,6 +15,7 @@
#include "mlir/IR/Operation.h" #include "mlir/IR/Operation.h"
#include "mlir/IR/Region.h" #include "mlir/IR/Region.h"
#include "mlir/IR/Value.h" #include "mlir/IR/Value.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetOperations.h" #include "llvm/ADT/SetOperations.h"
#include "llvm/ADT/SetVector.h" #include "llvm/ADT/SetVector.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
@ -288,10 +289,9 @@ void Liveness::print(raw_ostream &os) const {
auto printValueRefs = [&](const ValueSetT &values) { auto printValueRefs = [&](const ValueSetT &values) {
std::vector<Value> orderedValues(values.begin(), values.end()); std::vector<Value> orderedValues(values.begin(), values.end());
std::sort(orderedValues.begin(), orderedValues.end(), llvm::sort(orderedValues, [&](Value left, Value right) {
[&](Value left, Value right) { return valueIds[left] < valueIds[right];
return valueIds[left] < valueIds[right]; });
});
for (Value value : orderedValues) for (Value value : orderedValues)
printValueRef(value); printValueRef(value);
}; };
@ -317,10 +317,9 @@ void Liveness::print(raw_ostream &os) const {
printValueRef(result); printValueRef(result);
os << ":"; os << ":";
auto liveOperations = resolveLiveness(result); auto liveOperations = resolveLiveness(result);
std::sort(liveOperations.begin(), liveOperations.end(), llvm::sort(liveOperations, [&](Operation *left, Operation *right) {
[&](Operation *left, Operation *right) { return operationIds[left] < operationIds[right];
return operationIds[left] < operationIds[right]; });
});
for (Operation *operation : liveOperations) { for (Operation *operation : liveOperations) {
os << "\n// "; os << "\n// ";
operation->print(os); operation->print(os);

View File

@ -26,6 +26,7 @@
#include "mlir/Transforms/Passes.h" #include "mlir/Transforms/Passes.h"
#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h" #include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h" #include "llvm/ADT/SetVector.h"
#include "llvm/Support/CommandLine.h" #include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h" #include "llvm/Support/Debug.h"
@ -683,7 +684,7 @@ static void getProducerCandidates(unsigned dstId, MemRefDependenceGraph *mdg,
srcIdCandidates.push_back(srcNode->id); srcIdCandidates.push_back(srcNode->id);
} }
std::sort(srcIdCandidates.begin(), srcIdCandidates.end()); llvm::sort(srcIdCandidates);
srcIdCandidates.erase( srcIdCandidates.erase(
std::unique(srcIdCandidates.begin(), srcIdCandidates.end()), std::unique(srcIdCandidates.begin(), srcIdCandidates.end()),
srcIdCandidates.end()); srcIdCandidates.end());

View File

@ -673,7 +673,7 @@ void mlir::collapseParallelLoops(
// Presort combined dimensions. // Presort combined dimensions.
auto sortedDimensions = llvm::to_vector<3>(combinedDimensions); auto sortedDimensions = llvm::to_vector<3>(combinedDimensions);
for (auto &dims : sortedDimensions) for (auto &dims : sortedDimensions)
std::sort(dims.begin(), dims.end()); llvm::sort(dims);
// Normalize ParallelOp's iteration pattern. // Normalize ParallelOp's iteration pattern.
SmallVector<Value, 3> normalizedLowerBounds, normalizedSteps, SmallVector<Value, 3> normalizedLowerBounds, normalizedSteps,

View File

@ -1073,7 +1073,7 @@ static AffineExpr getSemiAffineExprFromFlatForm(ArrayRef<int64_t> flatExprs,
// Constructing the simplified semi-affine sum of product/division/mod // Constructing the simplified semi-affine sum of product/division/mod
// expression from the flattened form in the desired sorted order of indices // expression from the flattened form in the desired sorted order of indices
// of the various individual product/division/mod expressions. // of the various individual product/division/mod expressions.
std::sort(indices.begin(), indices.end()); llvm::sort(indices);
for (const std::pair<unsigned, unsigned> index : indices) { for (const std::pair<unsigned, unsigned> index : indices) {
assert(indexToExprMap.lookup(index) && assert(indexToExprMap.lookup(index) &&
"cannot find key in `indexToExprMap` map"); "cannot find key in `indexToExprMap` map");