[LLVMdev] Creating Pointer Constants

Gordon Henriksen gordonhenriksen at me.com
Wed Mar 11 06:03:59 PDT 2009


On 2009-03-08, at 12:46, Nyx wrote:

> I am writing a JIT compiler for a subset of the Matlab language and  
> as a
> part of my implementation, I would like to be able to pass a constant
> pointer to a native function I'm calling.
>
> Right now, this is what I do:
>
> llvm::Constant* constInt = llvm::ConstantInt::get(llvm::Type::Int64Ty,
> (int64)thePointer);
> llvm::Value* constPtr = llvm::ConstantExpr::getIntToPtr(constInt,
> llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
> 	
> builder.CreateCall(my_function, constPtr);
>
> The resulting IR call looks like this:
>
> call void @nativeFunc(i32* inttoptr (i64 146876396 to i32*))

This is correct.

> I'm just wondering if there is a better way to approach this.  
> Casting a
> pointer to a signed integer and back to a pointer looks both hack- 
> ish, and
> potentially risky (what happens if the address falls in the negative  
> range
> of the signed integer?).

The inttoptr/ptrtoint conversion is perfectly safe so long as you  
match the pointer size and the integer size. (i.e., a 64-bit pointer  
obviously can't fit in an i32.)

— Gordon



More information about the llvm-dev mailing list