Reputation: 736
I encountered a problem when attempting to create a call to function malloc. Below is the code that I use to allocate memory to a pointer
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);
}
}
But I got an error:
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
I just want to do a simple thing: suppose there is a variable p, if p is a pointer then allocate memory to p. Any hint to get around of this error?
Upvotes: 5
Views: 2960
Reputation: 1727
If Ty is the Type of the allocation:
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, "");
is roughly what you want.
Upvotes: 6