[llvm] [Transforms] Use *Set::insert_range (NFC) (PR #132652)

via llvm-commits llvm-commits at lists.llvm.org
Sun Mar 23 18:27:28 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-transforms

Author: Kazu Hirata (kazutakahirata)

<details>
<summary>Changes</summary>

We can use *Set::insert_range to collapse:

  for (auto Elem : Range)
    Set.insert(E);

down to:

  Set.insert_range(Range);

In some cases, we can further fold that into the set declaration.


---
Full diff: https://github.com/llvm/llvm-project/pull/132652.diff


19 Files Affected:

- (modified) llvm/lib/Transforms/IPO/FunctionAttrs.cpp (+1-2) 
- (modified) llvm/lib/Transforms/IPO/FunctionImport.cpp (+3-6) 
- (modified) llvm/lib/Transforms/IPO/LowerTypeTests.cpp (+1-2) 
- (modified) llvm/lib/Transforms/IPO/PartialInlining.cpp (+2-5) 
- (modified) llvm/lib/Transforms/Instrumentation/ControlHeightReduction.cpp (+4-11) 
- (modified) llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Scalar/DFAJumpThreading.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Scalar/GVNSink.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Scalar/LICM.cpp (+2-3) 
- (modified) llvm/lib/Transforms/Scalar/Reassociate.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Scalar/SROA.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Utils/CloneFunction.cpp (+1-3) 
- (modified) llvm/lib/Transforms/Utils/InlineFunction.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Utils/LoopPeel.cpp (+3-7) 
- (modified) llvm/lib/Transforms/Utils/LoopUnroll.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Utils/SSAUpdaterBulk.cpp (+2-3) 


``````````diff
diff --git a/llvm/lib/Transforms/IPO/FunctionAttrs.cpp b/llvm/lib/Transforms/IPO/FunctionAttrs.cpp
index f70686bc57ee4..ef7989507c89f 100644
--- a/llvm/lib/Transforms/IPO/FunctionAttrs.cpp
+++ b/llvm/lib/Transforms/IPO/FunctionAttrs.cpp
@@ -1467,8 +1467,7 @@ static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
       }
       case Instruction::PHI: {
         PHINode *PN = cast<PHINode>(RVI);
-        for (Value *IncValue : PN->incoming_values())
-          FlowsToReturn.insert(IncValue);
+        FlowsToReturn.insert_range(PN->incoming_values());
         continue;
       }
 
diff --git a/llvm/lib/Transforms/IPO/FunctionImport.cpp b/llvm/lib/Transforms/IPO/FunctionImport.cpp
index 4a36f49bcbf4b..f0daf1a558316 100644
--- a/llvm/lib/Transforms/IPO/FunctionImport.cpp
+++ b/llvm/lib/Transforms/IPO/FunctionImport.cpp
@@ -1219,14 +1219,11 @@ void llvm::ComputeCrossModuleImport(
         // we convert such variables initializers to "zeroinitializer".
         // See processGlobalForThinLTO.
         if (!Index.isWriteOnly(GVS))
-          for (const auto &VI : GVS->refs())
-            NewExports.insert(VI);
+          NewExports.insert_range(GVS->refs());
       } else {
         auto *FS = cast<FunctionSummary>(S);
-        for (const auto &Edge : FS->calls())
-          NewExports.insert(Edge.first);
-        for (const auto &Ref : FS->refs())
-          NewExports.insert(Ref);
+        NewExports.insert_range(llvm::make_first_range(FS->calls()));
+        NewExports.insert_range(FS->refs());
       }
     }
     // Prune list computed above to only include values defined in the
diff --git a/llvm/lib/Transforms/IPO/LowerTypeTests.cpp b/llvm/lib/Transforms/IPO/LowerTypeTests.cpp
index 596a3c1f01f64..6cc5d1dc78d99 100644
--- a/llvm/lib/Transforms/IPO/LowerTypeTests.cpp
+++ b/llvm/lib/Transforms/IPO/LowerTypeTests.cpp
@@ -1866,8 +1866,7 @@ LowerTypeTestsModule::LowerTypeTestsModule(
   if (GlobalAnnotation && GlobalAnnotation->hasInitializer()) {
     const ConstantArray *CA =
         cast<ConstantArray>(GlobalAnnotation->getInitializer());
-    for (Value *Op : CA->operands())
-      FunctionAnnotations.insert(Op);
+    FunctionAnnotations.insert_range(CA->operands());
   }
 }
 
diff --git a/llvm/lib/Transforms/IPO/PartialInlining.cpp b/llvm/lib/Transforms/IPO/PartialInlining.cpp
index 56b7b8bfe1f66..e2df95ed23c10 100644
--- a/llvm/lib/Transforms/IPO/PartialInlining.cpp
+++ b/llvm/lib/Transforms/IPO/PartialInlining.cpp
@@ -490,8 +490,7 @@ PartialInlinerImpl::computeOutliningColdRegionsInfo(
       // candidate for outlining.  In the future, we may want to look
       // at inner regions because the outer region may have live-exit
       // variables.
-      for (auto *BB : DominateVector)
-        VisitedSet.insert(BB);
+      VisitedSet.insert_range(DominateVector);
 
       // ReturnBlock here means the block after the outline call
       BasicBlock *ReturnBlock = ExitBlock->getSingleSuccessor();
@@ -593,9 +592,7 @@ PartialInlinerImpl::computeOutliningInfo(Function &F) const {
   // {ReturnBlock, NonReturnBlock}
   assert(OutliningInfo->Entries[0] == &F.front() &&
          "Function Entry must be the first in Entries vector");
-  DenseSet<BasicBlock *> Entries;
-  for (BasicBlock *E : OutliningInfo->Entries)
-    Entries.insert(E);
+  DenseSet<BasicBlock *> Entries(llvm::from_range, OutliningInfo->Entries);
 
   // Returns true of BB has Predecessor which is not
   // in Entries set.
diff --git a/llvm/lib/Transforms/Instrumentation/ControlHeightReduction.cpp b/llvm/lib/Transforms/Instrumentation/ControlHeightReduction.cpp
index 0b35ff82478e3..c14bbecf0d4e1 100644
--- a/llvm/lib/Transforms/Instrumentation/ControlHeightReduction.cpp
+++ b/llvm/lib/Transforms/Instrumentation/ControlHeightReduction.cpp
@@ -881,11 +881,8 @@ void CHR::checkScopeHoistable(CHRScope *Scope) {
     // Avoid a data dependence from a select or a branch to a(nother)
     // select. Note no instruction can't data-depend on a branch (a branch
     // instruction doesn't produce a value).
-    DenseSet<Instruction *> Unhoistables;
     // Initialize Unhoistables with the selects.
-    for (SelectInst *SI : Selects) {
-      Unhoistables.insert(SI);
-    }
+    DenseSet<Instruction *> Unhoistables(llvm::from_range, Selects);
     // Remove Selects that can't be hoisted.
     for (auto it = Selects.begin(); it != Selects.end(); ) {
       SelectInst *SI = *it;
@@ -1104,8 +1101,7 @@ static bool shouldSplit(Instruction *InsertPoint,
 static void getSelectsInScope(CHRScope *Scope,
                               DenseSet<Instruction *> &Output) {
   for (RegInfo &RI : Scope->RegInfos)
-    for (SelectInst *SI : RI.Selects)
-      Output.insert(SI);
+    Output.insert_range(RI.Selects);
   for (CHRScope *Sub : Scope->Subs)
     getSelectsInScope(Sub, Output);
 }
@@ -1370,11 +1366,8 @@ void CHR::setCHRRegions(CHRScope *Scope, CHRScope *OutermostScope) {
   // Put the biased selects in Unhoistables because they should stay where they
   // are and constant-folded after CHR (in case one biased select or a branch
   // can depend on another biased select.)
-  for (RegInfo &RI : Scope->RegInfos) {
-    for (SelectInst *SI : RI.Selects) {
-      Unhoistables.insert(SI);
-    }
-  }
+  for (RegInfo &RI : Scope->RegInfos)
+    Unhoistables.insert_range(RI.Selects);
   Instruction *InsertPoint = OutermostScope->BranchInsertPoint;
   for (RegInfo &RI : Scope->RegInfos) {
     Region *R = RI.R;
diff --git a/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
index 1ef650723a30b..090e7cf7345f7 100644
--- a/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
@@ -874,8 +874,7 @@ DataFlowSanitizer::DataFlowSanitizer(
   ABIList.set(
       SpecialCaseList::createOrDie(AllABIListFiles, *vfs::getRealFileSystem()));
 
-  for (StringRef v : ClCombineTaintLookupTables)
-    CombineTaintLookupTableNames.insert(v);
+  CombineTaintLookupTableNames.insert_range(ClCombineTaintLookupTables);
 }
 
 TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
diff --git a/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp b/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp
index 528d259f4caff..6817be23be5f8 100644
--- a/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp
+++ b/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp
@@ -1003,8 +1003,7 @@ static bool promoteIndirectCalls(Module &M, ProfileSummaryInfo *PSI, bool InLTO,
   if (EnableVTableProfileUse) {
     computeVirtualCallSiteTypeInfoMap(M, MAM, VirtualCSInfo);
 
-    for (StringRef Str : ICPIgnoredBaseTypes)
-      IgnoredBaseTypes.insert(Str);
+    IgnoredBaseTypes.insert_range(ICPIgnoredBaseTypes);
   }
 
   // VTableAddressPointOffsetVal stores the vtable address points. The vtable
diff --git a/llvm/lib/Transforms/Scalar/DFAJumpThreading.cpp b/llvm/lib/Transforms/Scalar/DFAJumpThreading.cpp
index 8a5c506eed694..c99238a2d5ff4 100644
--- a/llvm/lib/Transforms/Scalar/DFAJumpThreading.cpp
+++ b/llvm/lib/Transforms/Scalar/DFAJumpThreading.cpp
@@ -957,8 +957,7 @@ struct TransformDFA {
     DefMap NewDefs;
 
     SmallSet<BasicBlock *, 16> BlocksToClean;
-    for (BasicBlock *BB : successors(SwitchBlock))
-      BlocksToClean.insert(BB);
+    BlocksToClean.insert_range(successors(SwitchBlock));
 
     for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
       createExitPath(NewDefs, TPath, DuplicateMap, BlocksToClean, &DTU);
diff --git a/llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp b/llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp
index 06ac209f9fe5c..935f21fd484f3 100644
--- a/llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp
+++ b/llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp
@@ -1824,8 +1824,7 @@ struct DSEState {
         if (!DT.isReachableFromEntry(Current))
           continue;
 
-        for (BasicBlock *Pred : predecessors(Current))
-          WorkList.insert(Pred);
+        WorkList.insert_range(predecessors(Current));
 
         if (WorkList.size() >= MemorySSAPathCheckLimit)
           return std::nullopt;
diff --git a/llvm/lib/Transforms/Scalar/GVNSink.cpp b/llvm/lib/Transforms/Scalar/GVNSink.cpp
index 5d9a5f90af186..24d7f9381c045 100644
--- a/llvm/lib/Transforms/Scalar/GVNSink.cpp
+++ b/llvm/lib/Transforms/Scalar/GVNSink.cpp
@@ -566,8 +566,7 @@ class GVNSink {
     for (PHINode &PN : BB->phis()) {
       auto MPHI = ModelledPHI(&PN, RPOTOrder);
       PHIs.insert(MPHI);
-      for (auto *V : MPHI.getValues())
-        PHIContents.insert(V);
+      PHIContents.insert_range(MPHI.getValues());
     }
   }
 
diff --git a/llvm/lib/Transforms/Scalar/LICM.cpp b/llvm/lib/Transforms/Scalar/LICM.cpp
index 119696c2afad5..39f72703bd46e 100644
--- a/llvm/lib/Transforms/Scalar/LICM.cpp
+++ b/llvm/lib/Transforms/Scalar/LICM.cpp
@@ -731,10 +731,9 @@ class ControlFlowHoister {
       return false;
     // We can hoist phis if the block they are in is the target of hoistable
     // branches which cover all of the predecessors of the block.
-    SmallPtrSet<BasicBlock *, 8> PredecessorBlocks;
     BasicBlock *BB = PN->getParent();
-    for (BasicBlock *PredBB : predecessors(BB))
-      PredecessorBlocks.insert(PredBB);
+    SmallPtrSet<BasicBlock *, 8> PredecessorBlocks(llvm::from_range,
+                                                   predecessors(BB));
     // If we have less predecessor blocks than predecessors then the phi will
     // have more than one incoming value for the same block which we can't
     // handle.
diff --git a/llvm/lib/Transforms/Scalar/Reassociate.cpp b/llvm/lib/Transforms/Scalar/Reassociate.cpp
index a7db9fd817883..f9aef064641d8 100644
--- a/llvm/lib/Transforms/Scalar/Reassociate.cpp
+++ b/llvm/lib/Transforms/Scalar/Reassociate.cpp
@@ -762,8 +762,7 @@ void ReassociatePass::RewriteExprTree(BinaryOperator *I,
   }
 
   // Throw away any left over nodes from the original expression.
-  for (BinaryOperator *BO : NodesToRewrite)
-    RedoInsts.insert(BO);
+  RedoInsts.insert_range(NodesToRewrite);
 }
 
 /// Insert instructions before the instruction pointed to by BI,
diff --git a/llvm/lib/Transforms/Scalar/SROA.cpp b/llvm/lib/Transforms/Scalar/SROA.cpp
index 1b82e5dc58707..86be20c799a68 100644
--- a/llvm/lib/Transforms/Scalar/SROA.cpp
+++ b/llvm/lib/Transforms/Scalar/SROA.cpp
@@ -4988,8 +4988,7 @@ AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
       // If we have either PHIs or Selects to speculate, add them to those
       // worklists and re-queue the new alloca so that we promote in on the
       // next iteration.
-      for (PHINode *PHIUser : PHIUsers)
-        SpeculatablePHIs.insert(PHIUser);
+      SpeculatablePHIs.insert_range(PHIUsers);
       SelectsToRewrite.reserve(SelectsToRewrite.size() +
                                NewSelectsToRewrite.size());
       for (auto &&KV : llvm::make_range(
diff --git a/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp b/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp
index 62b4b545f29bb..544dcc86d2ced 100644
--- a/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp
+++ b/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp
@@ -345,8 +345,7 @@ bool llvm::SplitIndirectBrCriticalEdges(Function &F,
   SmallSetVector<BasicBlock *, 16> Targets;
   for (auto &BB : F) {
     if (isa<IndirectBrInst>(BB.getTerminator()))
-      for (BasicBlock *Succ : successors(&BB))
-        Targets.insert(Succ);
+      Targets.insert_range(successors(&BB));
   }
 
   if (Targets.empty())
diff --git a/llvm/lib/Transforms/Utils/CloneFunction.cpp b/llvm/lib/Transforms/Utils/CloneFunction.cpp
index b411d4cb87fd4..e58585705e82f 100644
--- a/llvm/lib/Transforms/Utils/CloneFunction.cpp
+++ b/llvm/lib/Transforms/Utils/CloneFunction.cpp
@@ -313,9 +313,7 @@ void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
   auto *NewModule = NewFunc->getParent();
   auto *NMD = NewModule->getOrInsertNamedMetadata("llvm.dbg.cu");
   // Avoid multiple insertions of the same DICompileUnit to NMD.
-  SmallPtrSet<const void *, 8> Visited;
-  for (auto *Operand : NMD->operands())
-    Visited.insert(Operand);
+  SmallPtrSet<const void *, 8> Visited(llvm::from_range, NMD->operands());
 
   // Collect and clone all the compile units referenced from the instructions in
   // the function (e.g. as instructions' scope).
diff --git a/llvm/lib/Transforms/Utils/InlineFunction.cpp b/llvm/lib/Transforms/Utils/InlineFunction.cpp
index 66fda5b1ec7c9..1404867fda6bc 100644
--- a/llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ b/llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -1245,8 +1245,7 @@ static void AddAliasScopeMetadata(CallBase &CB, ValueToValueMapTy &VMap,
         SmallVector<const Value *, 4> Objects;
         getUnderlyingObjects(V, Objects, /* LI = */ nullptr);
 
-        for (const Value *O : Objects)
-          ObjSet.insert(O);
+        ObjSet.insert_range(Objects);
       }
 
       // Figure out if we're derived from anything that is not a noalias
diff --git a/llvm/lib/Transforms/Utils/LoopPeel.cpp b/llvm/lib/Transforms/Utils/LoopPeel.cpp
index 0f3a92b65686c..f6ace9c4e5d2f 100644
--- a/llvm/lib/Transforms/Utils/LoopPeel.cpp
+++ b/llvm/lib/Transforms/Utils/LoopPeel.cpp
@@ -302,11 +302,8 @@ static unsigned peelToTurnInvariantLoadsDerefencebale(Loop &L,
       if (I.mayWriteToMemory())
         return 0;
 
-      auto Iter = LoadUsers.find(&I);
-      if (Iter != LoadUsers.end()) {
-        for (Value *U : I.users())
-          LoadUsers.insert(U);
-      }
+      if (LoadUsers.contains(&I))
+        LoadUsers.insert_range(I.users());
       // Do not look for reads in the header; they can already be hoisted
       // without peeling.
       if (BB == Header)
@@ -315,8 +312,7 @@ static unsigned peelToTurnInvariantLoadsDerefencebale(Loop &L,
         Value *Ptr = LI->getPointerOperand();
         if (DT.dominates(BB, Latch) && L.isLoopInvariant(Ptr) &&
             !isDereferenceablePointer(Ptr, LI->getType(), DL, LI, AC, &DT))
-          for (Value *U : I.users())
-            LoadUsers.insert(U);
+          LoadUsers.insert_range(I.users());
       }
     }
   }
diff --git a/llvm/lib/Transforms/Utils/LoopUnroll.cpp b/llvm/lib/Transforms/Utils/LoopUnroll.cpp
index af6f9c2a8edd3..45b49671dd3b6 100644
--- a/llvm/lib/Transforms/Utils/LoopUnroll.cpp
+++ b/llvm/lib/Transforms/Utils/LoopUnroll.cpp
@@ -684,8 +684,7 @@ llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
   // share the same exit blocks). We'll keep track of loops for which we can
   // break this so that later we can re-simplify them.
   SmallSetVector<Loop *, 4> LoopsToSimplify;
-  for (Loop *SubLoop : *L)
-    LoopsToSimplify.insert(SubLoop);
+  LoopsToSimplify.insert_range(*L);
 
   // When a FSDiscriminator is enabled, we don't need to add the multiply
   // factors to the discriminators.
diff --git a/llvm/lib/Transforms/Utils/SSAUpdaterBulk.cpp b/llvm/lib/Transforms/Utils/SSAUpdaterBulk.cpp
index da2686063ad1b..d7bf791a23edf 100644
--- a/llvm/lib/Transforms/Utils/SSAUpdaterBulk.cpp
+++ b/llvm/lib/Transforms/Utils/SSAUpdaterBulk.cpp
@@ -124,9 +124,8 @@ void SSAUpdaterBulk::RewriteAllUses(DominatorTree *DT,
     LLVM_DEBUG(dbgs() << "SSAUpdater: rewriting " << R.Uses.size()
                       << " use(s)\n");
 
-    SmallPtrSet<BasicBlock *, 2> DefBlocks;
-    for (auto [BB, V] : R.Defines)
-      DefBlocks.insert(BB);
+    SmallPtrSet<BasicBlock *, 2> DefBlocks(llvm::from_range,
+                                           llvm::make_first_range(R.Defines));
     IDF.setDefiningBlocks(DefBlocks);
 
     SmallPtrSet<BasicBlock *, 2> UsingBlocks;

``````````

</details>


https://github.com/llvm/llvm-project/pull/132652


More information about the llvm-commits mailing list