CloneFunction 然后在 LLVM opt pass 中用克隆函数替换原始函数

CloneFunction then replace original function with cloned one in LLVM opt pass

我正在编写一个 LLVM 优化模块 pass,如果我不喜欢结果,我希望能够恢复原始功能。所以我写了一个具有以下基本结构的ModulePass:

while(cloneAndTryAgain){

    ValueToValueMapTy vmap;
    Function *F_clone = CloneFunction(F, vmap, true);

    .... trying out things on F

    if(cloneAndTryAgain){ //not happy with changes to F
        //replace F with clone
        replaceCurrentFunction(F, F_clone);
        F_clone = NULL;
    } 
}

但是,在 运行 replaceCurrentFunction(..) 之后,我尝试打印 F 但出现段错误。尝试用克隆替换后 F 出现问题。

replaceCurrentFunction(..) 看起来像这样:

void replaceCurrentFunction(Function *F, Function *F_clone) {

  Module *M = F->getParent();

  // New function will take the name of the current function.
  F_clone->takeName(F);

  // Insert new function right next to current function.
  M->getFunctionList().insert(F, F_clone);

  // Erase current function.
  F->eraseFromParent();

  // The new function is now the current function.
  F = F_clone;

}

这是段错误和堆栈跟踪:

Program received signal SIGSEGV, Segmentation fault.
(anonymous namespace)::SlotTracker::SlotTracker (this=0x7fffffff94b0, F=0x1b) at AsmWriter.cpp:438
438     mNext(0), fNext(0), mdnNext(0) {

#0  (anonymous namespace)::SlotTracker::SlotTracker (this=0x7fffffff94b0, F=0x1b) at AsmWriter.cpp:438
#1  0x00007ffff63c66dc in llvm::Value::print (this=0x6d4a30, ROS=..., AAW=0x0) at AsmWriter.cpp:2092
#2  0x00007ffff6fb536c in operator<< (V=..., OS=...) at /llvm/include/llvm/Value.h:318
#4 ....

哇,你在这里使用了一堆不安全的 API,有些语句甚至没有意义。例如,您对 void replaceCurrentFunction(Function *F, Function *F_clone) 的最后一行 F = F_clone; 有什么期望?如果你想更新调用者中的 "F",你应该以 return F_clone 结束这个函数,然后这样调用它 F = replaceCurrentFunction(F, F_clone);.

对于实际的 LLVM API,正确的顺序是:

  1. 用克隆函数替换旧函数的所有使用: F->replaceAllUsesWith(F_clone)
  2. 保存名称:std::string Name = F->getName()
  3. 删除F:F->eraseFromParent()
  4. 重命名克隆:F_clone->setName(Name)