Author: eugenezelenko Date: Tue Mar 20 17:14:43 2018 New Revision: 328063 URL: http://llvm.org/viewvc/llvm-project?rev=328063&view=rev Log: [Analysis] Fix some Clang-tidy modernize and Include What You Use warnings; other minor fixes (NFC).
Modified: cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyCommon.h cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyUtil.h cfe/trunk/include/clang/Analysis/Analyses/UninitializedValues.h cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp cfe/trunk/lib/Analysis/UninitializedValues.cpp Modified: cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyCommon.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyCommon.h?rev=328063&r1=328062&r2=328063&view=diff ============================================================================== --- cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyCommon.h (original) +++ cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyCommon.h Tue Mar 20 17:14:43 2018 @@ -361,7 +361,7 @@ public: : Prev(P), AttrDecl(D) {} }; - SExprBuilder(til::MemRegionRef A) : Arena(A), CurrentBB() { + SExprBuilder(til::MemRegionRef A) : Arena(A) { // FIXME: we don't always have a self-variable. SelfVar = new (Arena) til::Variable(nullptr); SelfVar->setKind(til::Variable::VK_SFun); Modified: cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h?rev=328063&r1=328062&r2=328063&view=diff ============================================================================== --- cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h (original) +++ cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h Tue Mar 20 17:14:43 2018 @@ -1,4 +1,4 @@ -//===- ThreadSafetyTraverse.h ----------------------------------*- C++ --*-===// +//===- ThreadSafetyTraverse.h -----------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -17,7 +17,13 @@ #ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYTRAVERSE_H #define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYTRAVERSE_H -#include "ThreadSafetyTIL.h" +#include "clang/AST/Decl.h" +#include "clang/Analysis/Analyses/ThreadSafetyTIL.h" +#include "clang/Analysis/Analyses/ThreadSafetyUtil.h" +#include "clang/Basic/LLVM.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/Casting.h" +#include <cstdint> #include <ostream> namespace clang { @@ -92,21 +98,27 @@ public: #undef TIL_OPCODE_DEF }; - // Base class for simple reducers that don't much care about the context. class SimpleReducerBase { public: enum TraversalKind { - TRV_Normal, // ordinary subexpressions - TRV_Decl, // declarations (e.g. function bodies) - TRV_Lazy, // expressions that require lazy evaluation - TRV_Type // type expressions + // Ordinary subexpressions. + TRV_Normal, + + // Declarations (e.g. function bodies). + TRV_Decl, + + // Expressions that require lazy evaluation. + TRV_Lazy, + + // Type expressions. + TRV_Type }; // R_Ctx defines a "context" for the traversal, which encodes information // about where a term appears. This can be used to encoding the // "current continuation" for CPS transforms, or other information. - typedef TraversalKind R_Ctx; + using R_Ctx = TraversalKind; // Create context for an ordinary subexpression. R_Ctx subExprCtx(R_Ctx Ctx) { return TRV_Normal; } @@ -123,14 +135,13 @@ public: R_Ctx typeCtx(R_Ctx Ctx) { return TRV_Type; } }; - // Base class for traversals that rewrite an SExpr to another SExpr. class CopyReducerBase : public SimpleReducerBase { public: // R_SExpr is the result type for a traversal. // A copy or non-destructive rewrite returns a newly allocated term. - typedef SExpr *R_SExpr; - typedef BasicBlock *R_BasicBlock; + using R_SExpr = SExpr *; + using R_BasicBlock = BasicBlock *; // Container is a minimal interface used to store results when traversing // SExprs of variable arity, such as Phi, Goto, and SCFG. @@ -151,32 +162,31 @@ protected: MemRegionRef Arena; }; - // Base class for visit traversals. class VisitReducerBase : public SimpleReducerBase { public: // A visitor returns a bool, representing success or failure. - typedef bool R_SExpr; - typedef bool R_BasicBlock; + using R_SExpr = bool; + using R_BasicBlock = bool; // A visitor "container" is a single bool, which accumulates success. template <class T> class Container { public: - Container(VisitReducerBase &S, unsigned N) : Success(true) {} - void push_back(bool E) { Success = Success && E; } + bool Success = true; - bool Success; + Container(VisitReducerBase &S, unsigned N) {} + + void push_back(bool E) { Success = Success && E; } }; }; - // Implements a traversal that visits each subexpression, and returns either // true or false. template <class Self> class VisitReducer : public Traversal<Self, VisitReducerBase>, public VisitReducerBase { public: - VisitReducer() {} + VisitReducer() = default; public: R_SExpr reduceNull() { return true; } @@ -191,54 +201,70 @@ public: R_SExpr reduceFunction(Function &Orig, Variable *Nvd, R_SExpr E0) { return Nvd && E0; } + R_SExpr reduceSFunction(SFunction &Orig, Variable *Nvd, R_SExpr E0) { return Nvd && E0; } + R_SExpr reduceCode(Code &Orig, R_SExpr E0, R_SExpr E1) { return E0 && E1; } + R_SExpr reduceField(Field &Orig, R_SExpr E0, R_SExpr E1) { return E0 && E1; } + R_SExpr reduceApply(Apply &Orig, R_SExpr E0, R_SExpr E1) { return E0 && E1; } + R_SExpr reduceSApply(SApply &Orig, R_SExpr E0, R_SExpr E1) { return E0 && E1; } + R_SExpr reduceProject(Project &Orig, R_SExpr E0) { return E0; } R_SExpr reduceCall(Call &Orig, R_SExpr E0) { return E0; } R_SExpr reduceAlloc(Alloc &Orig, R_SExpr E0) { return E0; } R_SExpr reduceLoad(Load &Orig, R_SExpr E0) { return E0; } R_SExpr reduceStore(Store &Orig, R_SExpr E0, R_SExpr E1) { return E0 && E1; } + R_SExpr reduceArrayIndex(Store &Orig, R_SExpr E0, R_SExpr E1) { return E0 && E1; } + R_SExpr reduceArrayAdd(Store &Orig, R_SExpr E0, R_SExpr E1) { return E0 && E1; } + R_SExpr reduceUnaryOp(UnaryOp &Orig, R_SExpr E0) { return E0; } + R_SExpr reduceBinaryOp(BinaryOp &Orig, R_SExpr E0, R_SExpr E1) { return E0 && E1; } + R_SExpr reduceCast(Cast &Orig, R_SExpr E0) { return E0; } R_SExpr reduceSCFG(SCFG &Orig, Container<BasicBlock *> Bbs) { return Bbs.Success; } + R_BasicBlock reduceBasicBlock(BasicBlock &Orig, Container<R_SExpr> &As, Container<R_SExpr> &Is, R_SExpr T) { return (As.Success && Is.Success && T); } + R_SExpr reducePhi(Phi &Orig, Container<R_SExpr> &As) { return As.Success; } + R_SExpr reduceGoto(Goto &Orig, BasicBlock *B) { return true; } + R_SExpr reduceBranch(Branch &O, R_SExpr C, BasicBlock *B0, BasicBlock *B1) { return C; } + R_SExpr reduceReturn(Return &O, R_SExpr E) { return E; } @@ -246,9 +272,11 @@ public: R_SExpr reduceIdentifier(Identifier &Orig) { return true; } + R_SExpr reduceIfThenElse(IfThenElse &Orig, R_SExpr C, R_SExpr T, R_SExpr E) { return C && T && E; } + R_SExpr reduceLet(Let &Orig, Variable *Nvd, R_SExpr B) { return Nvd && B; } @@ -260,7 +288,7 @@ public: void enterBasicBlock(BasicBlock &BB) {} void exitBasicBlock(BasicBlock &BB) {} - Variable *reduceVariableRef (Variable *Ovd) { return Ovd; } + Variable *reduceVariableRef(Variable *Ovd) { return Ovd; } BasicBlock *reduceBasicBlockRef(BasicBlock *Obb) { return Obb; } public: @@ -278,7 +306,6 @@ private: bool Success; }; - // Basic class for comparison operations over expressions. template <typename Self> class Comparator { @@ -298,19 +325,18 @@ public: } }; - class EqualsComparator : public Comparator<EqualsComparator> { public: // Result type for the comparison, e.g. bool for simple equality, // or int for lexigraphic comparison (-1, 0, 1). Must have one value which // denotes "true". - typedef bool CType; + using CType = bool; CType trueResult() { return true; } bool notTrue(CType ct) { return !ct; } - bool compareIntegers(unsigned i, unsigned j) { return i == j; } - bool compareStrings (StringRef s, StringRef r) { return s == r; } + bool compareIntegers(unsigned i, unsigned j) { return i == j; } + bool compareStrings (StringRef s, StringRef r) { return s == r; } bool comparePointers(const void* P, const void* Q) { return P == Q; } bool compare(const SExpr *E1, const SExpr* E2) { @@ -320,10 +346,10 @@ public: } // TODO -- handle alpha-renaming of variables - void enterScope(const Variable* V1, const Variable* V2) { } - void leaveScope() { } + void enterScope(const Variable *V1, const Variable *V2) {} + void leaveScope() {} - bool compareVariableRefs(const Variable* V1, const Variable* V2) { + bool compareVariableRefs(const Variable *V1, const Variable *V2) { return V1 == V2; } @@ -333,23 +359,21 @@ public: } }; - - class MatchComparator : public Comparator<MatchComparator> { public: // Result type for the comparison, e.g. bool for simple equality, // or int for lexigraphic comparison (-1, 0, 1). Must have one value which // denotes "true". - typedef bool CType; + using CType = bool; CType trueResult() { return true; } bool notTrue(CType ct) { return !ct; } - bool compareIntegers(unsigned i, unsigned j) { return i == j; } - bool compareStrings (StringRef s, StringRef r) { return s == r; } - bool comparePointers(const void* P, const void* Q) { return P == Q; } + bool compareIntegers(unsigned i, unsigned j) { return i == j; } + bool compareStrings (StringRef s, StringRef r) { return s == r; } + bool comparePointers(const void *P, const void *Q) { return P == Q; } - bool compare(const SExpr *E1, const SExpr* E2) { + bool compare(const SExpr *E1, const SExpr *E2) { // Wildcards match anything. if (E1->opcode() == COP_Wildcard || E2->opcode() == COP_Wildcard) return true; @@ -360,8 +384,8 @@ public: } // TODO -- handle alpha-renaming of variables - void enterScope(const Variable* V1, const Variable* V2) { } - void leaveScope() { } + void enterScope(const Variable* V1, const Variable* V2) {} + void leaveScope() {} bool compareVariableRefs(const Variable* V1, const Variable* V2) { return V1 == V2; @@ -373,8 +397,6 @@ public: } }; - - // inline std::ostream& operator<<(std::ostream& SS, StringRef R) { // return SS.write(R.data(), R.size()); // } @@ -383,14 +405,18 @@ public: template <typename Self, typename StreamType> class PrettyPrinter { private: - bool Verbose; // Print out additional information - bool Cleanup; // Omit redundant decls. - bool CStyle; // Print exprs in C-like syntax. + // Print out additional information. + bool Verbose; + + // Omit redundant decls. + bool Cleanup; + + // Print exprs in C-like syntax. + bool CStyle; public: PrettyPrinter(bool V = false, bool C = true, bool CS = true) - : Verbose(V), Cleanup(C), CStyle(CS) - {} + : Verbose(V), Cleanup(C), CStyle(CS) {} static void print(const SExpr *E, StreamType &SS) { Self printer; @@ -470,7 +496,6 @@ protected: } } - void printSExpr(const SExpr *E, StreamType &SS, unsigned P, bool Sub=true) { if (!E) { self()->printNull(SS); @@ -531,18 +556,16 @@ protected: else { ValueType VT = E->valueType(); switch (VT.Base) { - case ValueType::BT_Void: { + case ValueType::BT_Void: SS << "void"; return; - } - case ValueType::BT_Bool: { + case ValueType::BT_Bool: if (E->as<bool>().value()) SS << "true"; else SS << "false"; return; - } - case ValueType::BT_Int: { + case ValueType::BT_Int: switch (VT.Size) { case ValueType::ST_8: if (VT.Signed) @@ -572,8 +595,7 @@ protected: break; } break; - } - case ValueType::BT_Float: { + case ValueType::BT_Float: switch (VT.Size) { case ValueType::ST_32: printLiteralT(&E->as<float>(), SS); @@ -585,22 +607,18 @@ protected: break; } break; - } - case ValueType::BT_String: { + case ValueType::BT_String: SS << "\""; printLiteralT(&E->as<StringRef>(), SS); SS << "\""; return; - } - case ValueType::BT_Pointer: { + case ValueType::BT_Pointer: SS << "#ptr"; return; - } - case ValueType::BT_ValueRef: { + case ValueType::BT_ValueRef: SS << "#vref"; return; } - } } SS << "#lit"; } @@ -688,8 +706,8 @@ protected: void printProject(const Project *E, StreamType &SS) { if (CStyle) { // Omit the this-> - if (const SApply *SAP = dyn_cast<SApply>(E->record())) { - if (const Variable *V = dyn_cast<Variable>(SAP->sfun())) { + if (const auto *SAP = dyn_cast<SApply>(E->record())) { + if (const auto *V = dyn_cast<Variable>(SAP->sfun())) { if (!SAP->isDelegation() && V->kind() == Variable::VK_SFun) { SS << E->slotName(); return; @@ -704,12 +722,10 @@ protected: } } self()->printSExpr(E->record(), SS, Prec_Postfix); - if (CStyle && E->isArrow()) { + if (CStyle && E->isArrow()) SS << "->"; - } - else { + else SS << "."; - } SS << E->slotName(); } @@ -780,18 +796,16 @@ protected: void printSCFG(const SCFG *E, StreamType &SS) { SS << "CFG {\n"; - for (auto BBI : *E) { + for (const auto *BBI : *E) printBasicBlock(BBI, SS); - } SS << "}"; newline(SS); } - void printBBInstr(const SExpr *E, StreamType &SS) { bool Sub = false; if (E->opcode() == COP_Variable) { - auto *V = cast<Variable>(E); + const auto *V = cast<Variable>(E); SS << "let " << V->name() << V->id() << " = "; E = V->definition(); Sub = true; @@ -810,10 +824,10 @@ protected: SS << " BB_" << E->parent()->blockID(); newline(SS); - for (auto *A : E->arguments()) + for (const auto *A : E->arguments()) printBBInstr(A, SS); - for (auto *I : E->instructions()) + for (const auto *I : E->instructions()) printBBInstr(I, SS); const SExpr *T = E->terminator(); @@ -831,7 +845,7 @@ protected: self()->printSExpr(E->values()[0], SS, Prec_MAX); else { unsigned i = 0; - for (auto V : E->values()) { + for (const auto *V : E->values()) { if (i++ > 0) SS << ", "; self()->printSExpr(V, SS, Prec_MAX); @@ -890,13 +904,10 @@ protected: } }; +class StdPrinter : public PrettyPrinter<StdPrinter, std::ostream> {}; -class StdPrinter : public PrettyPrinter<StdPrinter, std::ostream> { }; - - - -} // end namespace til -} // end namespace threadSafety -} // end namespace clang +} // namespace til +} // namespace threadSafety +} // namespace clang -#endif // LLVM_CLANG_THREAD_SAFETY_TRAVERSE_H +#endif // LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYTRAVERSE_H Modified: cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyUtil.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyUtil.h?rev=328063&r1=328062&r2=328063&view=diff ============================================================================== --- cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyUtil.h (original) +++ cfe/trunk/include/clang/Analysis/Analyses/ThreadSafetyUtil.h Tue Mar 20 17:14:43 2018 @@ -88,7 +88,7 @@ public: SimpleArray(T *Dat, size_t Cp, size_t Sz = 0) : Data(Dat), Size(Sz), Capacity(Cp) {} SimpleArray(MemRegionRef A, size_t Cp) - : Data(Cp == 0 ? nullptr : A.allocateT<T>(Cp)), Size(0), Capacity(Cp) {} + : Data(Cp == 0 ? nullptr : A.allocateT<T>(Cp)), Capacity(Cp) {} SimpleArray(const SimpleArray<T> &A) = delete; SimpleArray(SimpleArray<T> &&A) Modified: cfe/trunk/include/clang/Analysis/Analyses/UninitializedValues.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/UninitializedValues.h?rev=328063&r1=328062&r2=328063&view=diff ============================================================================== --- cfe/trunk/include/clang/Analysis/Analyses/UninitializedValues.h (original) +++ cfe/trunk/include/clang/Analysis/Analyses/UninitializedValues.h Tue Mar 20 17:14:43 2018 @@ -1,4 +1,4 @@ -//= UninitializedValues.h - Finding uses of uninitialized values -*- C++ -*-==// +//=- UninitializedValues.h - Finding uses of uninitialized values -*- C++ -*-=// // // The LLVM Compiler Infrastructure // @@ -15,7 +15,7 @@ #ifndef LLVM_CLANG_ANALYSIS_ANALYSES_UNINITIALIZEDVALUES_H #define LLVM_CLANG_ANALYSIS_ANALYSES_UNINITIALIZEDVALUES_H -#include "clang/AST/Stmt.h" +#include "clang/Basic/LLVM.h" #include "llvm/ADT/SmallVector.h" namespace clang { @@ -24,6 +24,7 @@ class AnalysisDeclContext; class CFG; class DeclContext; class Expr; +class Stmt; class VarDecl; /// A use of a variable, which might be uninitialized. @@ -39,10 +40,10 @@ private: const Expr *User; /// Is this use uninitialized whenever the function is called? - bool UninitAfterCall; + bool UninitAfterCall = false; /// Is this use uninitialized whenever the variable declaration is reached? - bool UninitAfterDecl; + bool UninitAfterDecl = false; /// Does this use always see an uninitialized value? bool AlwaysUninit; @@ -53,8 +54,7 @@ private: public: UninitUse(const Expr *User, bool AlwaysUninit) - : User(User), UninitAfterCall(false), UninitAfterDecl(false), - AlwaysUninit(AlwaysUninit) {} + : User(User), AlwaysUninit(AlwaysUninit) {} void addUninitBranch(Branch B) { UninitBranches.push_back(B); @@ -70,14 +70,18 @@ public: enum Kind { /// The use might be uninitialized. Maybe, + /// The use is uninitialized whenever a certain branch is taken. Sometimes, + /// The use is uninitialized the first time it is reached after we reach /// the variable's declaration. AfterDecl, + /// The use is uninitialized the first time it is reached after the function /// is called. AfterCall, + /// The use is always uninitialized. Always }; @@ -90,7 +94,8 @@ public: !branch_empty() ? Sometimes : Maybe; } - typedef SmallVectorImpl<Branch>::const_iterator branch_iterator; + using branch_iterator = SmallVectorImpl<Branch>::const_iterator; + /// Branches which inevitably result in the variable being used uninitialized. branch_iterator branch_begin() const { return UninitBranches.begin(); } branch_iterator branch_end() const { return UninitBranches.end(); } @@ -99,7 +104,7 @@ public: class UninitVariablesHandler { public: - UninitVariablesHandler() {} + UninitVariablesHandler() = default; virtual ~UninitVariablesHandler(); /// Called when the uninitialized variable is used at the given expression. @@ -122,5 +127,6 @@ void runUninitializedVariablesAnalysis(c UninitVariablesHandler &handler, UninitVariablesAnalysisStats &stats); -} -#endif +} // namespace clang + +#endif // LLVM_CLANG_ANALYSIS_ANALYSES_UNINITIALIZEDVALUES_H Modified: cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h?rev=328063&r1=328062&r2=328063&view=diff ============================================================================== --- cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h (original) +++ cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h Tue Mar 20 17:14:43 2018 @@ -1,4 +1,4 @@ -//=== AnalysisDeclContext.h - Analysis context for Path Sens analysis --*- C++ -*-// +// AnalysisDeclContext.h - Analysis context for Path Sens analysis -*- C++ -*-// // // The LLVM Compiler Infrastructure // @@ -15,37 +15,42 @@ #ifndef LLVM_CLANG_ANALYSIS_ANALYSISDECLCONTEXT_H #define LLVM_CLANG_ANALYSIS_ANALYSISDECLCONTEXT_H -#include "clang/AST/Decl.h" +#include "clang/AST/DeclBase.h" #include "clang/Analysis/BodyFarm.h" #include "clang/Analysis/CFG.h" #include "clang/Analysis/CodeInjector.h" +#include "clang/Basic/LLVM.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/FoldingSet.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/iterator_range.h" #include "llvm/Support/Allocator.h" +#include <functional> #include <memory> namespace clang { -class Stmt; +class AnalysisDeclContextManager; +class ASTContext; +class BlockDecl; +class BlockInvocationContext; class CFGReverseBlockReachabilityAnalysis; class CFGStmtMap; -class LiveVariables; -class ManagedAnalysis; +class ImplicitParamDecl; +class LocationContext; +class LocationContextManager; class ParentMap; class PseudoConstantAnalysis; -class LocationContextManager; class StackFrameContext; -class BlockInvocationContext; -class AnalysisDeclContextManager; -class LocationContext; - -namespace idx { class TranslationUnit; } +class Stmt; +class VarDecl; /// The base class of a hierarchy of objects representing analyses tied /// to AnalysisDeclContext. class ManagedAnalysis { protected: - ManagedAnalysis() {} + ManagedAnalysis() = default; + public: virtual ~ManagedAnalysis(); @@ -61,7 +66,6 @@ public: // which creates the analysis object given an AnalysisDeclContext. }; - /// AnalysisDeclContext contains the context data for the function or method /// under analysis. class AnalysisDeclContext { @@ -75,18 +79,19 @@ class AnalysisDeclContext { std::unique_ptr<CFGStmtMap> cfgStmtMap; CFG::BuildOptions cfgBuildOptions; - CFG::BuildOptions::ForcedBlkExprs *forcedBlkExprs; + CFG::BuildOptions::ForcedBlkExprs *forcedBlkExprs = nullptr; - bool builtCFG, builtCompleteCFG; + bool builtCFG = false; + bool builtCompleteCFG = false; std::unique_ptr<ParentMap> PM; std::unique_ptr<PseudoConstantAnalysis> PCA; std::unique_ptr<CFGReverseBlockReachabilityAnalysis> CFA; llvm::BumpPtrAllocator A; - llvm::DenseMap<const BlockDecl*,void*> *ReferencedBlockVars; + llvm::DenseMap<const BlockDecl *,void *> *ReferencedBlockVars = nullptr; - void *ManagedAnalyses; + void *ManagedAnalyses = nullptr; public: AnalysisDeclContext(AnalysisDeclContextManager *Mgr, @@ -172,7 +177,7 @@ public: ParentMap &getParentMap(); PseudoConstantAnalysis *getPseudoConstantAnalysis(); - typedef const VarDecl * const * referenced_decls_iterator; + using referenced_decls_iterator = const VarDecl * const *; llvm::iterator_range<referenced_decls_iterator> getReferencedBlockVars(const BlockDecl *BD); @@ -200,12 +205,13 @@ public: if (!data) { data = T::create(*this); } - return static_cast<T*>(data); + return static_cast<T *>(data); } /// Returns true if the root namespace of the given declaration is the 'std' /// C++ namespace. static bool isInStdNamespace(const Decl *D); + private: ManagedAnalysis *&getAnalysisImpl(const void* tag); @@ -228,7 +234,7 @@ private: protected: LocationContext(ContextKind k, AnalysisDeclContext *ctx, const LocationContext *parent) - : Kind(k), Ctx(ctx), Parent(parent) {} + : Kind(k), Ctx(ctx), Parent(parent) {} public: virtual ~LocationContext(); @@ -266,7 +272,7 @@ public: virtual void Profile(llvm::FoldingSetNodeID &ID) = 0; void dumpStack( - raw_ostream &OS, StringRef Indent = "", const char *NL = "\n", + raw_ostream &OS, StringRef Indent = {}, const char *NL = "\n", const char *Sep = "", std::function<void(const LocationContext *)> printMoreInfoPerContext = [](const LocationContext *) {}) const; @@ -281,6 +287,8 @@ public: }; class StackFrameContext : public LocationContext { + friend class LocationContextManager; + // The callsite where this stack frame is established. const Stmt *CallSite; @@ -290,15 +298,14 @@ class StackFrameContext : public Locatio // The index of the callsite in the CFGBlock. unsigned Index; - friend class LocationContextManager; StackFrameContext(AnalysisDeclContext *ctx, const LocationContext *parent, const Stmt *s, const CFGBlock *blk, unsigned idx) - : LocationContext(StackFrame, ctx, parent), CallSite(s), - Block(blk), Index(idx) {} + : LocationContext(StackFrame, ctx, parent), CallSite(s), + Block(blk), Index(idx) {} public: - ~StackFrameContext() override {} + ~StackFrameContext() override = default; const Stmt *getCallSite() const { return CallSite; } @@ -325,15 +332,16 @@ public: }; class ScopeContext : public LocationContext { + friend class LocationContextManager; + const Stmt *Enter; - friend class LocationContextManager; ScopeContext(AnalysisDeclContext *ctx, const LocationContext *parent, const Stmt *s) - : LocationContext(Scope, ctx, parent), Enter(s) {} + : LocationContext(Scope, ctx, parent), Enter(s) {} public: - ~ScopeContext() override {} + ~ScopeContext() override = default; void Profile(llvm::FoldingSetNodeID &ID) override; @@ -348,20 +356,20 @@ public: }; class BlockInvocationContext : public LocationContext { + friend class LocationContextManager; + const BlockDecl *BD; // FIXME: Come up with a more type-safe way to model context-sensitivity. const void *ContextData; - friend class LocationContextManager; - BlockInvocationContext(AnalysisDeclContext *ctx, const LocationContext *parent, const BlockDecl *bd, const void *contextData) - : LocationContext(Block, ctx, parent), BD(bd), ContextData(contextData) {} + : LocationContext(Block, ctx, parent), BD(bd), ContextData(contextData) {} public: - ~BlockInvocationContext() override {} + ~BlockInvocationContext() override = default; const BlockDecl *getBlockDecl() const { return BD; } @@ -383,6 +391,7 @@ public: class LocationContextManager { llvm::FoldingSet<LocationContext> Contexts; + public: ~LocationContextManager(); @@ -411,8 +420,8 @@ private: }; class AnalysisDeclContextManager { - typedef llvm::DenseMap<const Decl *, std::unique_ptr<AnalysisDeclContext>> - ContextMap; + using ContextMap = + llvm::DenseMap<const Decl *, std::unique_ptr<AnalysisDeclContext>>; ContextMap Contexts; LocationContextManager LocContexts; @@ -495,5 +504,6 @@ private: } }; -} // end clang namespace -#endif +} // namespace clang + +#endif // LLVM_CLANG_ANALYSIS_ANALYSISDECLCONTEXT_H Modified: cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp?rev=328063&r1=328062&r2=328063&view=diff ============================================================================== --- cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp (original) +++ cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp Tue Mar 20 17:14:43 2018 @@ -1,4 +1,4 @@ -//== AnalysisDeclContext.cpp - Analysis context for Path Sens analysis -*- C++ -*-// +//===- AnalysisDeclContext.cpp - Analysis context for Path Sens analysis --===// // // The LLVM Compiler Infrastructure // @@ -7,59 +7,62 @@ // //===----------------------------------------------------------------------===// // -// This file defines AnalysisDeclContext, a class that manages the analysis context -// data for path sensitive analysis. +// This file defines AnalysisDeclContext, a class that manages the analysis +// context data for path sensitive analysis. // //===----------------------------------------------------------------------===// #include "clang/Analysis/AnalysisDeclContext.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" +#include "clang/AST/DeclBase.h" +#include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" +#include "clang/AST/Expr.h" +#include "clang/AST/LambdaCapture.h" #include "clang/AST/ParentMap.h" +#include "clang/AST/PrettyPrinter.h" +#include "clang/AST/Stmt.h" +#include "clang/AST/StmtCXX.h" #include "clang/AST/StmtVisitor.h" #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h" -#include "clang/Analysis/Analyses/LiveVariables.h" #include "clang/Analysis/Analyses/PseudoConstantAnalysis.h" #include "clang/Analysis/BodyFarm.h" #include "clang/Analysis/CFG.h" #include "clang/Analysis/CFGStmtMap.h" #include "clang/Analysis/Support/BumpVector.h" +#include "clang/Basic/LLVM.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Basic/SourceManager.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/FoldingSet.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/iterator_range.h" +#include "llvm/Support/Allocator.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/SaveAndRestore.h" #include "llvm/Support/raw_ostream.h" +#include <cassert> +#include <memory> using namespace clang; -typedef llvm::DenseMap<const void *, ManagedAnalysis *> ManagedAnalysisMap; +using ManagedAnalysisMap = llvm::DenseMap<const void *, ManagedAnalysis *>; AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr, const Decl *d, const CFG::BuildOptions &buildOptions) - : Manager(Mgr), - D(d), - cfgBuildOptions(buildOptions), - forcedBlkExprs(nullptr), - builtCFG(false), - builtCompleteCFG(false), - ReferencedBlockVars(nullptr), - ManagedAnalyses(nullptr) -{ + : Manager(Mgr), D(d), cfgBuildOptions(buildOptions) { cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs; } AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr, const Decl *d) -: Manager(Mgr), - D(d), - forcedBlkExprs(nullptr), - builtCFG(false), - builtCompleteCFG(false), - ReferencedBlockVars(nullptr), - ManagedAnalyses(nullptr) -{ + : Manager(Mgr), D(d) { cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs; } @@ -87,7 +90,7 @@ void AnalysisDeclContextManager::clear() Stmt *AnalysisDeclContext::getBody(bool &IsAutosynthesized) const { IsAutosynthesized = false; - if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { + if (const auto *FD = dyn_cast<FunctionDecl>(D)) { Stmt *Body = FD->getBody(); if (auto *CoroBody = dyn_cast_or_null<CoroutineBodyStmt>(Body)) Body = CoroBody->getBody(); @@ -100,7 +103,7 @@ Stmt *AnalysisDeclContext::getBody(bool } return Body; } - else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { + else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { Stmt *Body = MD->getBody(); if (Manager && Manager->synthesizeBodies()) { Stmt *SynthesizedBody = Manager->getBodyFarm().getBody(MD); @@ -110,10 +113,9 @@ Stmt *AnalysisDeclContext::getBody(bool } } return Body; - } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) + } else if (const auto *BD = dyn_cast<BlockDecl>(D)) return BD->getBody(); - else if (const FunctionTemplateDecl *FunTmpl - = dyn_cast_or_null<FunctionTemplateDecl>(D)) + else if (const auto *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D)) return FunTmpl->getTemplatedDecl()->getBody(); llvm_unreachable("unknown code decl"); @@ -142,9 +144,9 @@ static bool isSelfDecl(const VarDecl *VD } const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const { - if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) + if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) return MD->getSelfDecl(); - if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { + if (const auto *BD = dyn_cast<BlockDecl>(D)) { // See if 'self' was captured by the block. for (const auto &I : BD->captures()) { const VarDecl *VD = I.getVariable(); @@ -161,7 +163,7 @@ const ImplicitParamDecl *AnalysisDeclCon if (!parent->isLambda()) return nullptr; - for (const LambdaCapture &LC : parent->captures()) { + for (const auto &LC : parent->captures()) { if (!LC.capturesVariable()) continue; @@ -177,7 +179,7 @@ void AnalysisDeclContext::registerForced if (!forcedBlkExprs) forcedBlkExprs = new CFG::BuildOptions::ForcedBlkExprs(); // Default construct an entry for 'stmt'. - if (const Expr *e = dyn_cast<Expr>(stmt)) + if (const auto *e = dyn_cast<Expr>(stmt)) stmt = e->IgnoreParens(); (void) (*forcedBlkExprs)[stmt]; } @@ -185,7 +187,7 @@ void AnalysisDeclContext::registerForced const CFGBlock * AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) { assert(forcedBlkExprs); - if (const Expr *e = dyn_cast<Expr>(stmt)) + if (const auto *e = dyn_cast<Expr>(stmt)) stmt = e->IgnoreParens(); CFG::BuildOptions::ForcedBlkExprs::const_iterator itr = forcedBlkExprs->find(stmt); @@ -269,13 +271,13 @@ CFGReverseBlockReachabilityAnalysis *Ana } void AnalysisDeclContext::dumpCFG(bool ShowColors) { - getCFG()->dump(getASTContext().getLangOpts(), ShowColors); + getCFG()->dump(getASTContext().getLangOpts(), ShowColors); } ParentMap &AnalysisDeclContext::getParentMap() { if (!PM) { PM.reset(new ParentMap(getBody())); - if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(getDecl())) { + if (const auto *C = dyn_cast<CXXConstructorDecl>(getDecl())) { for (const auto *I : C->inits()) { PM->addStmt(I->getInit()); } @@ -295,7 +297,7 @@ PseudoConstantAnalysis *AnalysisDeclCont } AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D) { - if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { + if (const auto *FD = dyn_cast<FunctionDecl>(D)) { // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl // that has the body. FD->hasBody(FD); @@ -318,7 +320,7 @@ AnalysisDeclContext::getStackFrame(Locat const BlockInvocationContext * AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent, - const clang::BlockDecl *BD, + const BlockDecl *BD, const void *ContextData) { return getLocationContextManager().getBlockInvocationContext(this, parent, BD, ContextData); @@ -326,7 +328,7 @@ AnalysisDeclContext::getBlockInvocationC bool AnalysisDeclContext::isInStdNamespace(const Decl *D) { const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext(); - const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC); + const auto *ND = dyn_cast<NamespaceDecl>(DC); if (!ND) return false; @@ -339,7 +341,7 @@ bool AnalysisDeclContext::isInStdNamespa return ND->isStdNamespace(); } -LocationContextManager & AnalysisDeclContext::getLocationContextManager() { +LocationContextManager &AnalysisDeclContext::getLocationContextManager() { assert(Manager && "Cannot create LocationContexts without an AnalysisDeclContextManager!"); return Manager->getLocationContextManager(); @@ -402,7 +404,7 @@ LocationContextManager::getStackFrame(An llvm::FoldingSetNodeID ID; StackFrameContext::Profile(ID, ctx, parent, s, blk, idx); void *InsertPos; - StackFrameContext *L = + auto *L = cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos)); if (!L) { L = new StackFrameContext(ctx, parent, s, blk, idx); @@ -426,7 +428,7 @@ LocationContextManager::getBlockInvocati llvm::FoldingSetNodeID ID; BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData); void *InsertPos; - BlockInvocationContext *L = + auto *L = cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos)); if (!L) { @@ -443,7 +445,7 @@ LocationContextManager::getBlockInvocati const StackFrameContext *LocationContext::getCurrentStackFrame() const { const LocationContext *LC = this; while (LC) { - if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC)) + if (const auto *SFC = dyn_cast<StackFrameContext>(LC)) return SFC; LC = LC->getParent(); } @@ -486,12 +488,11 @@ void LocationContext::dumpStack( unsigned Frame = 0; for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) { - switch (LCtx->getKind()) { case StackFrame: OS << Indent << '#' << Frame << ' '; ++Frame; - if (const NamedDecl *D = dyn_cast<NamedDecl>(LCtx->getDecl())) + if (const auto *D = dyn_cast<NamedDecl>(LCtx->getDecl())) OS << "Calling " << D->getQualifiedNameAsString(); else OS << "Calling anonymous code"; @@ -526,25 +527,27 @@ LLVM_DUMP_METHOD void LocationContext::d //===----------------------------------------------------------------------===// namespace { + class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{ - BumpVector<const VarDecl*> &BEVals; + BumpVector<const VarDecl *> &BEVals; BumpVectorContext &BC; - llvm::SmallPtrSet<const VarDecl*, 4> Visited; - llvm::SmallPtrSet<const DeclContext*, 4> IgnoredContexts; + llvm::SmallPtrSet<const VarDecl *, 4> Visited; + llvm::SmallPtrSet<const DeclContext *, 4> IgnoredContexts; + public: FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals, BumpVectorContext &bc) - : BEVals(bevals), BC(bc) {} + : BEVals(bevals), BC(bc) {} void VisitStmt(Stmt *S) { - for (Stmt *Child : S->children()) + for (auto *Child : S->children()) if (Child) Visit(Child); } void VisitDeclRefExpr(DeclRefExpr *DR) { // Non-local variables are also directly modified. - if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { + if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) { if (!VD->hasLocalStorage()) { if (Visited.insert(VD).second) BEVals.push_back(VD, BC); @@ -562,15 +565,16 @@ public: for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(), et = PE->semantics_end(); it != et; ++it) { Expr *Semantic = *it; - if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic)) + if (auto *OVE = dyn_cast<OpaqueValueExpr>(Semantic)) Semantic = OVE->getSourceExpr(); Visit(Semantic); } } }; -} // end anonymous namespace -typedef BumpVector<const VarDecl*> DeclVec; +} // namespace + +using DeclVec = BumpVector<const VarDecl *>; static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD, void *&Vec, @@ -616,7 +620,7 @@ ManagedAnalysis *&AnalysisDeclContext::g // Cleanup. //===----------------------------------------------------------------------===// -ManagedAnalysis::~ManagedAnalysis() {} +ManagedAnalysis::~ManagedAnalysis() = default; AnalysisDeclContext::~AnalysisDeclContext() { delete forcedBlkExprs; @@ -629,7 +633,7 @@ AnalysisDeclContext::~AnalysisDeclContex } } -LocationContext::~LocationContext() {} +LocationContext::~LocationContext() = default; LocationContextManager::~LocationContextManager() { clear(); @@ -642,7 +646,5 @@ void LocationContextManager::clear() { ++I; delete LC; } - Contexts.clear(); } - Modified: cfe/trunk/lib/Analysis/UninitializedValues.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/UninitializedValues.cpp?rev=328063&r1=328062&r2=328063&view=diff ============================================================================== --- cfe/trunk/lib/Analysis/UninitializedValues.cpp (original) +++ cfe/trunk/lib/Analysis/UninitializedValues.cpp Tue Mar 20 17:14:43 2018 @@ -1,4 +1,4 @@ -//==- UninitializedValues.cpp - Find Uninitialized Values -------*- C++ --*-==// +//===- UninitializedValues.cpp - Find Uninitialized Values ----------------===// // // The LLVM Compiler Infrastructure // @@ -11,23 +11,31 @@ // //===----------------------------------------------------------------------===// -#include "clang/AST/ASTContext.h" +#include "clang/Analysis/Analyses/UninitializedValues.h" #include "clang/AST/Attr.h" #include "clang/AST/Decl.h" -#include "clang/AST/DeclCXX.h" +#include "clang/AST/DeclBase.h" +#include "clang/AST/Expr.h" +#include "clang/AST/OperationKinds.h" +#include "clang/AST/Stmt.h" +#include "clang/AST/StmtObjC.h" #include "clang/AST/StmtVisitor.h" +#include "clang/AST/Type.h" #include "clang/Analysis/Analyses/PostOrderCFGView.h" -#include "clang/Analysis/Analyses/UninitializedValues.h" #include "clang/Analysis/AnalysisDeclContext.h" #include "clang/Analysis/CFG.h" #include "clang/Analysis/DomainSpecific/ObjCNoReturn.h" +#include "clang/Basic/LLVM.h" +#include "llvm/ADT/BitVector.h" #include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/PackedVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallVector.h" -#include "llvm/Support/SaveAndRestore.h" -#include <utility> +#include "llvm/Support/Casting.h" +#include <algorithm> +#include <cassert> using namespace clang; @@ -48,10 +56,12 @@ static bool isTrackedVar(const VarDecl * //====------------------------------------------------------------------------// namespace { + class DeclToIndex { llvm::DenseMap<const VarDecl *, unsigned> map; + public: - DeclToIndex() {} + DeclToIndex() = default; /// Compute the actual mapping from declarations to bits. void computeMap(const DeclContext &dc); @@ -62,7 +72,8 @@ public: /// Returns the bit vector index for a given declaration. Optional<unsigned> getValueIndex(const VarDecl *d) const; }; -} + +} // namespace void DeclToIndex::computeMap(const DeclContext &dc) { unsigned count = 0; @@ -96,25 +107,28 @@ enum Value { Unknown = 0x0, /* 0 static bool isUninitialized(const Value v) { return v >= Uninitialized; } + static bool isAlwaysUninit(const Value v) { return v == Uninitialized; } namespace { -typedef llvm::PackedVector<Value, 2, llvm::SmallBitVector> ValueVector; +using ValueVector = llvm::PackedVector<Value, 2, llvm::SmallBitVector>; class CFGBlockValues { const CFG &cfg; SmallVector<ValueVector, 8> vals; ValueVector scratch; DeclToIndex declToIndex; + public: CFGBlockValues(const CFG &cfg); unsigned getNumEntries() const { return declToIndex.size(); } void computeSetOfDeclarations(const DeclContext &dc); + ValueVector &getValueVector(const CFGBlock *block) { return vals[block->getBlockID()]; } @@ -138,7 +152,8 @@ public: return getValueVector(block)[idx.getValue()]; } }; -} // end anonymous namespace + +} // namespace CFGBlockValues::CFGBlockValues(const CFG &c) : cfg(c), vals(0) {} @@ -150,17 +165,16 @@ void CFGBlockValues::computeSetOfDeclara if (!n) return; vals.resize(n); - for (unsigned i = 0; i < n; ++i) - vals[i].resize(decls); + for (auto &val : vals) + val.resize(decls); } #if DEBUG_LOGGING static void printVector(const CFGBlock *block, ValueVector &bv, unsigned num) { llvm::errs() << block->getBlockID() << " :"; - for (unsigned i = 0; i < bv.size(); ++i) { - llvm::errs() << ' ' << bv[i]; - } + for (const auto &i : bv) + llvm::errs() << ' ' << i; llvm::errs() << " : " << num << '\n'; } #endif @@ -204,28 +218,31 @@ ValueVector::reference CFGBlockValues::o //====------------------------------------------------------------------------// namespace { + class DataflowWorklist { PostOrderCFGView::iterator PO_I, PO_E; SmallVector<const CFGBlock *, 20> worklist; llvm::BitVector enqueuedBlocks; + public: DataflowWorklist(const CFG &cfg, PostOrderCFGView &view) - : PO_I(view.begin()), PO_E(view.end()), - enqueuedBlocks(cfg.getNumBlockIDs(), true) { - // Treat the first block as already analyzed. - if (PO_I != PO_E) { - assert(*PO_I == &cfg.getEntry()); - enqueuedBlocks[(*PO_I)->getBlockID()] = false; - ++PO_I; - } - } + : PO_I(view.begin()), PO_E(view.end()), + enqueuedBlocks(cfg.getNumBlockIDs(), true) { + // Treat the first block as already analyzed. + if (PO_I != PO_E) { + assert(*PO_I == &cfg.getEntry()); + enqueuedBlocks[(*PO_I)->getBlockID()] = false; + ++PO_I; + } + } void enqueueSuccessors(const CFGBlock *block); const CFGBlock *dequeue(); }; -} -void DataflowWorklist::enqueueSuccessors(const clang::CFGBlock *block) { +} // namespace + +void DataflowWorklist::enqueueSuccessors(const CFGBlock *block) { for (CFGBlock::const_succ_iterator I = block->succ_begin(), E = block->succ_end(); I != E; ++I) { const CFGBlock *Successor = *I; @@ -250,9 +267,8 @@ const CFGBlock *DataflowWorklist::dequeu B = *PO_I; ++PO_I; } - else { + else return nullptr; - } assert(enqueuedBlocks[B->getBlockID()] == true); enqueuedBlocks[B->getBlockID()] = false; @@ -264,9 +280,11 @@ const CFGBlock *DataflowWorklist::dequeu //====------------------------------------------------------------------------// namespace { + class FindVarResult { const VarDecl *vd; const DeclRefExpr *dr; + public: FindVarResult(const VarDecl *vd, const DeclRefExpr *dr) : vd(vd), dr(dr) {} @@ -274,10 +292,12 @@ public: const VarDecl *getDecl() const { return vd; } }; +} // namespace + static const Expr *stripCasts(ASTContext &C, const Expr *Ex) { while (Ex) { Ex = Ex->IgnoreParenNoopCasts(C); - if (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { + if (const auto *CE = dyn_cast<CastExpr>(Ex)) { if (CE->getCastKind() == CK_LValueBitCast) { Ex = CE->getSubExpr(); continue; @@ -291,14 +311,16 @@ static const Expr *stripCasts(ASTContext /// If E is an expression comprising a reference to a single variable, find that /// variable. static FindVarResult findVar(const Expr *E, const DeclContext *DC) { - if (const DeclRefExpr *DRE = - dyn_cast<DeclRefExpr>(stripCasts(DC->getParentASTContext(), E))) - if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) + if (const auto *DRE = + dyn_cast<DeclRefExpr>(stripCasts(DC->getParentASTContext(), E))) + if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) if (isTrackedVar(VD, DC)) return FindVarResult(VD, DRE); return FindVarResult(nullptr, nullptr); } +namespace { + /// \brief Classify each DeclRefExpr as an initialization or a use. Any /// DeclRefExpr which isn't explicitly classified will be assumed to have /// escaped the analysis and will be treated as an initialization. @@ -313,7 +335,7 @@ public: private: const DeclContext *DC; - llvm::DenseMap<const DeclRefExpr*, Class> Classification; + llvm::DenseMap<const DeclRefExpr *, Class> Classification; bool isTrackedVar(const VarDecl *VD) const { return ::isTrackedVar(VD, DC); @@ -338,21 +360,22 @@ public: if (I != Classification.end()) return I->second; - const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()); + const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); if (!VD || !isTrackedVar(VD)) return Ignore; return Init; } }; -} + +} // namespace static const DeclRefExpr *getSelfInitExpr(VarDecl *VD) { if (VD->getType()->isRecordType()) return nullptr; if (Expr *Init = VD->getInit()) { - const DeclRefExpr *DRE - = dyn_cast<DeclRefExpr>(stripCasts(VD->getASTContext(), Init)); + const auto *DRE = + dyn_cast<DeclRefExpr>(stripCasts(VD->getASTContext(), Init)); if (DRE && DRE->getDecl() == VD) return DRE; } @@ -362,32 +385,31 @@ static const DeclRefExpr *getSelfInitExp void ClassifyRefs::classify(const Expr *E, Class C) { // The result of a ?: could also be an lvalue. E = E->IgnoreParens(); - if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { + if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { classify(CO->getTrueExpr(), C); classify(CO->getFalseExpr(), C); return; } - if (const BinaryConditionalOperator *BCO = - dyn_cast<BinaryConditionalOperator>(E)) { + if (const auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) { classify(BCO->getFalseExpr(), C); return; } - if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { + if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { classify(OVE->getSourceExpr(), C); return; } - if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { - if (VarDecl *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) { + if (const auto *ME = dyn_cast<MemberExpr>(E)) { + if (const auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) { if (!VD->isStaticDataMember()) classify(ME->getBase(), C); } return; } - if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { + if (const auto *BO = dyn_cast<BinaryOperator>(E)) { switch (BO->getOpcode()) { case BO_PtrMemD: case BO_PtrMemI: @@ -408,7 +430,7 @@ void ClassifyRefs::classify(const Expr * void ClassifyRefs::VisitDeclStmt(DeclStmt *DS) { for (auto *DI : DS->decls()) { - VarDecl *VD = dyn_cast<VarDecl>(DI); + auto *VD = dyn_cast<VarDecl>(DI); if (VD && isTrackedVar(VD)) if (const DeclRefExpr *DRE = getSelfInitExpr(VD)) Classification[DRE] = SelfInit; @@ -457,7 +479,7 @@ void ClassifyRefs::VisitCallExpr(CallExp classify((*I), Ignore); } else if (isPointerToConst((*I)->getType())) { const Expr *Ex = stripCasts(DC->getParentASTContext(), *I); - const UnaryOperator *UO = dyn_cast<UnaryOperator>(Ex); + const auto *UO = dyn_cast<UnaryOperator>(Ex); if (UO && UO->getOpcode() == UO_AddrOf) Ex = UO->getSubExpr(); classify(Ex, Ignore); @@ -468,7 +490,7 @@ void ClassifyRefs::VisitCallExpr(CallExp void ClassifyRefs::VisitCastExpr(CastExpr *CE) { if (CE->getCastKind() == CK_LValueToRValue) classify(CE->getSubExpr(), Use); - else if (CStyleCastExpr *CSE = dyn_cast<CStyleCastExpr>(CE)) { + else if (const auto *CSE = dyn_cast<CStyleCastExpr>(CE)) { if (CSE->getType()->isVoidType()) { // Squelch any detected load of an uninitialized value if // we cast it to void. @@ -483,6 +505,7 @@ void ClassifyRefs::VisitCastExpr(CastExp //====------------------------------------------------------------------------// namespace { + class TransferFunctions : public StmtVisitor<TransferFunctions> { CFGBlockValues &vals; const CFG &cfg; @@ -497,9 +520,9 @@ public: const CFGBlock *block, AnalysisDeclContext &ac, const ClassifyRefs &classification, UninitVariablesHandler &handler) - : vals(vals), cfg(cfg), block(block), ac(ac), - classification(classification), objCNoRet(ac.getASTContext()), - handler(handler) {} + : vals(vals), cfg(cfg), block(block), ac(ac), + classification(classification), objCNoRet(ac.getASTContext()), + handler(handler) {} void reportUse(const Expr *ex, const VarDecl *vd); @@ -627,8 +650,7 @@ public: // Scan the frontier, looking for blocks where the variable was // uninitialized. - for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) { - const CFGBlock *Block = *BI; + for (const auto *Block : cfg) { unsigned BlockID = Block->getBlockID(); const Stmt *Term = Block->getTerminator(); if (SuccsVisited[BlockID] && SuccsVisited[BlockID] < Block->succ_size() && @@ -668,7 +690,8 @@ public: return Use; } }; -} + +} // namespace void TransferFunctions::reportUse(const Expr *ex, const VarDecl *vd) { Value v = vals[vd]; @@ -678,8 +701,8 @@ void TransferFunctions::reportUse(const void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS) { // This represents an initialization of the 'element' value. - if (DeclStmt *DS = dyn_cast<DeclStmt>(FS->getElement())) { - const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); + if (const auto *DS = dyn_cast<DeclStmt>(FS->getElement())) { + const auto *VD = cast<VarDecl>(DS->getSingleDecl()); if (isTrackedVar(VD)) vals[VD] = Initialized; } @@ -748,7 +771,7 @@ void TransferFunctions::VisitBinaryOpera void TransferFunctions::VisitDeclStmt(DeclStmt *DS) { for (auto *DI : DS->decls()) { - VarDecl *VD = dyn_cast<VarDecl>(DI); + auto *VD = dyn_cast<VarDecl>(DI); if (VD && isTrackedVar(VD)) { if (getSelfInitExpr(VD)) { // If the initializer consists solely of a reference to itself, we @@ -815,34 +838,32 @@ static bool runOnBlock(const CFGBlock *b } // Apply the transfer function. TransferFunctions tf(vals, cfg, block, ac, classification, handler); - for (CFGBlock::const_iterator I = block->begin(), E = block->end(); - I != E; ++I) { - if (Optional<CFGStmt> cs = I->getAs<CFGStmt>()) - tf.Visit(const_cast<Stmt*>(cs->getStmt())); + for (const auto &I : *block) { + if (Optional<CFGStmt> cs = I.getAs<CFGStmt>()) + tf.Visit(const_cast<Stmt *>(cs->getStmt())); } return vals.updateValueVectorWithScratch(block); } +namespace { + /// PruneBlocksHandler is a special UninitVariablesHandler that is used /// to detect when a CFGBlock has any *potential* use of an uninitialized /// variable. It is mainly used to prune out work during the final /// reporting pass. -namespace { struct PruneBlocksHandler : public UninitVariablesHandler { - PruneBlocksHandler(unsigned numBlocks) - : hadUse(numBlocks, false), hadAnyUse(false), - currentBlock(0) {} - - ~PruneBlocksHandler() override {} - /// Records if a CFGBlock had a potential use of an uninitialized variable. llvm::BitVector hadUse; /// Records if any CFGBlock had a potential use of an uninitialized variable. - bool hadAnyUse; + bool hadAnyUse = false; /// The current block to scribble use information. - unsigned currentBlock; + unsigned currentBlock = 0; + + PruneBlocksHandler(unsigned numBlocks) : hadUse(numBlocks, false) {} + + ~PruneBlocksHandler() override = default; void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) override { @@ -858,7 +879,8 @@ struct PruneBlocksHandler : public Unini hadAnyUse = true; } }; -} + +} // namespace void clang::runUninitializedVariablesAnalysis( const DeclContext &dc, @@ -881,7 +903,7 @@ void clang::runUninitializedVariablesAna const CFGBlock &entry = cfg.getEntry(); ValueVector &vec = vals.getValueVector(&entry); const unsigned n = vals.getNumEntries(); - for (unsigned j = 0; j < n ; ++j) { + for (unsigned j = 0; j < n; ++j) { vec[j] = Uninitialized; } @@ -909,13 +931,11 @@ void clang::runUninitializedVariablesAna return; // Run through the blocks one more time, and report uninitialized variables. - for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) { - const CFGBlock *block = *BI; + for (const auto *block : cfg) if (PBH.hadUse[block->getBlockID()]) { runOnBlock(block, cfg, ac, vals, classification, wasAnalyzed, handler); ++stats.NumBlockVisits; } - } } -UninitVariablesHandler::~UninitVariablesHandler() {} +UninitVariablesHandler::~UninitVariablesHandler() = default; _______________________________________________ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits