Hi,all
I have a Value* type named indexValue, and the type is i32.
I think “indexValue” must hold a number which type is int.
Now I want to use the exact number which pointed by indexValue , so I do like this:
ConstantInt* CI = llvm::castllvm::ConstantInt(indexValue); //This is wrong, so is dyn_cast.
uint64_t index = indexValue->getZExtValue();
uint64_t size = index + 1;
I don’t know if it is the right way.
So, could anybody tell the way to get the integer content from a Value* which type is i32?
I’ll be very very grateful if there is any answer.
From: llvmdev-bounces@cs.uiuc.edu [mailto:llvmdev-bounces@cs.uiuc.edu]
On Behalf Of weixuegong
Subject: [LLVMdev] How to get the exact integer from a Value
I have a Value* type named indexValue, and the type is i32.
I think "indexValue" must hold a number which type is int.
Correct, but it might not be a constant.
ConstantInt* CI = llvm::cast<llvm::ConstantInt>(indexValue); //This is wrong, so is dyn_cast.
uint64_t index = indexValue->getZExtValue();
uint64_t size = index + 1;
Actually dyn_cast<> is what you want, used like this:
ConstantInt* CI = dyn_cast<ConstantInt>(indexValue);
int64_t index = (CI == NULL) ? -1 : CI->getZExtValue();
Note that you must use the result of the cast, not the original Value* variable. Also, you must deal with the fact that the result of the cast might be NULL.
- Chuck
Thank you, Chuck! It works.
And, please forgive my greed : ), another question:
I found that: In IR of llvm which generated by my testing code, there is a Inst said " getelementptr inbounds [5 x i32]* %idxarr, i32 0, i64 3".
The idxarr is my array name, and I think Inst means getting the ptr of the 4th (3+1) element of array "idxarr", am I right?
So the question is: how can I add this Inst in IR (In other words, is there an API method in IRBuilder or other class to generate "getelementptr"?). I searched for a while, but I found nothing.
I will appreciate if you could give me some suggestion on this.
Thank you.
Hello Wei,
One of the trick I use to know what and how llvm functions to use to generate desired llvm instructions, types etc is -
Write a C code which will produce the desired instructions and then compile using C++ backend.
eg. Write the C code
int arr[10];
main(int argc, char* argv[])
{
arr[2] = argc;
printf("%d",arr[2]);
}
Compile it to llvm IR using clang, check if this generate instruction you want. Then use llc -march=cpp and you get the code you are supposed to write 
Something like -
const_ptr_15_indices.push_back(const_int32_14);
ConstantInt* const_int64_16 = ConstantInt::get(mod->getContext(), APInt(64, StringRef(“2”), 10));
const_ptr_15_indices.push_back(const_int64_16);
Constant* const_ptr_15 = ConstantExpr::getGetElementPtr(gvar_array_arr, &const_ptr_15_indices[0], const_ptr_15_indices.size());
Earlier it was even easier with online demo tool http://llvm.org/demo/.
Hope it helps.
Regards,
Ankur