I have the following prototype for a function:
void bkp_memory(char *, int);
Inside my LLVM IR, I have a callsite looks like the following:
tail call void @bkp_memory(i8* bitcast (i32** @P to i8*), i32 4) nounwind
When I try to obtain its 1st argument and check whether it is a valid instruction, using:
Instruction *Inst = dyn_cast<Instruction *>(I->getOperand(0));
it gives me a NULL Ptr, which is quite a surprise to me.
Am I doing anything wrong here?
The bitcast you see above is not an instruction. Rather, it is a constant expression and is represented by a ConstExpr object in the C++ API. That is most likely because @P is a constant (a function pointer, global value, or something similar).
- Use the stripPointerCasts() method of llvm::Value to strip away all pointer casts (whether they are cast instructions or ConstExpr casts):
- Realize that not all operands are instructions. In this case, the operand is probably a global variable. Chances are good that:
… will return NULL because the operand is a constant and not an instruction.
Note that in many other cases, the bkp_memory() callsite won’t have the embedded form. They look like:
store i32* %21, i32** @P, align 4
%22 = bitcast i32* %21 to i8*
tail call void @bkp_memory(i8* %22, i32 4) nounwind
And the dyn_cast<> conversion is fine in these cases.
Would that be the problem?
The “embedded” form is a constant expression. The “unembedded” form is an instruction. LLVM has several constant expressions that are modeled after instructions; the difference is that a constant expression’s operands are all constants, and therefore the constant expression can also be used like a constant.
For more details, please see the LLVM Language Reference manual.
– John T.