如何在llvm中发现锁声明指令?

How to discover lock declaration instruction in llvm?

我是 llvm 的新手,试图找到锁声明语句然后做一些检测工作,代码如下:

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

int share = 42;
mutex m;

void f()
{
    m.lock();
    --share;
    cout << "function f -> share: " << share << '\n';
    m.unlock();
}



int main()
{
    thread thf{f};

    thf.join();

    return 0;
}

我想找到锁声明指令例如: mutex m; LLVM 检测过程如下:

struct SkeletonPass : public FunctionPass {
static char ID;
SkeletonPass() : FunctionPass(ID) {}

virtual bool runOnFunction(Function &F) {
  // Get the function to call from our runtime library.
  LLVMContext &Ctx = F.getContext();
  Constant *logFunc = F.getParent()->getOrInsertFunction(
    "logop", Type::getVoidTy(Ctx), Type::getInt32Ty(Ctx), NULL
  );

  for (auto &B : F) {
    for (auto &I : B) {
      ***if ((&I) is lock declaration instruction)*** { 

        // Insert something *after* `op`.
        IRBuilder<> builder(op);
        builder.SetInsertPoint(&B, ++builder.GetInsertPoint());

        // Insert a call to function.

        builder.CreateCall(logFunc, ConstantInt::get(Type::getInt32Ty(Ctx), 2));

        return true;
      }
    }
  }

总之,请问如何发现锁声明指令,谢谢!

您可以使用 LLVM 的 CppBackend 来编译您的代码。这将生成构成源代码的 C++ 代码。然后,您可以轻松地找出 mutex m; 定义是如何通过 LLVM API.

构造的

运行 clang -march=cpp foo.cpp 使用 CppBackend。或者,您可以使用 this demo page 在线编译您的代码。

该声明将显示为全局,因此您应该编写模块传递来查找它,而不是函数传递。它应该显示为:

@m = global %mutex zeroinitializer

其实用http://ellcc.org/demo/index.cgi的demo试试,确实可以看到:

...    
%"class.std::__1::mutex" = type { %struct.pthread_mutex_t }
%struct.pthread_mutex_t = type { %union.anon }
%union.anon = type { [5 x i8*] }
...
@m = global %"class.std::__1::mutex" zeroinitializer, align 8