diff --git a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h --- a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h +++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h @@ -608,8 +608,9 @@ /// Iterator over the set of BugReports tracked by the BugReporter. using EQClasses_iterator = llvm::FoldingSet::iterator; - EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); } - EQClasses_iterator EQClasses_end() { return EQClasses.end(); } + llvm::iterator_range 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 --- a/clang/include/clang/StaticAnalyzer/Core/Checker.h +++ b/clang/include/clang/StaticAnalyzer/Core/Checker.h @@ -370,13 +370,12 @@ 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 @@ 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 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h @@ -620,10 +620,9 @@ 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 --- 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 #include @@ -175,21 +176,11 @@ 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 @@ 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 --- 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 @@ -395,13 +396,9 @@ using node_iterator = AllNodesTy::iterator; using const_node_iterator = AllNodesTy::const_iterator; - node_iterator nodes_begin() { return Nodes.begin(); } + llvm::iterator_range 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 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 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h @@ -602,8 +602,7 @@ 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 --- 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 @@ -737,6 +738,11 @@ ++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 @@ referenced_vars_iterator referenced_vars_begin() const; referenced_vars_iterator referenced_vars_end() const; + llvm::iterator_range 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 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h @@ -203,9 +203,9 @@ auto CZ = State->get(); auto &CZFactory = State->get_context(); - 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(CZ); diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h --- 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 #include @@ -180,16 +181,11 @@ 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 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 --- 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 namespace clang { @@ -83,8 +84,9 @@ 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 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 --- 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 @@ -631,10 +632,9 @@ /// 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 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 --- 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 @@ 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 @@ 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 --- 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 @@ } // 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 @@ 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 @@ // Remove the dead symbols from the collection count map. ContainerCountMapTy Tracked = State->get(); - 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(Sym); State = State->remove(Sym); diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp --- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp @@ -2575,9 +2575,7 @@ llvm::SmallPtrSet SuperRegions; // First build sets for the changed regions and their super-regions. - for (ArrayRef::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 @@ CStringLengthTy::Factory &F = state->get_context(); // 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 @@ // Mark all symbols in our string length map as valid. CStringLengthTy Entries = state->get(); - 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 @@ return; CStringLengthTy::Factory &F = state->get_context(); - 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 --- a/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp @@ -820,8 +820,8 @@ 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(*I); + for (const NamedDecl *D : R) { + auto *ShadowedPropDecl = dyn_cast(D); if (!ShadowedPropDecl) continue; diff --git a/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp --- a/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp @@ -93,9 +93,9 @@ 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 --- a/clang/lib/StaticAnalyzer/Checkers/DebugCheckers.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/DebugCheckers.cpp @@ -271,9 +271,8 @@ const Table &Config = mgr.options.Config; SmallVector 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 --- 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 using namespace clang; @@ -233,11 +234,9 @@ MostSpecializedTypeArgsMapTy TyArgMap = State->get(); - for (MostSpecializedTypeArgsMapTy::iterator I = TyArgMap.begin(), - E = TyArgMap.end(); - I != E; ++I) { - if (SR.isDead(I->first)) { - State = State->remove(I->first); + for (SymbolRef Sym : llvm::make_first_range(TyArgMap)) { + if (SR.isDead(Sym)) { + State = State->remove(Sym); } } diff --git a/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp --- a/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp @@ -393,8 +393,7 @@ ProgramStateRef State = C.getState(); const MarkedSymbolsTy &Syms = State->get(); 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 --- a/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp @@ -686,11 +686,10 @@ 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 --- 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 @@ SymbolReaper &SR) const { // Keep symbolic expressions of iterator positions alive auto RegionMap = State->get(); - for (const auto &Reg : RegionMap) { - const auto Offset = Reg.second.getOffset(); - for (auto i = Offset->symbol_begin(); i != Offset->symbol_end(); ++i) - if (isa(*i)) - SR.markLive(*i); + for (const IteratorPosition &Pos : llvm::make_second_range(RegionMap)) { + for (SymbolRef Sym : Pos.getOffset()->symbols()) + if (isa(Sym)) + SR.markLive(Sym); } auto SymbolMap = State->get(); - for (const auto &Sym : SymbolMap) { - const auto Offset = Sym.second.getOffset(); - for (auto i = Offset->symbol_begin(); i != Offset->symbol_end(); ++i) - if (isa(*i)) - SR.markLive(*i); + for (const IteratorPosition &Pos : llvm::make_second_range(SymbolMap)) { + for (SymbolRef Sym : Pos.getOffset()->symbols()) + if (isa(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 --- 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 @@ 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 @@ // 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 @@ 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 @@ // 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 @@ // 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 @@ 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 @@ 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 --- 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 @@ -847,10 +848,9 @@ if (argumentNumber < 0) { // There was no match in UIMethods if (const Decl *D = msg.getDecl()) { if (const ObjCMethodDecl *OMD = dyn_cast_or_null(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 --- 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 @@ -530,9 +531,9 @@ } if (ReturnSymbol) - for (auto I = AMap.begin(), E = AMap.end(); I != E; ++I) { - if (ReturnSymbol == I->second.Region) - State = State->remove(I->first); + for (auto [Sym, AllocState] : AMap) { + if (ReturnSymbol == AllocState.Region) + State = State->remove(Sym); } return State; @@ -547,18 +548,18 @@ 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(I->first); + State = State->remove(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 @@ 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 --- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp @@ -1688,9 +1688,9 @@ 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 @@ RegionStateTy RS = OldRS; SmallVector 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 @@ // Cleanup the Realloc Pairs Map. ReallocPairsTy RP = state->get(); - 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(I->first); + for (auto [Sym, ReallocPair] : RP) { + if (SymReaper.isDead(Sym) || SymReaper.isDead(ReallocPair.ReallocatedSym)) { + state = state->remove(Sym); } } // Cleanup the FreeReturnValue Map. FreeReturnValueTy FR = state->get(); - for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) { - if (SymReaper.isDead(I->first) || - SymReaper.isDead(I->second)) { - state = state->remove(I->first); + for (auto [Sym, RetSym] : FR) { + if (SymReaper.isDead(Sym) || SymReaper.isDead(RetSym)) { + state = state->remove(Sym); } } @@ -2840,9 +2838,8 @@ static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak"); N = C.generateNonFatalErrorNode(C.getState(), &Tag); if (N) { - for (SmallVectorImpl::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 @@ const BlockDataRegion *R = cast(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 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 @@ SVal Cond, bool Assumption) const { RegionStateTy RS = state->get(); - 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(I.getKey()); + state = state->remove(Sym); } // Realloc returns 0 when reallocation fails, which means that we should // restore the state of the pointer being reallocated. ReallocPairsTy RP = state->get(); - 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(ReallocSym)) { if (RS->isReleased()) { - switch (I.getData().Kind) { + switch (ReallocPair.Kind) { case OAR_ToBeFreedAfterFailure: state = state->set(ReallocSym, RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt())); @@ -3102,11 +3097,11 @@ state = state->remove(ReallocSym); break; default: - assert(I.getData().Kind == OAR_FreeOnFailure); + assert(ReallocPair.Kind == OAR_FreeOnFailure); } } } - state = state->remove(I.getKey()); + state = state->remove(Sym); } return state; @@ -3312,11 +3307,7 @@ 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 @@ if (!RS.isEmpty()) { Out << Sep << "MallocChecker :" << NL; - for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) { - const RefState *RefS = State->get(I.getKey()); + for (auto [Sym, Data] : RS) { + const RefState *RefS = State->get(Sym); AllocationFamily Family = RefS->getAllocationFamily(); std::optional 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 --- a/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp @@ -280,17 +280,13 @@ 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 --- 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 @@ 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 @@ continue; const TypeSourceInfo *TSI = nullptr; - if (i->CastedExprParent.is()) { - TSI = - i->CastedExprParent.get()->getTypeSourceInfo(); + if (CallRec.CastedExprParent.is()) { + TSI = CallRec.CastedExprParent.get() + ->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 @@ << "', which is incompatible with " << "sizeof operand type '" << SizeofType << "'"; SmallVector 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 --- 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 @@ CheckerContext &C) const { ProgramStateRef State = C.getState(); NullabilityMapTy Nullabilities = State->get(); - for (NullabilityMapTy::iterator I = Nullabilities.begin(), - E = Nullabilities.end(); - I != E; ++I) { - const auto *Region = I->first->getAs(); + for (const MemRegion *Reg : llvm::make_first_range(Nullabilities)) { + const auto *Region = Reg->getAs(); assert(Region && "Non-symbolic region is tracked."); if (SR.isDead(Region->getSymbol())) { - State = State->remove(I->first); + State = State->remove(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(); - 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(I->first); + State = State->remove(PropKey); } } @@ -945,18 +942,16 @@ ProgramStateRef NullabilityChecker::evalAssume(ProgramStateRef State, SVal Cond, bool Assumption) const { PropertyAccessesMapTy PropertyAccesses = State->get(); - 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(I->first, Replacement); + State = State->set(PropKey, Replacement); } else if (IsNonNull.isConstrainedFalse()) { // Space optimization: no point in tracking constrained-null cases - State = State->remove(I->first); + State = State->remove(PropKey); } } } @@ -1375,9 +1370,9 @@ if (!State->get()) 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 --- a/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp @@ -103,9 +103,7 @@ llvm::SmallPtrSet &ClassSelectors = SelectorsForClass[ClassName]; // Fill the Selectors SmallSet with all selectors we want to check. - for (ArrayRef::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 --- a/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp @@ -362,18 +362,17 @@ } 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 --- 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 @@ } if (const PseudoObjectExpr *POE = dyn_cast(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(sub)) sub = OVE->getSourceExpr(); Scan(M, sub); @@ -134,8 +133,8 @@ // 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 @@ 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 --- a/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp @@ -79,10 +79,9 @@ // see http://reviews.llvm.org/D14203 for further information. /*ProgramStateRef State = C.getState(); RegionStateTy RegionStates = State->get(); - for (RegionStateTy::iterator I = RegionStates.begin(), E = RegionStates.end(); - I != E; ++I) { - if (!SR.isLiveRegion(I->first)) - State = State->remove(I->first); + for (const MemRegion *Reg: llvm::make_first_range(RegionStates)) { + if (!SR.isLiveRegion(Reg)) + State = State->remove(Reg); } C.addTransition(State);*/ } diff --git a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp --- a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp @@ -155,10 +155,8 @@ ProgramStateRef state = C.getState(); auto *R = cast(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 @@ 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 --- a/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp @@ -163,13 +163,11 @@ ProgramStateRef State = C.getState(); SymbolVector LeakedStreams; StreamMapTy TrackedStreams = State->get(); - 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 @@ 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(Sym); diff --git a/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp b/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp --- 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 @@ -588,10 +589,9 @@ SymbolReaper &SR) const { // Marking tracked symbols alive TrackedRegionMapTy TrackedRegions = State->get(); - 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 --- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp @@ -138,10 +138,8 @@ StackAddrEscapeChecker::getCapturedStackRegions(const BlockDataRegion &B, CheckerContext &C) { SmallVector 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(Region->getMemorySpace())) Regions.push_back(Region); diff --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp --- 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 @@ 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 @@ } // 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 --- a/clang/lib/StaticAnalyzer/Checkers/Taint.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/Taint.cpp @@ -259,21 +259,19 @@ 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(*SI)) + for (SymbolRef SubSym : Sym->symbols()) { + if (!isa(SubSym)) continue; - if (const TaintTagType *Tag = State->get(*SI)) { + if (const TaintTagType *Tag = State->get(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(*SI)) { + if (const auto *SD = dyn_cast(SubSym)) { // If this is a SymbolDerived with a tainted parent, it's also tainted. std::vector TaintedParents = getTaintedSymbolsImpl( State, SD->getParentSymbol(), Kind, returnFirstOnly); @@ -302,7 +300,7 @@ } // If memory region is tainted, data is also tainted. - if (const auto *SRV = dyn_cast(*SI)) { + if (const auto *SRV = dyn_cast(SubSym)) { std::vector TaintedRegions = getTaintedSymbolsImpl(State, SRV->getRegion(), Kind, returnFirstOnly); llvm::append_range(TaintedSymbols, TaintedRegions); @@ -311,7 +309,7 @@ } // If this is a SymbolCast from a tainted value, it's also tainted. - if (const auto *SC = dyn_cast(*SI)) { + if (const auto *SC = dyn_cast(SubSym)) { std::vector 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 --- a/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp @@ -188,10 +188,7 @@ return; DivZeroMapTy::Factory &F = State->get_context(); - for (llvm::ImmutableSet::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 --- a/clang/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp @@ -69,8 +69,7 @@ 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 --- a/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp @@ -57,13 +57,10 @@ ProgramStateRef state = C.getState(); auto *R = cast(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() || !VD->hasLocalStorage()) @@ -71,7 +68,7 @@ // Get the VarRegion associated with VD in the local stack frame. if (std::optional V = - state->getSVal(I.getOriginalRegion()).getAs()) { + state->getSVal(Var.getOriginalRegion()).getAs()) { 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 --- a/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp @@ -59,9 +59,8 @@ 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 @@ 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 @@ 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 S = I->getAs()) { + for (const CFGElement &Elem : *CB) { + if (std::optional S = Elem.getAs()) { if (!isa(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 --- a/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp +++ b/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp @@ -50,17 +50,14 @@ 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 --- a/clang/lib/StaticAnalyzer/Core/BugReporter.cpp +++ b/clang/lib/StaticAnalyzer/Core/BugReporter.cpp @@ -296,26 +296,24 @@ 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 Reg = SV.getAs()) { // 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 --- 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 --- a/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp +++ b/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp @@ -508,9 +508,8 @@ // 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 @@ // 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(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 --- 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 @@ // 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 CS = Elem.getAs(); if (!CS) continue; @@ -2850,9 +2849,9 @@ if (std::optional LV = V.getAs()) { 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 @@ // 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 @@ BugReporter &BR = static_cast( 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(I.get()); + for (const auto &Class : BR.equivalenceClasses()) { + for (const auto &Report : Class.getReports()) { + const auto *PR = dyn_cast(Report.get()); if (!PR) continue; const ExplodedNode *EN = PR->getErrorNode(); @@ -3908,10 +3904,9 @@ std::vector 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(EI->getReports()[0].get()); + dyn_cast(Class.getReports()[0].get()); if (!R) continue; const auto *N = const_cast(R->getErrorNode()); diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp --- 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 @@ -133,11 +133,9 @@ 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 @@ 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 different value then the // computation type. LHSVal = svalBuilder.evalCast(Result, LTy, CTy); @@ -185,7 +182,7 @@ 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 @@ if (const BlockDataRegion *BDR = dyn_cast_or_null(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 @@ 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 @@ 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 @@ 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 @@ 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 @@ // 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 @@ 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 @@ // 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 @@ 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 @@ const ValueDecl *VD = DRE->getDecl(); if (isa(VD)) { - ProgramStateRef State = (*I)->getState(); - const LocationContext *LCtx = (*I)->getLocationContext(); + ProgramStateRef State = N->getState(); + const LocationContext *LCtx = N->getLocationContext(); SVal SV = svalBuilder.getMemberPointer(cast(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 @@ [[fallthrough]]; case UO_Deref: case UO_Extension: { - handleUOExtension(I, U, Bldr); + handleUOExtension(N, U, Bldr); break; } @@ -1014,14 +1000,14 @@ 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 @@ state = state->BindExpr(U, LCtx, Result); break; } - Bldr.generateNode(U, *I, state); + Bldr.generateNode(U, N, state); break; } } @@ -1084,10 +1070,9 @@ 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 @@ 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 @@ 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 --- 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 using namespace clang; @@ -85,14 +87,13 @@ 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 @@ 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 @@ 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 @@ !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 @@ 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 @@ // 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(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 --- a/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp +++ b/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp @@ -374,17 +374,15 @@ 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 @@ // 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 --- a/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp +++ b/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp @@ -602,9 +602,9 @@ // Output any other meta data. - for (PathDiagnostic::meta_iterator I = D.meta_begin(), E = D.meta_end(); - I != E; ++I) { - os << "" << html::EscapeText(*I) << "\n"; + for (const std::string &Metadata : + llvm::make_range(D.meta_begin(), D.meta_end())) { + os << "" << html::EscapeText(Metadata) << "\n"; } os << R"<<<( diff --git a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp --- 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 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 @@ if (const auto *BC = dyn_cast(LC)) { const auto *BR = static_cast(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(OrigR)) { if (VR->getDecl() == VD) - return cast(I.getCapturedRegion()); + return cast(Var.getCapturedRegion()); } } } @@ -1745,10 +1742,13 @@ VecOriginal->end()); } +llvm::iterator_range +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 --- a/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp +++ b/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp @@ -367,10 +367,8 @@ 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 @@ // 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) << "" << FileKey << "\n"; Indent(o, IndentLevel) << "\n"; IndentLevel++; - for (unsigned LineNo : I->second) { + for (unsigned LineNo : Lines) { Indent(o, IndentLevel); EmitInteger(o, LineNo) << "\n"; } @@ -597,8 +595,8 @@ o << " \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 << " \n"; diff --git a/clang/lib/StaticAnalyzer/Core/ProgramState.cpp b/clang/lib/StaticAnalyzer/Core/ProgramState.cpp --- a/clang/lib/StaticAnalyzer/Core/ProgramState.cpp +++ b/clang/lib/StaticAnalyzer/Core/ProgramState.cpp @@ -156,9 +156,8 @@ const CallEvent *Call, RegionAndSymbolInvalidationTraits *ITraits) const { SmallVector 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::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 @@ // Regions captured by a block are also implicitly reachable. if (const BlockDataRegion *BDR = dyn_cast(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 --- 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 #include @@ -231,7 +232,7 @@ 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 @@ ++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 @@ 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(K.getRegion())) { + if (const SubRegion *R = dyn_cast(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 @@ 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 @@ 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 @@ // 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 @@ // 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(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 @@ /*IncludeAllDefaultBindings=*/false); ClusterBindingsRef Result(*Cluster, CBFactory); - for (SmallVectorImpl::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 @@ 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 @@ // BlockDataRegion? If so, invalidate captured variables that are passed // by reference. if (const BlockDataRegion *BR = dyn_cast(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() || !VD->hasLocalStorage()) { AddToWorkList(VR); @@ -1200,9 +1194,7 @@ 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 ROffset = BK.hasSymbolicOffset() ? std::optional() : BK.getOffset(); @@ -1213,10 +1205,9 @@ (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(R)) VisitBinding(V); @@ -1289,12 +1280,8 @@ void RegionStoreManager::populateWorkList(InvalidateRegionsWorker &W, ArrayRef Values, InvalidatedRegions *TopLevelRegions) { - for (ArrayRef::iterator I = Values.begin(), - E = Values.end(); I != E; ++I) { - SVal V = *I; - if (std::optional LCS = - V.getAs()) { - + for (SVal V : Values) { + if (auto LCS = V.getAs()) { for (SVal S : getInterestingValues(*LCS)) if (const MemRegion *R = S.getAsRegion()) W.AddToWorkList(R); @@ -2281,10 +2268,7 @@ SmallVector Bindings; collectSubRegionBindings(Bindings, svalBuilder, *Cluster, LazyR, /*IncludeAllDefaultBindings=*/true); - for (SmallVectorImpl::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 @@ 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 @@ if (const SymbolicRegion *SymR = dyn_cast(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 @@ // All regions captured by a block are also live. if (const BlockDataRegion *BR = dyn_cast(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 @@ // 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 @@ 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 @@ // 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 --- a/clang/lib/StaticAnalyzer/Core/Store.cpp +++ b/clang/lib/StaticAnalyzer/Core/Store.cpp @@ -257,10 +257,8 @@ // 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 --- a/clang/lib/StaticAnalyzer/Core/SymbolManager.cpp +++ b/clang/lib/StaticAnalyzer/Core/SymbolManager.cpp @@ -414,8 +414,8 @@ SR = dyn_cast(SR->getSuperRegion())) { if (const auto ER = dyn_cast(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 --- a/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp +++ b/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp @@ -86,10 +86,7 @@ } }; - for (std::vector::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 --- a/clang/lib/StaticAnalyzer/Frontend/ModelConsumer.cpp +++ b/clang/lib/StaticAnalyzer/Frontend/ModelConsumer.cpp @@ -28,11 +28,10 @@ ModelConsumer::ModelConsumer(llvm::StringMap &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(*I); + const auto *func = llvm::dyn_cast(D); if (func && func->hasBody()) { Bodies.insert(std::make_pair(func->getName(), func->getBody())); }