Qoros
Qoros

Reputation: 513

How to Compare Pointers in LLVM-IR?

I want to analyze the pointer values in LLVM IR.

As illustrated in LLVM Value Class,

Value is is a very important LLVM class. It is the base class of all values computed by a program that may be used as operands to other values. Value is the super class of other important classes such as Instruction and Function. All Values have a Type. Type is not a subclass of Value. Some values can have a name and they belong to some Module. Setting the name on the Value automatically updates the module's symbol table.

To test if a Value is a pointer or not, there is a function a->getType()->isPointerTy(). LLVM also provides a LLVM PointerType class, however there are not direct apis to compare the values of pointers.

So I wonder how to compare these pointer values, to test if they are equal or not. I know there is AliasAnalysis, but I have doubt with the AliasAnalysis results, so I want to validate it myself.

Upvotes: 2

Views: 3245

Answers (2)

horses.of.evil
horses.of.evil

Reputation: 1

Old post, but the answer given here is not correct anymore. LLVM's icmp instruction will compare pointers. ptrtoint is not needed. CreateICmpEQ should work fine to check if two pointers are equal.

From the docs:

The ‘icmp’ instruction returns a boolean value or a vector of 
boolean values based on comparison of its two integer, 
integer vector, pointer, or pointer vector operands.

Upvotes: 0

acheron
acheron

Reputation: 116

The quick solution is to use IRBuilder::CreatePtrDiff. This will compute the difference between the two pointers, and return an i64 result. If the pointers are equal, this will be zero, and otherwise, it will be nonzero.

It might seem excessive, seeing as CreatePtrDiff will make an extra effort to compute the result in terms of number of elements rather than number of bytes, but in all likelihood that extra division will get optimized out.

The other option is to use a ptrtoint instruction, with a reasonably large result type such as i64, and then do an integer comparison.

From the online reference:

Value *     CreatePtrDiff (Value *LHS, Value *RHS, const Twine &Name="")
Return the i64 difference between two pointer values, dividing out the size of the pointed-to objects.

Upvotes: 5

Related Questions