clang 23.0.0git
AnalysisDeclContext.h
Go to the documentation of this file.
1//===- AnalysisDeclContext.h - Context for path sensitivity -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This file defines AnalysisDeclContext, a class that manages the analysis
11/// context data for context sensitive and path sensitive analysis.
12/// It also defines the helper classes to model entering, leaving or inlining
13/// function calls.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_ANALYSIS_ANALYSISDECLCONTEXT_H
18#define LLVM_CLANG_ANALYSIS_ANALYSISDECLCONTEXT_H
19
20#include "clang/AST/DeclBase.h"
22#include "clang/Analysis/CFG.h"
25#include "clang/Basic/LLVM.h"
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/iterator_range.h"
30#include "llvm/Support/Allocator.h"
31#include <functional>
32#include <memory>
33
34namespace clang {
35
37class ASTContext;
38class BlockDecl;
42class ParentMap;
43class StackFrame;
44class Stmt;
45class VarDecl;
46
47/// The base class of a hierarchy of objects representing analyses tied
48/// to AnalysisDeclContext.
50protected:
51 ManagedAnalysis() = default;
52
53public:
55
56 // Subclasses need to implement:
57 //
58 // static const void *getTag();
59 //
60 // Which returns a fixed pointer address to distinguish classes of
61 // analysis objects. They also need to implement:
62 //
63 // static [Derived*] create(AnalysisDeclContext &Ctx);
64 //
65 // which creates the analysis object given an AnalysisDeclContext.
66};
67
68/// AnalysisDeclContext contains the context data for the function, method
69/// or block under analysis.
71 // Backpoint to the AnalysisManager object that created this
72 // AnalysisDeclContext. This may be null.
74
75 const Decl *const D;
76
77 std::unique_ptr<CFG> cfg, completeCFG;
78 std::optional<CFGStmtMap> cfgStmtMap;
79
80 CFG::BuildOptions cfgBuildOptions;
81 CFG::BuildOptions::ForcedBlkExprs *forcedBlkExprs = nullptr;
82
83 bool builtCFG = false;
84 bool builtCompleteCFG = false;
85 std::unique_ptr<ParentMap> PM;
86 std::unique_ptr<CFGReverseBlockReachabilityAnalysis> CFA;
87
88 llvm::BumpPtrAllocator A;
89
90 llvm::DenseMap<const BlockDecl *, void *> *ReferencedBlockVars = nullptr;
91
92 void *ManagedAnalyses = nullptr;
93
94public:
96
98 const CFG::BuildOptions &BuildOptions);
99
101
102 ASTContext &getASTContext() const { return D->getASTContext(); }
103
104 const Decl *getDecl() const { return D; }
105
106 AnalysisDeclContextManager *getManager() const { return ADCMgr; }
107
108 CFG::BuildOptions &getCFGBuildOptions() { return cfgBuildOptions; }
109
111 return cfgBuildOptions;
112 }
113
114 /// \returns Whether we are adding exception handling edges from CallExprs.
115 /// If this is false, then try/catch statements and blocks reachable from them
116 /// can appear to be dead in the CFG, analysis passes must cope with that.
117 bool getAddEHEdges() const { return cfgBuildOptions.AddEHEdges; }
118 bool getUseUnoptimizedCFG() const {
119 return !cfgBuildOptions.PruneTriviallyFalseEdges;
120 }
121 bool getAddImplicitDtors() const { return cfgBuildOptions.AddImplicitDtors; }
122 bool getAddInitializers() const { return cfgBuildOptions.AddInitializers; }
123
126
127 /// \returns The body of the stored Decl \c D.
128 Stmt *getBody() const;
129
130 /// \copydoc AnalysisDeclContext::getBody()
131 /// \param[out] IsAutosynthesized Specifies if the body is auto-generated
132 /// by the BodyFarm.
133 Stmt *getBody(bool &IsAutosynthesized) const;
134
135 /// \returns Whether the body of the Decl \c D is generated by the BodyFarm.
136 ///
137 /// \note The lookup is not free. We are going to call getBody behind
138 /// the scenes.
139 /// \sa getBody
140 bool isBodyAutosynthesized() const;
141
142 /// \returns Whether the body of the Decl \c D is generated by the BodyFarm
143 /// from a model file.
144 ///
145 /// \note The lookup is not free. We are going to call getBody behind
146 /// the scenes.
147 /// \sa getBody
149
150 CFG *getCFG();
151
152 const CFGStmtMap *getCFGStmtMap();
153
155
156 /// \returns A version of the CFG without any edges pruned.
158
159 void dumpCFG(bool ShowColors);
160
161 /// \returns Whether we have built a CFG for this analysis context.
162 ///
163 /// \note This doesn't correspond to whether or not a valid CFG exists, it
164 /// corresponds to whether we *attempted* to build one.
165 bool isCFGBuilt() const { return builtCFG; }
166
168
169 using referenced_decls_iterator = const VarDecl *const *;
170
171 llvm::iterator_range<referenced_decls_iterator>
173
174 /// \returns The ImplicitParamDecl associated with \c self if this
175 /// AnalysisDeclContext wraps an ObjCMethodDecl or nullptr otherwise.
176 const ImplicitParamDecl *getSelfDecl() const;
177
178 /// \copydoc StackFrameManager::getStackFrame()
179 const StackFrame *getStackFrame(const StackFrame *ParentSF, const void *Data,
180 const Expr *E, const CFGBlock *Blk,
181 unsigned BlockCount, unsigned Index);
182
183 /// \returns The specified analysis object, lazily running the analysis if
184 /// necessary or nullptr if the analysis could not run.
185 template <typename T> T *getAnalysis() {
186 const void *tag = T::getTag();
187 std::unique_ptr<ManagedAnalysis> &data = getAnalysisImpl(tag);
188 if (!data)
189 data = T::create(*this);
190 return static_cast<T *>(data.get());
191 }
192
193 /// \returns Whether the root namespace of \p D is the \c std C++ namespace.
194 static bool isInStdNamespace(const Decl *D);
195
196 static std::string getFunctionName(const Decl *D);
197
198private:
199 std::unique_ptr<ManagedAnalysis> &getAnalysisImpl(const void *tag);
200
201 StackFrameManager &getStackFrameManager();
202};
203
204/// It represents a stack frame of the call stack
205class StackFrame final : public llvm::FoldingSetNode {
206 friend class StackFrameManager;
207
208 // AnalysisDeclContext can't be const since some methods may modify its
209 // member.
211
212 const StackFrame *Parent;
213
214 int64_t ID;
215
216 // Extra data for BlockInvocations
217 const void *Data;
218
219 // The call site where this stack frame is established.
220 const Expr *CallSite;
221
222 // The parent block of the call site.
223 const CFGBlock *Block;
224
225 // The number of times the 'Block' has been visited.
226 // It allows discriminating between stack frames of the same call that is
227 // called multiple times in a loop.
228 const unsigned BlockCount;
229
230 // The index of the call site in the CFGBlock.
231 const unsigned Index;
232
233public:
235 const void *Data, const Expr *E, const CFGBlock *Block,
236 unsigned BlockCount, unsigned Index, int64_t ID)
237 : Ctx(ADC), Parent(Parent), ID(ID), Data(Data), CallSite(E), Block(Block),
238 BlockCount(BlockCount), Index(Index) {
239 assert(ADC);
240 }
241
242 ~StackFrame() = default;
243
244 LLVM_ATTRIBUTE_RETURNS_NONNULL
246
247 /// It might return null.
248 const StackFrame *getParent() const { return Parent; }
249
250 int64_t getID() const { return ID; }
251
252 bool isParentOf(const StackFrame *SF) const;
253
254 const Decl *getDecl() const { return Ctx->getDecl(); }
255
256 CFG *getCFG() const { return Ctx->getCFG(); }
257
258 template <typename T> T *getAnalysis() const { return Ctx->getAnalysis<T>(); }
259
260 const ParentMap &getParentMap() const { return Ctx->getParentMap(); }
261
262 /// \copydoc AnalysisDeclContext::getSelfDecl()
263 const ImplicitParamDecl *getSelfDecl() const { return Ctx->getSelfDecl(); }
264
265 const void *getData() const { return Data; }
266
267 const Expr *getCallSite() const { return CallSite; }
268
269 const CFGBlock *getCallSiteBlock() const { return Block; }
270
271 /// \returns Whether the current StackFrame has no caller context.
272 bool inTopFrame() const { return getParent() == nullptr; }
273
274 unsigned getIndex() const { return Index; }
275
276 CFGElement getCallSiteCFGElement() const { return (*Block)[Index]; }
277
278 /// Prints out the call stack in \c json format.
279 ///
280 /// \param Out The out stream.
281 /// \param NL The newline.
282 /// \param Space The space count for indentation.
283 /// \param IsDot Whether the output format is \c dot.
284 /// \param printMoreInfoPerStackFrame
285 /// A callback to print more information for each stack frame, for example:
286 /// \code
287 /// [&](const StackFrame *SF) { SF->dump(); }
288 /// \endcode
289 void printJson(
290 raw_ostream &Out, const char *NL = "\n", unsigned int Space = 0,
291 bool IsDot = false,
292 std::function<void(const StackFrame *)> printMoreInfoPerStackFrame =
293 [](const StackFrame *) {}) const;
294
295 /// Prints out the call stack.
296 ///
297 /// \param Out The out stream.
298 LLVM_DUMP_METHOD void dumpStack(raw_ostream &Out) const;
299
300 LLVM_DUMP_METHOD void dump() const;
301
302 void Profile(llvm::FoldingSetNodeID &ID);
303
304 static void Profile(llvm::FoldingSetNodeID &ID, AnalysisDeclContext *ADC,
305 const StackFrame *SF, const void *Data, const Expr *E,
306 const CFGBlock *Block, unsigned BlockCount,
307 unsigned Index) {
308 ID.AddPointer(ADC);
309 ID.AddPointer(SF);
310 ID.AddPointer(E);
311 ID.AddPointer(Data);
312 ID.AddPointer(Block);
313 ID.AddInteger(BlockCount);
314 ID.AddInteger(Index);
315 }
316};
317
319 llvm::FoldingSet<StackFrame> Frames;
320
321 // ID used for generating a new stack frame.
322 int64_t NewID = 0;
323
324public:
326
327 /// Obtain a context of the call stack using its parent context.
328 ///
329 /// \param ADC The AnalysisDeclContext.
330 /// \param ParentSF The parent context of this newly created
331 /// context.
332 /// \param Data Extra data in case this StackFrame is
333 /// created for a BlockInvocation.
334 /// \param E The call expression.
335 /// \param Block The basic block.
336 /// \param BlockCount The current count of entering into \p Block.
337 /// \param StmtIdx The index of the call expression \p E among the
338 /// statements of the CFGBlock \p Block.
339 /// \returns The stack frame context corresponding to the call.
341 const StackFrame *ParentSF, const void *Data,
342 const Expr *E, const CFGBlock *Block,
343 unsigned BlockCount, unsigned StmtIdx);
344
345 /// Discard all previously created StackFrame objects.
346 void clear();
347};
348
350 using ContextMap =
351 llvm::DenseMap<const Decl *, std::unique_ptr<AnalysisDeclContext>>;
352
353 ContextMap Contexts;
354 StackFrameManager SFMgr;
355 CFG::BuildOptions cfgBuildOptions;
356
357 // Pointer to an interface that can provide function bodies for
358 // declarations from external source.
359 std::unique_ptr<CodeInjector> Injector;
360
361 // A factory for creating and caching implementations for common
362 // methods during the analysis.
363 BodyFarm FunctionBodyFarm;
364
365 // Flag to indicate whether or not bodies should be synthesized
366 // for well-known functions.
367 bool SynthesizeBodies;
368
369public:
371 ASTContext &ASTCtx, bool useUnoptimizedCFG = false,
372 bool addImplicitDtors = false, bool addInitializers = false,
373 bool addTemporaryDtors = false, bool addLifetime = false,
374 bool addLoopExit = false, bool addScopes = false,
375 bool synthesizeBodies = false, bool addStaticInitBranches = false,
376 bool addCXXNewAllocator = true, bool addRichCXXConstructors = true,
377 bool markElidedCXXConstructors = true, bool addVirtualBaseBranches = true,
378 std::unique_ptr<CodeInjector> injector = nullptr);
379
381
382 bool getUseUnoptimizedCFG() const {
383 return !cfgBuildOptions.PruneTriviallyFalseEdges;
384 }
385
386 CFG::BuildOptions &getCFGBuildOptions() { return cfgBuildOptions; }
387
388 /// \returns Whether faux bodies should be synthesized for known functions.
389 bool synthesizeBodies() const { return SynthesizeBodies; }
390
391 /// Obtain the beginning context of the analysis.
392 ///
393 /// \returns The top level stack frame for \p D.
395 return SFMgr.getStackFrame(getContext(D), nullptr, nullptr, nullptr,
396 nullptr, 0, 0);
397 }
398
400
401 /// Discard all previously created AnalysisDeclContexts.
402 void clear();
403
404private:
406
407 StackFrameManager &getStackFrameManager() { return SFMgr; }
408};
409
410} // namespace clang
411
412#endif // LLVM_CLANG_ANALYSIS_ANALYSISDECLCONTEXT_H
Defines the clang::CodeInjector interface which is responsible for injecting AST of function definiti...
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
AnalysisDeclContextManager(ASTContext &ASTCtx, bool useUnoptimizedCFG=false, bool addImplicitDtors=false, bool addInitializers=false, bool addTemporaryDtors=false, bool addLifetime=false, bool addLoopExit=false, bool addScopes=false, bool synthesizeBodies=false, bool addStaticInitBranches=false, bool addCXXNewAllocator=true, bool addRichCXXConstructors=true, bool markElidedCXXConstructors=true, bool addVirtualBaseBranches=true, std::unique_ptr< CodeInjector > injector=nullptr)
const StackFrame * getTopStackFrame(const Decl *D)
Obtain the beginning context of the analysis.
void clear()
Discard all previously created AnalysisDeclContexts.
AnalysisDeclContext * getContext(const Decl *D)
AnalysisDeclContext contains the context data for the function, method or block under analysis.
static std::string getFunctionName(const Decl *D)
void registerForcedBlockExpression(const Stmt *stmt)
const CFGBlock * getBlockForRegisteredExpression(const Stmt *stmt)
const VarDecl *const * referenced_decls_iterator
static bool isInStdNamespace(const Decl *D)
CFGReverseBlockReachabilityAnalysis * getCFGReachablityAnalysis()
const CFG::BuildOptions & getCFGBuildOptions() const
const ImplicitParamDecl * getSelfDecl() const
ASTContext & getASTContext() const
AnalysisDeclContextManager * getManager() const
llvm::iterator_range< referenced_decls_iterator > getReferencedBlockVars(const BlockDecl *BD)
const StackFrame * getStackFrame(const StackFrame *ParentSF, const void *Data, const Expr *E, const CFGBlock *Blk, unsigned BlockCount, unsigned Index)
Obtain a context of the call stack using its parent context.
AnalysisDeclContext(AnalysisDeclContextManager *Mgr, const Decl *D)
CFG::BuildOptions & getCFGBuildOptions()
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4694
Represents a single basic block in a source-level CFG.
Definition CFG.h:652
Represents a top-level expression in a basic block.
Definition CFG.h:55
llvm::DenseMap< const Stmt *, const CFGBlock * > ForcedBlkExprs
Definition CFG.h:1283
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition CFG.h:1271
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:112
void clear()
Discard all previously created StackFrame objects.
const StackFrame * getStackFrame(AnalysisDeclContext *ADC, const StackFrame *ParentSF, const void *Data, const Expr *E, const CFGBlock *Block, unsigned BlockCount, unsigned StmtIdx)
Obtain a context of the call stack using its parent context.
It represents a stack frame of the call stack.
const ParentMap & getParentMap() const
LLVM_DUMP_METHOD void dump() const
~StackFrame()=default
StackFrame(AnalysisDeclContext *ADC, const StackFrame *Parent, const void *Data, const Expr *E, const CFGBlock *Block, unsigned BlockCount, unsigned Index, int64_t ID)
LLVM_DUMP_METHOD void dumpStack(raw_ostream &Out) const
Prints out the call stack.
const void * getData() const
bool isParentOf(const StackFrame *SF) const
void Profile(llvm::FoldingSetNodeID &ID)
friend class StackFrameManager
unsigned getIndex() const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
void printJson(raw_ostream &Out, const char *NL="\n", unsigned int Space=0, bool IsDot=false, std::function< void(const StackFrame *)> printMoreInfoPerStackFrame=[](const StackFrame *) {}) const
Prints out the call stack in json format.
const Expr * getCallSite() const
CFGElement getCallSiteCFGElement() const
const Decl * getDecl() const
const ImplicitParamDecl * getSelfDecl() const
const StackFrame * getParent() const
It might return null.
const CFGBlock * getCallSiteBlock() const
static void Profile(llvm::FoldingSetNodeID &ID, AnalysisDeclContext *ADC, const StackFrame *SF, const void *Data, const Expr *E, const CFGBlock *Block, unsigned BlockCount, unsigned Index)
Stmt - This represents one statement.
Definition Stmt.h:86
Represents a variable declaration or definition.
Definition Decl.h:924
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
The JSON file list parser is used to communicate input to InstallAPI.
int const char * function
Definition c++config.h:31