clang 24.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 <iterator>
33#include <memory>
34
35namespace clang {
36
38class ASTContext;
39class BlockDecl;
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 StackFrameManager::getStackFrame()
180 const StackFrame *getStackFrame(const StackFrame *ParentSF, const void *Data,
181 const Expr *E, const CFGBlock *Blk,
182 unsigned BlockCount, unsigned Index);
183
184 /// \returns The specified analysis object, lazily running the analysis if
185 /// necessary or nullptr if the analysis could not run.
186 template <typename T> T *getAnalysis() {
187 const void *tag = T::getTag();
188 std::unique_ptr<ManagedAnalysis> &data = getAnalysisImpl(tag);
189 if (!data)
190 data = T::create(*this);
191 return static_cast<T *>(data.get());
192 }
193
194 /// \returns Whether the root namespace of \p D is the \c std C++ namespace.
195 static bool isInStdNamespace(const Decl *D);
196
197 static std::string getFunctionName(const Decl *D);
198
199private:
200 std::unique_ptr<ManagedAnalysis> &getAnalysisImpl(const void *tag);
201
202 StackFrameManager &getStackFrameManager();
203};
204
205/// It represents a stack frame of the call stack
206class StackFrame final : public llvm::FoldingSetNode {
207 friend class StackFrameManager;
208
209 // AnalysisDeclContext can't be const since some methods may modify its
210 // member.
212
213 const StackFrame *Parent;
214
215 int64_t ID;
216
217 // Extra data for BlockInvocations
218 const void *Data;
219
220 // The call site where this stack frame is established.
221 const Expr *CallSite;
222
223 // The parent block of the call site.
224 const CFGBlock *Block;
225
226 // The number of times the 'Block' has been visited.
227 // It allows discriminating between stack frames of the same call that is
228 // called multiple times in a loop.
229 const unsigned BlockCount;
230
231 // The index of the call site in the CFGBlock.
232 const unsigned Index;
233
234public:
236 const void *Data, const Expr *E, const CFGBlock *Block,
237 unsigned BlockCount, unsigned Index, int64_t ID)
238 : Ctx(ADC), Parent(Parent), ID(ID), Data(Data), CallSite(E), Block(Block),
239 BlockCount(BlockCount), Index(Index) {
240 assert(ADC);
241 }
242
243 ~StackFrame() = default;
244
245 LLVM_ATTRIBUTE_RETURNS_NONNULL
247
248 /// It might return null.
249 const StackFrame *getParent() const { return Parent; }
250
251 /// Forward iterator over a chain of \c StackFrame parents. Advancing follows
252 /// \c getParent(); the past-the-end iterator holds a null frame.
254 const StackFrame *Current = nullptr;
255
256 public:
257 using iterator_category = std::forward_iterator_tag;
258 using value_type = const StackFrame;
259 using difference_type = std::ptrdiff_t;
260 using pointer = const StackFrame *;
261 using reference = const StackFrame &;
262
263 parent_iterator() = default;
264 explicit parent_iterator(const StackFrame *SF) : Current(SF) {}
265
266 reference operator*() const { return *Current; }
267 pointer operator->() const { return Current; }
269 assert(Current && "Cannot call ++ on the end iterator");
270 Current = Current->getParent();
271 return *this;
272 }
274 parent_iterator Tmp = *this;
275 ++*this;
276 return Tmp;
277 }
278 bool operator==(const parent_iterator &Other) const {
279 return Current == Other.Current;
280 }
281 bool operator!=(const parent_iterator &Other) const {
282 return !(*this == Other);
283 }
284 };
285
286 /// Iterates over the strict ancestors of this frame, i.e. \c getParent(),
287 /// \c getParent()->getParent(), ... up to (but excluding) the null frame.
288 /// Does not include \c *this.
289 llvm::iterator_range<parent_iterator> parents() const {
291 }
292
293 /// Iterates over this frame followed by all of its ancestors.
294 llvm::iterator_range<parent_iterator> parentsIncludingSelf() const {
295 return {parent_iterator(this), parent_iterator()};
296 }
297
298 int64_t getID() const { return ID; }
299
300 bool isParentOf(const StackFrame *SF) const;
301
302 const Decl *getDecl() const { return Ctx->getDecl(); }
303
304 CFG *getCFG() const { return Ctx->getCFG(); }
305
306 template <typename T> T *getAnalysis() const { return Ctx->getAnalysis<T>(); }
307
308 const ParentMap &getParentMap() const { return Ctx->getParentMap(); }
309
310 /// \copydoc AnalysisDeclContext::getSelfDecl()
311 const ImplicitParamDecl *getSelfDecl() const { return Ctx->getSelfDecl(); }
312
313 const void *getData() const { return Data; }
314
315 const Expr *getCallSite() const { return CallSite; }
316
317 const CFGBlock *getCallSiteBlock() const { return Block; }
318
319 /// \returns Whether the current StackFrame has no caller context.
320 bool inTopFrame() const { return getParent() == nullptr; }
321
322 unsigned getIndex() const { return Index; }
323
324 CFGElement getCallSiteCFGElement() const { return (*Block)[Index]; }
325
326 /// Prints out the call stack in \c json format.
327 ///
328 /// \param Out The out stream.
329 /// \param NL The newline.
330 /// \param Space The space count for indentation.
331 /// \param IsDot Whether the output format is \c dot.
332 /// \param printMoreInfoPerStackFrame
333 /// A callback to print more information for each stack frame, for example:
334 /// \code
335 /// [&](const StackFrame *SF) { SF->dump(); }
336 /// \endcode
337 void printJson(
338 raw_ostream &Out, const char *NL = "\n", unsigned int Space = 0,
339 bool IsDot = false,
340 std::function<void(const StackFrame *)> printMoreInfoPerStackFrame =
341 [](const StackFrame *) {}) const;
342
343 /// Prints out the call stack.
344 ///
345 /// \param Out The out stream.
346 LLVM_DUMP_METHOD void dumpStack(raw_ostream &Out) const;
347
348 LLVM_DUMP_METHOD void dump() const;
349
350 void Profile(llvm::FoldingSetNodeID &ID);
351
352 static void Profile(llvm::FoldingSetNodeID &ID, AnalysisDeclContext *ADC,
353 const StackFrame *SF, const void *Data, const Expr *E,
354 const CFGBlock *Block, unsigned BlockCount,
355 unsigned Index) {
356 ID.AddPointer(ADC);
357 ID.AddPointer(SF);
358 ID.AddPointer(E);
359 ID.AddPointer(Data);
360 ID.AddPointer(Block);
361 ID.AddInteger(BlockCount);
362 ID.AddInteger(Index);
363 }
364};
365
367 llvm::FoldingSet<StackFrame> Frames;
368
369 // ID used for generating a new stack frame.
370 int64_t NewID = 0;
371
372public:
374
375 /// Obtain a context of the call stack using its parent context.
376 ///
377 /// \param ADC The AnalysisDeclContext.
378 /// \param ParentSF The parent context of this newly created
379 /// context.
380 /// \param Data Extra data in case this StackFrame is
381 /// created for a BlockInvocation.
382 /// \param E The call expression.
383 /// \param Block The basic block.
384 /// \param BlockCount The current count of entering into \p Block.
385 /// \param StmtIdx The index of the call expression \p E among the
386 /// statements of the CFGBlock \p Block.
387 /// \returns The stack frame context corresponding to the call.
389 const StackFrame *ParentSF, const void *Data,
390 const Expr *E, const CFGBlock *Block,
391 unsigned BlockCount, unsigned StmtIdx);
392
393 /// Discard all previously created StackFrame objects.
394 void clear();
395};
396
398 using ContextMap =
399 llvm::DenseMap<const Decl *, std::unique_ptr<AnalysisDeclContext>>;
400
401 ContextMap Contexts;
402 StackFrameManager SFMgr;
403 CFG::BuildOptions cfgBuildOptions;
404
405 // Pointer to an interface that can provide function bodies for
406 // declarations from external source.
407 std::unique_ptr<CodeInjector> Injector;
408
409 // A factory for creating and caching implementations for common
410 // methods during the analysis.
411 BodyFarm FunctionBodyFarm;
412
413 // Flag to indicate whether or not bodies should be synthesized
414 // for well-known functions.
415 bool SynthesizeBodies;
416
417public:
419 ASTContext &ASTCtx, bool useUnoptimizedCFG = false,
420 bool addImplicitDtors = false, bool addInitializers = false,
421 bool addTemporaryDtors = false, bool addLifetime = false,
422 bool addLoopExit = false, bool addScopes = false,
423 bool synthesizeBodies = false, bool addStaticInitBranches = false,
424 bool addCXXNewAllocator = true, bool addRichCXXConstructors = true,
425 bool markElidedCXXConstructors = true, bool addVirtualBaseBranches = true,
426 std::unique_ptr<CodeInjector> injector = nullptr);
427
429
430 bool getUseUnoptimizedCFG() const {
431 return !cfgBuildOptions.PruneTriviallyFalseEdges;
432 }
433
434 CFG::BuildOptions &getCFGBuildOptions() { return cfgBuildOptions; }
435
436 /// \returns Whether faux bodies should be synthesized for known functions.
437 bool synthesizeBodies() const { return SynthesizeBodies; }
438
439 /// Obtain the beginning context of the analysis.
440 ///
441 /// \returns The top level stack frame for \p D.
443 return SFMgr.getStackFrame(getContext(D), nullptr, nullptr, nullptr,
444 nullptr, 0, 0);
445 }
446
448
449 /// Discard all previously created AnalysisDeclContexts.
450 void clear();
451
452private:
454
455 StackFrameManager &getStackFrameManager() { return SFMgr; }
456};
457
458} // namespace clang
459
460#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:4716
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.
Forward iterator over a chain of StackFrame parents.
std::forward_iterator_tag iterator_category
bool operator!=(const parent_iterator &Other) const
bool operator==(const parent_iterator &Other) const
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
llvm::iterator_range< parent_iterator > parents() const
Iterates over the strict ancestors of this frame, i.e.
CFGElement getCallSiteCFGElement() const
const Decl * getDecl() const
const ImplicitParamDecl * getSelfDecl() const
const StackFrame * getParent() const
It might return null.
const CFGBlock * getCallSiteBlock() const
llvm::iterator_range< parent_iterator > parentsIncludingSelf() const
Iterates over this frame followed by all of its ancestors.
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:932
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
The JSON file list parser is used to communicate input to InstallAPI.
const FunctionProtoType * T
@ Other
Other implicit parameter.
Definition Decl.h:1774
int const char * function
Definition c++config.h:31