https://github.com/artagnon updated 
https://github.com/llvm/llvm-project/pull/232372

>From 53c60523d9a55e2665e9d409a424084a3ea9a3e9 Mon Sep 17 00:00:00 2001
From: Ramkumar Ramachandra <[email protected]>
Date: Thu, 15 Oct 2026 09:45:17 +0100
Subject: [PATCH 1/2] [SetVector] Make SetVector::insert consistent (NFC)

Return a pair of iterator and bool, instead of a plain bool, like all
other ADT structures. This is a nice-to-have that does not degrade
compile time, as the iterator is never used.
---
 clang/include/clang/Sema/Weak.h                 |  6 ++++--
 clang/lib/APINotes/APINotesManager.cpp          |  2 +-
 clang/lib/AST/VTableBuilder.cpp                 |  6 +++---
 clang/lib/CodeGen/CGCleanup.h                   |  2 +-
 clang/lib/CodeGen/CodeGenModule.cpp             |  2 +-
 clang/lib/Sema/SemaLookup.cpp                   |  2 +-
 clang/lib/Sema/SemaOverload.cpp                 |  4 ++--
 clang/lib/Serialization/ASTWriter.cpp           |  3 ++-
 lld/ELF/Driver.cpp                              |  2 +-
 lld/MachO/SyntheticSections.cpp                 |  6 +++---
 lld/include/lld/Common/BPSectionOrdererBase.inc |  6 +++---
 llvm/include/llvm/ADT/CachedHashString.h        |  3 +++
 llvm/include/llvm/ADT/DirectedGraph.h           |  2 +-
 llvm/include/llvm/ADT/GenericUniformityImpl.h   |  2 +-
 llvm/include/llvm/ADT/SetVector.h               | 17 ++++++++++-------
 llvm/include/llvm/CodeGen/MachinePipeliner.h    |  2 +-
 llvm/include/llvm/IR/ModuleSummaryIndex.h       |  6 ++++++
 llvm/include/llvm/MC/MCContext.h                |  2 +-
 .../llvm/Transforms/Utils/InstructionWorklist.h |  2 +-
 .../lib/Analysis/FunctionPropertiesAnalysis.cpp |  3 +--
 llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp    |  4 ++--
 llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp  |  2 +-
 llvm/lib/CodeGen/MachineInstrBundle.cpp         |  4 ++--
 llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp   |  2 +-
 .../CodeGen/SelectionDAG/StatepointLowering.cpp | 14 +++++++-------
 llvm/lib/IR/ReplaceConstant.cpp                 |  2 +-
 llvm/lib/IR/SafepointIRVerifier.cpp             |  2 +-
 llvm/lib/Linker/IRMover.cpp                     |  2 +-
 .../lib/Target/AArch64/AArch64FrameLowering.cpp |  2 +-
 .../Target/AMDGPU/AMDGPUCoExecSchedStrategy.cpp |  2 +-
 .../Target/AMDGPU/AMDGPURewriteAGPRCopyMFMA.cpp |  2 +-
 llvm/lib/Target/ARM/MVELaneInterleavingPass.cpp |  6 +++---
 .../Hexagon/HexagonLoopIdiomRecognition.cpp     |  2 +-
 llvm/lib/Target/X86/X86LowerAMXType.cpp         |  2 +-
 llvm/lib/Transforms/Coroutines/SpillUtils.cpp   |  4 ++--
 .../lib/Transforms/IPO/AttributorAttributes.cpp | 14 +++++++-------
 llvm/lib/Transforms/IPO/FunctionImport.cpp      |  2 +-
 llvm/lib/Transforms/IPO/OpenMPOpt.cpp           |  8 ++++----
 .../Transforms/InstCombine/InstCombineCasts.cpp |  2 +-
 .../InstCombine/InstCombineLoadStoreAlloca.cpp  |  4 ++--
 llvm/lib/Transforms/Scalar/LoopDistribute.cpp   |  2 +-
 llvm/lib/Transforms/Utils/CodeExtractor.cpp     |  2 +-
 llvm/lib/Transforms/Utils/InlineFunction.cpp    |  2 +-
 llvm/lib/Transforms/Utils/LCSSA.cpp             |  2 +-
 llvm/lib/Transforms/Vectorize/LoopVectorize.cpp |  2 +-
 llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp |  2 +-
 llvm/unittests/IR/DebugInfoTest.cpp             |  4 ++--
 llvm/utils/TableGen/AsmMatcherEmitter.cpp       |  7 ++++---
 .../TableGen/Basic/AMDGPUTargetDefEmitter.cpp   |  2 +-
 llvm/utils/TableGen/Common/CodeGenRegisters.cpp |  4 ++--
 mlir/include/mlir/TableGen/Pattern.h            |  2 ++
 mlir/lib/Analysis/DataFlow/DeadCodeAnalysis.cpp |  4 ++--
 mlir/lib/Analysis/DataFlowFramework.cpp         |  4 ++--
 mlir/lib/Bytecode/Writer/IRNumbering.cpp        |  2 +-
 .../Transforms/OneShotAnalysis.cpp              |  4 ++--
 .../Transforms/OneShotModuleBufferize.cpp       |  2 +-
 .../GPU/TransformOps/GPUTransformOps.cpp        |  2 +-
 .../Vector/Transforms/VectorDistribute.cpp      |  2 +-
 mlir/lib/Tools/PDLL/CodeGen/CPPGen.cpp          |  2 +-
 mlir/lib/Tools/mlir-lsp-server/MLIRServer.cpp   |  2 +-
 mlir/tools/mlir-tblgen/OpFormatGen.cpp          |  4 ++--
 polly/lib/Analysis/ScopBuilder.cpp              |  2 +-
 polly/lib/Analysis/ScopDetection.cpp            |  2 +-
 polly/lib/Analysis/ScopInfo.cpp                 |  2 +-
 polly/lib/CodeGen/BlockGenerators.cpp           |  2 +-
 65 files changed, 123 insertions(+), 106 deletions(-)

diff --git a/clang/include/clang/Sema/Weak.h b/clang/include/clang/Sema/Weak.h
index 60341086abf61a..fb3d034f375332 100644
--- a/clang/include/clang/Sema/Weak.h
+++ b/clang/include/clang/Sema/Weak.h
@@ -31,8 +31,10 @@ class WeakInfo {
       : alias(Alias), loc(Loc) {}
   inline const IdentifierInfo *getAlias() const { return alias; }
   inline SourceLocation getLocation() const { return loc; }
-  bool operator==(WeakInfo RHS) const = delete;
-  bool operator!=(WeakInfo RHS) const = delete;
+  bool operator==(const WeakInfo &RHS) const {
+    return getAlias() == RHS.getAlias() && getLocation() == RHS.getLocation();
+  }
+  bool operator!=(const WeakInfo &RHS) const { return !(*this == RHS); }
 
   struct DenseMapInfoByAliasOnly
       : private llvm::DenseMapInfo<const IdentifierInfo *> {
diff --git a/clang/lib/APINotes/APINotesManager.cpp 
b/clang/lib/APINotes/APINotesManager.cpp
index 184d9fde0e6756..c829d54d30f90c 100644
--- a/clang/lib/APINotes/APINotesManager.cpp
+++ b/clang/lib/APINotes/APINotesManager.cpp
@@ -452,7 +452,7 @@ APINotesManager::findAPINotes(SourceLocation Loc) {
     }
 
     // We didn't find anything. Look at the parent directory.
-    if (!DirsVisited.insert(*Dir)) {
+    if (!DirsVisited.insert(*Dir).second) {
       Dir = std::nullopt;
       break;
     }
diff --git a/clang/lib/AST/VTableBuilder.cpp b/clang/lib/AST/VTableBuilder.cpp
index 3c05d4b22b03e1..e079678ba2d0dd 100644
--- a/clang/lib/AST/VTableBuilder.cpp
+++ b/clang/lib/AST/VTableBuilder.cpp
@@ -1430,7 +1430,7 @@ bool ItaniumVTableBuilder::IsOverriderUsed(
              "Primary base should always be at offset 0!");
     }
 
-    if (!PrimaryBases.insert(PrimaryBase))
+    if (!PrimaryBases.insert(PrimaryBase).second)
       llvm_unreachable("Found a duplicate primary base!");
 
     RD = PrimaryBase;
@@ -1511,7 +1511,7 @@ void ItaniumVTableBuilder::AddMethods(
                PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
                FirstBaseOffsetInLayoutClass, PrimaryBases);
 
-    if (!PrimaryBases.insert(PrimaryBase))
+    if (!PrimaryBases.insert(PrimaryBase).second)
       llvm_unreachable("Found a duplicate primary base!");
   }
 
@@ -3072,7 +3072,7 @@ void VFTableBuilder::AddMethods(BaseSubobject Base, 
unsigned BaseDepth,
   if (NextBase) {
     AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
                NextLastVBase, VisitedBases);
-    if (!VisitedBases.insert(NextBase))
+    if (!VisitedBases.insert(NextBase).second)
       llvm_unreachable("Found a duplicate primary base!");
   }
 
diff --git a/clang/lib/CodeGen/CGCleanup.h b/clang/lib/CodeGen/CGCleanup.h
index fd8206fbccfe18..f8dc11ada379ab 100644
--- a/clang/lib/CodeGen/CGCleanup.h
+++ b/clang/lib/CodeGen/CGCleanup.h
@@ -310,7 +310,7 @@ class alignas(8) EHCleanupScope : public EHScope {
   private:
     void CollectUses(llvm::Instruction *I,
                      llvm::SetVector<llvm::Instruction *> &Uses) {
-      if (!I || !Uses.insert(I))
+      if (!I || !Uses.insert(I).second)
         return;
       for (auto *User : I->users())
         CollectUses(cast<llvm::Instruction>(User), Uses);
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index eec4d9e714abe6..03dbbffe064fd5 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -8222,7 +8222,7 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) {
     auto *Import = cast<ImportDecl>(D);
 
     // If we've already imported this module, we're done.
-    if (!ImportedModules.insert(Import->getImportedModule()))
+    if (!ImportedModules.insert(Import->getImportedModule()).second)
       break;
 
     // Emit debug information for direct imports.
diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp
index 75cad0bb433f89..b604fcb3ee3a8e 100644
--- a/clang/lib/Sema/SemaLookup.cpp
+++ b/clang/lib/Sema/SemaLookup.cpp
@@ -2903,7 +2903,7 @@ namespace {
 
     bool addClassTransitive(CXXRecordDecl *RD) {
       Classes.insert(RD);
-      return ClassesTransitive.insert(RD);
+      return ClassesTransitive.insert(RD).second;
     }
 
     Sema &S;
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index c56f8127834a51..f34e119c2bbac4 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -9287,7 +9287,7 @@ 
BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
                                              const Qualifiers &VisibleQuals) {
 
   // Insert this type.
-  if (!PointerTypes.insert(Ty))
+  if (!PointerTypes.insert(Ty).second)
     return false;
 
   QualType PointeeTy;
@@ -9355,7 +9355,7 @@ bool
 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
     QualType Ty) {
   // Insert this type.
-  if (!MemberPointerTypes.insert(Ty))
+  if (!MemberPointerTypes.insert(Ty).second)
     return false;
 
   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
diff --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index de1c2449138e58..a7996b02c07264 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -7806,7 +7806,8 @@ void ASTWriter::AddedVisibleDecl(const DeclContext *DC, 
const Decl *D) {
   assert(DC == DC->getPrimaryContext() && "added to non-primary context");
   assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
   assert(!WritingAST && "Already writing the AST!");
-  if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
+  if (UpdatedDeclContexts.insert(DC).second &&
+      !cast<Decl>(DC)->isFromASTFile()) {
     // We're adding a visible declaration to a predefined decl context. Ensure
     // that we write out all of its lookup results so we don't get a nasty
     // surprise when we try to emit its lookup table.
diff --git a/lld/ELF/Driver.cpp b/lld/ELF/Driver.cpp
index a08f6f2d384bc1..44e4b94c506423 100644
--- a/lld/ELF/Driver.cpp
+++ b/lld/ELF/Driver.cpp
@@ -1336,7 +1336,7 @@ static SmallVector<StringRef, 0> 
getSymbolOrderingFile(Ctx &ctx,
                                                        MemoryBufferRef mb) {
   SetVector<StringRef, SmallVector<StringRef, 0>> names;
   for (StringRef s : args::getLines(mb))
-    if (!names.insert(s) && ctx.arg.warnSymbolOrdering)
+    if (!names.insert(s).second && ctx.arg.warnSymbolOrdering)
       Warn(ctx) << mb.getBufferIdentifier()
                 << ": duplicate ordered symbol: " << s;
 
diff --git a/lld/MachO/SyntheticSections.cpp b/lld/MachO/SyntheticSections.cpp
index 2c25269d63d1dc..51fb0e0c974a0a 100644
--- a/lld/MachO/SyntheticSections.cpp
+++ b/lld/MachO/SyntheticSections.cpp
@@ -337,7 +337,7 @@ void macho::addNonLazyBindingEntries(const Symbol *sym,
 }
 
 void GotSection::addEntry(Symbol *sym) {
-  if (entries.insert(sym)) {
+  if (entries.insert(sym).second) {
     // Every symbol has at most one non-lazy pointer slot.
     assert(!sym->isInGot());
     sym->gotIndex = entries.size() - 1;
@@ -746,7 +746,7 @@ static void addBindingsForStub(Symbol *sym) {
 }
 
 void StubsSection::addEntry(Symbol *sym) {
-  bool inserted = entries.insert(sym);
+  bool inserted = entries.insert(sym).second;
   if (inserted) {
     sym->stubsIndex = entries.size() - 1;
 
@@ -1011,7 +1011,7 @@ void LazyBindingSection::writeTo(uint8_t *buf) const {
 
 void LazyBindingSection::addEntry(Symbol *sym) {
   assert(!config->emitChainedFixups && "Chained fixups always bind eagerly");
-  if (entries.insert(sym)) {
+  if (entries.insert(sym).second) {
     sym->stubsHelperIndex = entries.size() - 1;
     in.rebase->addEntry(in.lazyPointers->isec,
                         sym->stubsIndex * target->wordSize);
diff --git a/lld/include/lld/Common/BPSectionOrdererBase.inc 
b/lld/include/lld/Common/BPSectionOrdererBase.inc
index 841c46110ae0f1..a88026ef935bf5 100644
--- a/lld/include/lld/Common/BPSectionOrdererBase.inc
+++ b/lld/include/lld/Common/BPSectionOrdererBase.inc
@@ -381,7 +381,7 @@ auto BPOrderer<D>::computeOrder(
   // Order startup functions,
   for (auto &node : nodesForStartup) {
     const auto *isec = sections[node.Id];
-    if (orderedSections.insert(isec)) {
+    if (orderedSections.insert(isec).second) {
       startupSize += D::getSize(*isec);
       ++numStartupSections;
     }
@@ -390,7 +390,7 @@ auto BPOrderer<D>::computeOrder(
   for (const auto &nodes : nodesForCompression) {
     for (auto &node : nodes) {
       const auto *isec = sections[node.Id];
-      if (orderedSections.insert(isec)) {
+      if (orderedSections.insert(isec).second) {
         compressionSize += D::getSize(*isec);
         ++numCompressionSections;
       }
@@ -399,7 +399,7 @@ auto BPOrderer<D>::computeOrder(
         continue;
       for (auto dupSecIdx : It->getSecond()) {
         const auto *dupIsec = sections[dupSecIdx];
-        if (orderedSections.insert(dupIsec)) {
+        if (orderedSections.insert(dupIsec).second) {
           duplicateCompressionSize += D::getSize(*dupIsec);
           ++numDuplicateCompressionSections;
         }
diff --git a/llvm/include/llvm/ADT/CachedHashString.h 
b/llvm/include/llvm/ADT/CachedHashString.h
index 902951d0011bc1..169d8035706165 100644
--- a/llvm/include/llvm/ADT/CachedHashString.h
+++ b/llvm/include/llvm/ADT/CachedHashString.h
@@ -40,6 +40,9 @@ class CachedHashStringRef {
       : P(S.data()), Size(S.size()), Hash(Hash) {
     assert(S.size() <= std::numeric_limits<uint32_t>::max());
   }
+  bool operator==(const CachedHashStringRef &Other) const {
+    return hash() == Other.hash() && val() == Other.val();
+  }
 
   StringRef val() const { return StringRef(P, Size); }
   const char *data() const { return P; }
diff --git a/llvm/include/llvm/ADT/DirectedGraph.h 
b/llvm/include/llvm/ADT/DirectedGraph.h
index fe7c9e51cbd9af..e15c18f7970359 100644
--- a/llvm/include/llvm/ADT/DirectedGraph.h
+++ b/llvm/include/llvm/ADT/DirectedGraph.h
@@ -112,7 +112,7 @@ template <class NodeType, class EdgeType> class DGNode {
 
   /// Add the given edge \p E to this node, if it doesn't exist already. 
Returns
   /// true if the edge is added and false otherwise.
-  bool addEdge(EdgeType &E) { return Edges.insert(&E); }
+  bool addEdge(EdgeType &E) { return Edges.insert(&E).second; }
 
   /// Remove the given edge \p E from this node, if it exists.
   void removeEdge(EdgeType &E) { Edges.remove(&E); }
diff --git a/llvm/include/llvm/ADT/GenericUniformityImpl.h 
b/llvm/include/llvm/ADT/GenericUniformityImpl.h
index c6f0bba051b609..7fcc13f6f01006 100644
--- a/llvm/include/llvm/ADT/GenericUniformityImpl.h
+++ b/llvm/include/llvm/ADT/GenericUniformityImpl.h
@@ -924,7 +924,7 @@ void 
GenericUniformityAnalysisImpl<ContextT>::propagateCycleExitDivergence(
   LLVM_DEBUG(dbgs() << "\tOuter-most exiting cycle: "
                     << Context.print(CI.getHeader(OuterDivCycle)) << "\n");
 
-  if (!DivergentExitCycles.insert(OuterDivCycle))
+  if (!DivergentExitCycles.insert(OuterDivCycle).second)
     return;
 
   // Exit divergence does not matter if the cycle itself is assumed to
diff --git a/llvm/include/llvm/ADT/SetVector.h 
b/llvm/include/llvm/ADT/SetVector.h
index bc0ac2583327b3..24defb802c9c16 100644
--- a/llvm/include/llvm/ADT/SetVector.h
+++ b/llvm/include/llvm/ADT/SetVector.h
@@ -153,23 +153,26 @@ class SetVector {
   }
 
   /// Insert a new element into the SetVector.
-  /// \returns true if the element was inserted into the SetVector.
-  bool insert(const value_type &X) {
+  /// \returns a pair, whose first member is the iterator pointed to the
+  /// element, and the second member indicates if the element was inserted.
+  std::pair<iterator, bool> insert(const value_type &X) {
     if constexpr (canBeSmall())
       if (isSmall()) {
         if (!llvm::is_contained(vector_, X)) {
           vector_.push_back(X);
           if (vector_.size() > N)
             makeBig();
-          return true;
+          return {std::prev(vector_.end()), true};
         }
-        return false;
+        return {find(vector_, X), false};
       }
 
     bool result = set_.insert(X).second;
-    if (result)
+    if (result) {
       vector_.push_back(X);
-    return result;
+      return {std::prev(vector_.end()), result};
+    }
+    return {find(vector_, X), result};
   }
 
   /// Insert a range of elements into the SetVector.
@@ -304,7 +307,7 @@ class SetVector {
     bool Changed = false;
 
     for (const auto &Elem : S)
-      if (insert(Elem))
+      if (insert(Elem).second)
         Changed = true;
 
     return Changed;
diff --git a/llvm/include/llvm/CodeGen/MachinePipeliner.h 
b/llvm/include/llvm/CodeGen/MachinePipeliner.h
index bd9c52d6ed5e24..2290c0d8e09e70 100644
--- a/llvm/include/llvm/CodeGen/MachinePipeliner.h
+++ b/llvm/include/llvm/CodeGen/MachinePipeliner.h
@@ -534,7 +534,7 @@ class NodeSet {
     Latency = SUnitToDistance[Nodes.front()];
   }
 
-  bool insert(SUnit *SU) { return Nodes.insert(SU); }
+  bool insert(SUnit *SU) { return Nodes.insert(SU).second; }
 
   void insert(iterator S, iterator E) { Nodes.insert(S, E); }
 
diff --git a/llvm/include/llvm/IR/ModuleSummaryIndex.h 
b/llvm/include/llvm/IR/ModuleSummaryIndex.h
index 31e6898130e7d4..622b07e135d3c4 100644
--- a/llvm/include/llvm/IR/ModuleSummaryIndex.h
+++ b/llvm/include/llvm/IR/ModuleSummaryIndex.h
@@ -863,6 +863,9 @@ class FunctionSummary : public GlobalValueSummary {
   struct VFuncId {
     GlobalValue::GUID GUID;
     uint64_t Offset;
+    bool operator==(const VFuncId &Other) const {
+      return GUID == Other.GUID && Offset == Other.Offset;
+    }
   };
 
   /// A specification for a virtual function call with all constant integer
@@ -871,6 +874,9 @@ class FunctionSummary : public GlobalValueSummary {
   struct ConstVCall {
     VFuncId VFunc;
     std::vector<uint64_t> Args;
+    bool operator==(const ConstVCall &Other) const {
+      return VFunc == Other.VFunc && Args == Other.Args;
+    }
   };
 
   /// All type identifier related information. Because these fields are
diff --git a/llvm/include/llvm/MC/MCContext.h b/llvm/include/llvm/MC/MCContext.h
index c38609c93e142c..2c08d2ef6521ba 100644
--- a/llvm/include/llvm/MC/MCContext.h
+++ b/llvm/include/llvm/MC/MCContext.h
@@ -790,7 +790,7 @@ class MCContext {
   }
 
   bool addGenDwarfSection(MCSection *Sec) {
-    return SectionsForRanges.insert(Sec);
+    return SectionsForRanges.insert(Sec).second;
   }
 
   LLVM_ABI void finalizeDwarfSections(MCStreamer &MCOS);
diff --git a/llvm/include/llvm/Transforms/Utils/InstructionWorklist.h 
b/llvm/include/llvm/Transforms/Utils/InstructionWorklist.h
index 5a46fff651336b..a1b6f7967a946a 100644
--- a/llvm/include/llvm/Transforms/Utils/InstructionWorklist.h
+++ b/llvm/include/llvm/Transforms/Utils/InstructionWorklist.h
@@ -42,7 +42,7 @@ class InstructionWorklist {
   /// Instructions will be visited in the order they are added.
   /// You likely want to use this method.
   void add(Instruction *I) {
-    if (Deferred.insert(I))
+    if (Deferred.insert(I).second)
       LLVM_DEBUG(dbgs() << "ADD DEFERRED: " << *I << '\n');
   }
 
diff --git a/llvm/lib/Analysis/FunctionPropertiesAnalysis.cpp 
b/llvm/lib/Analysis/FunctionPropertiesAnalysis.cpp
index e07cdbeb240eff..c4e00fae1e0ef8 100644
--- a/llvm/lib/Analysis/FunctionPropertiesAnalysis.cpp
+++ b/llvm/lib/Analysis/FunctionPropertiesAnalysis.cpp
@@ -546,8 +546,7 @@ void 
FunctionPropertiesUpdater::finish(FunctionAnalysisManager &FAM) const {
   // ending at those successors, we also want to perform a traversal.
   // IncludeSuccessorsMark is the index after which we include successors.
   const auto IncludeSuccessorsMark = Reinclude.size();
-  bool CSInsertion = Reinclude.insert(&CallSiteBB);
-  (void)CSInsertion;
+  [[maybe_unused]] bool CSInsertion = Reinclude.insert(&CallSiteBB).second;
   assert(CSInsertion);
   for (size_t I = 0; I < Reinclude.size(); ++I) {
     const auto *BB = Reinclude[I];
diff --git a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp 
b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
index 5a6341b79b6d31..1a0460e5fa6e7b 100644
--- a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
+++ b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
@@ -455,7 +455,7 @@ static const MDNode *getLeastCommonType(const MDNode *A, 
const MDNode *B) {
   SmallSetVector<const MDNode *, 4> PathA;
   TBAANode TA(A);
   while (TA.getNode()) {
-    [[maybe_unused]] bool Inserted = PathA.insert(TA.getNode());
+    [[maybe_unused]] bool Inserted = PathA.insert(TA.getNode()).second;
     assert(Inserted && "Cycle found in TBAA metadata.");
     TA = TA.getParent();
   }
@@ -463,7 +463,7 @@ static const MDNode *getLeastCommonType(const MDNode *A, 
const MDNode *B) {
   SmallSetVector<const MDNode *, 4> PathB;
   TBAANode TB(B);
   while (TB.getNode()) {
-    [[maybe_unused]] bool Inserted = PathB.insert(TB.getNode());
+    [[maybe_unused]] bool Inserted = PathB.insert(TB.getNode()).second;
     assert(Inserted && "Cycle found in TBAA metadata.");
     TB = TB.getParent();
   }
diff --git a/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp 
b/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
index df0122489b252d..44ec55dd7b8ec8 100644
--- a/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
+++ b/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
@@ -4340,7 +4340,7 @@ void CombinerHelper::applyExtendThroughPhis(MachineInstr 
&MI,
     MachineInstr *SrcMI;
     if (!mi_match(SrcReg, MRI, m_MInstr(SrcMI)))
       continue;
-    if (!SrcMIs.insert(SrcMI))
+    if (!SrcMIs.insert(SrcMI).second)
       continue;
 
     // Build an extend after each src inst.
diff --git a/llvm/lib/CodeGen/MachineInstrBundle.cpp 
b/llvm/lib/CodeGen/MachineInstrBundle.cpp
index c6eeed3adcb405..2a27f18fa51376 100644
--- a/llvm/lib/CodeGen/MachineInstrBundle.cpp
+++ b/llvm/lib/CodeGen/MachineInstrBundle.cpp
@@ -173,7 +173,7 @@ void llvm::finalizeBundle(MachineBasicBlock &MBB,
           DeadDefSet.insert(Reg);
         }
       } else {
-        if (ExternUses.insert(Reg)) {
+        if (ExternUses.insert(Reg).second) {
           if (MO.isUndef())
             UndefUseSet.insert(Reg);
         }
@@ -198,7 +198,7 @@ void llvm::finalizeBundle(MachineBasicBlock &MBB,
       if (!Reg)
         continue;
 
-      if (LocalDefs.insert(Reg)) {
+      if (LocalDefs.insert(Reg).second) {
         if (!MO.isDead() && Reg.isPhysical()) {
           for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
             LocalDefsP.set(static_cast<unsigned>(Unit));
diff --git a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp 
b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
index d5dfc5598cde37..4c3837d77bbc3b 100644
--- a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
@@ -28573,7 +28573,7 @@ static SDValue 
foldExtractSubvectorFromShuffleVector(EVT NarrowVT, SDValue Src,
     const std::pair<SDValue, int> DemandedSubvector =
         std::make_pair(Op, OpSubvecIdx);
 
-    if (DemandedSubvectors.insert(DemandedSubvector)) {
+    if (DemandedSubvectors.insert(DemandedSubvector).second) {
       if (DemandedSubvectors.size() > 2)
         return SDValue(); // We can't handle more than two subvectors.
       // How many elements into the WideVT does this subvector start?
diff --git a/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp 
b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp
index b7a9464c6661c8..76c1ec51ec6eeb 100644
--- a/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp
@@ -455,7 +455,7 @@ lowerIncomingStatepointValue(SDValue Incoming, bool 
RequireSpillSlot,
                              SmallVectorImpl<SDValue> &Ops,
                              SmallVectorImpl<MachineMemOperand *> &MemRefs,
                              SelectionDAGBuilder &Builder) {
-  
+
   if (willLowerDirectly(Incoming)) {
     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
       // This handles allocas as arguments to the statepoint (this is only
@@ -473,7 +473,7 @@ lowerIncomingStatepointValue(SDValue Incoming, bool 
RequireSpillSlot,
     }
 
     assert(Incoming.getValueType().getSizeInBits() <= 64);
-    
+
     if (Incoming.isUndef()) {
       // Put an easily recognized constant that's unlikely to be a valid
       // value so that uses of undef by the consumer of the stackmap is
@@ -515,7 +515,7 @@ lowerIncomingStatepointValue(SDValue Incoming, bool 
RequireSpillSlot,
     // found by the runtime later.  Note: We know all of these spills are
     // independent, but don't bother to exploit that chain wise.  DAGCombine
     // will happily do so as needed, so doing it here would be a small compile
-    // time win at most. 
+    // time win at most.
     SDValue Chain = Builder.getRoot();
     auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
     Ops.push_back(std::get<0>(Res));
@@ -605,7 +605,7 @@ lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
 
   auto processGCPtr = [&](const Value *V) {
     SDValue PtrSD = Builder.getValue(V);
-    if (!LoweredGCPtrs.insert(PtrSD))
+    if (!LoweredGCPtrs.insert(PtrSD).second)
       return; // skip duplicates
     GCPtrIndexMap[PtrSD] = LoweredGCPtrs.size() - 1;
 
@@ -1145,7 +1145,7 @@ SelectionDAGBuilder::LowerStatepoint(const 
GCStatepointInst &I,
   if (GCResultLocality.first) {
     // Result value will be used in a same basic block. Don't export it or
     // perform any explicit register copies. The gc_result will simply grab
-    // this value. 
+    // this value.
     setValue(&I, ReturnValue);
   }
 
@@ -1165,7 +1165,7 @@ SelectionDAGBuilder::LowerStatepoint(const 
GCStatepointInst &I,
                    DAG.getDataLayout(), Reg, RetTy,
                    I.getCallingConv());
   SDValue Chain = DAG.getEntryNode();
-  
+
   RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
   PendingExports.push_back(Chain);
   FuncInfo.ValueMap[&I] = Reg;
@@ -1235,7 +1235,7 @@ void SelectionDAGBuilder::visitGCResult(const 
GCResultInst &CI) {
   // which is always i32 in our case.
   Type *RetTy = CI.getType();
   SDValue CopyFromReg = getCopyFromRegs(SI, RetTy);
-  
+
   assert(CopyFromReg.getNode());
   setValue(&CI, CopyFromReg);
 }
diff --git a/llvm/lib/IR/ReplaceConstant.cpp b/llvm/lib/IR/ReplaceConstant.cpp
index b1864c3dc9eebe..f0cd4d88b48ba7 100644
--- a/llvm/lib/IR/ReplaceConstant.cpp
+++ b/llvm/lib/IR/ReplaceConstant.cpp
@@ -72,7 +72,7 @@ bool 
llvm::convertUsersOfConstantsToInstructions(ArrayRef<Constant *> Consts,
   SetVector<Constant *> ExpandableUsers;
   while (!Stack.empty()) {
     Constant *C = Stack.pop_back_val();
-    if (!ExpandableUsers.insert(C))
+    if (!ExpandableUsers.insert(C).second)
       continue;
 
     for (auto *Nested : C->users())
diff --git a/llvm/lib/IR/SafepointIRVerifier.cpp 
b/llvm/lib/IR/SafepointIRVerifier.cpp
index 946d5c863bb502..fc1efd0d6e3f0b 100644
--- a/llvm/lib/IR/SafepointIRVerifier.cpp
+++ b/llvm/lib/IR/SafepointIRVerifier.cpp
@@ -174,7 +174,7 @@ class CFGDeadness {
   }
 
   void addDeadEdge(const Use &DeadEdge) {
-    if (!DeadEdges.insert(&DeadEdge))
+    if (!DeadEdges.insert(&DeadEdge).second)
       return;
 
     BasicBlock *BB = cast_or_null<BasicBlock>(DeadEdge.get());
diff --git a/llvm/lib/Linker/IRMover.cpp b/llvm/lib/Linker/IRMover.cpp
index 214a25055a613a..f18c10c0c2b6ef 100644
--- a/llvm/lib/Linker/IRMover.cpp
+++ b/llvm/lib/Linker/IRMover.cpp
@@ -1212,7 +1212,7 @@ Error IRLinker::linkModuleFlagsMetadata() {
     if (SrcBehaviorValue == Module::Require) {
       // If the destination module does not already have this requirement, add
       // it.
-      if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
+      if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2))).second) {
         DstModFlags->addOperand(SrcOp);
       }
       continue;
diff --git a/llvm/lib/Target/AArch64/AArch64FrameLowering.cpp 
b/llvm/lib/Target/AArch64/AArch64FrameLowering.cpp
index 49e0148d72f544..c5b0ce6b271128 100644
--- a/llvm/lib/Target/AArch64/AArch64FrameLowering.cpp
+++ b/llvm/lib/Target/AArch64/AArch64FrameLowering.cpp
@@ -499,7 +499,7 @@ AArch64FrameLowering::getFixedObjectSize(const 
MachineFunction &MF,
         for (const WinEHHandlerType &H : TBME.HandlerArray) {
           int FrameIndex = H.CatchObj.FrameIndex;
           if ((FrameIndex != INT_MAX) &&
-              CatchObjFrameIndices.insert(FrameIndex)) {
+              CatchObjFrameIndices.insert(FrameIndex).second) {
             FixedObjectSize = alignTo(FixedObjectSize,
                                       MFI.getObjectAlign(FrameIndex).value()) +
                               MFI.getObjectSize(FrameIndex);
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUCoExecSchedStrategy.cpp 
b/llvm/lib/Target/AMDGPU/AMDGPUCoExecSchedStrategy.cpp
index 0a4961285584dc..d83ee98e7df65d 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUCoExecSchedStrategy.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUCoExecSchedStrategy.cpp
@@ -464,7 +464,7 @@ SUnit *HardwareUnitInfo::getNextTargetSU(bool LookDeep) 
const {
 }
 
 void HardwareUnitInfo::insert(SUnit *SU, unsigned BlockingCycles) {
-  if (!AllSUs.insert(SU))
+  if (!AllSUs.insert(SU).second)
     llvm_unreachable("HardwareUnit already contains SU!");
 
   TotalCycles += BlockingCycles;
diff --git a/llvm/lib/Target/AMDGPU/AMDGPURewriteAGPRCopyMFMA.cpp 
b/llvm/lib/Target/AMDGPU/AMDGPURewriteAGPRCopyMFMA.cpp
index 65d76d75072674..05bc0221d348a8 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPURewriteAGPRCopyMFMA.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPURewriteAGPRCopyMFMA.cpp
@@ -191,7 +191,7 @@ bool 
AMDGPURewriteAGPRCopyMFMAImpl::recomputeRegClassExceptRewritable(
           if (OtherReg.isPhysical())
             return false;
 
-          if (OtherReg != Reg && RewriteRegs.insert(OtherReg))
+          if (OtherReg != Reg && RewriteRegs.insert(OtherReg).second)
             Worklist.push_back(OtherReg);
         }
 
diff --git a/llvm/lib/Target/ARM/MVELaneInterleavingPass.cpp 
b/llvm/lib/Target/ARM/MVELaneInterleavingPass.cpp
index 251cee3438e193..bf18ab5a15bbfd 100644
--- a/llvm/lib/Target/ARM/MVELaneInterleavingPass.cpp
+++ b/llvm/lib/Target/ARM/MVELaneInterleavingPass.cpp
@@ -171,7 +171,7 @@ static bool tryInterleave(Instruction *Start,
     // Truncs
     case Instruction::Trunc:
     case Instruction::FPTrunc:
-      if (!Truncs.insert(I))
+      if (!Truncs.insert(I).second)
         continue;
       Visited.insert(I);
       break;
@@ -193,7 +193,7 @@ static bool tryInterleave(Instruction *Start,
         return false;
 
       if (II->getIntrinsicID() == Intrinsic::vector_reduce_add) {
-        if (!Reducts.insert(I))
+        if (!Reducts.insert(I).second)
           continue;
         Visited.insert(I);
         break;
@@ -236,7 +236,7 @@ static bool tryInterleave(Instruction *Start,
     case Instruction::FAdd:
     case Instruction::FMul:
     case Instruction::Select:
-      if (!Ops.insert(I))
+      if (!Ops.insert(I).second)
         continue;
 
       for (Use &Op : I->operands()) {
diff --git a/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp 
b/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp
index f2175483f24d6d..cf90d35b2a79b0 100644
--- a/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp
+++ b/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp
@@ -1129,7 +1129,7 @@ bool PolynomialMultiplyRecognize::findCycle(Value *Out, 
Value *In,
     if (IsPhi && HadPhi)
       return false;
     HadPhi |= IsPhi;
-    if (!Cycle.insert(I))
+    if (!Cycle.insert(I).second)
       return false;
     if (findCycle(I, In, Cycle))
       break;
diff --git a/llvm/lib/Target/X86/X86LowerAMXType.cpp 
b/llvm/lib/Target/X86/X86LowerAMXType.cpp
index 9d01f572b3125d..8ed8256e129f89 100644
--- a/llvm/lib/Target/X86/X86LowerAMXType.cpp
+++ b/llvm/lib/Target/X86/X86LowerAMXType.cpp
@@ -835,7 +835,7 @@ bool X86LowerAMXCast::optimizeAMXCastFromPhi(
       }
 
       if (auto *PNode = dyn_cast<PHINode>(IncValue)) {
-        if (OldPhiNodes.insert(PNode))
+        if (OldPhiNodes.insert(PNode).second)
           PhiWorklist.push_back(PNode);
         continue;
       }
diff --git a/llvm/lib/Transforms/Coroutines/SpillUtils.cpp 
b/llvm/lib/Transforms/Coroutines/SpillUtils.cpp
index 5078b3a026ae18..13e7f9a88ed73f 100644
--- a/llvm/lib/Transforms/Coroutines/SpillUtils.cpp
+++ b/llvm/lib/Transforms/Coroutines/SpillUtils.cpp
@@ -551,7 +551,7 @@ void coro::sinkSpillUsesAfterCoroBegin(
       if (Inst->getParent() != CoroBegin->getParent() ||
           Dom.dominates(CoroBegin, Inst))
         continue;
-      if (ToMove.insert(Inst))
+      if (ToMove.insert(Inst).second)
         Worklist.push_back(Inst);
     }
   };
@@ -567,7 +567,7 @@ void coro::sinkSpillUsesAfterCoroBegin(
       auto Inst = cast<Instruction>(U);
       if (Dom.dominates(CoroBegin, Inst))
         continue;
-      if (ToMove.insert(Inst))
+      if (ToMove.insert(Inst).second)
         Worklist.push_back(Inst);
     }
   }
diff --git a/llvm/lib/Transforms/IPO/AttributorAttributes.cpp 
b/llvm/lib/Transforms/IPO/AttributorAttributes.cpp
index 8251f8858c9f19..20e61315ad71af 100644
--- a/llvm/lib/Transforms/IPO/AttributorAttributes.cpp
+++ b/llvm/lib/Transforms/IPO/AttributorAttributes.cpp
@@ -4912,7 +4912,7 @@ ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) {
     } else if (AliveSuccessors.empty() ||
                (I->isTerminator() &&
                 AliveSuccessors.size() < I->getNumSuccessors())) {
-      if (KnownDeadEnds.insert(I))
+      if (KnownDeadEnds.insert(I).second)
         Change = ChangeStatus::CHANGED;
     }
 
@@ -10688,7 +10688,7 @@ struct AACallEdgesImpl : public AACallEdges {
 
 protected:
   void addCalledFunction(Function *Fn, ChangeStatus &Change) {
-    if (CalledFunctions.insert(Fn)) {
+    if (CalledFunctions.insert(Fn).second) {
       Change = ChangeStatus::CHANGED;
       LLVM_DEBUG(dbgs() << "[AACallEdges] New call edge: " << Fn->getName()
                         << "\n");
@@ -12098,7 +12098,7 @@ struct AAUnderlyingObjectsImpl
 
       if (!A.getAssumedSimplifiedValues(IRPosition::value(Ptr), *this, Values,
                                         Scope, UsedAssumedInformation))
-        return UnderlyingObjects.insert(&Ptr);
+        return UnderlyingObjects.insert(&Ptr).second;
 
       bool Changed = false;
 
@@ -12110,7 +12110,7 @@ struct AAUnderlyingObjectsImpl
           continue;
         if (UO && UO != Obj) {
           if (isa<AllocaInst>(UO) || isa<GlobalValue>(UO)) {
-            Changed |= UnderlyingObjects.insert(UO);
+            Changed |= UnderlyingObjects.insert(UO).second;
             continue;
           }
 
@@ -12118,7 +12118,7 @@ struct AAUnderlyingObjectsImpl
               *this, IRPosition::value(*UO), DepClassTy::OPTIONAL);
           auto Pred = [&](Value &V) {
             if (&V == UO)
-              Changed |= UnderlyingObjects.insert(UO);
+              Changed |= UnderlyingObjects.insert(UO).second;
             else
               Values.emplace_back(V, nullptr);
             return true;
@@ -12147,7 +12147,7 @@ struct AAUnderlyingObjectsImpl
           continue;
         }
 
-        Changed |= UnderlyingObjects.insert(Obj);
+        Changed |= UnderlyingObjects.insert(Obj).second;
       }
 
       return Changed;
@@ -12187,7 +12187,7 @@ struct AAUnderlyingObjectsImpl
     const auto *AA = A.getAAFor<AAUnderlyingObjects>(
         *this, IRPosition::value(V), DepClassTy::OPTIONAL);
     auto Pred = [&](Value &V) {
-      Changed |= UnderlyingObjects.insert(&V);
+      Changed |= UnderlyingObjects.insert(&V).second;
       return true;
     };
     if (!AA || !AA->forallUnderlyingObjects(Pred, Scope))
diff --git a/llvm/lib/Transforms/IPO/FunctionImport.cpp 
b/llvm/lib/Transforms/IPO/FunctionImport.cpp
index 63265ca3a65477..18cd4e42704f02 100644
--- a/llvm/lib/Transforms/IPO/FunctionImport.cpp
+++ b/llvm/lib/Transforms/IPO/FunctionImport.cpp
@@ -2187,7 +2187,7 @@ Expected<bool> FunctionImporter::importFunctions(
         if (ImportDefinition) {
           if (Error Err = GV.materialize())
             return std::move(Err);
-          ImportedGVCount += GlobalsToImport.insert(&GV);
+          ImportedGVCount += GlobalsToImport.insert(&GV).second;
         }
       }
     }
diff --git a/llvm/lib/Transforms/IPO/OpenMPOpt.cpp 
b/llvm/lib/Transforms/IPO/OpenMPOpt.cpp
index ced26c213f0225..19cb0d153aebf6 100644
--- a/llvm/lib/Transforms/IPO/OpenMPOpt.cpp
+++ b/llvm/lib/Transforms/IPO/OpenMPOpt.cpp
@@ -728,7 +728,7 @@ struct BooleanStateWithSetVector : public BooleanState {
   bool insert(const Ty &Elem) {
     if (InsertInvalidates)
       BooleanState::indicatePessimisticFixpoint();
-    return Set.insert(Elem);
+    return Set.insert(Elem).second;
   }
 
   const Ty &operator[](int Idx) const { return Set[Idx]; }
@@ -2925,7 +2925,7 @@ struct AAExecutionDomainFunction : public 
AAExecutionDomain {
         SmallSetVector<CallBase *, 16> Visited;
         while (!Worklist.empty()) {
           CallBase *LastCB = Worklist.pop_back_val();
-          if (!Visited.insert(LastCB))
+          if (!Visited.insert(LastCB).second)
             continue;
           if (LastCB->getFunction() != getAnchorScope())
             continue;
@@ -3243,7 +3243,7 @@ ChangeStatus 
AAExecutionDomainFunction::updateImpl(Attributor &A) {
   // traversal. \p CB is the aligned barrier, \p ED is the execution domain 
when
   // it was encountered.
   auto HandleAlignedBarrier = [&](CallBase &CB, ExecutionDomainTy &ED) {
-    Changed |= AlignedBarriers.insert(&CB);
+    Changed |= AlignedBarriers.insert(&CB).second;
     // First, update the barrier ED kept in the separate CEDMap.
     auto &CallInED = CEDMap[{&CB, PRE}];
     Changed |= mergeInPredecessor(A, CallInED, ED);
@@ -3517,7 +3517,7 @@ ChangeStatus 
AAExecutionDomainFunction::updateImpl(Attributor &A) {
     for (auto *PredBB : predecessors(SyncBB)) {
       if (LivenessAA && LivenessAA->isEdgeDead(PredBB, SyncBB))
         continue;
-      if (!Visited.insert(PredBB))
+      if (!Visited.insert(PredBB).second)
         continue;
       auto &PredED = BEDMap[PredBB];
       if (setAndRecord(PredED.IsReachingAlignedBarrierOnly, false)) {
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
index 647c5b6d589e10..ec87b90c9afc9e 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
@@ -3347,7 +3347,7 @@ Instruction 
*InstCombinerImpl::optimizeBitCastFromPhi(CastInst &CI,
       }
 
       if (auto *PNode = dyn_cast<PHINode>(IncValue)) {
-        if (OldPhiNodes.insert(PNode))
+        if (OldPhiNodes.insert(PNode).second)
           PhiWorklist.push_back(PNode);
         continue;
       }
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp
index 60331a3d37b05b..91fc199f4477db 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp
@@ -273,7 +273,7 @@ bool PointerReplacer::collectUsers() {
 
   auto TryPushInstOperand = [&](Instruction *InstOp) {
     if (!UsersToReplace.contains(InstOp)) {
-      if (!ValuesToRevisit.insert(InstOp))
+      if (!ValuesToRevisit.insert(InstOp).second)
         return false;
       Worklist.emplace_back(InstOp);
     }
@@ -304,7 +304,7 @@ bool PointerReplacer::collectUsers() {
       // Either an incoming value is not an instruction or not all
       // incoming values are available. If this PHI was already
       // visited prior to this iteration, return false.
-      if (!IsReplaceable || !ValuesToRevisit.insert(PHI))
+      if (!IsReplaceable || !ValuesToRevisit.insert(PHI).second)
         return false;
 
       // Push PHI back into the stack, followed by unavailable
diff --git a/llvm/lib/Transforms/Scalar/LoopDistribute.cpp 
b/llvm/lib/Transforms/Scalar/LoopDistribute.cpp
index 6f0f6f833cd6c7..133bdc3f2c1ae3 100644
--- a/llvm/lib/Transforms/Scalar/LoopDistribute.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopDistribute.cpp
@@ -138,7 +138,7 @@ class InstPartition {
       // Insert instructions from the loop that we depend on.
       for (Value *V : I->operand_values()) {
         auto *I = dyn_cast<Instruction>(V);
-        if (I && OrigLoop->contains(I->getParent()) && Set.insert(I))
+        if (I && OrigLoop->contains(I->getParent()) && Set.insert(I).second)
           Worklist.push_back(I);
       }
     }
diff --git a/llvm/lib/Transforms/Utils/CodeExtractor.cpp 
b/llvm/lib/Transforms/Utils/CodeExtractor.cpp
index 06725e70f8aaf5..6f59fca7876126 100644
--- a/llvm/lib/Transforms/Utils/CodeExtractor.cpp
+++ b/llvm/lib/Transforms/Utils/CodeExtractor.cpp
@@ -212,7 +212,7 @@ buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, 
DominatorTree *DT,
     if (DT && !DT->isReachableFromEntry(BB))
       continue;
 
-    if (!Result.insert(BB))
+    if (!Result.insert(BB).second)
       llvm_unreachable("Repeated basic blocks in extraction input");
   }
 
diff --git a/llvm/lib/Transforms/Utils/InlineFunction.cpp 
b/llvm/lib/Transforms/Utils/InlineFunction.cpp
index e8d630491dd750..ca51d4756d85e2 100644
--- a/llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ b/llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -1154,7 +1154,7 @@ void 
ScopedAliasMetadataDeepCloner::addRecursiveMetadataUses() {
     const MDNode *M = cast<MDNode>(Queue.pop_back_val());
     for (const Metadata *Op : M->operands())
       if (const MDNode *OpMD = dyn_cast<MDNode>(Op))
-        if (MD.insert(OpMD))
+        if (MD.insert(OpMD).second)
           Queue.push_back(OpMD);
   }
 }
diff --git a/llvm/lib/Transforms/Utils/LCSSA.cpp 
b/llvm/lib/Transforms/Utils/LCSSA.cpp
index 415c6baff20d7c..01a080be999539 100644
--- a/llvm/lib/Transforms/Utils/LCSSA.cpp
+++ b/llvm/lib/Transforms/Utils/LCSSA.cpp
@@ -374,7 +374,7 @@ static void computeBlocksDominatingExits(
     if (!L.contains(IDomBB))
       continue;
 
-    if (BlocksDominatingExits.insert(IDomBB))
+    if (BlocksDominatingExits.insert(IDomBB).second)
       BBWorklist.push_back(IDomBB);
   }
 }
diff --git a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp 
b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
index f6ff566469b23e..a2568cdf508b91 100644
--- a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
+++ b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
@@ -4420,7 +4420,7 @@ void 
LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
     for (auto &Op : I->operands())
       if (auto *InstOp = dyn_cast<Instruction>(Op))
         if (TheLoop->contains(InstOp) && !isa<PHINode>(InstOp) &&
-            AddrDefs.insert(InstOp))
+            AddrDefs.insert(InstOp).second)
           Worklist.push_back(InstOp);
   }
 
diff --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp 
b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
index 7806f3d9d135e9..ab4a017cc53bb2 100644
--- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -16864,7 +16864,7 @@ BoUpSLP::getEntryCost(const TreeEntry *E, 
ArrayRef<Value *> VectorizedVals,
   SmallSetVector<Value *, 16> UniqueValues;
   SmallVector<unsigned, 16> UniqueIndexes;
   for (auto [Idx, V] : enumerate(VL))
-    if (UniqueValues.insert(V))
+    if (UniqueValues.insert(V).second)
       UniqueIndexes.push_back(Idx);
   const unsigned Sz = UniqueValues.size();
   SmallBitVector UsedScalars(Sz, false);
diff --git a/llvm/unittests/IR/DebugInfoTest.cpp 
b/llvm/unittests/IR/DebugInfoTest.cpp
index e85bec6b5509db..9e4abb10155202 100644
--- a/llvm/unittests/IR/DebugInfoTest.cpp
+++ b/llvm/unittests/IR/DebugInfoTest.cpp
@@ -854,11 +854,11 @@ TEST(AssignmentTrackingTest, InstrMethods) {
   SetVector<DbgVariableRecord *> Markers;
   for (const Instruction *SI : Stores) {
     Metadata *ID = SI->getMetadata(LLVMContext::MD_DIAssignID);
-    ASSERT_TRUE(OrigIDs.insert(ID));
+    ASSERT_TRUE(OrigIDs.insert(ID).second);
     ASSERT_TRUE(ID != nullptr);
     auto Range = at::getDVRAssignmentMarkers(SI);
     ASSERT_TRUE(std::distance(Range.begin(), Range.end()) == 1);
-    ASSERT_TRUE(Markers.insert(*Range.begin()));
+    ASSERT_TRUE(Markers.insert(*Range.begin()).second);
   }
 
   // Test 1 - mergeDIAssignID.
diff --git a/llvm/utils/TableGen/AsmMatcherEmitter.cpp 
b/llvm/utils/TableGen/AsmMatcherEmitter.cpp
index cb8eb58a221ddc..9dfdc04c078d41 100644
--- a/llvm/utils/TableGen/AsmMatcherEmitter.cpp
+++ b/llvm/utils/TableGen/AsmMatcherEmitter.cpp
@@ -2029,7 +2029,7 @@ static unsigned
 getConverterOperandID(const std::string &Name,
                       SmallSetVector<CachedHashString, 16> &Table,
                       bool &IsNew) {
-  IsNew = Table.insert(CachedHashString(Name));
+  IsNew = Table.insert(CachedHashString(Name)).second;
 
   unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
 
@@ -2145,7 +2145,8 @@ emitConvertFuncs(CodeGenTarget &Target, StringRef 
ClassName,
       II->ConversionFnKind = Signature;
 
       // Check if we have already generated this signature.
-      if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
+      if (!InstructionConversionKinds.insert(CachedHashString(Signature))
+               .second)
         continue;
 
       // Remember this converter for the kind enum.
@@ -2351,7 +2352,7 @@ emitConvertFuncs(CodeGenTarget &Target, StringRef 
ClassName,
 
     // Save the signature. If we already have it, don't add a new row
     // to the table.
-    if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
+    if (!InstructionConversionKinds.insert(CachedHashString(Signature)).second)
       continue;
 
     // Add the row to the table.
diff --git a/llvm/utils/TableGen/Basic/AMDGPUTargetDefEmitter.cpp 
b/llvm/utils/TableGen/Basic/AMDGPUTargetDefEmitter.cpp
index 376222cf754fb2..b24a6c0c8863a7 100644
--- a/llvm/utils/TableGen/Basic/AMDGPUTargetDefEmitter.cpp
+++ b/llvm/utils/TableGen/Basic/AMDGPUTargetDefEmitter.cpp
@@ -199,7 +199,7 @@ static void collectFeatureClosure(const Record *GPU,
   while (!Worklist.empty()) {
     const Record *F = Worklist.back();
     Worklist.pop_back();
-    if (Closure.insert(F))
+    if (Closure.insert(F).second)
       append_range(Worklist, F->getValueAsListOfDefs("Implies"));
   }
 }
diff --git a/llvm/utils/TableGen/Common/CodeGenRegisters.cpp 
b/llvm/utils/TableGen/Common/CodeGenRegisters.cpp
index 90f10c2052e56f..5b788c48fc4b83 100644
--- a/llvm/utils/TableGen/Common/CodeGenRegisters.cpp
+++ b/llvm/utils/TableGen/Common/CodeGenRegisters.cpp
@@ -591,7 +591,7 @@ void CodeGenRegister::addSubRegsPreOrder(
     SetVector<const CodeGenRegister *> &OSet, CodeGenRegBank &RegBank) const {
   assert(SuperRegsComplete && "Must precompute super-registers");
   for (CodeGenRegister *SR : ExplicitSubRegs) {
-    if (OSet.insert(SR))
+    if (OSet.insert(SR).second)
       SR->addSubRegsPreOrder(OSet, RegBank);
   }
   // Add any secondary sub-registers that weren't part of the explicit tree.
@@ -2945,7 +2945,7 @@ CodeGenRegBank::computeCoveredRegisters(ArrayRef<const 
Record *> Regs) {
   // First add Regs with all sub-registers.
   for (const Record *RegDef : Regs) {
     CodeGenRegister *Reg = getReg(RegDef);
-    if (Set.insert(Reg))
+    if (Set.insert(Reg).second)
       // Reg is new, add all sub-registers.
       // The pre-ordering is not important here.
       Reg->addSubRegsPreOrder(Set, *this);
diff --git a/mlir/include/mlir/TableGen/Pattern.h 
b/mlir/include/mlir/TableGen/Pattern.h
index 16172fcfba6be2..0b6c88851da957 100644
--- a/mlir/include/mlir/TableGen/Pattern.h
+++ b/mlir/include/mlir/TableGen/Pattern.h
@@ -60,6 +60,8 @@ class DagLeaf {
 public:
   explicit DagLeaf(const llvm::Init *def) : def(def) {}
 
+  bool operator==(const DagLeaf &other) const { return def == other.def; }
+
   // Returns true if this DAG leaf is not specified in the pattern. That is, it
   // places no further constraints/transforms and just carries over the 
original
   // value.
diff --git a/mlir/lib/Analysis/DataFlow/DeadCodeAnalysis.cpp 
b/mlir/lib/Analysis/DataFlow/DeadCodeAnalysis.cpp
index 37aaf1f634a643..004f064f5377e3 100644
--- a/mlir/lib/Analysis/DataFlow/DeadCodeAnalysis.cpp
+++ b/mlir/lib/Analysis/DataFlow/DeadCodeAnalysis.cpp
@@ -94,8 +94,8 @@ void PredecessorState::print(raw_ostream &os) const {
 }
 
 ChangeResult PredecessorState::join(Operation *predecessor) {
-  return knownPredecessors.insert(predecessor) ? ChangeResult::Change
-                                               : ChangeResult::NoChange;
+  return knownPredecessors.insert(predecessor).second ? ChangeResult::Change
+                                                      : ChangeResult::NoChange;
 }
 
 ChangeResult PredecessorState::join(Operation *predecessor, ValueRange inputs) 
{
diff --git a/mlir/lib/Analysis/DataFlowFramework.cpp 
b/mlir/lib/Analysis/DataFlowFramework.cpp
index a2aa380749068e..506e49787cae96 100644
--- a/mlir/lib/Analysis/DataFlowFramework.cpp
+++ b/mlir/lib/Analysis/DataFlowFramework.cpp
@@ -41,8 +41,8 @@ AnalysisState::~AnalysisState() = default;
 
 void AnalysisState::addDependency(ProgramPoint *dependent,
                                   DataFlowAnalysis *analysis) {
-  auto inserted = dependents.insert({dependent, analysis});
-  (void)inserted;
+  [[maybe_unused]] bool inserted =
+      dependents.insert({dependent, analysis}).second;
   DATAFLOW_DEBUG({
     if (inserted) {
       LDBG() << "Creating dependency between " << debugName << " of " << anchor
diff --git a/mlir/lib/Bytecode/Writer/IRNumbering.cpp 
b/mlir/lib/Bytecode/Writer/IRNumbering.cpp
index dcc87871ead491..59ed06030c4b5a 100644
--- a/mlir/lib/Bytecode/Writer/IRNumbering.cpp
+++ b/mlir/lib/Bytecode/Writer/IRNumbering.cpp
@@ -566,7 +566,7 @@ void IRNumberingState::number(Dialect *dialect,
 
   for (const auto &resource : resources) {
     // Check if this is a newly seen resource.
-    if (!dialectNumber.resources.insert(resource))
+    if (!dialectNumber.resources.insert(resource).second)
       return;
 
     auto *numbering =
diff --git a/mlir/lib/Dialect/Bufferization/Transforms/OneShotAnalysis.cpp 
b/mlir/lib/Dialect/Bufferization/Transforms/OneShotAnalysis.cpp
index 4a5752c8b7fbe0..0d5366f8b2ca57 100644
--- a/mlir/lib/Dialect/Bufferization/Transforms/OneShotAnalysis.cpp
+++ b/mlir/lib/Dialect/Bufferization/Transforms/OneShotAnalysis.cpp
@@ -1404,7 +1404,7 @@ bottomUpFromTerminatorsHeuristic(Operation *op,
 
   // Find region terminators.
   op->walk<WalkOrder::PostOrder>([&](RegionBranchTerminatorOpInterface term) {
-    if (!traversedOps.insert(term))
+    if (!traversedOps.insert(term).second)
       return;
     // Follow the reverse SSA use-def chain from each yielded value as long as
     // we stay within the same region.
@@ -1420,7 +1420,7 @@ bottomUpFromTerminatorsHeuristic(Operation *op,
     while (!worklist.empty()) {
       OpResult opResult = worklist.pop_back_val();
       Operation *defOp = opResult.getDefiningOp();
-      if (!traversedOps.insert(defOp))
+      if (!traversedOps.insert(defOp).second)
         continue;
       if (!term->getParentRegion()->findAncestorOpInRegion(*defOp))
         continue;
diff --git 
a/mlir/lib/Dialect/Bufferization/Transforms/OneShotModuleBufferize.cpp 
b/mlir/lib/Dialect/Bufferization/Transforms/OneShotModuleBufferize.cpp
index 41d9a37844c9a0..342a3bd5eb94ad 100644
--- a/mlir/lib/Dialect/Bufferization/Transforms/OneShotModuleBufferize.cpp
+++ b/mlir/lib/Dialect/Bufferization/Transforms/OneShotModuleBufferize.cpp
@@ -335,7 +335,7 @@ static LogicalResult getFuncOpsOrderedByCalls(
             return WalkResult::skip();
 
           callerMap[calledFunction].insert(callOp);
-          if (calledBy[calledFunction].insert(funcOp)) {
+          if (calledBy[calledFunction].insert(funcOp).second) {
             numberCallOpsContainedInFuncOp[funcOp]++;
           }
           return WalkResult::advance();
diff --git a/mlir/lib/Dialect/GPU/TransformOps/GPUTransformOps.cpp 
b/mlir/lib/Dialect/GPU/TransformOps/GPUTransformOps.cpp
index 1b2988a1abe9e3..c8104e54f8fb0b 100644
--- a/mlir/lib/Dialect/GPU/TransformOps/GPUTransformOps.cpp
+++ b/mlir/lib/Dialect/GPU/TransformOps/GPUTransformOps.cpp
@@ -483,7 +483,7 @@ static DiagnosedSilenceableFailure 
rewriteOneForallCommonImpl(
     if (maxLinearMapping && comparator(maxLinearMapping, attr))
       continue;
     // Try to insert. If element was already present, just continue.
-    if (!forallMappingAttrs.insert(attr))
+    if (!forallMappingAttrs.insert(attr).second)
       continue;
     // Otherwise, we have a new insertion without a size -> use size 1.
     tmpMappingSizes.push_back(1);
diff --git a/mlir/lib/Dialect/Vector/Transforms/VectorDistribute.cpp 
b/mlir/lib/Dialect/Vector/Transforms/VectorDistribute.cpp
index 0340452c75d075..9f8de65b615a0e 100644
--- a/mlir/lib/Dialect/Vector/Transforms/VectorDistribute.cpp
+++ b/mlir/lib/Dialect/Vector/Transforms/VectorDistribute.cpp
@@ -396,7 +396,7 @@ getInnerRegionEscapingValues(WarpExecuteOnLane0Op warpOp, 
Region &innerRegion,
   mlir::visitUsedValuesDefinedAbove(innerRegion, [&](OpOperand *operand) {
     Operation *parent = operand->get().getParentRegion()->getParentOp();
     if (warpOp->isAncestor(parent)) {
-      if (!escapingValues.insert(operand->get()))
+      if (!escapingValues.insert(operand->get()).second)
         return;
       Type distType = operand->get().getType();
       if (auto vecType = dyn_cast<VectorType>(distType)) {
diff --git a/mlir/lib/Tools/PDLL/CodeGen/CPPGen.cpp 
b/mlir/lib/Tools/PDLL/CodeGen/CPPGen.cpp
index 3fda5a7a933443..81133964290264 100644
--- a/mlir/lib/Tools/PDLL/CodeGen/CPPGen.cpp
+++ b/mlir/lib/Tools/PDLL/CodeGen/CPPGen.cpp
@@ -84,7 +84,7 @@ void CodeGen::generate(const ast::Module &astModule, ModuleOp 
module) {
       std::string name;
       do {
         name = (basePatternName + Twine(patternIndex++)).str();
-      } while (!patternNames.insert(name));
+      } while (!patternNames.insert(name).second);
     }
 
     generate(pattern, patternNames.back(), nativeFunctions);
diff --git a/mlir/lib/Tools/mlir-lsp-server/MLIRServer.cpp 
b/mlir/lib/Tools/mlir-lsp-server/MLIRServer.cpp
index f5ab91ce6f9a82..6dc814cf6f76d2 100644
--- a/mlir/lib/Tools/mlir-lsp-server/MLIRServer.cpp
+++ b/mlir/lib/Tools/mlir-lsp-server/MLIRServer.cpp
@@ -133,7 +133,7 @@ static void collectLocationsFromLoc(Location loc,
   SetVector<Location> visitedLocs;
   loc->walk([&](Location nestedLoc) {
     FileLineColLoc fileLoc = dyn_cast<FileLineColLoc>(nestedLoc);
-    if (!fileLoc || !visitedLocs.insert(nestedLoc))
+    if (!fileLoc || !visitedLocs.insert(nestedLoc).second)
       return WalkResult::advance();
 
     std::optional<lsp::Location> sourceLoc =
diff --git a/mlir/tools/mlir-tblgen/OpFormatGen.cpp 
b/mlir/tools/mlir-tblgen/OpFormatGen.cpp
index 1fd993cc197a9a..bcab466401f23e 100644
--- a/mlir/tools/mlir-tblgen/OpFormatGen.cpp
+++ b/mlir/tools/mlir-tblgen/OpFormatGen.cpp
@@ -4152,7 +4152,7 @@ OpFormatParser::parseVariableImpl(SMLoc loc, StringRef 
name, Context ctx) {
       if (!seenAttrs.count(attr))
         return emitError(loc, "attribute '" + name +
                                   "' must be bound before it is referenced");
-    } else if (!seenAttrs.insert(attr)) {
+    } else if (!seenAttrs.insert(attr).second) {
       return emitError(loc, "attribute '" + name + "' is already bound");
     }
 
@@ -4168,7 +4168,7 @@ OpFormatParser::parseVariableImpl(SMLoc loc, StringRef 
name, Context ctx) {
         return emitError(loc, "property '" + name +
                                   "' must be bound before it is referenced");
     } else {
-      if (!seenProperties.insert(property))
+      if (!seenProperties.insert(property).second)
         return emitError(loc, "property '" + name + "' is already bound");
     }
 
diff --git a/polly/lib/Analysis/ScopBuilder.cpp 
b/polly/lib/Analysis/ScopBuilder.cpp
index a33a630c7bbdb1..3cfd6aa6ec8490 100644
--- a/polly/lib/Analysis/ScopBuilder.cpp
+++ b/polly/lib/Analysis/ScopBuilder.cpp
@@ -1987,7 +1987,7 @@ joinOrderedInstructions(EquivalenceClasses<Instruction *> 
&UnionFind,
     // SeenLeaders are not leaders anymore. However, The new leader of
     // previously merged instructions must be one of the former leaders of
     // these merged instructions.
-    bool Inserted = SeenLeaders.insert(Leader);
+    bool Inserted = SeenLeaders.insert(Leader).second;
     if (Inserted)
       continue;
 
diff --git a/polly/lib/Analysis/ScopDetection.cpp 
b/polly/lib/Analysis/ScopDetection.cpp
index 12cbee3a95a49a..a3cd292df35790 100644
--- a/polly/lib/Analysis/ScopDetection.cpp
+++ b/polly/lib/Analysis/ScopDetection.cpp
@@ -450,7 +450,7 @@ std::string ScopDetection::regionIsInvalidBecause(const 
Region *R) const {
 bool ScopDetection::addOverApproximatedRegion(Region *AR,
                                               DetectionContext &Context) const 
{
   // If we already know about Ar we can exit.
-  if (!Context.NonAffineSubRegionSet.insert(AR))
+  if (!Context.NonAffineSubRegionSet.insert(AR).second)
     return true;
 
   // All loops in the region have to be overapproximated too if there
diff --git a/polly/lib/Analysis/ScopInfo.cpp b/polly/lib/Analysis/ScopInfo.cpp
index 6757f3ba057ea0..526094f80bfcfe 100644
--- a/polly/lib/Analysis/ScopInfo.cpp
+++ b/polly/lib/Analysis/ScopInfo.cpp
@@ -1530,7 +1530,7 @@ void Scop::addParams(const ParameterSetTy &NewParameters) 
{
     Parameter = extractConstantFactor(Parameter, *SE).second;
     Parameter = getRepresentingInvariantLoadSCEV(Parameter);
 
-    if (Parameters.insert(Parameter))
+    if (Parameters.insert(Parameter).second)
       createParameterId(Parameter);
   }
 }
diff --git a/polly/lib/CodeGen/BlockGenerators.cpp 
b/polly/lib/CodeGen/BlockGenerators.cpp
index 4cba4f366d820e..220b53855ede1e 100644
--- a/polly/lib/CodeGen/BlockGenerators.cpp
+++ b/polly/lib/CodeGen/BlockGenerators.cpp
@@ -1123,7 +1123,7 @@ void RegionGenerator::copyStmt(ScopStmt &Stmt, 
LoopToScevMapT &LTS,
 
     // And continue with new successors inside the region.
     for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
-      if (R->contains(*SI) && SeenBlocks.insert(*SI))
+      if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
         Blocks.push_back(*SI);
 
     // Remember value in case it is visible after this subregion.

>From e98b8f0ddfff054d588164a8c38a8576a0d406dd Mon Sep 17 00:00:00 2001
From: Ramkumar Ramachandra <[email protected]>
Date: Thu, 29 Oct 2026 09:50:13 +0000
Subject: [PATCH 2/2] [SetVector] Avoid double-find, update more instances

---
 clang-tools-extra/clang-tidy/misc/NoRecursionCheck.cpp   | 2 +-
 flang/lib/Optimizer/Builder/CUFCommon.cpp                | 2 +-
 llvm/include/llvm/ADT/SetVector.h                        | 5 +++--
 llvm/tools/llvm-extract/llvm-extract.cpp                 | 2 +-
 llvm/tools/llvm-reduce/deltas/ReduceDIMetadata.cpp       | 2 +-
 llvm/tools/llvm-reduce/deltas/ReduceDistinctMetadata.cpp | 6 +++---
 llvm/tools/llvm-reduce/deltas/ReduceOperandsSkip.cpp     | 2 +-
 7 files changed, 11 insertions(+), 10 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/misc/NoRecursionCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/NoRecursionCheck.cpp
index 599e7fbf0f21e3..9ae8b081822dab 100644
--- a/clang-tools-extra/clang-tidy/misc/NoRecursionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/NoRecursionCheck.cpp
@@ -46,7 +46,7 @@ static CallStackTy pathfindSomeCycle(ArrayRef<CallGraphNode 
*> SCC) {
   const CallGraphNode::CallRecord *Node = &EntryNode;
   while (true) {
     // Did we see this node before?
-    if (!CallStackSet.insert(*Node))
+    if (!CallStackSet.insert(*Node).second)
       break; // Cycle completed! Note that didn't insert the node into stack!
     // Else, perform depth-first traversal: out of all callees, pick first one
     // that is part of this SCC. This is not guaranteed to yield shortest 
cycle.
diff --git a/flang/lib/Optimizer/Builder/CUFCommon.cpp 
b/flang/lib/Optimizer/Builder/CUFCommon.cpp
index f2691dacab0ebd..544c1ef7eda5d8 100644
--- a/flang/lib/Optimizer/Builder/CUFCommon.cpp
+++ b/flang/lib/Optimizer/Builder/CUFCommon.cpp
@@ -252,7 +252,7 @@ cuf::DeviceCodeSet cuf::collectDeviceCode(mlir::ModuleOp 
mod,
     if (!callee || mlir::acc::isAccRoutine(callee) ||
         code.deviceFuncs.count(callee))
       return;
-    if (code.calledFromDevice.insert(callee) && !callee.isDeclaration())
+    if (code.calledFromDevice.insert(callee).second && !callee.isDeclaration())
       worklist.push_back(callee);
   };
   auto scan = [&](mlir::Operation *root) {
diff --git a/llvm/include/llvm/ADT/SetVector.h 
b/llvm/include/llvm/ADT/SetVector.h
index 24defb802c9c16..118450af947737 100644
--- a/llvm/include/llvm/ADT/SetVector.h
+++ b/llvm/include/llvm/ADT/SetVector.h
@@ -158,13 +158,14 @@ class SetVector {
   std::pair<iterator, bool> insert(const value_type &X) {
     if constexpr (canBeSmall())
       if (isSmall()) {
-        if (!llvm::is_contained(vector_, X)) {
+        auto It = find(vector_, X);
+        if (It == end()) {
           vector_.push_back(X);
           if (vector_.size() > N)
             makeBig();
           return {std::prev(vector_.end()), true};
         }
-        return {find(vector_, X), false};
+        return {It, false};
       }
 
     bool result = set_.insert(X).second;
diff --git a/llvm/tools/llvm-extract/llvm-extract.cpp 
b/llvm/tools/llvm-extract/llvm-extract.cpp
index 4c549951603d87..9349880b5c1065 100644
--- a/llvm/tools/llvm-extract/llvm-extract.cpp
+++ b/llvm/tools/llvm-extract/llvm-extract.cpp
@@ -302,7 +302,7 @@ int main(int argc, char **argv) {
           Function *CF = CB->getCalledFunction();
           if (!CF)
             continue;
-          if (CF->isDeclaration() || !GVs.insert(CF))
+          if (CF->isDeclaration() || !GVs.insert(CF).second)
             continue;
           Workqueue.push_back(CF);
         }
diff --git a/llvm/tools/llvm-reduce/deltas/ReduceDIMetadata.cpp 
b/llvm/tools/llvm-reduce/deltas/ReduceDIMetadata.cpp
index 3cc58b5d106a1e..859d0f1ec85e73 100644
--- a/llvm/tools/llvm-reduce/deltas/ReduceDIMetadata.cpp
+++ b/llvm/tools/llvm-reduce/deltas/ReduceDIMetadata.cpp
@@ -37,7 +37,7 @@ void identifyUninterestingMDNodes(Oracle &O, MDNodeList &MDs) 
{
     MDNode *MD = ToLook.back();
     ToLook.pop_back();
 
-    if (!Visited.insert(MD))
+    if (!Visited.insert(MD).second)
       continue;
 
     // Determine if the current MDNode is DebugInfo
diff --git a/llvm/tools/llvm-reduce/deltas/ReduceDistinctMetadata.cpp 
b/llvm/tools/llvm-reduce/deltas/ReduceDistinctMetadata.cpp
index 833a941b89f44a..59e5eff7eeef79 100644
--- a/llvm/tools/llvm-reduce/deltas/ReduceDistinctMetadata.cpp
+++ b/llvm/tools/llvm-reduce/deltas/ReduceDistinctMetadata.cpp
@@ -37,7 +37,7 @@ reduceNodes(MDNode *Root,
       if (MDNode *Operand =
               dyn_cast_or_null<MDNode>(CurrentNode->getOperand(I).get())) {
         // Check whether node has been visited
-        if (VisitedNodes.insert(Operand))
+        if (VisitedNodes.insert(Operand).second)
           NodesToTraverse.push(Operand);
         // Delete the node only if it is distinct
         if (Operand->isDistinct()) {
@@ -68,7 +68,7 @@ static void cleanUpTemporaries(NamedMDNode &NamedNode, 
MDTuple *TemporaryTuple,
     // If the node hasn't been traversed yet, add it to the queue of nodes to
     // traverse.
     if (MDTuple *TupleI = dyn_cast_or_null<MDTuple>((*I))) {
-      if (VisitedNodes.insert(TupleI))
+      if (VisitedNodes.insert(TupleI).second)
         NodesToTraverse.push(TupleI);
     }
   }
@@ -106,7 +106,7 @@ static void cleanUpTemporaries(NamedMDNode &NamedNode, 
MDTuple *TemporaryTuple,
     for (unsigned int I = 0; I < CurrentTuple->getNumOperands(); ++I) {
       MDTuple *Operand =
           dyn_cast_or_null<MDTuple>(CurrentTuple->getOperand(I).get());
-      if (Operand && VisitedNodes.insert(Operand))
+      if (Operand && VisitedNodes.insert(Operand).second)
         // If the node hasn't been traversed yet, add it to the queue of nodes
         // to traverse.
         NodesToTraverse.push(Operand);
diff --git a/llvm/tools/llvm-reduce/deltas/ReduceOperandsSkip.cpp 
b/llvm/tools/llvm-reduce/deltas/ReduceOperandsSkip.cpp
index 498588fb8d0956..d29dd91e665a97 100644
--- a/llvm/tools/llvm-reduce/deltas/ReduceOperandsSkip.cpp
+++ b/llvm/tools/llvm-reduce/deltas/ReduceOperandsSkip.cpp
@@ -30,7 +30,7 @@ static SetVector<Value *> collectReferencedValues(Value 
*Root) {
   while (!Worklist.empty()) {
     Value *Val = Worklist.front();
     Worklist.pop_front();
-    if (!Refs.insert(Val))
+    if (!Refs.insert(Val).second)
       continue;
 
     if (auto *O = dyn_cast<Operator>(Val)) {

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to