[clang] 5c23e27 - [analyzer][NFC] Move away from using raw-for loops inside StaticAnalyzer

Balazs Benics via cfe-commits cfe-commits at lists.llvm.org
Tue Jul 4 23:56:38 PDT 2023


Author: Balazs Benics
Date: 2023-07-05T08:56:13+02:00
New Revision: 5c23e27ba19c566b114f8a89a856f1d08238fa96

URL: https://github.com/llvm/llvm-project/commit/5c23e27ba19c566b114f8a89a856f1d08238fa96
DIFF: https://github.com/llvm/llvm-project/commit/5c23e27ba19c566b114f8a89a856f1d08238fa96.diff

LOG: [analyzer][NFC] Move away from using raw-for loops inside StaticAnalyzer

I'm involved with the Static Analyzer for the most part.
I think we should embrace newer language standard features and gradually
move forward.

Differential Revision: https://reviews.llvm.org/D154325

Added: 
    

Modified: 
    clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
    clang/include/clang/StaticAnalyzer/Core/Checker.h
    clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
    clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
    clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
    clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
    clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
    clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
    clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
    clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
    clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
    clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
    clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
    clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/DebugCheckers.cpp
    clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
    clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
    clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
    clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/Taint.cpp
    clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp
    clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
    clang/lib/StaticAnalyzer/Core/BugReporter.cpp
    clang/lib/StaticAnalyzer/Core/Environment.cpp
    clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
    clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
    clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
    clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
    clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
    clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
    clang/lib/StaticAnalyzer/Core/MemRegion.cpp
    clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
    clang/lib/StaticAnalyzer/Core/ProgramState.cpp
    clang/lib/StaticAnalyzer/Core/RegionStore.cpp
    clang/lib/StaticAnalyzer/Core/Store.cpp
    clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
    clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
    clang/lib/StaticAnalyzer/Frontend/ModelConsumer.cpp

Removed: 
    


################################################################################
diff  --git a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
index e5ebb04d67b2a0..826370c2648c28 100644
--- a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
+++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
@@ -608,8 +608,9 @@ class BugReporter {
 
   /// Iterator over the set of BugReports tracked by the BugReporter.
   using EQClasses_iterator = llvm::FoldingSet<BugReportEquivClass>::iterator;
-  EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); }
-  EQClasses_iterator EQClasses_end() { return EQClasses.end(); }
+  llvm::iterator_range<EQClasses_iterator> equivalenceClasses() {
+    return EQClasses;
+  }
 
   ASTContext &getContext() { return D.getASTContext(); }
 

diff  --git a/clang/include/clang/StaticAnalyzer/Core/Checker.h b/clang/include/clang/StaticAnalyzer/Core/Checker.h
index 36a8bcb26bd228..b92f0e1e9f0f47 100644
--- a/clang/include/clang/StaticAnalyzer/Core/Checker.h
+++ b/clang/include/clang/StaticAnalyzer/Core/Checker.h
@@ -370,13 +370,12 @@ class PointerEscape {
                                                             Kind);
 
     InvalidatedSymbols RegularEscape;
-    for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
-                                            E = Escaped.end(); I != E; ++I)
-      if (!ETraits->hasTrait(*I,
-              RegionAndSymbolInvalidationTraits::TK_PreserveContents) &&
-          !ETraits->hasTrait(*I,
-              RegionAndSymbolInvalidationTraits::TK_SuppressEscape))
-        RegularEscape.insert(*I);
+    for (SymbolRef Sym : Escaped)
+      if (!ETraits->hasTrait(
+              Sym, RegionAndSymbolInvalidationTraits::TK_PreserveContents) &&
+          !ETraits->hasTrait(
+              Sym, RegionAndSymbolInvalidationTraits::TK_SuppressEscape))
+        RegularEscape.insert(Sym);
 
     if (RegularEscape.empty())
       return State;
@@ -410,13 +409,13 @@ class ConstPointerEscape {
       return State;
 
     InvalidatedSymbols ConstEscape;
-    for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
-                                            E = Escaped.end(); I != E; ++I)
-      if (ETraits->hasTrait(*I,
-              RegionAndSymbolInvalidationTraits::TK_PreserveContents) &&
-          !ETraits->hasTrait(*I,
-              RegionAndSymbolInvalidationTraits::TK_SuppressEscape))
-        ConstEscape.insert(*I);
+    for (SymbolRef Sym : Escaped) {
+      if (ETraits->hasTrait(
+              Sym, RegionAndSymbolInvalidationTraits::TK_PreserveContents) &&
+          !ETraits->hasTrait(
+              Sym, RegionAndSymbolInvalidationTraits::TK_SuppressEscape))
+        ConstEscape.insert(Sym);
+    }
 
     if (ConstEscape.empty())
       return State;

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
index a44ca660cd07df..8129ebc8fdc693 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -620,10 +620,9 @@ class BlockCall : public CallEvent {
     const BlockDataRegion *BR = getBlockRegion();
     assert(BR && "Block converted from lambda must have a block region");
 
-    auto I = BR->referenced_vars_begin();
-    assert(I != BR->referenced_vars_end());
-
-    return I.getCapturedRegion();
+    auto ReferencedVars = BR->referenced_vars();
+    assert(!ReferencedVars.empty());
+    return ReferencedVars.begin().getCapturedRegion();
   }
 
   RuntimeDefinition getRuntimeDefinition() const override {

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
index a595d517cd2768..8dbe767cef9d7e 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
@@ -25,6 +25,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Casting.h"
 #include <cassert>
 #include <memory>
@@ -175,21 +176,11 @@ class CoreEngine {
   WorkList *getWorkList() const { return WList.get(); }
   WorkList *getCTUWorkList() const { return CTUWList.get(); }
 
-  BlocksExhausted::const_iterator blocks_exhausted_begin() const {
-    return blocksExhausted.begin();
+  auto exhausted_blocks() const {
+    return llvm::iterator_range(blocksExhausted);
   }
 
-  BlocksExhausted::const_iterator blocks_exhausted_end() const {
-    return blocksExhausted.end();
-  }
-
-  BlocksAborted::const_iterator blocks_aborted_begin() const {
-    return blocksAborted.begin();
-  }
-
-  BlocksAborted::const_iterator blocks_aborted_end() const {
-    return blocksAborted.end();
-  }
+  auto aborted_blocks() const { return llvm::iterator_range(blocksAborted); }
 
   /// Enqueue the given set of nodes onto the work list.
   void enqueue(ExplodedNodeSet &Set);
@@ -507,6 +498,11 @@ class IndirectGotoNodeBuilder {
     iterator(CFGBlock::const_succ_iterator i) : I(i) {}
 
   public:
+    // This isn't really a conventional iterator.
+    // We just implement the deref as a no-op for now to make range-based for
+    // loops work.
+    const iterator &operator*() const { return *this; }
+
     iterator &operator++() { ++I; return *this; }
     bool operator!=(const iterator &X) const { return I != X.I; }
 

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
index cb424ba5f3e72b..2fb05ac46e8fad 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
@@ -32,6 +32,7 @@
 #include "llvm/ADT/GraphTraits.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Compiler.h"
 #include <cassert>
@@ -395,13 +396,9 @@ class ExplodedGraph {
   using node_iterator = AllNodesTy::iterator;
   using const_node_iterator = AllNodesTy::const_iterator;
 
-  node_iterator nodes_begin() { return Nodes.begin(); }
+  llvm::iterator_range<node_iterator> nodes() { return Nodes; }
 
-  node_iterator nodes_end() { return Nodes.end(); }
-
-  const_node_iterator nodes_begin() const { return Nodes.begin(); }
-
-  const_node_iterator nodes_end() const { return Nodes.end(); }
+  llvm::iterator_range<const_node_iterator> nodes() const { return Nodes; }
 
   roots_iterator roots_begin() { return Roots.begin(); }
 

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index b59917e9dfc9f3..ed5c4adb5e3d56 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -602,8 +602,7 @@ class ExprEngine {
                                       StmtNodeBuilder &Bldr,
                                       ExplodedNode *Pred);
 
-  void handleUOExtension(ExplodedNodeSet::iterator I,
-                         const UnaryOperator* U,
+  void handleUOExtension(ExplodedNode *N, const UnaryOperator *U,
                          StmtNodeBuilder &Bldr);
 
 public:

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
index 3b818327ead7b9..151d3e57c1cb81 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
@@ -31,6 +31,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/PointerIntPair.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Casting.h"
 #include <cassert>
@@ -737,6 +738,11 @@ class BlockDataRegion : public TypedRegion {
       ++OriginalR;
       return *this;
     }
+
+    // This isn't really a conventional iterator.
+    // We just implement the deref as a no-op for now to make range-based for
+    // loops work.
+    const referenced_vars_iterator &operator*() const { return *this; }
   };
 
   /// Return the original region for a captured region, if
@@ -745,6 +751,7 @@ class BlockDataRegion : public TypedRegion {
 
   referenced_vars_iterator referenced_vars_begin() const;
   referenced_vars_iterator referenced_vars_end() const;
+  llvm::iterator_range<referenced_vars_iterator> referenced_vars() const;
 
   void dumpToStream(raw_ostream &os) const override;
 

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
index d5c2dc6172438a..5116a4c06850d1 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
@@ -203,9 +203,9 @@ class SMTConstraintManager : public clang::ento::SimpleConstraintManager {
     auto CZ = State->get<ConstraintSMT>();
     auto &CZFactory = State->get_context<ConstraintSMT>();
 
-    for (auto I = CZ.begin(), E = CZ.end(); I != E; ++I) {
-      if (SymReaper.isDead(I->first))
-        CZ = CZFactory.remove(CZ, *I);
+    for (const auto &Entry : CZ) {
+      if (SymReaper.isDead(Entry.first))
+        CZ = CZFactory.remove(CZ, Entry);
     }
 
     return State->set<ConstraintSMT>(CZ);

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
index 32a1125ce4d8b6..00cce21151a707 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
@@ -21,6 +21,7 @@
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/ImmutableList.h"
 #include "llvm/ADT/PointerUnion.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Casting.h"
 #include <cassert>
 #include <cstdint>
@@ -180,16 +181,11 @@ class SVal {
   void dumpToStream(raw_ostream &OS) const;
   void dump() const;
 
-  SymExpr::symbol_iterator symbol_begin() const {
-    const SymExpr *SE = getAsSymbol(/*IncludeBaseRegions=*/true);
-    if (SE)
-      return SE->symbol_begin();
-    else
-      return SymExpr::symbol_iterator();
-  }
-
-  SymExpr::symbol_iterator symbol_end() const {
-    return SymExpr::symbol_end();
+  llvm::iterator_range<SymExpr::symbol_iterator> symbols() const {
+    if (const SymExpr *SE = getAsSymbol(/*IncludeBaseRegions=*/true))
+      return SE->symbols();
+    SymExpr::symbol_iterator end{};
+    return llvm::make_range(end, end);
   }
 
   /// Try to get a reasonable type for the given value.

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
index abd05fe34f54a8..862a30c0e73633 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
@@ -17,6 +17,7 @@
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/iterator_range.h"
 #include <cassert>
 
 namespace clang {
@@ -83,8 +84,9 @@ class SymExpr : public llvm::FoldingSetNode {
     bool operator!=(const symbol_iterator &X) const;
   };
 
-  symbol_iterator symbol_begin() const { return symbol_iterator(this); }
-  static symbol_iterator symbol_end() { return symbol_iterator(); }
+  llvm::iterator_range<symbol_iterator> symbols() const {
+    return llvm::make_range(symbol_iterator(this), symbol_iterator());
+  }
 
   virtual unsigned computeComplexity() const = 0;
 

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
index 363eeba82d4c1a..3b64d38ee2b233 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
@@ -24,6 +24,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Allocator.h"
 #include <cassert>
 
@@ -631,10 +632,9 @@ class SymbolReaper {
   /// symbol marking has occurred, i.e. in the MarkLiveSymbols callback.
   void markInUse(SymbolRef sym);
 
-  using region_iterator = RegionSetTy::const_iterator;
-
-  region_iterator region_begin() const { return LiveRegionRoots.begin(); }
-  region_iterator region_end() const { return LiveRegionRoots.end(); }
+  llvm::iterator_range<RegionSetTy::const_iterator> regions() const {
+    return LiveRegionRoots;
+  }
 
   /// Returns whether or not a symbol has been confirmed dead.
   ///

diff  --git a/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp
index 45783729e14268..a54f1b1e71d47b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp
@@ -7,14 +7,15 @@
 //===----------------------------------------------------------------------===//
 // This file reports various statistics about analyzer visitation.
 //===----------------------------------------------------------------------===//
-#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/Statistic.h"
@@ -52,9 +53,8 @@ void AnalyzerStatsChecker::checkEndAnalysis(ExplodedGraph &G,
   const Decl *D = LC->getDecl();
 
   // Iterate over the exploded graph.
-  for (ExplodedGraph::node_iterator I = G.nodes_begin();
-      I != G.nodes_end(); ++I) {
-    const ProgramPoint &P = I->getLocation();
+  for (const ExplodedNode &N : G.nodes()) {
+    const ProgramPoint &P = N.getLocation();
 
     // Only check the coverage in the top level function (optimization).
     if (D != P.getLocationContext()->getDecl())
@@ -115,11 +115,8 @@ void AnalyzerStatsChecker::checkEndAnalysis(ExplodedGraph &G,
                     output.str(), PathDiagnosticLocation(D, SM));
 
   // Emit warning for each block we bailed out on.
-  typedef CoreEngine::BlocksExhausted::const_iterator ExhaustedIterator;
   const CoreEngine &CE = Eng.getCoreEngine();
-  for (ExhaustedIterator I = CE.blocks_exhausted_begin(),
-      E = CE.blocks_exhausted_end(); I != E; ++I) {
-    const BlockEdge &BE =  I->first;
+  for (const BlockEdge &BE : make_first_range(CE.exhausted_blocks())) {
     const CFGBlock *Exit = BE.getDst();
     if (Exit->empty())
       continue;

diff  --git a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
index f88b17d437eaa3..4a5b8913c22fd6 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
@@ -30,6 +30,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/Support/raw_ostream.h"
@@ -973,9 +974,8 @@ static bool alreadyExecutedAtLeastOneLoopIteration(const ExplodedNode *N,
   }
 
   // Keep looking for a block edge.
-  for (ExplodedNode::const_pred_iterator I = N->pred_begin(),
-                                         E = N->pred_end(); I != E; ++I) {
-    if (alreadyExecutedAtLeastOneLoopIteration(*I, FCS))
+  for (const ExplodedNode *N : N->preds()) {
+    if (alreadyExecutedAtLeastOneLoopIteration(N, FCS))
       return true;
   }
 
@@ -1104,11 +1104,7 @@ ObjCLoopChecker::checkPointerEscape(ProgramStateRef State,
   SymbolRef ImmutableReceiver = getMethodReceiverIfKnownImmutable(Call);
 
   // Remove the invalidated symbols from the collection count map.
-  for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
-       E = Escaped.end();
-       I != E; ++I) {
-    SymbolRef Sym = *I;
-
+  for (SymbolRef Sym : Escaped) {
     // Don't invalidate this symbol's count if we know the method being called
     // is declared on an immutable class. This isn't completely correct if the
     // receiver is also passed as an argument, but in most uses of NSArray,
@@ -1130,9 +1126,7 @@ void ObjCLoopChecker::checkDeadSymbols(SymbolReaper &SymReaper,
 
   // Remove the dead symbols from the collection count map.
   ContainerCountMapTy Tracked = State->get<ContainerCountMap>();
-  for (ContainerCountMapTy::iterator I = Tracked.begin(),
-                                     E = Tracked.end(); I != E; ++I) {
-    SymbolRef Sym = I->first;
+  for (SymbolRef Sym : llvm::make_first_range(Tracked)) {
     if (SymReaper.isDead(Sym)) {
       State = State->remove<ContainerCountMap>(Sym);
       State = State->remove<ContainerNonEmptyMap>(Sym);

diff  --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
index af9cf1443bacd3..e27b006903af3e 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -2575,9 +2575,7 @@ CStringChecker::checkRegionChanges(ProgramStateRef state,
   llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
 
   // First build sets for the changed regions and their super-regions.
-  for (ArrayRef<const MemRegion *>::iterator
-      I = Regions.begin(), E = Regions.end(); I != E; ++I) {
-    const MemRegion *MR = *I;
+  for (const MemRegion *MR : Regions) {
     Invalidated.insert(MR);
 
     SuperRegions.insert(MR);
@@ -2590,10 +2588,7 @@ CStringChecker::checkRegionChanges(ProgramStateRef state,
   CStringLengthTy::Factory &F = state->get_context<CStringLength>();
 
   // Then loop over the entries in the current state.
-  for (CStringLengthTy::iterator I = Entries.begin(),
-      E = Entries.end(); I != E; ++I) {
-    const MemRegion *MR = I.getKey();
-
+  for (const MemRegion *MR : llvm::make_first_range(Entries)) {
     // Is this entry for a super-region of a changed region?
     if (SuperRegions.count(MR)) {
       Entries = F.remove(Entries, MR);
@@ -2619,13 +2614,9 @@ void CStringChecker::checkLiveSymbols(ProgramStateRef state,
   // Mark all symbols in our string length map as valid.
   CStringLengthTy Entries = state->get<CStringLength>();
 
-  for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
-      I != E; ++I) {
-    SVal Len = I.getData();
-
-    for (SymExpr::symbol_iterator si = Len.symbol_begin(),
-        se = Len.symbol_end(); si != se; ++si)
-      SR.markInUse(*si);
+  for (SVal Len : llvm::make_second_range(Entries)) {
+    for (SymbolRef Sym : Len.symbols())
+      SR.markInUse(Sym);
   }
 }
 
@@ -2637,12 +2628,10 @@ void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
     return;
 
   CStringLengthTy::Factory &F = state->get_context<CStringLength>();
-  for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
-      I != E; ++I) {
-    SVal Len = I.getData();
+  for (auto [Reg, Len] : Entries) {
     if (SymbolRef Sym = Len.getAsSymbol()) {
       if (SR.isDead(Sym))
-        Entries = F.remove(Entries, I.getKey());
+        Entries = F.remove(Entries, Reg);
     }
   }
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp b/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
index baf9618baccd49..bf911e3de65dcd 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
@@ -820,8 +820,8 @@ const ObjCPropertyDecl *ObjCDeallocChecker::findShadowedPropertyDecl(
 
   IdentifierInfo *ID = PropDecl->getIdentifier();
   DeclContext::lookup_result R = CatDecl->getClassInterface()->lookup(ID);
-  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
-    auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(*I);
+  for (const NamedDecl *D : R) {
+    auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(D);
     if (!ShadowedPropDecl)
       continue;
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
index 01b662064d7bde..5f44c9476928dd 100644
--- a/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
@@ -93,9 +93,9 @@ void ReachableCode::computeReachableBlocks() {
     if (isReachable)
       continue;
     isReachable = true;
-    for (CFGBlock::const_succ_iterator i = block->succ_begin(),
-                                       e = block->succ_end(); i != e; ++i)
-      if (const CFGBlock *succ = *i)
+
+    for (const CFGBlock *succ : block->succs())
+      if (succ)
         worklist.push_back(succ);
   }
 }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/DebugCheckers.cpp b/clang/lib/StaticAnalyzer/Checkers/DebugCheckers.cpp
index 7841fd82e37080..2fe91467c8c563 100644
--- a/clang/lib/StaticAnalyzer/Checkers/DebugCheckers.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/DebugCheckers.cpp
@@ -271,9 +271,8 @@ class ConfigDumper : public Checker< check::EndOfTranslationUnit > {
     const Table &Config = mgr.options.Config;
 
     SmallVector<const Table::MapEntryTy *, 32> Keys;
-    for (Table::const_iterator I = Config.begin(), E = Config.end(); I != E;
-         ++I)
-      Keys.push_back(&*I);
+    for (const auto &Entry : Config)
+      Keys.push_back(&Entry);
     llvm::array_pod_sort(Keys.begin(), Keys.end(), compareEntry);
 
     llvm::errs() << "[config]\n";

diff  --git a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
index 26f82fb67472be..1f3e9e00d3e693 100644
--- a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
@@ -31,6 +31,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+#include "llvm/ADT/STLExtras.h"
 #include <optional>
 
 using namespace clang;
@@ -233,11 +234,9 @@ void DynamicTypePropagation::checkDeadSymbols(SymbolReaper &SR,
 
   MostSpecializedTypeArgsMapTy TyArgMap =
       State->get<MostSpecializedTypeArgsMap>();
-  for (MostSpecializedTypeArgsMapTy::iterator I = TyArgMap.begin(),
-                                              E = TyArgMap.end();
-       I != E; ++I) {
-    if (SR.isDead(I->first)) {
-      State = State->remove<MostSpecializedTypeArgsMap>(I->first);
+  for (SymbolRef Sym : llvm::make_first_range(TyArgMap)) {
+    if (SR.isDead(Sym)) {
+      State = State->remove<MostSpecializedTypeArgsMap>(Sym);
     }
   }
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
index 355e9c2238a4c5..15ba29050e9032 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
@@ -393,8 +393,7 @@ void ExprInspectionChecker::checkDeadSymbols(SymbolReaper &SymReaper,
   ProgramStateRef State = C.getState();
   const MarkedSymbolsTy &Syms = State->get<MarkedSymbols>();
   ExplodedNode *N = C.getPredecessor();
-  for (auto I = Syms.begin(), E = Syms.end(); I != E; ++I) {
-    SymbolRef Sym = *I;
+  for (SymbolRef Sym : Syms) {
     if (!SymReaper.isDead(Sym))
       continue;
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
index 65ff1be8ec0545..38b4caa12aef16 100644
--- a/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
@@ -686,11 +686,10 @@ void FuchsiaHandleChecker::printState(raw_ostream &Out, ProgramStateRef State,
 
   if (!StateMap.isEmpty()) {
     Out << Sep << "FuchsiaHandleChecker :" << NL;
-    for (HStateMapTy::iterator I = StateMap.begin(), E = StateMap.end(); I != E;
-         ++I) {
-      I.getKey()->dumpToStream(Out);
+    for (const auto &[Sym, HandleState] : StateMap) {
+      Sym->dumpToStream(Out);
       Out << " : ";
-      I.getData().dump(Out);
+      HandleState.dump(Out);
       Out << NL;
     }
   }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp b/clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
index 80431e65519ec4..2d51a000ece3c1 100644
--- a/clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
@@ -72,6 +72,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h"
+#include "llvm/ADT/STLExtras.h"
 
 #include "Iterator.h"
 
@@ -303,21 +304,18 @@ void IteratorModeling::checkLiveSymbols(ProgramStateRef State,
                                         SymbolReaper &SR) const {
   // Keep symbolic expressions of iterator positions alive
   auto RegionMap = State->get<IteratorRegionMap>();
-  for (const auto &Reg : RegionMap) {
-    const auto Offset = Reg.second.getOffset();
-    for (auto i = Offset->symbol_begin(); i != Offset->symbol_end(); ++i)
-      if (isa<SymbolData>(*i))
-        SR.markLive(*i);
+  for (const IteratorPosition &Pos : llvm::make_second_range(RegionMap)) {
+    for (SymbolRef Sym : Pos.getOffset()->symbols())
+      if (isa<SymbolData>(Sym))
+        SR.markLive(Sym);
   }
 
   auto SymbolMap = State->get<IteratorSymbolMap>();
-  for (const auto &Sym : SymbolMap) {
-    const auto Offset = Sym.second.getOffset();
-    for (auto i = Offset->symbol_begin(); i != Offset->symbol_end(); ++i)
-      if (isa<SymbolData>(*i))
-        SR.markLive(*i);
+  for (const IteratorPosition &Pos : llvm::make_second_range(SymbolMap)) {
+    for (SymbolRef Sym : Pos.getOffset()->symbols())
+      if (isa<SymbolData>(Sym))
+        SR.markLive(Sym);
   }
-
 }
 
 void IteratorModeling::checkDeadSymbols(SymbolReaper &SR,

diff  --git a/clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp
index b3f2d7f4d26870..3496af731aa683 100644
--- a/clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp
@@ -27,14 +27,15 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/AST/Attr.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/StmtVisitor.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallString.h"
 
@@ -80,9 +81,8 @@ class IvarInvalidationCheckerImpl {
     bool hasMethod(const ObjCMethodDecl *MD) {
       if (IsInvalidated)
         return true;
-      for (MethodSet::iterator I = InvalidationMethods.begin(),
-          E = InvalidationMethods.end(); I != E; ++I) {
-        if (*I == MD) {
+      for (const ObjCMethodDecl *Curr : InvalidationMethods) {
+        if (Curr == MD) {
           IsInvalidated = true;
           return true;
         }
@@ -318,9 +318,7 @@ const ObjCIvarDecl *IvarInvalidationCheckerImpl::findPropertyBackingIvar(
 
   // Lookup IVars named "_PropName"or "PropName" among the tracked Ivars.
   StringRef PropName = Prop->getIdentifier()->getName();
-  for (IvarSet::const_iterator I = TrackedIvars.begin(),
-                               E = TrackedIvars.end(); I != E; ++I) {
-    const ObjCIvarDecl *Iv = I->first;
+  for (const ObjCIvarDecl *Iv : llvm::make_first_range(TrackedIvars)) {
     StringRef IvarName = Iv->getName();
 
     if (IvarName == PropName)
@@ -381,9 +379,7 @@ visit(const ObjCImplementationDecl *ImplD) const {
   ObjCInterfaceDecl::PropertyMap PropMap;
   InterfaceD->collectPropertiesToImplement(PropMap);
 
-  for (ObjCInterfaceDecl::PropertyMap::iterator
-      I = PropMap.begin(), E = PropMap.end(); I != E; ++I) {
-    const ObjCPropertyDecl *PD = I->second;
+  for (const ObjCPropertyDecl *PD : llvm::make_second_range(PropMap)) {
     if (PD->isClassProperty())
       continue;
 
@@ -422,11 +418,7 @@ visit(const ObjCImplementationDecl *ImplD) const {
   // Remove ivars invalidated by the partial invalidation methods. They do not
   // need to be invalidated in the regular invalidation methods.
   bool AtImplementationContainsAtLeastOnePartialInvalidationMethod = false;
-  for (MethodSet::iterator
-      I = PartialInfo.InvalidationMethods.begin(),
-      E = PartialInfo.InvalidationMethods.end(); I != E; ++I) {
-    const ObjCMethodDecl *InterfD = *I;
-
+  for (const ObjCMethodDecl *InterfD : PartialInfo.InvalidationMethods) {
     // Get the corresponding method in the @implementation.
     const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(),
                                                InterfD->isInstanceMethod());
@@ -475,10 +467,7 @@ visit(const ObjCImplementationDecl *ImplD) const {
 
   // Check that all ivars are invalidated by the invalidation methods.
   bool AtImplementationContainsAtLeastOneInvalidationMethod = false;
-  for (MethodSet::iterator I = Info.InvalidationMethods.begin(),
-                           E = Info.InvalidationMethods.end(); I != E; ++I) {
-    const ObjCMethodDecl *InterfD = *I;
-
+  for (const ObjCMethodDecl *InterfD : Info.InvalidationMethods) {
     // Get the corresponding method in the @implementation.
     const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(),
                                                InterfD->isInstanceMethod());
@@ -501,9 +490,8 @@ visit(const ObjCImplementationDecl *ImplD) const {
         continue;
 
       // Warn on the ivars that were not invalidated by the method.
-      for (IvarSet::const_iterator
-          I = IvarsI.begin(), E = IvarsI.end(); I != E; ++I)
-        reportIvarNeedsInvalidation(I->first, IvarToPopertyMap, D);
+      for (const ObjCIvarDecl *Ivar : llvm::make_first_range(IvarsI))
+        reportIvarNeedsInvalidation(Ivar, IvarToPopertyMap, D);
     }
   }
 
@@ -512,9 +500,8 @@ visit(const ObjCImplementationDecl *ImplD) const {
     if (AtImplementationContainsAtLeastOnePartialInvalidationMethod) {
       // Warn on the ivars that were not invalidated by the prrtial
       // invalidation methods.
-      for (IvarSet::const_iterator
-           I = Ivars.begin(), E = Ivars.end(); I != E; ++I)
-        reportIvarNeedsInvalidation(I->first, IvarToPopertyMap, nullptr);
+      for (const ObjCIvarDecl *Ivar : llvm::make_first_range(Ivars))
+        reportIvarNeedsInvalidation(Ivar, IvarToPopertyMap, nullptr);
     } else {
       // Otherwise, no invalidation methods were implemented.
       reportNoInvalidationMethod(Filter.checkName_InstanceVariableInvalidation,

diff  --git a/clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp
index bca10ec96cea5a..b77e9bf09a3320 100644
--- a/clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp
@@ -14,13 +14,13 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/AST/Attr.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/Lex/Lexer.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
@@ -28,6 +28,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Unicode.h"
 #include <optional>
 
@@ -847,10 +848,9 @@ void NonLocalizedStringChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
   if (argumentNumber < 0) { // There was no match in UIMethods
     if (const Decl *D = msg.getDecl()) {
       if (const ObjCMethodDecl *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
-        auto formals = OMD->parameters();
-        for (unsigned i = 0, ei = formals.size(); i != ei; ++i) {
-          if (isAnnotatedAsTakingLocalized(formals[i])) {
-            argumentNumber = i;
+        for (auto [Idx, FormalParam] : llvm::enumerate(OMD->parameters())) {
+          if (isAnnotatedAsTakingLocalized(FormalParam)) {
+            argumentNumber = Idx;
             break;
           }
         }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
index c1b85ace3e2dbc..771c0a5fbb8d80 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
@@ -19,6 +19,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/raw_ostream.h"
 #include <optional>
@@ -530,9 +531,9 @@ ProgramStateRef MacOSKeychainAPIChecker::evalAssume(ProgramStateRef State,
   }
 
   if (ReturnSymbol)
-    for (auto I = AMap.begin(), E = AMap.end(); I != E; ++I) {
-      if (ReturnSymbol == I->second.Region)
-        State = State->remove<AllocatedData>(I->first);
+    for (auto [Sym, AllocState] : AMap) {
+      if (ReturnSymbol == AllocState.Region)
+        State = State->remove<AllocatedData>(Sym);
     }
 
   return State;
@@ -547,18 +548,18 @@ void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
 
   bool Changed = false;
   AllocationPairVec Errors;
-  for (auto I = AMap.begin(), E = AMap.end(); I != E; ++I) {
-    if (!SR.isDead(I->first))
+  for (const auto &[Sym, AllocState] : AMap) {
+    if (!SR.isDead(Sym))
       continue;
 
     Changed = true;
-    State = State->remove<AllocatedData>(I->first);
+    State = State->remove<AllocatedData>(Sym);
     // If the allocated symbol is null do not report.
     ConstraintManager &CMgr = State->getConstraintManager();
-    ConditionTruthVal AllocFailed = CMgr.isNull(State, I.getKey());
+    ConditionTruthVal AllocFailed = CMgr.isNull(State, Sym);
     if (AllocFailed.isConstrainedTrue())
       continue;
-    Errors.push_back(std::make_pair(I->first, &I->second));
+    Errors.push_back(std::make_pair(Sym, &AllocState));
   }
   if (!Changed) {
     // Generate the new, cleaned up state.
@@ -656,8 +657,8 @@ void MacOSKeychainAPIChecker::printState(raw_ostream &Out,
 
   if (!AMap.isEmpty()) {
     Out << Sep << "KeychainAPIChecker :" << NL;
-    for (auto I = AMap.begin(), E = AMap.end(); I != E; ++I) {
-      I.getKey()->dumpToStream(Out);
+    for (SymbolRef Sym : llvm::make_first_range(AMap)) {
+      Sym->dumpToStream(Out);
     }
   }
 }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index b94b7836fc612f..d2b564d022b5d3 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -1688,9 +1688,9 @@ MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call,
   if (Att->getModule()->getName() != "malloc")
     return nullptr;
 
-  OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
-  if (I != E) {
-    return MallocMemAux(C, Call, Call.getArgExpr(I->getASTIndex()),
+  if (!Att->args().empty()) {
+    return MallocMemAux(C, Call,
+                        Call.getArgExpr(Att->args_begin()->getASTIndex()),
                         UndefinedVal(), State, AF_Malloc);
   }
   return MallocMemAux(C, Call, UnknownVal(), UndefinedVal(), State, AF_Malloc);
@@ -2798,12 +2798,12 @@ void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
 
   RegionStateTy RS = OldRS;
   SmallVector<SymbolRef, 2> Errors;
-  for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
-    if (SymReaper.isDead(I->first)) {
-      if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
-        Errors.push_back(I->first);
+  for (auto [Sym, State] : RS) {
+    if (SymReaper.isDead(Sym)) {
+      if (State.isAllocated() || State.isAllocatedOfSizeZero())
+        Errors.push_back(Sym);
       // Remove the dead symbol from the map.
-      RS = F.remove(RS, I->first);
+      RS = F.remove(RS, Sym);
     }
   }
 
@@ -2818,19 +2818,17 @@ void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
 
   // Cleanup the Realloc Pairs Map.
   ReallocPairsTy RP = state->get<ReallocPairs>();
-  for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
-    if (SymReaper.isDead(I->first) ||
-        SymReaper.isDead(I->second.ReallocatedSym)) {
-      state = state->remove<ReallocPairs>(I->first);
+  for (auto [Sym, ReallocPair] : RP) {
+    if (SymReaper.isDead(Sym) || SymReaper.isDead(ReallocPair.ReallocatedSym)) {
+      state = state->remove<ReallocPairs>(Sym);
     }
   }
 
   // Cleanup the FreeReturnValue Map.
   FreeReturnValueTy FR = state->get<FreeReturnValue>();
-  for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
-    if (SymReaper.isDead(I->first) ||
-        SymReaper.isDead(I->second)) {
-      state = state->remove<FreeReturnValue>(I->first);
+  for (auto [Sym, RetSym] : FR) {
+    if (SymReaper.isDead(Sym) || SymReaper.isDead(RetSym)) {
+      state = state->remove<FreeReturnValue>(Sym);
     }
   }
 
@@ -2840,9 +2838,8 @@ void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
     static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
     N = C.generateNonFatalErrorNode(C.getState(), &Tag);
     if (N) {
-      for (SmallVectorImpl<SymbolRef>::iterator
-           I = Errors.begin(), E = Errors.end(); I != E; ++I) {
-        HandleLeak(*I, N, C);
+      for (SymbolRef Sym : Errors) {
+        HandleLeak(Sym, N, C);
       }
     }
   }
@@ -2965,18 +2962,16 @@ void MallocChecker::checkPostStmt(const BlockExpr *BE,
   const BlockDataRegion *R =
     cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
 
-  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
-                                            E = R->referenced_vars_end();
-
-  if (I == E)
+  auto ReferencedVars = R->referenced_vars();
+  if (ReferencedVars.empty())
     return;
 
   SmallVector<const MemRegion*, 10> Regions;
   const LocationContext *LC = C.getLocationContext();
   MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
 
-  for ( ; I != E; ++I) {
-    const VarRegion *VR = I.getCapturedRegion();
+  for (const auto &Var : ReferencedVars) {
+    const VarRegion *VR = Var.getCapturedRegion();
     if (VR->getSuperRegion() == R) {
       VR = MemMgr.getVarRegion(VR->getDecl(), LC);
     }
@@ -3072,28 +3067,28 @@ ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
                                               SVal Cond,
                                               bool Assumption) const {
   RegionStateTy RS = state->get<RegionState>();
-  for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
+  for (SymbolRef Sym : llvm::make_first_range(RS)) {
     // If the symbol is assumed to be NULL, remove it from consideration.
     ConstraintManager &CMgr = state->getConstraintManager();
-    ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
+    ConditionTruthVal AllocFailed = CMgr.isNull(state, Sym);
     if (AllocFailed.isConstrainedTrue())
-      state = state->remove<RegionState>(I.getKey());
+      state = state->remove<RegionState>(Sym);
   }
 
   // Realloc returns 0 when reallocation fails, which means that we should
   // restore the state of the pointer being reallocated.
   ReallocPairsTy RP = state->get<ReallocPairs>();
-  for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
+  for (auto [Sym, ReallocPair] : RP) {
     // If the symbol is assumed to be NULL, remove it from consideration.
     ConstraintManager &CMgr = state->getConstraintManager();
-    ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
+    ConditionTruthVal AllocFailed = CMgr.isNull(state, Sym);
     if (!AllocFailed.isConstrainedTrue())
       continue;
 
-    SymbolRef ReallocSym = I.getData().ReallocatedSym;
+    SymbolRef ReallocSym = ReallocPair.ReallocatedSym;
     if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
       if (RS->isReleased()) {
-        switch (I.getData().Kind) {
+        switch (ReallocPair.Kind) {
         case OAR_ToBeFreedAfterFailure:
           state = state->set<RegionState>(ReallocSym,
               RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
@@ -3102,11 +3097,11 @@ ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
           state = state->remove<RegionState>(ReallocSym);
           break;
         default:
-          assert(I.getData().Kind == OAR_FreeOnFailure);
+          assert(ReallocPair.Kind == OAR_FreeOnFailure);
         }
       }
     }
-    state = state->remove<ReallocPairs>(I.getKey());
+    state = state->remove<ReallocPairs>(Sym);
   }
 
   return state;
@@ -3312,11 +3307,7 @@ ProgramStateRef MallocChecker::checkPointerEscapeAux(
     return State;
   }
 
-  for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
-       E = Escaped.end();
-       I != E; ++I) {
-    SymbolRef sym = *I;
-
+  for (SymbolRef sym : Escaped) {
     if (EscapingSymbol && EscapingSymbol != sym)
       continue;
 
@@ -3564,17 +3555,17 @@ void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
 
   if (!RS.isEmpty()) {
     Out << Sep << "MallocChecker :" << NL;
-    for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
-      const RefState *RefS = State->get<RegionState>(I.getKey());
+    for (auto [Sym, Data] : RS) {
+      const RefState *RefS = State->get<RegionState>(Sym);
       AllocationFamily Family = RefS->getAllocationFamily();
       std::optional<MallocChecker::CheckKind> CheckKind =
           getCheckIfTracked(Family);
       if (!CheckKind)
         CheckKind = getCheckIfTracked(Family, true);
 
-      I.getKey()->dumpToStream(Out);
+      Sym->dumpToStream(Out);
       Out << " : ";
-      I.getData().dump(Out);
+      Data.dump(Out);
       if (CheckKind)
         Out << " (" << CheckNames[*CheckKind].getName() << ")";
       Out << NL;

diff  --git a/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp
index 5266df2ae6a68f..3c8b38973c6b8c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp
@@ -280,17 +280,13 @@ void MallocOverflowSecurityChecker::OutputPossibleOverflows(
   c.Visit(mgr.getAnalysisDeclContext(D)->getBody());
 
   // Output warnings for all overflows that are left.
-  for (CheckOverflowOps::theVecType::iterator
-       i = PossibleMallocOverflows.begin(),
-       e = PossibleMallocOverflows.end();
-       i != e;
-       ++i) {
+  for (const MallocOverflowCheck &Check : PossibleMallocOverflows) {
     BR.EmitBasicReport(
         D, this, "malloc() size overflow", categories::UnixAPI,
         "the computation of the size of the memory allocation may overflow",
-        PathDiagnosticLocation::createOperatorLoc(i->mulop,
+        PathDiagnosticLocation::createOperatorLoc(Check.mulop,
                                                   BR.getSourceManager()),
-        i->mulop->getSourceRange());
+        Check.mulop->getSourceRange());
   }
 }
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp
index 58ba3dac69aba6..9e81a6bd19fc5b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp
@@ -12,14 +12,15 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/AST/TypeLoc.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/raw_ostream.h"
 
 using namespace clang;
@@ -182,22 +183,20 @@ class MallocSizeofChecker : public Checker<check::ASTCodeBody> {
     AnalysisDeclContext *ADC = mgr.getAnalysisDeclContext(D);
     CastedAllocFinder Finder(&BR.getContext());
     Finder.Visit(D->getBody());
-    for (CastedAllocFinder::CallVec::iterator i = Finder.Calls.begin(),
-         e = Finder.Calls.end(); i != e; ++i) {
-      QualType CastedType = i->CastedExpr->getType();
+    for (const auto &CallRec : Finder.Calls) {
+      QualType CastedType = CallRec.CastedExpr->getType();
       if (!CastedType->isPointerType())
         continue;
       QualType PointeeType = CastedType->getPointeeType();
       if (PointeeType->isVoidType())
         continue;
 
-      for (CallExpr::const_arg_iterator ai = i->AllocCall->arg_begin(),
-           ae = i->AllocCall->arg_end(); ai != ae; ++ai) {
-        if (!(*ai)->getType()->isIntegralOrUnscopedEnumerationType())
+      for (const Expr *Arg : CallRec.AllocCall->arguments()) {
+        if (!Arg->getType()->isIntegralOrUnscopedEnumerationType())
           continue;
 
         SizeofFinder SFinder;
-        SFinder.Visit(*ai);
+        SFinder.Visit(Arg);
         if (SFinder.Sizeofs.size() != 1)
           continue;
 
@@ -212,18 +211,18 @@ class MallocSizeofChecker : public Checker<check::ASTCodeBody> {
           continue;
 
         const TypeSourceInfo *TSI = nullptr;
-        if (i->CastedExprParent.is<const VarDecl *>()) {
-          TSI =
-              i->CastedExprParent.get<const VarDecl *>()->getTypeSourceInfo();
+        if (CallRec.CastedExprParent.is<const VarDecl *>()) {
+          TSI = CallRec.CastedExprParent.get<const VarDecl *>()
+                    ->getTypeSourceInfo();
         } else {
-          TSI = i->ExplicitCastType;
+          TSI = CallRec.ExplicitCastType;
         }
 
         SmallString<64> buf;
         llvm::raw_svector_ostream OS(buf);
 
         OS << "Result of ";
-        const FunctionDecl *Callee = i->AllocCall->getDirectCallee();
+        const FunctionDecl *Callee = CallRec.AllocCall->getDirectCallee();
         if (Callee && Callee->getIdentifier())
           OS << '\'' << Callee->getIdentifier()->getName() << '\'';
         else
@@ -232,14 +231,13 @@ class MallocSizeofChecker : public Checker<check::ASTCodeBody> {
            << "', which is incompatible with "
            << "sizeof operand type '" << SizeofType << "'";
         SmallVector<SourceRange, 4> Ranges;
-        Ranges.push_back(i->AllocCall->getCallee()->getSourceRange());
+        Ranges.push_back(CallRec.AllocCall->getCallee()->getSourceRange());
         Ranges.push_back(SFinder.Sizeofs[0]->getSourceRange());
         if (TSI)
           Ranges.push_back(TSI->getTypeLoc().getSourceRange());
 
-        PathDiagnosticLocation L =
-            PathDiagnosticLocation::createBegin(i->AllocCall->getCallee(),
-                BR.getSourceManager(), ADC);
+        PathDiagnosticLocation L = PathDiagnosticLocation::createBegin(
+            CallRec.AllocCall->getCallee(), BR.getSourceManager(), ADC);
 
         BR.EmitBasicReport(D, this, "Allocator sizeof operand mismatch",
                            categories::UnixAPI, OS.str(), L, Ranges);

diff  --git a/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
index 635b6e4f6bd71d..653a235b41a4fc 100644
--- a/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
@@ -34,6 +34,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
 
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Path.h"
 
@@ -498,25 +499,21 @@ void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
                                           CheckerContext &C) const {
   ProgramStateRef State = C.getState();
   NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
-  for (NullabilityMapTy::iterator I = Nullabilities.begin(),
-                                  E = Nullabilities.end();
-       I != E; ++I) {
-    const auto *Region = I->first->getAs<SymbolicRegion>();
+  for (const MemRegion *Reg : llvm::make_first_range(Nullabilities)) {
+    const auto *Region = Reg->getAs<SymbolicRegion>();
     assert(Region && "Non-symbolic region is tracked.");
     if (SR.isDead(Region->getSymbol())) {
-      State = State->remove<NullabilityMap>(I->first);
+      State = State->remove<NullabilityMap>(Reg);
     }
   }
 
   // When an object goes out of scope, we can free the history associated
   // with any property accesses on that object
   PropertyAccessesMapTy PropertyAccesses = State->get<PropertyAccessesMap>();
-  for (PropertyAccessesMapTy::iterator I = PropertyAccesses.begin(),
-                                       E = PropertyAccesses.end();
-       I != E; ++I) {
-    const MemRegion *ReceiverRegion = I->first.first;
+  for (ObjectPropPair PropKey : llvm::make_first_range(PropertyAccesses)) {
+    const MemRegion *ReceiverRegion = PropKey.first;
     if (!SR.isLiveRegion(ReceiverRegion)) {
-      State = State->remove<PropertyAccessesMap>(I->first);
+      State = State->remove<PropertyAccessesMap>(PropKey);
     }
   }
 
@@ -945,18 +942,16 @@ static Nullability getReceiverNullability(const ObjCMethodCall &M,
 ProgramStateRef NullabilityChecker::evalAssume(ProgramStateRef State, SVal Cond,
                                                bool Assumption) const {
   PropertyAccessesMapTy PropertyAccesses = State->get<PropertyAccessesMap>();
-  for (PropertyAccessesMapTy::iterator I = PropertyAccesses.begin(),
-                                       E = PropertyAccesses.end();
-       I != E; ++I) {
-    if (!I->second.isConstrainedNonnull) {
-      ConditionTruthVal IsNonNull = State->isNonNull(I->second.Value);
+  for (auto [PropKey, PropVal] : PropertyAccesses) {
+    if (!PropVal.isConstrainedNonnull) {
+      ConditionTruthVal IsNonNull = State->isNonNull(PropVal.Value);
       if (IsNonNull.isConstrainedTrue()) {
-        ConstrainedPropertyVal Replacement = I->second;
+        ConstrainedPropertyVal Replacement = PropVal;
         Replacement.isConstrainedNonnull = true;
-        State = State->set<PropertyAccessesMap>(I->first, Replacement);
+        State = State->set<PropertyAccessesMap>(PropKey, Replacement);
       } else if (IsNonNull.isConstrainedFalse()) {
         // Space optimization: no point in tracking constrained-null cases
-        State = State->remove<PropertyAccessesMap>(I->first);
+        State = State->remove<PropertyAccessesMap>(PropKey);
       }
     }
   }
@@ -1375,9 +1370,9 @@ void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State,
   if (!State->get<InvariantViolated>())
     Out << Sep << NL;
 
-  for (NullabilityMapTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
-    Out << I->first << " : ";
-    I->second.print(Out);
+  for (auto [Region, State] : B) {
+    Out << Region << " : ";
+    State.print(Out);
     Out << NL;
   }
 }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp
index 35a600f2d7b866..fbbc32a40e8919 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp
@@ -103,9 +103,7 @@ void ObjCSuperCallChecker::fillSelectors(ASTContext &Ctx,
   llvm::SmallPtrSet<Selector, 16> &ClassSelectors =
       SelectorsForClass[ClassName];
   // Fill the Selectors SmallSet with all selectors we want to check.
-  for (ArrayRef<SelectorDescriptor>::iterator I = Sel.begin(), E = Sel.end();
-       I != E; ++I) {
-    SelectorDescriptor Descriptor = *I;
+  for (SelectorDescriptor Descriptor : Sel) {
     assert(Descriptor.ArgumentCount <= 1); // No multi-argument selectors yet.
 
     // Get the selector.

diff  --git a/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp
index 9f1a6e416dc6db..d88d6a94a30f28 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp
@@ -362,18 +362,17 @@ void ObjCSelfInitChecker::printState(raw_ostream &Out, ProgramStateRef State,
   }
 
   Out << NL;
-  for (SelfFlagTy::iterator I = FlagMap.begin(), E = FlagMap.end();
-       I != E; ++I) {
-    Out << I->first << " : ";
+  for (auto [Sym, Flag] : FlagMap) {
+    Out << Sym << " : ";
 
-    if (I->second == SelfFlag_None)
+    if (Flag == SelfFlag_None)
       Out << "none";
 
-    if (I->second & SelfFlag_Self)
+    if (Flag & SelfFlag_Self)
       Out << "self variable";
 
-    if (I->second & SelfFlag_InitRes) {
-      if (I->second != SelfFlag_InitRes)
+    if (Flag & SelfFlag_InitRes) {
+      if (Flag != SelfFlag_InitRes)
         Out << " | ";
       Out << "result of init method";
     }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp
index c9828c36a06a0a..1c2d84254d4645 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp
@@ -12,16 +12,17 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
-#include "clang/Analysis/PathDiagnostic.h"
 #include "clang/AST/Attr.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprObjC.h"
+#include "clang/Analysis/PathDiagnostic.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
+#include "llvm/ADT/STLExtras.h"
 
 using namespace clang;
 using namespace ento;
@@ -48,9 +49,7 @@ static void Scan(IvarUsageMap& M, const Stmt *S) {
   }
 
   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(S))
-    for (PseudoObjectExpr::const_semantics_iterator
-        i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
-      const Expr *sub = *i;
+    for (const Expr *sub : POE->semantics()) {
       if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(sub))
         sub = OVE->getSourceExpr();
       Scan(M, sub);
@@ -134,8 +133,8 @@ static void checkObjCUnusedIvar(const ObjCImplementationDecl *D,
 
   // Any potentially unused ivars?
   bool hasUnused = false;
-  for (IvarUsageMap::iterator I = M.begin(), E = M.end(); I!=E; ++I)
-    if (I->second == Unused) {
+  for (IVarState State : llvm::make_second_range(M))
+    if (State == Unused) {
       hasUnused = true;
       break;
     }
@@ -152,16 +151,16 @@ static void checkObjCUnusedIvar(const ObjCImplementationDecl *D,
   Scan(M, D->getDeclContext(), SM.getFileID(D->getLocation()), SM);
 
   // Find ivars that are unused.
-  for (IvarUsageMap::iterator I = M.begin(), E = M.end(); I!=E; ++I)
-    if (I->second == Unused) {
+  for (auto [Ivar, State] : M)
+    if (State == Unused) {
       std::string sbuf;
       llvm::raw_string_ostream os(sbuf);
-      os << "Instance variable '" << *I->first << "' in class '" << *ID
+      os << "Instance variable '" << *Ivar << "' in class '" << *ID
          << "' is never used by the methods in its @implementation "
             "(although it may be used by category methods).";
 
       PathDiagnosticLocation L =
-        PathDiagnosticLocation::create(I->first, BR.getSourceManager());
+          PathDiagnosticLocation::create(Ivar, BR.getSourceManager());
       BR.EmitBasicReport(D, Checker, "Unused instance variable", "Optimization",
                          os.str(), L);
     }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
index d3e2849a0ce694..27364eb72523d3 100644
--- a/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
@@ -79,10 +79,9 @@ void PointerArithChecker::checkDeadSymbols(SymbolReaper &SR,
   // see http://reviews.llvm.org/D14203 for further information.
   /*ProgramStateRef State = C.getState();
   RegionStateTy RegionStates = State->get<RegionState>();
-  for (RegionStateTy::iterator I = RegionStates.begin(), E = RegionStates.end();
-       I != E; ++I) {
-    if (!SR.isLiveRegion(I->first))
-      State = State->remove<RegionState>(I->first);
+  for (const MemRegion *Reg: llvm::make_first_range(RegionStates)) {
+    if (!SR.isLiveRegion(Reg))
+      State = State->remove<RegionState>(Reg);
   }
   C.addTransition(State);*/
 }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
index 01c71d91d1a1a1..7e74b418b33536 100644
--- a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
@@ -155,10 +155,8 @@ void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
   ProgramStateRef state = C.getState();
   auto *R = cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
 
-  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
-                                            E = R->referenced_vars_end();
-
-  if (I == E)
+  auto ReferencedVars = R->referenced_vars();
+  if (ReferencedVars.empty())
     return;
 
   // FIXME: For now we invalidate the tracking of all symbols passed to blocks
@@ -168,8 +166,8 @@ void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
   const LocationContext *LC = C.getLocationContext();
   MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
 
-  for ( ; I != E; ++I) {
-    const VarRegion *VR = I.getCapturedRegion();
+  for (auto Var : ReferencedVars) {
+    const VarRegion *VR = Var.getCapturedRegion();
     if (VR->getSuperRegion() == R) {
       VR = MemMgr.getVarRegion(VR->getDecl(), LC);
     }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
index 9251c895614ca9..32d95e94419539 100644
--- a/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
@@ -163,13 +163,11 @@ void SimpleStreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
   ProgramStateRef State = C.getState();
   SymbolVector LeakedStreams;
   StreamMapTy TrackedStreams = State->get<StreamMap>();
-  for (StreamMapTy::iterator I = TrackedStreams.begin(),
-                             E = TrackedStreams.end(); I != E; ++I) {
-    SymbolRef Sym = I->first;
+  for (auto [Sym, StreamStatus] : TrackedStreams) {
     bool IsSymDead = SymReaper.isDead(Sym);
 
     // Collect leaked symbols.
-    if (isLeaked(Sym, I->second, IsSymDead, State))
+    if (isLeaked(Sym, StreamStatus, IsSymDead, State))
       LeakedStreams.push_back(Sym);
 
     // Remove the dead symbol from the streams map.
@@ -241,11 +239,7 @@ SimpleStreamChecker::checkPointerEscape(ProgramStateRef State,
     return State;
   }
 
-  for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
-                                          E = Escaped.end();
-                                          I != E; ++I) {
-    SymbolRef Sym = *I;
-
+  for (SymbolRef Sym : Escaped) {
     // The symbol escaped. Optimistically, assume that the corresponding file
     // handle will be closed somewhere else.
     State = State->remove<StreamMap>(Sym);

diff  --git a/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp b/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
index 5689a63f8dd81b..a20d24db158f50 100644
--- a/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
@@ -31,6 +31,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/Support/ErrorHandling.h"
 #include <optional>
@@ -588,10 +589,9 @@ void SmartPtrModeling::checkLiveSymbols(ProgramStateRef State,
                                         SymbolReaper &SR) const {
   // Marking tracked symbols alive
   TrackedRegionMapTy TrackedRegions = State->get<TrackedRegionMap>();
-  for (auto I = TrackedRegions.begin(), E = TrackedRegions.end(); I != E; ++I) {
-    SVal Val = I->second;
-    for (auto si = Val.symbol_begin(), se = Val.symbol_end(); si != se; ++si) {
-      SR.markLive(*si);
+  for (SVal Val : llvm::make_second_range(TrackedRegions)) {
+    for (SymbolRef Sym : Val.symbols()) {
+      SR.markLive(Sym);
     }
   }
 }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index 32f88728466aac..80fd2e4d219496 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -138,10 +138,8 @@ SmallVector<const MemRegion *, 4>
 StackAddrEscapeChecker::getCapturedStackRegions(const BlockDataRegion &B,
                                                 CheckerContext &C) {
   SmallVector<const MemRegion *, 4> Regions;
-  BlockDataRegion::referenced_vars_iterator I = B.referenced_vars_begin();
-  BlockDataRegion::referenced_vars_iterator E = B.referenced_vars_end();
-  for (; I != E; ++I) {
-    SVal Val = C.getState()->getSVal(I.getCapturedRegion());
+  for (auto Var : B.referenced_vars()) {
+    SVal Val = C.getState()->getSVal(Var.getCapturedRegion());
     const MemRegion *Region = Val.getAsRegion();
     if (Region && isa<StackSpaceRegion>(Region->getMemorySpace()))
       Regions.push_back(Region);

diff  --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 57d3c99e4dcfaf..0228e8278f057a 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -49,6 +49,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
 
@@ -941,11 +942,9 @@ void StdLibraryFunctionsChecker::RangeConstraint::applyOnWithinRange(
   if (Ranges.empty())
     return;
 
-  const IntRangeVector &R = getRanges();
-  size_t E = R.size();
-  for (size_t I = 0; I != E; ++I) {
-    const llvm::APSInt &Min = BVF.getValue(R[I].first, ArgT);
-    const llvm::APSInt &Max = BVF.getValue(R[I].second, ArgT);
+  for (auto [Start, End] : getRanges()) {
+    const llvm::APSInt &Min = BVF.getValue(Start, ArgT);
+    const llvm::APSInt &Max = BVF.getValue(End, ArgT);
     assert(Min <= Max);
     if (!F(Min, Max))
       return;
@@ -1376,12 +1375,11 @@ bool StdLibraryFunctionsChecker::Signature::matches(
   }
 
   // Check the argument types.
-  for (size_t I = 0, E = ArgTys.size(); I != E; ++I) {
-    QualType ArgTy = ArgTys[I];
+  for (auto [Idx, ArgTy] : llvm::enumerate(ArgTys)) {
     if (isIrrelevant(ArgTy))
       continue;
     QualType FDArgTy =
-        RemoveRestrict(FD->getParamDecl(I)->getType().getCanonicalType());
+        RemoveRestrict(FD->getParamDecl(Idx)->getType().getCanonicalType());
     if (ArgTy != FDArgTy)
       return false;
   }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/Taint.cpp b/clang/lib/StaticAnalyzer/Checkers/Taint.cpp
index daf2e1851b3d75..4edb671753bf45 100644
--- a/clang/lib/StaticAnalyzer/Checkers/Taint.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/Taint.cpp
@@ -259,21 +259,19 @@ std::vector<SymbolRef> taint::getTaintedSymbolsImpl(ProgramStateRef State,
     return TaintedSymbols;
 
   // Traverse all the symbols this symbol depends on to see if any are tainted.
-  for (SymExpr::symbol_iterator SI = Sym->symbol_begin(),
-                                SE = Sym->symbol_end();
-       SI != SE; ++SI) {
-    if (!isa<SymbolData>(*SI))
+  for (SymbolRef SubSym : Sym->symbols()) {
+    if (!isa<SymbolData>(SubSym))
       continue;
 
-    if (const TaintTagType *Tag = State->get<TaintMap>(*SI)) {
+    if (const TaintTagType *Tag = State->get<TaintMap>(SubSym)) {
       if (*Tag == Kind) {
-        TaintedSymbols.push_back(*SI);
+        TaintedSymbols.push_back(SubSym);
         if (returnFirstOnly)
           return TaintedSymbols; // return early if needed
       }
     }
 
-    if (const auto *SD = dyn_cast<SymbolDerived>(*SI)) {
+    if (const auto *SD = dyn_cast<SymbolDerived>(SubSym)) {
       // If this is a SymbolDerived with a tainted parent, it's also tainted.
       std::vector<SymbolRef> TaintedParents = getTaintedSymbolsImpl(
           State, SD->getParentSymbol(), Kind, returnFirstOnly);
@@ -302,7 +300,7 @@ std::vector<SymbolRef> taint::getTaintedSymbolsImpl(ProgramStateRef State,
     }
 
     // If memory region is tainted, data is also tainted.
-    if (const auto *SRV = dyn_cast<SymbolRegionValue>(*SI)) {
+    if (const auto *SRV = dyn_cast<SymbolRegionValue>(SubSym)) {
       std::vector<SymbolRef> TaintedRegions =
           getTaintedSymbolsImpl(State, SRV->getRegion(), Kind, returnFirstOnly);
       llvm::append_range(TaintedSymbols, TaintedRegions);
@@ -311,7 +309,7 @@ std::vector<SymbolRef> taint::getTaintedSymbolsImpl(ProgramStateRef State,
     }
 
     // If this is a SymbolCast from a tainted value, it's also tainted.
-    if (const auto *SC = dyn_cast<SymbolCast>(*SI)) {
+    if (const auto *SC = dyn_cast<SymbolCast>(SubSym)) {
       std::vector<SymbolRef> TaintedCasts =
           getTaintedSymbolsImpl(State, SC->getOperand(), Kind, returnFirstOnly);
       llvm::append_range(TaintedSymbols, TaintedCasts);

diff  --git a/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp
index 28fe11d5ed06e6..9d3a909f50c10c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp
@@ -188,10 +188,7 @@ void TestAfterDivZeroChecker::checkEndFunction(const ReturnStmt *,
     return;
 
   DivZeroMapTy::Factory &F = State->get_context<DivZeroMap>();
-  for (llvm::ImmutableSet<ZeroState>::iterator I = DivZeroes.begin(),
-                                               E = DivZeroes.end();
-       I != E; ++I) {
-    ZeroState ZS = *I;
+  for (const ZeroState &ZS : DivZeroes) {
     if (ZS.getStackFrameContext() == C.getStackFrame())
       DivZeroes = F.remove(DivZeroes, ZS);
   }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp
index 5cc7131725274c..e2f8bd541c9670 100644
--- a/clang/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp
@@ -69,8 +69,7 @@ class TrustNonnullChecker : public Checker<check::PostCall,
     if (!CondS || CondS->computeComplexity() > ComplexityThreshold)
       return State;
 
-    for (auto B=CondS->symbol_begin(), E=CondS->symbol_end(); B != E; ++B) {
-      const SymbolRef Antecedent = *B;
+    for (SymbolRef Antecedent : CondS->symbols()) {
       State = addImplication(Antecedent, State, true);
       State = addImplication(Antecedent, State, false);
     }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
index 27f3345e67ac8e..2973dd5457c620 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
@@ -57,13 +57,10 @@ UndefCapturedBlockVarChecker::checkPostStmt(const BlockExpr *BE,
   ProgramStateRef state = C.getState();
   auto *R = cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
 
-  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
-                                            E = R->referenced_vars_end();
-
-  for (; I != E; ++I) {
+  for (auto Var : R->referenced_vars()) {
     // This VarRegion is the region associated with the block; we need
     // the one associated with the encompassing context.
-    const VarRegion *VR = I.getCapturedRegion();
+    const VarRegion *VR = Var.getCapturedRegion();
     const VarDecl *VD = VR->getDecl();
 
     if (VD->hasAttr<BlocksAttr>() || !VD->hasLocalStorage())
@@ -71,7 +68,7 @@ UndefCapturedBlockVarChecker::checkPostStmt(const BlockExpr *BE,
 
     // Get the VarRegion associated with VD in the local stack frame.
     if (std::optional<UndefinedVal> V =
-            state->getSVal(I.getOriginalRegion()).getAs<UndefinedVal>()) {
+            state->getSVal(Var.getOriginalRegion()).getAs<UndefinedVal>()) {
       if (ExplodedNode *N = C.generateErrorNode()) {
         if (!BT)
           BT.reset(

diff  --git a/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp
index 3ad6858ead46ae..d24a124f5ffee0 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp
@@ -59,9 +59,8 @@ void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
   const ParentMap *PM = nullptr;
   const LocationContext *LC = nullptr;
   // Iterate over ExplodedGraph
-  for (ExplodedGraph::node_iterator I = G.nodes_begin(), E = G.nodes_end();
-      I != E; ++I) {
-    const ProgramPoint &P = I->getLocation();
+  for (const ExplodedNode &N : G.nodes()) {
+    const ProgramPoint &P = N.getLocation();
     LC = P.getLocationContext();
     if (!LC->inTopFrame())
       continue;
@@ -93,8 +92,7 @@ void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
       return;
 
   // Find CFGBlocks that were not covered by any node
-  for (CFG::const_iterator I = C->begin(), E = C->end(); I != E; ++I) {
-    const CFGBlock *CB = *I;
+  for (const CFGBlock *CB : *C) {
     // Check if the block is unreachable
     if (reachable.count(CB->getBlockID()))
       continue;
@@ -181,34 +179,30 @@ void UnreachableCodeChecker::FindUnreachableEntryPoints(const CFGBlock *CB,
                                                         CFGBlocksSet &visited) {
   visited.insert(CB->getBlockID());
 
-  for (CFGBlock::const_pred_iterator I = CB->pred_begin(), E = CB->pred_end();
-      I != E; ++I) {
-    if (!*I)
+  for (const CFGBlock *PredBlock : CB->preds()) {
+    if (!PredBlock)
       continue;
 
-    if (!reachable.count((*I)->getBlockID())) {
+    if (!reachable.count(PredBlock->getBlockID())) {
       // If we find an unreachable predecessor, mark this block as reachable so
       // we don't report this block
       reachable.insert(CB->getBlockID());
-      if (!visited.count((*I)->getBlockID()))
+      if (!visited.count(PredBlock->getBlockID()))
         // If we haven't previously visited the unreachable predecessor, recurse
-        FindUnreachableEntryPoints(*I, reachable, visited);
+        FindUnreachableEntryPoints(PredBlock, reachable, visited);
     }
   }
 }
 
 // Find the Stmt* in a CFGBlock for reporting a warning
 const Stmt *UnreachableCodeChecker::getUnreachableStmt(const CFGBlock *CB) {
-  for (CFGBlock::const_iterator I = CB->begin(), E = CB->end(); I != E; ++I) {
-    if (std::optional<CFGStmt> S = I->getAs<CFGStmt>()) {
+  for (const CFGElement &Elem : *CB) {
+    if (std::optional<CFGStmt> S = Elem.getAs<CFGStmt>()) {
       if (!isa<DeclStmt>(S->getStmt()))
         return S->getStmt();
     }
   }
-  if (const Stmt *S = CB->getTerminatorStmt())
-    return S;
-  else
-    return nullptr;
+  return CB->getTerminatorStmt();
 }
 
 // Determines if the path to this CFGBlock contained an element that infers this

diff  --git a/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp b/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
index ecfc7106560e89..f9750db7b50170 100644
--- a/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
@@ -50,17 +50,14 @@ AnalysisManager::AnalysisManager(ASTContext &ASTCtx, Preprocessor &PP,
 
 AnalysisManager::~AnalysisManager() {
   FlushDiagnostics();
-  for (PathDiagnosticConsumers::iterator I = PathConsumers.begin(),
-       E = PathConsumers.end(); I != E; ++I) {
-    delete *I;
+  for (PathDiagnosticConsumer *Consumer : PathConsumers) {
+    delete Consumer;
   }
 }
 
 void AnalysisManager::FlushDiagnostics() {
   PathDiagnosticConsumer::FilesMade filesMade;
-  for (PathDiagnosticConsumers::iterator I = PathConsumers.begin(),
-       E = PathConsumers.end();
-       I != E; ++I) {
-    (*I)->FlushDiagnostics(&filesMade);
+  for (PathDiagnosticConsumer *Consumer : PathConsumers) {
+    Consumer->FlushDiagnostics(&filesMade);
   }
 }

diff  --git a/clang/lib/StaticAnalyzer/Core/BugReporter.cpp b/clang/lib/StaticAnalyzer/Core/BugReporter.cpp
index 5b79e5d486286c..dc9820b61f1f62 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporter.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporter.cpp
@@ -296,26 +296,24 @@ std::string StackHintGeneratorForSymbol::getMessage(const ExplodedNode *N){
     return {};
 
   // Check if one of the parameters are set to the interesting symbol.
-  unsigned ArgIndex = 0;
-  for (CallExpr::const_arg_iterator I = CE->arg_begin(),
-                                    E = CE->arg_end(); I != E; ++I, ++ArgIndex){
-    SVal SV = N->getSVal(*I);
+  for (auto [Idx, ArgExpr] : llvm::enumerate(CE->arguments())) {
+    SVal SV = N->getSVal(ArgExpr);
 
     // Check if the variable corresponding to the symbol is passed by value.
     SymbolRef AS = SV.getAsLocSymbol();
     if (AS == Sym) {
-      return getMessageForArg(*I, ArgIndex);
+      return getMessageForArg(ArgExpr, Idx);
     }
 
     // Check if the parameter is a pointer to the symbol.
     if (std::optional<loc::MemRegionVal> Reg = SV.getAs<loc::MemRegionVal>()) {
       // Do not attempt to dereference void*.
-      if ((*I)->getType()->isVoidPointerType())
+      if (ArgExpr->getType()->isVoidPointerType())
         continue;
       SVal PSV = N->getState()->getSVal(Reg->getRegion());
       SymbolRef AS = PSV.getAsLocSymbol();
       if (AS == Sym) {
-        return getMessageForArg(*I, ArgIndex);
+        return getMessageForArg(ArgExpr, Idx);
       }
     }
   }

diff  --git a/clang/lib/StaticAnalyzer/Core/Environment.cpp b/clang/lib/StaticAnalyzer/Core/Environment.cpp
index 3d017b81762aa8..0102f743c9110d 100644
--- a/clang/lib/StaticAnalyzer/Core/Environment.cpp
+++ b/clang/lib/StaticAnalyzer/Core/Environment.cpp
@@ -17,9 +17,9 @@
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtObjC.h"
 #include "clang/Analysis/AnalysisDeclContext.h"
+#include "clang/Basic/JsonSupport.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/LangOptions.h"
-#include "clang/Basic/JsonSupport.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"

diff  --git a/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp b/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
index e1f26a50cbc5e4..f84da769d182f8 100644
--- a/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
@@ -508,9 +508,8 @@ ExplodedGraph::trim(ArrayRef<const NodeTy *> Sinks,
 
     // Walk through the predecessors of 'N' and hook up their corresponding
     // nodes in the new graph (if any) to the freshly created node.
-    for (ExplodedNode::pred_iterator I = N->Preds.begin(), E = N->Preds.end();
-         I != E; ++I) {
-      Pass2Ty::iterator PI = Pass2.find(*I);
+    for (const ExplodedNode *Pred : N->Preds) {
+      Pass2Ty::iterator PI = Pass2.find(Pred);
       if (PI == Pass2.end())
         continue;
 
@@ -521,17 +520,16 @@ ExplodedGraph::trim(ArrayRef<const NodeTy *> Sinks,
     // been created, we should hook them up as successors.  Otherwise, enqueue
     // the new nodes from the original graph that should have nodes created
     // in the new graph.
-    for (ExplodedNode::succ_iterator I = N->Succs.begin(), E = N->Succs.end();
-         I != E; ++I) {
-      Pass2Ty::iterator PI = Pass2.find(*I);
+    for (const ExplodedNode *Succ : N->Succs) {
+      Pass2Ty::iterator PI = Pass2.find(Succ);
       if (PI != Pass2.end()) {
         const_cast<ExplodedNode *>(PI->second)->addPredecessor(NewN, *G);
         continue;
       }
 
       // Enqueue nodes to the worklist that were marked during pass 1.
-      if (Pass1.count(*I))
-        WL2.push_back(*I);
+      if (Pass1.count(Succ))
+        WL2.push_back(Succ);
     }
   }
 

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 03dcdfe031f6d7..144f034a9dfeff 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -65,6 +65,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/ImmutableMap.h"
 #include "llvm/ADT/ImmutableSet.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Support/Casting.h"
@@ -2640,9 +2641,7 @@ static const Stmt *ResolveCondition(const Stmt *Condition,
   // The invariants are still shifting, but it is possible that the
   // last element in a CFGBlock is not a CFGStmt.  Look for the last
   // CFGStmt as the value of the condition.
-  CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
-  for (; I != E; ++I) {
-    CFGElement Elem = *I;
+  for (CFGElement Elem : llvm::reverse(*B)) {
     std::optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
     if (!CS)
       continue;
@@ -2850,9 +2849,9 @@ void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
   if (std::optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
     const LabelDecl *L = LV->getLabel();
 
-    for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
-      if (I.getLabel() == L) {
-        builder.generateNode(I, state);
+    for (iterator Succ : builder) {
+      if (Succ.getLabel() == L) {
+        builder.generateNode(Succ, state);
         return;
       }
     }
@@ -2871,8 +2870,8 @@ void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
   // This is really a catch-all.  We don't support symbolics yet.
   // FIXME: Implement dispatch for symbolic pointers.
 
-  for (iterator I = builder.begin(), E = builder.end(); I != E; ++I)
-    builder.generateNode(I, state);
+  for (iterator Succ : builder)
+    builder.generateNode(Succ, state);
 }
 
 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
@@ -3805,12 +3804,9 @@ struct DOTGraphTraits<ExplodedGraph*> : public DefaultDOTGraphTraits {
     BugReporter &BR = static_cast<ExprEngine &>(
       N->getState()->getStateManager().getOwningEngine()).getBugReporter();
 
-    const auto EQClasses =
-        llvm::make_range(BR.EQClasses_begin(), BR.EQClasses_end());
-
-    for (const auto &EQ : EQClasses) {
-      for (const auto &I : EQ.getReports()) {
-        const auto *PR = dyn_cast<PathSensitiveBugReport>(I.get());
+    for (const auto &Class : BR.equivalenceClasses()) {
+      for (const auto &Report : Class.getReports()) {
+        const auto *PR = dyn_cast<PathSensitiveBugReport>(Report.get());
         if (!PR)
           continue;
         const ExplodedNode *EN = PR->getErrorNode();
@@ -3908,10 +3904,9 @@ std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) {
     std::vector<const ExplodedNode *> Src;
 
     // Iterate through the reports and get their nodes.
-    for (BugReporter::EQClasses_iterator
-           EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
+    for (const auto &Class : BR.equivalenceClasses()) {
       const auto *R =
-          dyn_cast<PathSensitiveBugReport>(EI->getReports()[0].get());
+          dyn_cast<PathSensitiveBugReport>(Class.getReports()[0].get());
       if (!R)
         continue;
       const auto *N = const_cast<ExplodedNode *>(R->getErrorNode());

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
index 6652c065e04f40..2a47116db55a1a 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -10,8 +10,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "clang/AST/ExprCXX.h"
 #include "clang/AST/DeclCXX.h"
+#include "clang/AST/ExprCXX.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
 #include <optional>
@@ -133,11 +133,9 @@ void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
     SVal location = LeftV;
     evalLoad(Tmp, B, LHS, *it, state, location);
 
-    for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
-         ++I) {
-
-      state = (*I)->getState();
-      const LocationContext *LCtx = (*I)->getLocationContext();
+    for (ExplodedNode *N : Tmp) {
+      state = N->getState();
+      const LocationContext *LCtx = N->getLocationContext();
       SVal V = state->getSVal(LHS, LCtx);
 
       // Get the computation type.
@@ -171,8 +169,7 @@ void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
                                               currBldrCtx->blockCount());
         // However, we need to convert the symbol to the computation type.
         Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
-      }
-      else {
+      } else {
         // The left-hand side may bind to a 
diff erent value then the
         // computation type.
         LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
@@ -185,7 +182,7 @@ void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
       else
         state = state->BindExpr(B, LCtx, Result);
 
-      evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
+      evalStore(Tmp2, B, LHS, N, state, location, LHSVal);
     }
   }
 
@@ -211,14 +208,12 @@ void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
   if (const BlockDataRegion *BDR =
       dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
 
-    BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
-                                              E = BDR->referenced_vars_end();
-
+    auto ReferencedVars = BDR->referenced_vars();
     auto CI = BD->capture_begin();
     auto CE = BD->capture_end();
-    for (; I != E; ++I) {
-      const VarRegion *capturedR = I.getCapturedRegion();
-      const TypedValueRegion *originalR = I.getOriginalRegion();
+    for (auto Var : ReferencedVars) {
+      const VarRegion *capturedR = Var.getCapturedRegion();
+      const TypedValueRegion *originalR = Var.getOriginalRegion();
 
       // If the capture had a copy expression, use the result of evaluating
       // that expression, otherwise use the original value.
@@ -291,9 +286,7 @@ void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
 
   if (CastE->getCastKind() == CK_LValueToRValue ||
       CastE->getCastKind() == CK_LValueToRValueBitCast) {
-    for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
-         I!=E; ++I) {
-      ExplodedNode *subExprNode = *I;
+    for (ExplodedNode *subExprNode : dstPreStmt) {
       ProgramStateRef state = subExprNode->getState();
       const LocationContext *LCtx = subExprNode->getLocationContext();
       evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
@@ -309,10 +302,7 @@ void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
     T = ExCast->getTypeAsWritten();
 
   StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
-  for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
-       I != E; ++I) {
-
-    Pred = *I;
+  for (ExplodedNode *Pred : dstPreStmt) {
     ProgramStateRef state = Pred->getState();
     const LocationContext *LCtx = Pred->getLocationContext();
 
@@ -883,8 +873,7 @@ VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
 
   QualType T = Ex->getTypeOfArgument();
 
-  for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
-       I != E; ++I) {
+  for (ExplodedNode *N : CheckedSet) {
     if (Ex->getKind() == UETT_SizeOf) {
       if (!T->isIncompleteType() && !T->isConstantSizeType()) {
         assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
@@ -903,18 +892,17 @@ VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
     APSInt Value = Ex->EvaluateKnownConstInt(getContext());
     CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
 
-    ProgramStateRef state = (*I)->getState();
-    state = state->BindExpr(Ex, (*I)->getLocationContext(),
-                            svalBuilder.makeIntVal(amt.getQuantity(),
-                                                   Ex->getType()));
-    Bldr.generateNode(Ex, *I, state);
+    ProgramStateRef state = N->getState();
+    state = state->BindExpr(
+        Ex, N->getLocationContext(),
+        svalBuilder.makeIntVal(amt.getQuantity(), Ex->getType()));
+    Bldr.generateNode(Ex, N, state);
   }
 
   getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
 }
 
-void ExprEngine::handleUOExtension(ExplodedNodeSet::iterator I,
-                                   const UnaryOperator *U,
+void ExprEngine::handleUOExtension(ExplodedNode *N, const UnaryOperator *U,
                                    StmtNodeBuilder &Bldr) {
   // FIXME: We can probably just have some magic in Environment::getSVal()
   // that propagates values, instead of creating a new node here.
@@ -924,10 +912,9 @@ void ExprEngine::handleUOExtension(ExplodedNodeSet::iterator I,
   // generate an extra node that just propagates the value of the
   // subexpression.
   const Expr *Ex = U->getSubExpr()->IgnoreParens();
-  ProgramStateRef state = (*I)->getState();
-  const LocationContext *LCtx = (*I)->getLocationContext();
-  Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
-                                           state->getSVal(Ex, LCtx)));
+  ProgramStateRef state = N->getState();
+  const LocationContext *LCtx = N->getLocationContext();
+  Bldr.generateNode(U, N, state->BindExpr(U, LCtx, state->getSVal(Ex, LCtx)));
 }
 
 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
@@ -939,13 +926,12 @@ void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
   ExplodedNodeSet EvalSet;
   StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
 
-  for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
-       I != E; ++I) {
+  for (ExplodedNode *N : CheckedSet) {
     switch (U->getOpcode()) {
     default: {
-      Bldr.takeNodes(*I);
+      Bldr.takeNodes(N);
       ExplodedNodeSet Tmp;
-      VisitIncrementDecrementOperator(U, *I, Tmp);
+      VisitIncrementDecrementOperator(U, N, Tmp);
       Bldr.addNodes(Tmp);
       break;
     }
@@ -960,10 +946,10 @@ void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
 
       // For all other types, UO_Real is an identity operation.
       assert (U->getType() == Ex->getType());
-      ProgramStateRef state = (*I)->getState();
-      const LocationContext *LCtx = (*I)->getLocationContext();
-      Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
-                                               state->getSVal(Ex, LCtx)));
+      ProgramStateRef state = N->getState();
+      const LocationContext *LCtx = N->getLocationContext();
+      Bldr.generateNode(U, N,
+                        state->BindExpr(U, LCtx, state->getSVal(Ex, LCtx)));
       break;
     }
 
@@ -975,10 +961,10 @@ void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
         break;
       }
       // For all other types, UO_Imag returns 0.
-      ProgramStateRef state = (*I)->getState();
-      const LocationContext *LCtx = (*I)->getLocationContext();
+      ProgramStateRef state = N->getState();
+      const LocationContext *LCtx = N->getLocationContext();
       SVal X = svalBuilder.makeZeroVal(Ex->getType());
-      Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
+      Bldr.generateNode(U, N, state->BindExpr(U, LCtx, X));
       break;
     }
 
@@ -989,15 +975,15 @@ void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
         const ValueDecl *VD = DRE->getDecl();
 
         if (isa<CXXMethodDecl, FieldDecl, IndirectFieldDecl>(VD)) {
-          ProgramStateRef State = (*I)->getState();
-          const LocationContext *LCtx = (*I)->getLocationContext();
+          ProgramStateRef State = N->getState();
+          const LocationContext *LCtx = N->getLocationContext();
           SVal SV = svalBuilder.getMemberPointer(cast<NamedDecl>(VD));
-          Bldr.generateNode(U, *I, State->BindExpr(U, LCtx, SV));
+          Bldr.generateNode(U, N, State->BindExpr(U, LCtx, SV));
           break;
         }
       }
       // Explicitly proceed with default handler for this case cascade.
-      handleUOExtension(I, U, Bldr);
+      handleUOExtension(N, U, Bldr);
       break;
     }
     case UO_Plus:
@@ -1005,7 +991,7 @@ void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
       [[fallthrough]];
     case UO_Deref:
     case UO_Extension: {
-      handleUOExtension(I, U, Bldr);
+      handleUOExtension(N, U, Bldr);
       break;
     }
 
@@ -1014,14 +1000,14 @@ void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
     case UO_Not: {
       assert (!U->isGLValue());
       const Expr *Ex = U->getSubExpr()->IgnoreParens();
-      ProgramStateRef state = (*I)->getState();
-      const LocationContext *LCtx = (*I)->getLocationContext();
+      ProgramStateRef state = N->getState();
+      const LocationContext *LCtx = N->getLocationContext();
 
       // Get the value of the subexpression.
       SVal V = state->getSVal(Ex, LCtx);
 
       if (V.isUnknownOrUndef()) {
-        Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
+        Bldr.generateNode(U, N, state->BindExpr(U, LCtx, V));
         break;
       }
 
@@ -1058,7 +1044,7 @@ void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
           state = state->BindExpr(U, LCtx, Result);
           break;
       }
-      Bldr.generateNode(U, *I, state);
+      Bldr.generateNode(U, N, state);
       break;
     }
     }
@@ -1084,10 +1070,9 @@ void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
 
   ExplodedNodeSet Dst2;
   StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
-  for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
-
-    state = (*I)->getState();
-    assert(LCtx == (*I)->getLocationContext());
+  for (ExplodedNode *N : Tmp) {
+    state = N->getState();
+    assert(LCtx == N->getLocationContext());
     SVal V2_untested = state->getSVal(Ex, LCtx);
 
     // Propagate unknown and undefined values.
@@ -1095,9 +1080,9 @@ void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
       state = state->BindExpr(U, LCtx, V2_untested);
 
       // Perform the store, so that the uninitialized value detection happens.
-      Bldr.takeNodes(*I);
+      Bldr.takeNodes(N);
       ExplodedNodeSet Dst3;
-      evalStore(Dst3, U, Ex, *I, state, loc, V2_untested);
+      evalStore(Dst3, U, Ex, N, state, loc, V2_untested);
       Bldr.addNodes(Dst3);
 
       continue;
@@ -1163,9 +1148,9 @@ void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
       state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
 
     // Perform the store.
-    Bldr.takeNodes(*I);
+    Bldr.takeNodes(N);
     ExplodedNodeSet Dst3;
-    evalStore(Dst3, U, Ex, *I, state, loc, Result);
+    evalStore(Dst3, U, Ex, N, state, loc, Result);
     Bldr.addNodes(Dst3);
   }
   Dst.insert(Dst2);

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
index bcedd856268967..d1894d4447a2e9 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -20,6 +20,8 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/Sequence.h"
 #include <optional>
 
 using namespace clang;
@@ -85,14 +87,13 @@ void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
   evalBind(Dst, CallExpr, Pred, ThisVal, V, true);
 
   PostStmt PS(CallExpr, LCtx);
-  for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
-       I != E; ++I) {
-    ProgramStateRef State = (*I)->getState();
+  for (ExplodedNode *N : Dst) {
+    ProgramStateRef State = N->getState();
     if (AlwaysReturnsLValue)
       State = State->BindExpr(CallExpr, LCtx, ThisVal);
     else
       State = bindReturnValue(Call, LCtx, State);
-    Bldr.generateNode(PS, State, *I);
+    Bldr.generateNode(PS, State, N);
   }
 }
 
@@ -744,10 +745,8 @@ void ExprEngine::handleConstructor(const Expr *E,
   if (CE) {
     // FIXME: Is it possible and/or useful to do this before PreStmt?
     StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx);
-    for (ExplodedNodeSet::iterator I = DstPreVisit.begin(),
-                                   E = DstPreVisit.end();
-         I != E; ++I) {
-      ProgramStateRef State = (*I)->getState();
+    for (ExplodedNode *N : DstPreVisit) {
+      ProgramStateRef State = N->getState();
       if (CE->requiresZeroInitialization()) {
         // FIXME: Once we properly handle constructors in new-expressions, we'll
         // need to invalidate the region before setting a default value, to make
@@ -764,7 +763,7 @@ void ExprEngine::handleConstructor(const Expr *E,
         State = State->bindDefaultZero(Target, LCtx);
       }
 
-      Bldr.generateNode(CE, *I, State, /*tag=*/nullptr,
+      Bldr.generateNode(CE, N, State, /*tag=*/nullptr,
                         ProgramPoint::PreStmtKind);
     }
   } else {
@@ -782,14 +781,12 @@ void ExprEngine::handleConstructor(const Expr *E,
       !CallOpts.IsArrayCtorOrDtor) {
     StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
     // FIXME: Handle other kinds of trivial constructors as well.
-    for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
-         I != E; ++I)
-      performTrivialCopy(Bldr, *I, *Call);
+    for (ExplodedNode *N : DstPreCall)
+      performTrivialCopy(Bldr, N, *Call);
 
   } else {
-    for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
-         I != E; ++I)
-      getCheckerManager().runCheckersForEvalCall(DstEvaluated, *I, *Call, *this,
+    for (ExplodedNode *N : DstPreCall)
+      getCheckerManager().runCheckersForEvalCall(DstEvaluated, N, *Call, *this,
                                                  CallOpts);
   }
 
@@ -916,9 +913,8 @@ void ExprEngine::VisitCXXDestructor(QualType ObjectType,
 
   ExplodedNodeSet DstInvalidated;
   StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
-  for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
-       I != E; ++I)
-    defaultEvalCall(Bldr, *I, *Call, CallOpts);
+  for (ExplodedNode *N : DstPreCall)
+    defaultEvalCall(Bldr, N, *Call, CallOpts);
 
   getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
                                              *Call, *this);
@@ -1197,18 +1193,13 @@ void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
 
   // If we created a new MemRegion for the lambda, we should explicitly bind
   // the captures.
-  unsigned Idx = 0;
-  CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin();
-  for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(),
-                                               e = LE->capture_init_end();
-       i != e; ++i, ++CurField, ++Idx) {
-    FieldDecl *FieldForCapture = *CurField;
+  for (auto const [Idx, FieldForCapture, InitExpr] :
+       llvm::zip(llvm::seq<unsigned>(0, -1), LE->getLambdaClass()->fields(),
+                 LE->capture_inits())) {
     SVal FieldLoc = State->getLValue(FieldForCapture, V);
 
     SVal InitVal;
     if (!FieldForCapture->hasCapturedVLAType()) {
-      const Expr *InitExpr = *i;
-
       assert(InitExpr && "Capture missing initialization expression");
 
       // Capturing a 0 length array is a no-op, so we ignore it to get a more

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
index ac8b5003df1952..b987ce27893652 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
@@ -374,17 +374,15 @@ void ExprEngine::processCallExit(ExplodedNode *CEBNode) {
     CleanedNodes.Add(CEBNode);
   }
 
-  for (ExplodedNodeSet::iterator I = CleanedNodes.begin(),
-                                 E = CleanedNodes.end(); I != E; ++I) {
-
+  for (ExplodedNode *N : CleanedNodes) {
     // Step 4: Generate the CallExit and leave the callee's context.
     // CleanedNodes -> CEENode
     CallExitEnd Loc(calleeCtx, callerCtx);
     bool isNew;
-    ProgramStateRef CEEState = (*I == CEBNode) ? state : (*I)->getState();
+    ProgramStateRef CEEState = (N == CEBNode) ? state : N->getState();
 
     ExplodedNode *CEENode = G.getNode(Loc, CEEState, false, &isNew);
-    CEENode->addPredecessor(*I, G);
+    CEENode->addPredecessor(N, G);
     if (!isNew)
       return;
 
@@ -616,9 +614,8 @@ void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
   // Evaluate the function call.  We try each of the checkers
   // to see if the can evaluate the function call.
   ExplodedNodeSet dstCallEvaluated;
-  for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
-       I != E; ++I) {
-    evalCall(dstCallEvaluated, *I, *CallTemplate);
+  for (ExplodedNode *N : dstPreVisit) {
+    evalCall(dstCallEvaluated, N, *CallTemplate);
   }
 
   // Finally, perform the post-condition check of the CallExpr and store

diff  --git a/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp b/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
index b4578385a14790..0fe0c93dc01653 100644
--- a/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
+++ b/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
@@ -602,9 +602,9 @@ void HTMLDiagnostics::FinalizeHTML(const PathDiagnostic& D, Rewriter &R,
 
     // Output any other meta data.
 
-    for (PathDiagnostic::meta_iterator I = D.meta_begin(), E = D.meta_end();
-         I != E; ++I) {
-      os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
+    for (const std::string &Metadata :
+         llvm::make_range(D.meta_begin(), D.meta_end())) {
+      os << "<tr><td></td><td>" << html::EscapeText(Metadata) << "</td></tr>\n";
     }
 
     os << R"<<<(

diff  --git a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
index 820938fe950ec4..912ba71dd57381 100644
--- a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
+++ b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
@@ -39,6 +39,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Twine.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/CheckedArithmetic.h"
@@ -491,11 +492,9 @@ void BlockCodeRegion::dumpToStream(raw_ostream &os) const {
 void BlockDataRegion::dumpToStream(raw_ostream &os) const {
   os << "block_data{" << BC;
   os << "; ";
-  for (BlockDataRegion::referenced_vars_iterator
-         I = referenced_vars_begin(),
-         E = referenced_vars_end(); I != E; ++I)
-    os << "(" << I.getCapturedRegion() << "<-" <<
-                 I.getOriginalRegion() << ") ";
+  for (auto Var : referenced_vars())
+    os << "(" << Var.getCapturedRegion() << "<-" << Var.getOriginalRegion()
+       << ") ";
   os << '}';
 }
 
@@ -970,13 +969,11 @@ getStackOrCaptureRegionForDeclContext(const LocationContext *LC,
     if (const auto *BC = dyn_cast<BlockInvocationContext>(LC)) {
       const auto *BR = static_cast<const BlockDataRegion *>(BC->getData());
       // FIXME: This can be made more efficient.
-      for (BlockDataRegion::referenced_vars_iterator
-           I = BR->referenced_vars_begin(),
-           E = BR->referenced_vars_end(); I != E; ++I) {
-        const TypedValueRegion *OrigR = I.getOriginalRegion();
+      for (auto Var : BR->referenced_vars()) {
+        const TypedValueRegion *OrigR = Var.getOriginalRegion();
         if (const auto *VR = dyn_cast<VarRegion>(OrigR)) {
           if (VR->getDecl() == VD)
-            return cast<VarRegion>(I.getCapturedRegion());
+            return cast<VarRegion>(Var.getCapturedRegion());
         }
       }
     }
@@ -1745,10 +1742,13 @@ BlockDataRegion::referenced_vars_end() const {
                                                    VecOriginal->end());
 }
 
+llvm::iterator_range<BlockDataRegion::referenced_vars_iterator>
+BlockDataRegion::referenced_vars() const {
+  return llvm::make_range(referenced_vars_begin(), referenced_vars_end());
+}
+
 const VarRegion *BlockDataRegion::getOriginalRegion(const VarRegion *R) const {
-  for (referenced_vars_iterator I = referenced_vars_begin(),
-                                E = referenced_vars_end();
-       I != E; ++I) {
+  for (const auto &I : referenced_vars()) {
     if (I.getCapturedRegion() == R)
       return I.getOriginalRegion();
   }

diff  --git a/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp b/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
index a3b08d4581a556..bdf485364cef30 100644
--- a/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
+++ b/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
@@ -367,10 +367,8 @@ void PlistPrinter::ReportMacroSubPieces(raw_ostream &o,
                                         unsigned indent, unsigned depth) {
   MacroPieces.push_back(&P);
 
-  for (PathPieces::const_iterator I = P.subPieces.begin(),
-                                  E = P.subPieces.end();
-       I != E; ++I) {
-    ReportPiece(o, **I, indent, depth, /*includeControlFlow*/ false);
+  for (const auto &SubPiece : P.subPieces) {
+    ReportPiece(o, *SubPiece, indent, depth, /*includeControlFlow*/ false);
   }
 
   assert(P.getFixits().size() == 0 &&
@@ -500,12 +498,12 @@ static void printCoverage(const PathDiagnostic *D,
 
   // Mapping from file IDs to executed lines.
   const FilesToLineNumsMap &ExecutedLines = D->getExecutedLines();
-  for (auto I = ExecutedLines.begin(), E = ExecutedLines.end(); I != E; ++I) {
-    unsigned FileKey = AddFID(FM, Fids, I->first);
+  for (const auto &[FID, Lines] : ExecutedLines) {
+    unsigned FileKey = AddFID(FM, Fids, FID);
     Indent(o, IndentLevel) << "<key>" << FileKey << "</key>\n";
     Indent(o, IndentLevel) << "<array>\n";
     IndentLevel++;
-    for (unsigned LineNo : I->second) {
+    for (unsigned LineNo : Lines) {
       Indent(o, IndentLevel);
       EmitInteger(o, LineNo) << "\n";
     }
@@ -597,8 +595,8 @@ void PlistDiagnostics::printBugPath(llvm::raw_ostream &o, const FIDMap &FM,
 
   o << "   <array>\n";
 
-  for (PathPieces::const_iterator E = Path.end(); I != E; ++I)
-    Printer.ReportDiag(o, **I);
+  for (const auto &Piece : llvm::make_range(I, Path.end()))
+    Printer.ReportDiag(o, *Piece);
 
   o << "   </array>\n";
 

diff  --git a/clang/lib/StaticAnalyzer/Core/ProgramState.cpp b/clang/lib/StaticAnalyzer/Core/ProgramState.cpp
index e90ebab43c78e3..f12f1a5ac970dd 100644
--- a/clang/lib/StaticAnalyzer/Core/ProgramState.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -156,9 +156,8 @@ ProgramState::invalidateRegions(RegionList Regions,
                              const CallEvent *Call,
                              RegionAndSymbolInvalidationTraits *ITraits) const {
   SmallVector<SVal, 8> Values;
-  for (RegionList::const_iterator I = Regions.begin(),
-                                  End = Regions.end(); I != End; ++I)
-    Values.push_back(loc::MemRegionVal(*I));
+  for (const MemRegion *Reg : Regions)
+    Values.push_back(loc::MemRegionVal(Reg));
 
   return invalidateRegionsImpl(Values, E, Count, LCtx, CausedByPointerEscape,
                                IS, ITraits, Call);
@@ -556,22 +555,20 @@ bool ScanReachableSymbols::scan(nonloc::LazyCompoundVal val) {
 }
 
 bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
-  for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
-    if (!scan(*I))
+  for (SVal V : val)
+    if (!scan(V))
       return false;
 
   return true;
 }
 
 bool ScanReachableSymbols::scan(const SymExpr *sym) {
-  for (SymExpr::symbol_iterator SI = sym->symbol_begin(),
-                                SE = sym->symbol_end();
-       SI != SE; ++SI) {
-    bool wasVisited = !visited.insert(*SI).second;
+  for (SymbolRef SubSym : sym->symbols()) {
+    bool wasVisited = !visited.insert(SubSym).second;
     if (wasVisited)
       continue;
 
-    if (!visitor.VisitSymbol(*SI))
+    if (!visitor.VisitSymbol(SubSym))
       return false;
   }
 
@@ -630,10 +627,8 @@ bool ScanReachableSymbols::scan(const MemRegion *R) {
 
   // Regions captured by a block are also implicitly reachable.
   if (const BlockDataRegion *BDR = dyn_cast<BlockDataRegion>(R)) {
-    BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
-                                              E = BDR->referenced_vars_end();
-    for ( ; I != E; ++I) {
-      if (!scan(I.getCapturedRegion()))
+    for (auto Var : BDR->referenced_vars()) {
+      if (!scan(Var.getCapturedRegion()))
         return false;
     }
   }

diff  --git a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
index 49855305cecc08..c773cef30d5ec3 100644
--- a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -28,6 +28,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "llvm/ADT/ImmutableMap.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/raw_ostream.h"
 #include <optional>
 #include <utility>
@@ -231,7 +232,7 @@ class RegionBindingsRef : public llvm::ImmutableMapRef<const MemRegion *,
 
   void printJson(raw_ostream &Out, const char *NL = "\n",
                  unsigned int Space = 0, bool IsDot = false) const {
-    for (iterator I = begin(); I != end(); ++I) {
+    for (iterator I = begin(), E = end(); I != E; ++I) {
       // TODO: We might need a .printJson for I.getKey() as well.
       Indent(Out, Space, IsDot)
           << "{ \"cluster\": \"" << I.getKey() << "\", \"pointer\": \""
@@ -239,18 +240,19 @@ class RegionBindingsRef : public llvm::ImmutableMapRef<const MemRegion *,
 
       ++Space;
       const ClusterBindings &CB = I.getData();
-      for (ClusterBindings::iterator CI = CB.begin(); CI != CB.end(); ++CI) {
+      for (ClusterBindings::iterator CI = CB.begin(), CE = CB.end(); CI != CE;
+           ++CI) {
         Indent(Out, Space, IsDot) << "{ " << CI.getKey() << ", \"value\": ";
         CI.getData().printJson(Out, /*AddQuotes=*/true);
         Out << " }";
-        if (std::next(CI) != CB.end())
+        if (std::next(CI) != CE)
           Out << ',';
         Out << NL;
       }
 
       --Space;
       Indent(Out, Space, IsDot) << "]}";
-      if (std::next(I) != end())
+      if (std::next(I) != E)
         Out << ',';
       Out << NL;
     }
@@ -644,16 +646,13 @@ class RegionStoreManager : public StoreManager {
 
   void iterBindings(Store store, BindingsHandler& f) override {
     RegionBindingsRef B = getRegionBindings(store);
-    for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) {
-      const ClusterBindings &Cluster = I.getData();
-      for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
-           CI != CE; ++CI) {
-        const BindingKey &K = CI.getKey();
-        if (!K.isDirect())
+    for (const auto &[Region, Cluster] : B) {
+      for (const auto &[Key, Value] : Cluster) {
+        if (!Key.isDirect())
           continue;
-        if (const SubRegion *R = dyn_cast<SubRegion>(K.getRegion())) {
+        if (const SubRegion *R = dyn_cast<SubRegion>(Key.getRegion())) {
           // FIXME: Possibly incorporate the offset?
-          if (!f.HandleBinding(*this, store, R, CI.getData()))
+          if (!f.HandleBinding(*this, store, R, Value))
             return;
         }
       }
@@ -874,9 +873,8 @@ collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
       Length = FR->getDecl()->getBitWidthValue(SVB.getContext());
   }
 
-  for (ClusterBindings::iterator I = Cluster.begin(), E = Cluster.end();
-       I != E; ++I) {
-    BindingKey NextKey = I.getKey();
+  for (const auto &StoreEntry : Cluster) {
+    BindingKey NextKey = StoreEntry.first;
     if (NextKey.getRegion() == TopKey.getRegion()) {
       // FIXME: This doesn't catch the case where we're really invalidating a
       // region with a symbolic offset. Example:
@@ -887,7 +885,7 @@ collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
           NextKey.getOffset() - TopKey.getOffset() < Length) {
         // Case 1: The next binding is inside the region we're invalidating.
         // Include it.
-        Bindings.push_back(*I);
+        Bindings.push_back(StoreEntry);
 
       } else if (NextKey.getOffset() == TopKey.getOffset()) {
         // Case 2: The next binding is at the same offset as the region we're
@@ -897,7 +895,7 @@ collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
         // FIXME: This is probably incorrect; consider invalidating an outer
         // struct whose first field is bound to a LazyCompoundVal.
         if (IncludeAllDefaultBindings || NextKey.isDirect())
-          Bindings.push_back(*I);
+          Bindings.push_back(StoreEntry);
       }
 
     } else if (NextKey.hasSymbolicOffset()) {
@@ -908,13 +906,13 @@ collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
         // we'll be conservative and include it.
         if (IncludeAllDefaultBindings || NextKey.isDirect())
           if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
-            Bindings.push_back(*I);
+            Bindings.push_back(StoreEntry);
       } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) {
         // Case 4: The next key is symbolic, but we changed a known
         // super-region. In this case the binding is certainly included.
         if (BaseSR->isSubRegionOf(Top))
           if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
-            Bindings.push_back(*I);
+            Bindings.push_back(StoreEntry);
       }
     }
   }
@@ -956,10 +954,8 @@ RegionStoreManager::removeSubRegionBindings(RegionBindingsConstRef B,
                            /*IncludeAllDefaultBindings=*/false);
 
   ClusterBindingsRef Result(*Cluster, CBFactory);
-  for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
-                                                    E = Bindings.end();
-       I != E; ++I)
-    Result = Result.remove(I->first);
+  for (BindingKey Key : llvm::make_first_range(Bindings))
+    Result = Result.remove(Key);
 
   // If we're invalidating a region with a symbolic offset, we need to make sure
   // we don't treat the base region as uninitialized anymore.
@@ -1056,8 +1052,8 @@ void InvalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
                        RegionAndSymbolInvalidationTraits::TK_PreserveContents);
 
   if (C) {
-    for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I)
-      VisitBinding(I.getData());
+    for (SVal Val : llvm::make_second_range(*C))
+      VisitBinding(Val);
 
     // Invalidate regions contents.
     if (!PreserveRegionsContents)
@@ -1093,10 +1089,8 @@ void InvalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
   // BlockDataRegion?  If so, invalidate captured variables that are passed
   // by reference.
   if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
-    for (BlockDataRegion::referenced_vars_iterator
-         BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ;
-         BI != BE; ++BI) {
-      const VarRegion *VR = BI.getCapturedRegion();
+    for (auto Var : BR->referenced_vars()) {
+      const VarRegion *VR = Var.getCapturedRegion();
       const VarDecl *VD = VR->getDecl();
       if (VD->hasAttr<BlocksAttr>() || !VD->hasLocalStorage()) {
         AddToWorkList(VR);
@@ -1200,9 +1194,7 @@ void InvalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
       if (!C)
         goto conjure_default;
 
-      for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E;
-           ++I) {
-        const BindingKey &BK = I.getKey();
+      for (const auto &[BK, V] : *C) {
         std::optional<uint64_t> ROffset =
             BK.hasSymbolicOffset() ? std::optional<uint64_t>() : BK.getOffset();
 
@@ -1213,10 +1205,9 @@ void InvalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
              (UpperOverflow &&
               (*ROffset >= LowerOffset || *ROffset < UpperOffset)) ||
              (LowerOffset == UpperOffset && *ROffset == LowerOffset))) {
-          B = B.removeBinding(I.getKey());
+          B = B.removeBinding(BK);
           // Bound symbolic regions need to be invalidated for dead symbol
           // detection.
-          SVal V = I.getData();
           const MemRegion *R = V.getAsRegion();
           if (isa_and_nonnull<SymbolicRegion>(R))
             VisitBinding(V);
@@ -1289,12 +1280,8 @@ RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K,
 void RegionStoreManager::populateWorkList(InvalidateRegionsWorker &W,
                                           ArrayRef<SVal> Values,
                                           InvalidatedRegions *TopLevelRegions) {
-  for (ArrayRef<SVal>::iterator I = Values.begin(),
-                                E = Values.end(); I != E; ++I) {
-    SVal V = *I;
-    if (std::optional<nonloc::LazyCompoundVal> LCS =
-            V.getAs<nonloc::LazyCompoundVal>()) {
-
+  for (SVal V : Values) {
+    if (auto LCS = V.getAs<nonloc::LazyCompoundVal>()) {
       for (SVal S : getInterestingValues(*LCS))
         if (const MemRegion *R = S.getAsRegion())
           W.AddToWorkList(R);
@@ -2281,10 +2268,7 @@ RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV) {
   SmallVector<BindingPair, 32> Bindings;
   collectSubRegionBindings(Bindings, svalBuilder, *Cluster, LazyR,
                            /*IncludeAllDefaultBindings=*/true);
-  for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
-                                                    E = Bindings.end();
-       I != E; ++I) {
-    SVal V = I->second;
+  for (SVal V : llvm::make_second_range(Bindings)) {
     if (V.isUnknownOrUndef() || V.isConstant())
       continue;
 
@@ -2609,11 +2593,11 @@ std::optional<RegionBindingsRef> RegionStoreManager::tryBindSmallStruct(
 
   RegionBindingsRef NewB = B;
 
-  for (FieldVector::iterator I = Fields.begin(), E = Fields.end(); I != E; ++I){
-    const FieldRegion *SourceFR = MRMgr.getFieldRegion(*I, LCV.getRegion());
+  for (const FieldDecl *Field : Fields) {
+    const FieldRegion *SourceFR = MRMgr.getFieldRegion(Field, LCV.getRegion());
     SVal V = getBindingForField(getRegionBindings(LCV.getStore()), SourceFR);
 
-    const FieldRegion *DestFR = MRMgr.getFieldRegion(*I, R);
+    const FieldRegion *DestFR = MRMgr.getFieldRegion(Field, R);
     NewB = bind(NewB, loc::MemRegionVal(DestFR), V);
   }
 
@@ -2829,11 +2813,11 @@ void RemoveDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
   if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR))
     SymReaper.markLive(SymR->getSymbol());
 
-  for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I) {
+  for (const auto &[Key, Val] : *C) {
     // Element index of a binding key is live.
-    SymReaper.markElementIndicesLive(I.getKey().getRegion());
+    SymReaper.markElementIndicesLive(Key.getRegion());
 
-    VisitBinding(I.getData());
+    VisitBinding(Val);
   }
 }
 
@@ -2860,17 +2844,15 @@ void RemoveDeadBindingsWorker::VisitBinding(SVal V) {
 
     // All regions captured by a block are also live.
     if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) {
-      BlockDataRegion::referenced_vars_iterator I = BR->referenced_vars_begin(),
-                                                E = BR->referenced_vars_end();
-      for ( ; I != E; ++I)
-        AddToWorkList(I.getCapturedRegion());
+      for (auto Var : BR->referenced_vars())
+        AddToWorkList(Var.getCapturedRegion());
     }
   }
 
 
   // Update the set of live symbols.
-  for (auto SI = V.symbol_begin(), SE = V.symbol_end(); SI!=SE; ++SI)
-    SymReaper.markLive(*SI);
+  for (SymbolRef Sym : V.symbols())
+    SymReaper.markLive(Sym);
 }
 
 bool RemoveDeadBindingsWorker::UpdatePostponed() {
@@ -2878,12 +2860,10 @@ bool RemoveDeadBindingsWorker::UpdatePostponed() {
   // having done a scan.
   bool Changed = false;
 
-  for (auto I = Postponed.begin(), E = Postponed.end(); I != E; ++I) {
-    if (const SymbolicRegion *SR = *I) {
-      if (SymReaper.isLive(SR->getSymbol())) {
-        Changed |= AddToWorkList(SR);
-        *I = nullptr;
-      }
+  for (const SymbolicRegion *SR : Postponed) {
+    if (SymReaper.isLive(SR->getSymbol())) {
+      Changed |= AddToWorkList(SR);
+      SR = nullptr;
     }
   }
 
@@ -2898,9 +2878,8 @@ StoreRef RegionStoreManager::removeDeadBindings(Store store,
   W.GenerateClusters();
 
   // Enqueue the region roots onto the worklist.
-  for (SymbolReaper::region_iterator I = SymReaper.region_begin(),
-       E = SymReaper.region_end(); I != E; ++I) {
-    W.AddToWorkList(*I);
+  for (const MemRegion *Reg : SymReaper.regions()) {
+    W.AddToWorkList(Reg);
   }
 
   do W.RunWorkList(); while (W.UpdatePostponed());
@@ -2908,9 +2887,7 @@ StoreRef RegionStoreManager::removeDeadBindings(Store store,
   // We have now scanned the store, marking reachable regions and symbols
   // as live.  We now remove all the regions that are dead from the store
   // as well as update DSymbols with the set symbols that are now dead.
-  for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) {
-    const MemRegion *Base = I.getKey();
-
+  for (const MemRegion *Base : llvm::make_first_range(B)) {
     // If the cluster has been visited, we know the region has been marked.
     // Otherwise, remove the dead entry.
     if (!W.isVisited(Base))

diff  --git a/clang/lib/StaticAnalyzer/Core/Store.cpp b/clang/lib/StaticAnalyzer/Core/Store.cpp
index f343eba54f5962..7577b7682a958c 100644
--- a/clang/lib/StaticAnalyzer/Core/Store.cpp
+++ b/clang/lib/StaticAnalyzer/Core/Store.cpp
@@ -257,10 +257,8 @@ SVal StoreManager::evalDerivedToBase(SVal Derived, const CastExpr *Cast) {
 
   // Walk through the cast path to create nested CXXBaseRegions.
   SVal Result = Derived;
-  for (CastExpr::path_const_iterator I = Cast->path_begin(),
-                                     E = Cast->path_end();
-       I != E; ++I) {
-    Result = evalDerivedToBase(Result, (*I)->getType(), (*I)->isVirtual());
+  for (const CXXBaseSpecifier *Base : Cast->path()) {
+    Result = evalDerivedToBase(Result, Base->getType(), Base->isVirtual());
   }
   return Result;
 }

diff  --git a/clang/lib/StaticAnalyzer/Core/SymbolManager.cpp b/clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
index b484557ec73941..9025e11a3f51a3 100644
--- a/clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
@@ -414,8 +414,8 @@ void SymbolReaper::markElementIndicesLive(const MemRegion *region) {
        SR = dyn_cast<SubRegion>(SR->getSuperRegion())) {
     if (const auto ER = dyn_cast<ElementRegion>(SR)) {
       SVal Idx = ER->getIndex();
-      for (auto SI = Idx.symbol_begin(), SE = Idx.symbol_end(); SI != SE; ++SI)
-        markLive(*SI);
+      for (SymbolRef Sym : Idx.symbols())
+        markLive(Sym);
     }
   }
 }

diff  --git a/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp b/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
index 05f4d19ebda0e3..71268af22e2424 100644
--- a/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
+++ b/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
@@ -86,10 +86,7 @@ class TextDiagnostics : public PathDiagnosticConsumer {
       }
     };
 
-    for (std::vector<const PathDiagnostic *>::iterator I = Diags.begin(),
-         E = Diags.end();
-         I != E; ++I) {
-      const PathDiagnostic *PD = *I;
+    for (const PathDiagnostic *PD : Diags) {
       std::string WarningMsg = (DiagOpts.ShouldDisplayDiagnosticName
                                     ? " [" + PD->getCheckerName() + "]"
                                     : "")

diff  --git a/clang/lib/StaticAnalyzer/Frontend/ModelConsumer.cpp b/clang/lib/StaticAnalyzer/Frontend/ModelConsumer.cpp
index 276f7313b08f71..0f1039d81d52de 100644
--- a/clang/lib/StaticAnalyzer/Frontend/ModelConsumer.cpp
+++ b/clang/lib/StaticAnalyzer/Frontend/ModelConsumer.cpp
@@ -28,11 +28,10 @@ using namespace ento;
 ModelConsumer::ModelConsumer(llvm::StringMap<Stmt *> &Bodies)
     : Bodies(Bodies) {}
 
-bool ModelConsumer::HandleTopLevelDecl(DeclGroupRef D) {
-  for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
-
+bool ModelConsumer::HandleTopLevelDecl(DeclGroupRef DeclGroup) {
+  for (const Decl *D : DeclGroup) {
     // Only interested in definitions.
-    const FunctionDecl *func = llvm::dyn_cast<FunctionDecl>(*I);
+    const auto *func = llvm::dyn_cast<FunctionDecl>(D);
     if (func && func->hasBody()) {
       Bodies.insert(std::make_pair(func->getName(), func->getBody()));
     }


        


More information about the cfe-commits mailing list