Thiago Bezerra
Thiago Bezerra

Reputation: 61

Pre evaluate LLVM IR

Let's suppose we have expressions like:

  %rem = srem i32 %i.0, 10
  %mul = mul nsw i32 %rem, 2

The question is: Is there a way to get the value of %mul during compile time? I'm writing a llvm Pass and I need to evaluate some expressions which use %i.0. I'm searching for a function, class or something else which I will give a value to %i.0 and it will evaluate the expression and return the result.

Upvotes: 3

Views: 237

Answers (1)

Oak
Oak

Reputation: 26898

You could clone the code (the containing function or the entire module, depending on how much context you need), then replace %i.0 with a constant value, run the constant propagation pass on the code, and finally check whether %mul is assigned to a constant value and if so, extract it.

It's not elegant, but I think it would work. Just pay attention to:

  1. Make sure %mul is not elided out - for example, return it from the function, or store its value to memory, or something.
  2. Be aware constant propagation assumes some things about the code, in particular that it already passed through mem2reg.

Upvotes: 2

Related Questions