如何获取使用全局变量的所有函数名称?
How to get all the function names where the global variables are used?
我正在研究带有 clang 的 libtooling。我开发了一个工具来查找全局变量以及这些全局变量的引用位置。
现在,我想获取使用这些全局变量的函数名称。
这是示例代码
int Var;
int display()
{
Var = 10;
return Var;
}
int main()
{
display();
return 0;
}
在这里,我想获取函数display
中引用的全局变量Var
。
如何使用 LibTooling 叮当声获得此输出?如果有任何解决方案,请告诉我。
可以用libTooling
.如果已经找到引用全局变量的DeclRefExpr
节点,则可以将 AST 向上移动到其FunctionDecl
父节点。
另一方面,沿着 AST 向上走需要 Clang 构建从节点到其父节点的映射(这对于大型翻译单元来说可能非常昂贵(。在这里,我整理了一个简短的解决方案,它只找到引用全局变量的函数并打印它们的名称:
class GlobalVariableFinder final
: public RecursiveASTVisitor<GlobalVariableFinder> {
public:
static bool find(FunctionDecl *CandidateFunction) {
GlobalVariableFinder ActualFinder;
ActualFinder.TraverseDecl(CandidateFunction);
return ActualFinder.Found;
}
bool VisitDeclRefExpr(DeclRefExpr *SymbolUse) {
// we are interested only in variables
if (auto *Declaration = dyn_cast<VarDecl>(SymbolUse->getDecl())) {
Found = Declaration->hasGlobalStorage();
// if we found one global variable use, there is no need in traversing
// this function any further
if (Found) return false;
}
return true;
}
private:
bool Found = false;
};
class VisitingASTConsumer final
: public ASTConsumer,
public RecursiveASTVisitor<VisitingASTConsumer> {
public:
void HandleTranslationUnit(ASTContext &C) {
this->TraverseTranslationUnitDecl(Context->getTranslationUnitDecl());
}
bool VisitFunctionDecl(FunctionDecl *CandidateFunction) {
if (GlobalVariableFinder::find(CandidateFunction)) {
llvm::errs() << CandidateFunction->getQualifiedNameAsString() << "n";
}
return true;
}
};
如果要存储全局变量引用,则可能需要修改GlobalVariableFinder
类以包含其他逻辑。
以下解决方案在此代码段上生成以下输出:
int Var;
int display()
{
Var = 10;
return Var;
}
int foo() {
return Var;
}
int bar() {
return foo();
}
int main()
{
display();
return 0;
}
display
foo
您可以注意到,它仅包含语法上使用全局变量的函数。如果你想让算法也找到bar
,你需要构建目标程序的调用图,并通过图的反转边缘传播有关全局变量的信息(即在我们的示例中从foo
传播到bar
(。
我希望这些信息对您有所帮助。与叮当一起快乐!
相关文章:
- 内联函数中具有内部链接的全局变量
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- C++ 在编译时具有函数计算全局变量
- 修改程序的入口点时未调用全局变量的构造函数
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- std::线程不是全局变量,但在到达创建它的函数的末尾时不会超出范围?
- 如何在全局变量的构造函数之前运行函数
- 如何获取使用全局变量的所有函数名称?
- 在 C++17 中修改 constexpr 函数中的全局变量
- C++从 std::async 函数读取命名空间中的全局变量标志
- 为什么我的类函数不使用我的全局变量?
- 有什么理由C++ 11+ std::mutex 应该声明为全局变量,而不是作为函数参数传递到 std::thread 中
- 将全局变量的名称作为输入并更改其值的函数
- 如何使用 c++ 中的函数访问全局变量?
- 是否可以通过全局变量定义具有可变参数数的函数中的参数数量
- 如何创建用于多个源文件的全局变量/包含/函数
- 查找全局变量,而不是在 c++ 函数中构造它们
- 通过使用全局变量的函数访问在给定范围内被覆盖的变量
- 具有递归函数且不带全局变量的程序 - C++
- C++:如何从静态函数写入全局变量