填充LLVM CloneFunction VMAP

时间:2016-02-16 19:45:34

标签: llvm compiler-optimization llvm-c++-api

我想编写一些代码,在给定LLVM函数F的情况下,在同一模块中创建一个精确的副本(因此可以在保留原始文件的同时对副本进行操作)。我想用CloneFunctionInto方法做到这一点。

我当前的尝试涉及尝试将每个(新arg,旧arg)对插入VMap。以前我试过插入一个未初始化的VMap,然后反过来放这对。令人印象深刻的是,所有3个都产生了完全相同的错误消息:

断言`VMap.count(& I)&& “没有指定源参数的映射!”'失败。

//F and S are defined higher up in the code
FunctionType *FType = F->getFunctionType();
Function *new_F = cast<Function>(M->getOrInsertFunction(S,FType));
std::vector<Type*> ArgTypes;
ValueToValueMapTy VMap;
Function::arg_iterator old_args = F->arg_begin();
for (Function::arg_iterator new_args = new_F->arg_begin(), new_args_end = new_F->arg_end();new_args != new_args_end; new_args++) {
  std::pair<Value*,Value*> pair(&*new_args,&*old_args);
  VMap.insert(pair);
  if (VMap.count(&*new_args)>0) {
   errs().write_escaped("Mapping added") << '\n';
  }
  old_args++;
 }
 SmallVector<ReturnInst*, 8> Returns;
 CloneFunctionInto(new_F, F, VMap, false, Returns, "_new", 0, 0);

在使用中,'mapping added'消息打印的次数正确(即每个参数一次),所以我真的不确定错误在哪里。

1 个答案:

答案 0 :(得分:0)

当您只想克隆某个功能时,可以使用CloneFunction代替CloneFunctionInto

同样CloneFunction向您展示了如何处理ValueToValueMap克隆:

来自CloneFunction.cpp

00223 Function *llvm::CloneFunction(const Function *F, ValueToValueMapTy &VMap,
00224                               bool ModuleLevelChanges,
00225                               ClonedCodeInfo *CodeInfo) {
00226   std::vector<Type*> ArgTypes;
00227 
00228   // The user might be deleting arguments to the function by specifying them in
00229   // the VMap.  If so, we need to not add the arguments to the arg ty vector
00230   //
00231   for (const Argument &I : F->args())
00232     if (VMap.count(&I) == 0) // Haven't mapped the argument to anything yet?
00233       ArgTypes.push_back(I.getType());
00234 
00235   // Create a new function type...
00236   FunctionType *FTy = FunctionType::get(F->getFunctionType()->getReturnType(),
00237                                     ArgTypes, F->getFunctionType()->isVarArg());
00238 
00239   // Create the new function...
00240   Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName());
00241 
00242   // Loop over the arguments, copying the names of the mapped arguments over...
00243   Function::arg_iterator DestI = NewF->arg_begin();
00244   for (const Argument & I : F->args())
00245     if (VMap.count(&I) == 0) {     // Is this argument preserved?
00246       DestI->setName(I.getName()); // Copy the name over...
00247       VMap[&I] = &*DestI++;        // Add mapping to VMap
00248     }
00249 
00250   if (ModuleLevelChanges)
00251     CloneDebugInfoMetadata(NewF, F, VMap);
00252 
00253   SmallVector<ReturnInst*, 8> Returns;  // Ignore returns cloned.
00254   CloneFunctionInto(NewF, F, VMap, ModuleLevelChanges, Returns, "", CodeInfo);
00255   return NewF;
00256 }