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;
41class LocationContext;
43class ParentMap;
44class StackFrame;
45class Stmt;
46class VarDecl;
47
48/// The base class of a hierarchy of objects representing analyses tied
49/// to AnalysisDeclContext.
51protected:
52 ManagedAnalysis() = default;
53
54public:
56
57 // Subclasses need to implement:
58 //
59 // static const void *getTag();
60 //
61 // Which returns a fixed pointer address to distinguish classes of
62 // analysis objects. They also need to implement:
63 //
64 // static [Derived*] create(AnalysisDeclContext &Ctx);
65 //
66 // which creates the analysis object given an AnalysisDeclContext.
67};
68
69/// AnalysisDeclContext contains the context data for the function, method
70/// or block under analysis.
72 // Backpoint to the AnalysisManager object that created this
73 // AnalysisDeclContext. This may be null.
75
76 const Decl *const D;
77
78 std::unique_ptr<CFG> cfg, completeCFG;
79 std::optional<CFGStmtMap> cfgStmtMap;
80
81 CFG::BuildOptions cfgBuildOptions;
82 CFG::BuildOptions::ForcedBlkExprs *forcedBlkExprs = nullptr;
83
84 bool builtCFG = false;
85 bool builtCompleteCFG = false;
86 std::unique_ptr<ParentMap> PM;
87 std::unique_ptr<CFGReverseBlockReachabilityAnalysis> CFA;
88
89 llvm::BumpPtrAllocator A;
90
91 llvm::DenseMap<const BlockDecl *, void *> *ReferencedBlockVars = nullptr;
92
93 void *ManagedAnalyses = nullptr;
94
95public:
97
99 const CFG::BuildOptions &BuildOptions);
100
102
103 ASTContext &getASTContext() const { return D->getASTContext(); }
104
105 const Decl *getDecl() const { return D; }
106
107 AnalysisDeclContextManager *getManager() const { return ADCMgr; }
108
109 CFG::BuildOptions &getCFGBuildOptions() { return cfgBuildOptions; }
110
112 return cfgBuildOptions;
113 }
114
115 /// \returns Whether we are adding exception handling edges from CallExprs.
116 /// If this is false, then try/catch statements and blocks reachable from them
117 /// can appear to be dead in the CFG, analysis passes must cope with that.
118 bool getAddEHEdges() const { return cfgBuildOptions.AddEHEdges; }
119 bool getUseUnoptimizedCFG() const {
120 return !cfgBuildOptions.PruneTriviallyFalseEdges;
121 }
122 bool getAddImplicitDtors() const { return cfgBuildOptions.AddImplicitDtors; }
123 bool getAddInitializers() const { return cfgBuildOptions.AddInitializers; }
124
127
128 /// \returns The body of the stored Decl \c D.
129 Stmt *getBody() const;
130
131 /// \copydoc AnalysisDeclContext::getBody()
132 /// \param[out] IsAutosynthesized Specifies if the body is auto-generated
133 /// by the BodyFarm.
134 Stmt *getBody(bool &IsAutosynthesized) const;
135
136 /// \returns Whether the body of the Decl \c D is generated by the BodyFarm.
137 ///
138 /// \note The lookup is not free. We are going to call getBody behind
139 /// the scenes.
140 /// \sa getBody
141 bool isBodyAutosynthesized() const;
142
143 /// \returns Whether the body of the Decl \c D is generated by the BodyFarm
144 /// from a model file.
145 ///
146 /// \note The lookup is not free. We are going to call getBody behind
147 /// the scenes.
148 /// \sa getBody
150
151 CFG *getCFG();
152
153 const CFGStmtMap *getCFGStmtMap();
154
156
157 /// \returns A version of the CFG without any edges pruned.
159
160 void dumpCFG(bool ShowColors);
161
162 /// \returns Whether we have built a CFG for this analysis context.
163 ///
164 /// \note This doesn't correspond to whether or not a valid CFG exists, it
165 /// corresponds to whether we *attempted* to build one.
166 bool isCFGBuilt() const { return builtCFG; }
167
169
170 using referenced_decls_iterator = const VarDecl *const *;
171
172 llvm::iterator_range<referenced_decls_iterator>
174
175 /// \returns The ImplicitParamDecl associated with \c self if this
176 /// AnalysisDeclContext wraps an ObjCMethodDecl or nullptr otherwise.
177 const ImplicitParamDecl *getSelfDecl() const;
178
179 /// \copydoc LocationContextManager::getStackFrame()
180 const StackFrame *getStackFrame(LocationContext const *ParentLC,
181 const void *Data, const Expr *E,
182 const CFGBlock *Blk, unsigned BlockCount,
183 unsigned Index);
184
185 /// \returns The specified analysis object, lazily running the analysis if
186 /// necessary or nullptr if the analysis could not run.
187 template <typename T> T *getAnalysis() {
188 const void *tag = T::getTag();
189 std::unique_ptr<ManagedAnalysis> &data = getAnalysisImpl(tag);
190 if (!data)
191 data = T::create(*this);
192 return static_cast<T *>(data.get());
193 }
194
195 /// \returns Whether the root namespace of \p D is the \c std C++ namespace.
196 static bool isInStdNamespace(const Decl *D);
197
198 static std::string getFunctionName(const Decl *D);
199
200private:
201 std::unique_ptr<ManagedAnalysis> &getAnalysisImpl(const void *tag);
202
203 LocationContextManager &getLocationContextManager();
204};
205
206class LocationContext : public llvm::FoldingSetNode {
207public:
209
210private:
211 ContextKind Kind;
212
213 // AnalysisDeclContext can't be const since some methods may modify its
214 // member.
216
217 const LocationContext *Parent;
218 int64_t ID;
219
220protected:
222 const LocationContext *parent, int64_t ID)
223 : Kind(k), Ctx(ctx), Parent(parent), ID(ID) {
224 assert(ctx);
225 }
226
227public:
229
230 ContextKind getKind() const { return Kind; }
231
232 int64_t getID() const { return ID; }
233
234 LLVM_ATTRIBUTE_RETURNS_NONNULL
236
237 /// It might return null.
238 const LocationContext *getParent() const { return Parent; }
239
240 bool isParentOf(const LocationContext *LC) const;
241
242 const Decl *getDecl() const { return Ctx->getDecl(); }
243
244 CFG *getCFG() const { return Ctx->getCFG(); }
245
246 template <typename T> T *getAnalysis() const { return Ctx->getAnalysis<T>(); }
247
248 const ParentMap &getParentMap() const { return Ctx->getParentMap(); }
249
250 /// \copydoc AnalysisDeclContext::getSelfDecl()
251 const ImplicitParamDecl *getSelfDecl() const { return Ctx->getSelfDecl(); }
252
253 const StackFrame *getStackFrame() const;
254
255 /// \returns Whether the current LocationContext has no caller context.
256 virtual bool inTopFrame() const;
257
258 virtual void Profile(llvm::FoldingSetNodeID &ID) = 0;
259
260 /// Prints out the call stack.
261 ///
262 /// \param Out The out stream.
263 LLVM_DUMP_METHOD void dumpStack(raw_ostream &Out) const;
264
265 /// Prints out the call stack in \c json format.
266 ///
267 /// \param Out The out stream.
268 /// \param NL The newline.
269 /// \param Space The space count for indentation.
270 /// \param IsDot Whether the output format is \c dot.
271 /// \param printMoreInfoPerContext
272 /// A callback to print more information for each context, for example:
273 /// \code
274 /// [&](const LocationContext *LC) { LC->dump(); }
275 /// \endcode
276 void printJson(
277 raw_ostream &Out, const char *NL = "\n", unsigned int Space = 0,
278 bool IsDot = false,
279 std::function<void(const LocationContext *)> printMoreInfoPerContext =
280 [](const LocationContext *) {}) const;
281
282 LLVM_DUMP_METHOD void dump() const;
283
284 static void ProfileCommon(llvm::FoldingSetNodeID &ID, ContextKind ck,
286 const LocationContext *parent, const void *data);
287};
288
289/// It represents a stack frame of the call stack (based on CallEvent).
290class StackFrame : public LocationContext {
292
293 // Extra data for BlockInvocations
294 const void *Data;
295
296 // The call site where this stack frame is established.
297 const Expr *CallSite;
298
299 // The parent block of the call site.
300 const CFGBlock *Block;
301
302 // The number of times the 'Block' has been visited.
303 // It allows discriminating between stack frames of the same call that is
304 // called multiple times in a loop.
305 const unsigned BlockCount;
306
307 // The index of the call site in the CFGBlock.
308 const unsigned Index;
309
310 StackFrame(AnalysisDeclContext *ADC, const LocationContext *ParentLC,
311 const void *Data, const Expr *E, const CFGBlock *Block,
312 unsigned BlockCount, unsigned Index, int64_t ID)
313 : LocationContext(StackFrameKind, ADC, ParentLC, ID), Data(Data),
314 CallSite(E), Block(Block), BlockCount(BlockCount), Index(Index) {}
315
316public:
317 ~StackFrame() override = default;
318
319 const void *getData() const { return Data; }
320
321 const Expr *getCallSite() const { return CallSite; }
322
323 const CFGBlock *getCallSiteBlock() const { return Block; }
324
325 bool inTopFrame() const override { return getParent() == nullptr; }
326
327 unsigned getIndex() const { return Index; }
328
329 CFGElement getCallSiteCFGElement() const { return (*Block)[Index]; }
330
331 void Profile(llvm::FoldingSetNodeID &ID) override;
332
333 static void Profile(llvm::FoldingSetNodeID &ID, AnalysisDeclContext *ADC,
334 const LocationContext *ParentLC, const void *Data,
335 const Expr *E, const CFGBlock *Block, unsigned BlockCount,
336 unsigned Index) {
337 ProfileCommon(ID, StackFrameKind, ADC, ParentLC, E);
338 ID.AddPointer(Data);
339 ID.AddPointer(Block);
340 ID.AddInteger(BlockCount);
341 ID.AddInteger(Index);
342 }
343
344 static bool classof(const LocationContext *LC) {
345 return LC->getKind() == StackFrameKind;
346 }
347};
348
350 llvm::FoldingSet<LocationContext> Contexts;
351
352 // ID used for generating a new location context.
353 int64_t NewID = 0;
354
355public:
357
358 /// Obtain a context of the call stack using its parent context.
359 ///
360 /// \param ADC The AnalysisDeclContext.
361 /// \param ParentLC The parent context of this newly created
362 /// context.
363 /// \param Data Extra data in case this StackFrame is
364 /// created for a BlockInvocation.
365 /// \param E The call expression.
366 /// \param Block The basic block.
367 /// \param BlockCount The current count of entering into \p Block.
368 /// \param StmtIdx The index of the call expression \p E among the
369 /// statements of the CFGBlock \p Block.
370 /// \returns The stack frame context corresponding to the call.
372 const LocationContext *ParentLC,
373 const void *Data, const Expr *E,
374 const CFGBlock *Block, unsigned BlockCount,
375 unsigned StmtIdx);
376
377 /// Discard all previously created LocationContext objects.
378 void clear();
379};
380
382 using ContextMap =
383 llvm::DenseMap<const Decl *, std::unique_ptr<AnalysisDeclContext>>;
384
385 ContextMap Contexts;
386 LocationContextManager LocCtxMgr;
387 CFG::BuildOptions cfgBuildOptions;
388
389 // Pointer to an interface that can provide function bodies for
390 // declarations from external source.
391 std::unique_ptr<CodeInjector> Injector;
392
393 // A factory for creating and caching implementations for common
394 // methods during the analysis.
395 BodyFarm FunctionBodyFarm;
396
397 // Flag to indicate whether or not bodies should be synthesized
398 // for well-known functions.
399 bool SynthesizeBodies;
400
401public:
403 ASTContext &ASTCtx, bool useUnoptimizedCFG = false,
404 bool addImplicitDtors = false, bool addInitializers = false,
405 bool addTemporaryDtors = false, bool addLifetime = false,
406 bool addLoopExit = false, bool addScopes = false,
407 bool synthesizeBodies = false, bool addStaticInitBranches = false,
408 bool addCXXNewAllocator = true, bool addRichCXXConstructors = true,
409 bool markElidedCXXConstructors = true, bool addVirtualBaseBranches = true,
410 std::unique_ptr<CodeInjector> injector = nullptr);
411
413
414 bool getUseUnoptimizedCFG() const {
415 return !cfgBuildOptions.PruneTriviallyFalseEdges;
416 }
417
418 CFG::BuildOptions &getCFGBuildOptions() { return cfgBuildOptions; }
419
420 /// \returns Whether faux bodies should be synthesized for known functions.
421 bool synthesizeBodies() const { return SynthesizeBodies; }
422
423 /// Obtain the beginning context of the analysis.
424 ///
425 /// \returns The top level stack frame for \p D.
426 const StackFrame *getStackFrame(const Decl *D) {
427 return LocCtxMgr.getStackFrame(getContext(D), nullptr, nullptr, nullptr,
428 nullptr, 0, 0);
429 }
430
432
433 /// Discard all previously created AnalysisDeclContexts.
434 void clear();
435
436private:
438
439 LocationContextManager &getLocationContextManager() { return LocCtxMgr; }
440};
441
442} // namespace clang
443
444#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:227
const StackFrame * getStackFrame(const Decl *D)
Obtain the beginning context of the analysis.
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)
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)
AnalysisDeclContext(AnalysisDeclContextManager *Mgr, const Decl *D)
const StackFrame * getStackFrame(LocationContext const *ParentLC, const void *Data, const Expr *E, const CFGBlock *Blk, unsigned BlockCount, unsigned Index)
Obtain a context of the call stack using its parent context.
CFG::BuildOptions & getCFGBuildOptions()
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4690
Represents a single basic block in a source-level CFG.
Definition CFG.h:632
Represents a top-level expression in a basic block.
Definition CFG.h:55
llvm::DenseMap< const Stmt *, const CFGBlock * > ForcedBlkExprs
Definition CFG.h:1262
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition CFG.h:1250
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:112
const StackFrame * getStackFrame(AnalysisDeclContext *ADC, const LocationContext *ParentLC, const void *Data, const Expr *E, const CFGBlock *Block, unsigned BlockCount, unsigned StmtIdx)
Obtain a context of the call stack using its parent context.
void clear()
Discard all previously created LocationContext objects.
bool isParentOf(const LocationContext *LC) const
const Decl * getDecl() const
LocationContext(ContextKind k, AnalysisDeclContext *ctx, const LocationContext *parent, int64_t ID)
const ParentMap & getParentMap() const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
static void ProfileCommon(llvm::FoldingSetNodeID &ID, ContextKind ck, AnalysisDeclContext *ctx, const LocationContext *parent, const void *data)
const LocationContext * getParent() const
It might return null.
const StackFrame * getStackFrame() const
LLVM_DUMP_METHOD void dumpStack(raw_ostream &Out) const
Prints out the call stack.
LLVM_DUMP_METHOD void dump() const
virtual void Profile(llvm::FoldingSetNodeID &ID)=0
virtual bool inTopFrame() const
const ImplicitParamDecl * getSelfDecl() const
void printJson(raw_ostream &Out, const char *NL="\n", unsigned int Space=0, bool IsDot=false, std::function< void(const LocationContext *)> printMoreInfoPerContext=[](const LocationContext *) {}) const
Prints out the call stack in json format.
ContextKind getKind() const
It represents a stack frame of the call stack (based on CallEvent).
static bool classof(const LocationContext *LC)
const void * getData() const
bool inTopFrame() const override
static void Profile(llvm::FoldingSetNodeID &ID, AnalysisDeclContext *ADC, const LocationContext *ParentLC, const void *Data, const Expr *E, const CFGBlock *Block, unsigned BlockCount, unsigned Index)
void Profile(llvm::FoldingSetNodeID &ID) override
friend class LocationContextManager
unsigned getIndex() const
const Expr * getCallSite() const
CFGElement getCallSiteCFGElement() const
~StackFrame() override=default
const CFGBlock * getCallSiteBlock() const
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