[LLVMdev] Create a call to function malloc using LLVM API

Dingbao Xie xiedingbao at gmail.com
Mon Jan 26 17:50:52 PST 2015


Hi, I encountered an issue when attempting to create a call to function
malloc.
I just want to do a simple thing, suppose there is a variable p, if p is a
pointer
then allocate memory to p.
Source code:
int *p;
p = (int *) malloc(sizeof(*p));

Try to generate LLVM IR for it:
Type *tp = p->getType();
AllocaInst* arg_alloc = builder.CreateAlloca(tp);//builder is IRBuilder
if(tp->isPointerTy()){
    Type* tpp = tp->getPointerElementType();
    Type* ITy = Type::getInt32Ty(getGlobalContext());
  Constant* AllocSize = ConstantExpr::getSizeOf(tpp)
  AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, ITy);
    CallInst::CreateMalloc(arg_alloc, ITy, tpp, AllocSize);
}
But the generated LLVM IR seems incorrect:
%malloccall = tail call i8* bitcast (i8* (i64)* @malloc to i8* (i32)*)(i32
ptrtoint (i32* getelementptr (i32* null, i32 1) to i32))

I don't quite understand the arguments of the function
 CallInst::CreateMalloc.
Is the second argument  type of p and the third one  type of the element
that p points to?
The size of an integer variable is 4, but if I pass 4 as the last argument
to   CallInst::CreateMalloc, then an assertion failure will occur.







-- 
Dingbao Xie
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20150126/5655da53/attachment.html>


More information about the llvm-dev mailing list