LLVM 函数 * getParent() 从 mmap 读取模块后失败



我使用 mmap 将 IR 文件加载到内存中。但是在我这样做之后,我无法通过F->getParent((->getName(( API获取模块名称。谁能给我一些提示?相关代码如下:

for (unsigned i = 0; i < InputFilenames.size(); ++i) {
/*Use mmap to load files into memory*/
StringRef MName MName = StringRef(strdup(InputFilenames[i].data()));
if ((fd = open(MName.str().c_str(), O_RDWR)) < 0) {
perror(MName.str().c_str());
}
if ((fstat(fd, &sb)) == -1) {
errs() << "stat:n";
perror(MName.str().c_str());
continue;
}
else {
if (sb.st_mode & S_IFDIR) {
continue;
}
}
if ((mapped = (char *)mmap(NULL, sb.st_size, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0)) == (void *)-1) {
perror("mmap");
OP << MName.str() << " not mapped.n";
}
close(fd);
/*Get IR Module from memory buffer*/
std::string IRString(mapped, mapped + sb.st_size);
std::unique_ptr<MemoryBuffer> memBuffer = 
MemoryBuffer::getMemBuffer(IRString);
MemoryBuffer *mem = memBuffer.release();
std::unique_ptr<Module> M = parseIR(mem->getMemBufferRef(), Err, *LLVMCtx);
Module *Md = M.release();
for (auto curFref = Md->getFunctionList().begin(), 
endFref = Md->getFunctionList().end(); 
curFref != endFref; ++curFref) {
if (curFref->empty())
continue;
/*"curFref->getParent()->getName()" prints nothing. */
errs() << "--" << curFref->getName() 
<< " from Module : "<<curFref->getParent()->getName()<<"n";
}
}

我认为parseIR((是错误的函数,它会解析文本格式,而不是位码文件。你想要的那个叫做parseBitcodeFile((。也许是这样的:

auto buffer = MemoryBuffer::getFile(…);
if(buffer) {
auto bitcode = llvm::parseBitcodeFile(buffer.get()->getMemBufferRef(),
getContext());
if(bitcode) {
module = std::move(bitcode.get());

您必须添加错误处理,if()测试至关重要。LLVM 中有一个非常好的类似指针的类,它只允许您在检查它是否正常后取消引用"指针"。因此,以您想要的方式添加错误处理,感觉良好,并度过美好的一天。

最新更新