37 #include "llvm/ADT/DenseMap.h" 38 #include "llvm/ADT/FoldingSet.h" 39 #include "llvm/ADT/STLExtras.h" 40 #include "llvm/ADT/SmallPtrSet.h" 41 #include "llvm/ADT/iterator_range.h" 42 #include "llvm/Support/Allocator.h" 43 #include "llvm/Support/Casting.h" 44 #include "llvm/Support/Compiler.h" 45 #include "llvm/Support/ErrorHandling.h" 46 #include "llvm/Support/SaveAndRestore.h" 47 #include "llvm/Support/raw_ostream.h" 51 using namespace clang;
58 : Manager(Mgr), D(d), cfgBuildOptions(buildOptions) {
64 : Manager(Mgr), D(d) {
69 ASTContext &ASTCtx,
bool useUnoptimizedCFG,
bool addImplicitDtors,
70 bool addInitializers,
bool addTemporaryDtors,
bool addLifetime,
71 bool addLoopExit,
bool addScopes,
bool synthesizeBodies,
72 bool addStaticInitBranch,
bool addCXXNewAllocator,
73 bool addRichCXXConstructors,
bool markElidedCXXConstructors,
75 : Injector(injector), FunctionBodyFarm(ASTCtx, injector),
76 SynthesizeBodies(synthesizeBodies) {
93 IsAutosynthesized =
false;
94 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
95 Stmt *Body = FD->getBody();
96 if (
auto *CoroBody = dyn_cast_or_null<CoroutineBodyStmt>(Body))
97 Body = CoroBody->getBody();
98 if (Manager && Manager->synthesizeBodies()) {
99 Stmt *SynthesizedBody = Manager->getBodyFarm().getBody(FD);
100 if (SynthesizedBody) {
101 Body = SynthesizedBody;
102 IsAutosynthesized =
true;
107 else if (
const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
108 Stmt *Body = MD->getBody();
109 if (Manager && Manager->synthesizeBodies()) {
110 Stmt *SynthesizedBody = Manager->getBodyFarm().getBody(MD);
111 if (SynthesizedBody) {
112 Body = SynthesizedBody;
113 IsAutosynthesized =
true;
117 }
else if (
const auto *BD = dyn_cast<BlockDecl>(D))
118 return BD->getBody();
119 else if (
const auto *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
120 return FunTmpl->getTemplatedDecl()->getBody();
122 llvm_unreachable(
"unknown code decl");
138 Stmt *Body = getBody(Tmp);
144 return isa<ImplicitParamDecl>(VD) && VD->
getName() ==
"self";
148 if (
const auto *MD = dyn_cast<ObjCMethodDecl>(D))
149 return MD->getSelfDecl();
150 if (
const auto *BD = dyn_cast<BlockDecl>(D)) {
152 for (
const auto &I : BD->captures()) {
153 const VarDecl *VD = I.getVariable();
167 for (
const auto &LC : parent->
captures()) {
168 if (!LC.capturesVariable())
171 VarDecl *VD = LC.getCapturedVar();
183 if (
const auto *e = dyn_cast<Expr>(stmt))
184 stmt = e->IgnoreParens();
185 (void) (*forcedBlkExprs)[
stmt];
190 assert(forcedBlkExprs);
191 if (
const auto *e = dyn_cast<Expr>(stmt))
192 stmt = e->IgnoreParens();
193 CFG::BuildOptions::ForcedBlkExprs::const_iterator itr =
194 forcedBlkExprs->find(stmt);
195 assert(itr != forcedBlkExprs->end());
214 return getUnoptimizedCFG();
217 cfg =
CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
232 if (!builtCompleteCFG) {
236 CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
239 builtCompleteCFG =
true;
247 return completeCFG.get();
252 return cfgStmtMap.get();
254 if (
CFG *c = getCFG()) {
256 return cfgStmtMap.get();
266 if (
CFG *c = getCFG()) {
275 getCFG()->dump(getASTContext().getLangOpts(), ShowColors);
281 if (
const auto *
C = dyn_cast<CXXConstructorDecl>(getDecl())) {
282 for (
const auto *I :
C->inits()) {
288 if (builtCompleteCFG)
295 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
302 std::unique_ptr<AnalysisDeclContext> &AC = Contexts[D];
304 AC = llvm::make_unique<AnalysisDeclContext>(
this, D, cfgBuildOptions);
312 const CFGBlock *Blk,
unsigned Idx) {
313 return getLocationContextManager().
getStackFrame(
this, Parent, S, Blk, Idx);
319 const void *ContextData) {
331 if (!isa<NamespaceDecl>(
Parent))
333 ND = cast<NamespaceDecl>(
Parent);
341 "Cannot create LocationContexts without an AnalysisDeclContextManager!");
342 return Manager->getLocationContextManager();
356 ID.AddPointer(parent);
361 Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index);
365 Profile(ID, getAnalysisDeclContext(), getParent(), Enter);
369 Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData);
376 template <
typename LOC,
typename DATA>
381 llvm::FoldingSetNodeID
ID;
382 LOC::Profile(ID, ctx, parent, d);
385 LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
388 L =
new LOC(ctx, parent, d, ++NewID);
389 Contexts.InsertNode(L, InsertPos);
398 const CFGBlock *blk,
unsigned idx) {
399 llvm::FoldingSetNodeID
ID;
403 cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
406 Contexts.InsertNode(L, InsertPos);
415 return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
422 const void *ContextData) {
423 llvm::FoldingSetNodeID
ID;
427 cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID,
431 Contexts.InsertNode(L, InsertPos);
443 if (
const auto *SFC = dyn_cast<StackFrameContext>(LC))
475 raw_ostream &OS, StringRef Indent,
const char *NL,
const char *Sep,
476 std::function<
void(
const LocationContext *)> printMoreInfoPerContext)
const {
477 ASTContext &Ctx = getAnalysisDeclContext()->getASTContext();
482 getAnalysisDeclContext()->getASTContext().getSourceManager();
486 switch (LCtx->getKind()) {
488 OS << Indent <<
'#' << Frame <<
' ';
490 if (
const auto *D = dyn_cast<NamedDecl>(LCtx->getDecl()))
491 OS <<
"Calling " << D->getQualifiedNameAsString();
493 OS <<
"Calling anonymous code";
494 if (
const Stmt *S = cast<StackFrameContext>(LCtx)->getCallSite()) {
500 OS <<
"Entering scope";
503 OS <<
"Invoking block";
504 if (
const Decl *D = cast<BlockInvocationContext>(LCtx)->getDecl()) {
505 OS <<
" defined at ";
512 printMoreInfoPerContext(LCtx);
517 dumpStack(llvm::errs());
526 class FindBlockDeclRefExprsVals :
public StmtVisitor<FindBlockDeclRefExprsVals>{
529 llvm::SmallPtrSet<const VarDecl *, 4> Visited;
530 llvm::SmallPtrSet<const DeclContext *, 4> IgnoredContexts;
535 : BEVals(bevals), BC(bc) {}
537 void VisitStmt(
Stmt *S) {
545 if (
const auto *VD = dyn_cast<VarDecl>(DR->
getDecl())) {
546 if (!VD->hasLocalStorage()) {
547 if (Visited.insert(VD).second)
562 Expr *Semantic = *it;
563 if (
auto *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
564 Semantic = OVE->getSourceExpr();
576 llvm::BumpPtrAllocator &A) {
585 for (
const auto &CI : BD->
captures()) {
590 FindBlockDeclRefExprsVals F(*BV, BC);
597 llvm::iterator_range<AnalysisDeclContext::referenced_decls_iterator>
599 if (!ReferencedBlockVars)
600 ReferencedBlockVars =
new llvm::DenseMap<const BlockDecl*,void*>();
604 return llvm::make_range(V->begin(), V->end());
607 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(
const void *tag) {
608 if (!ManagedAnalyses)
621 delete forcedBlkExprs;
622 delete ReferencedBlockVars;
624 if (ManagedAnalyses) {
626 llvm::DeleteContainerSeconds(*M);
638 for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
639 E = Contexts.end(); I != E; ) {
Defines the clang::ASTContext interface.
const BlockDecl * getBlockDecl() const
The base class of a hierarchy of objects representing analyses tied to AnalysisDeclContext.
void Profile(llvm::FoldingSetNodeID &ID) override
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
Stmt * getBody() const
Get the body of the Declaration.
CFGStmtMap * getCFGStmtMap()
Expr *const * semantics_iterator
Stmt - This represents one statement.
Defines the SourceManager interface.
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, CodeInjector *injector=nullptr)
Decl - This represents one declaration (or definition), e.g.
Defines the C++ template declaration subclasses.
Stmt * getParent(Stmt *) const
Represent a C++ namespace.
capture_const_range captures() const
bool AddStaticInitBranches
Represents a variable declaration or definition.
Describes how types, statements, expressions, and declarations should be printed. ...
unsigned TerseOutput
Provide a 'terse' output.
bool isParentOf(const LocationContext *LC) const
void print(raw_ostream &OS, const SourceManager &SM) const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceLocation getBeginLoc() const LLVM_READONLY
AnalysisDeclContext contains the context data for the function or method under analysis.
void addStmt(Stmt *S)
Adds and/or updates the parent/child-relations of the complete stmt tree of S.
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
void setParent(const Stmt *S, const Stmt *Parent)
Manually sets the parent of S to Parent.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
static bool isInStdNamespace(const Decl *D)
Returns true if the root namespace of the given declaration is the 'std' C++ namespace.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
CFGReverseBlockReachabilityAnalysis * getCFGReachablityAnalysis()
virtual bool inTopFrame() const
Return true if the current LocationContext has no caller context.
semantics_iterator semantics_end()
const LocationContext * getParent() const
bool isLambda() const
Determine whether this class describes a lambda function object.
Scope - A scope is a transient data structure that is used while parsing the program.
void clear()
Discard all previously created LocationContext objects.
llvm::DenseMap< const DeclStmt *, const DeclStmt * >::const_iterator synthetic_stmt_iterator
llvm::DenseMap< const Stmt *, const CFGBlock * > ForcedBlkExprs
const StackFrameContext * getStackFrame(AnalysisDeclContext *Ctx, LocationContext const *Parent, const Stmt *S, const CFGBlock *Blk, unsigned Idx)
ForcedBlkExprs ** forcedBlkExprs
Represents a single basic block in a source-level CFG.
AnalysisDeclContext * getContext(const Decl *D)
static void printLocation(raw_ostream &OS, const SourceManager &SM, SourceLocation SLoc)
bool isBodyAutosynthesizedFromModelFile() const
Checks if the body of the Decl is generated by the BodyFarm from a model file.
Pepresents a block literal declaration, which is like an unnamed FunctionDecl.
This represents one expression.
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt...
BumpVector< const VarDecl * > DeclVec
void Profile(llvm::FoldingSetNodeID &ID) override
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
DeclContext * getDeclContext()
bool inTopFrame() const override
Return true if the current LocationContext has no caller context.
BodyFarm & getBodyFarm()
Get a reference to {.
const CFGBlock * getBlockForRegisteredExpression(const Stmt *stmt)
DeclContext * getParent()
getParent - Returns the containing DeclContext.
bool isBodyAutosynthesized() const
Checks if the body of the Decl is generated by the BodyFarm.
const ScopeContext * getScope(AnalysisDeclContext *ctx, const LocationContext *parent, const Stmt *s)
const StackFrameContext * getStackFrame(LocationContext const *Parent, const Stmt *S, const CFGBlock *Blk, unsigned Idx)
CFG::BuildOptions & getCFGBuildOptions()
const StackFrameContext * getStackFrame(AnalysisDeclContext *ctx, const LocationContext *parent, const Stmt *s, const CFGBlock *blk, unsigned idx)
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
CFG * getUnoptimizedCFG()
Return a version of the CFG without any edges pruned.
const ImplicitParamDecl * getSelfDecl() const
Return the ImplicitParamDecl* associated with 'self' if this AnalysisDeclContext wraps an ObjCMethodD...
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
~LocationContextManager()
Encodes a location in the source.
static std::unique_ptr< CFG > buildCFG(const Decl *D, Stmt *AST, ASTContext *C, const BuildOptions &BO)
Builds a CFG from an AST.
bool PruneTriviallyFalseEdges
Represents a static or instance method of a struct/union/class.
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
bool isStdNamespace() const
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool MarkElidedCXXConstructors
virtual ~ManagedAnalysis()
void push_back(const_reference Elt, BumpVectorContext &C)
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
static CFGStmtMap * Build(CFG *C, ParentMap *PM)
Returns a new CFGMap for the given CFG.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
ArrayRef< Capture > captures() const
CodeInjector is an interface which is responsible for injecting AST of function definitions that may ...
llvm::iterator_range< referenced_decls_iterator > getReferencedBlockVars(const BlockDecl *BD)
static DeclVec * LazyInitializeReferencedDecls(const BlockDecl *BD, void *&Vec, llvm::BumpPtrAllocator &A)
void Profile(llvm::FoldingSetNodeID &ID) override
virtual ~LocationContext()
semantics_iterator semantics_begin()
static bool isSelfDecl(const VarDecl *VD)
Returns true if.
static void addParentsForSyntheticStmts(const CFG *TheCFG, ParentMap &PM)
Add each synthetic statement in the CFG to the parent map, using the source statement's parent...
const StackFrameContext * getStackFrame() const
const BlockInvocationContext * getBlockInvocationContext(AnalysisDeclContext *ctx, const LocationContext *parent, const BlockDecl *BD, const void *ContextData)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
llvm::DenseMap< const void *, ManagedAnalysis * > ManagedAnalysisMap
Defines the clang::SourceLocation class and associated facilities.
Represents a C++ struct/union/class.
void dumpCFG(bool ShowColors)
synthetic_stmt_iterator synthetic_stmt_end() const
bool AddRichCXXConstructors
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
void registerForcedBlockExpression(const Stmt *stmt)
synthetic_stmt_iterator synthetic_stmt_begin() const
Iterates over synthetic DeclStmts in the CFG.
A reference to a declared variable, function, enum, etc.
const BlockInvocationContext * getBlockInvocationContext(const LocationContext *parent, const BlockDecl *BD, const void *ContextData)
ParentMap & getParentMap()
void clear()
Discard all previously created AnalysisDeclContexts.
const LangOptions & getLangOpts() const
This class handles loading and caching of source files into memory.
AnalysisDeclContext(AnalysisDeclContextManager *Mgr, const Decl *D)
static void ProfileCommon(llvm::FoldingSetNodeID &ID, ContextKind ck, AnalysisDeclContext *ctx, const LocationContext *parent, const void *data)
Defines the LambdaCapture class.