如何使用LLVM API创建对malloc函数的调用?

时间:2015-01-26 00:04:26

标签: llvm

我在尝试创建函数malloc的调用时遇到了问题。下面是我用来为指针分配内存的代码

Type* tp = argument->getType();
AllocaInst* arg_alloc = builder.CreateAlloca(tp);
if(tp->isPointerTy()){
    if(!tp->getContainedType(0)->isPointerTy()){
    Value *alloc_size = ConstantInt::get(Type::getInt64Ty(getGlobalContext()), 
                         dl->getTypeAllocSize(tp->getPointerElementType()), false);
    CallInst::CreateMalloc(arg_alloc, tp, tp->getPointerElementType(), alloc_size);

    }
}

但我收到了一个错误:

llvm-3.4/include/llvm/Support/Casting.h:239: typename 
llvm::cast_retty<X, Y*>::ret_type llvm::cast(Y*) [with X =    
llvm::IntegerType; Y = llvm::Type; typename llvm::cast_retty<X,   
Y*>::ret_type = llvm::IntegerType*]: Assertion `isa<X>(Val) && 
"cast<Ty>() argument of incompatible type!"' failed.
0  libLLVM-3.4.so  0x00007f01246a4035   llvm::sys::PrintStackTrace(_IO_FILE*) + 37
1  libLLVM-3.4.so  0x00007f01246a3fb3
2  libpthread.so.0 0x00007f012392d340
3  libc.so.6       0x00007f0122a0cbb9 gsignal + 57
4  libc.so.6       0x00007f0122a0ffc8 abort + 328
5  libc.so.6       0x00007f0122a05a76
6  libc.so.6       0x00007f0122a05b22
7  libLLVM-3.4.so  0x00007f01240a85bc llvm::ConstantInt::get(llvm::Type*, unsigned long, bool) + 140
8  libLLVM-3.4.so  0x00007f012413ce0e
9  libLLVM-3.4.so  0x00007f012413d6bb llvm::CallInst::CreateMalloc(llvm::Instruction*, llvm::Type*, llvm::Type*, llvm::Value*, llvm::Value*, llvm::Function*, llvm::Twine const&) + 43

我只想做一件简单的事情:假设有一个变量p,如果p是 然后指针将内存分配给p。是否有任何提示可以解决此错误?

1 个答案:

答案 0 :(得分:4)

如果Ty是分配类型:

Type* ITy = Type::getInt32Ty(Context);
Constant* AllocSize = ConstantExpr::getSizeOf(Ty);
AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, ITy);
Instruction* Malloc = CallInst::CreateMalloc(Builder->GetInsertBlock(),
                                             ITy, Ty, AllocSize,
                                             nullptr, nullptr, "");

大致是你想要的。