3

I am writing a pass to do constant folding. Like this C code:

int a = 4; int b = a + 5; 

I want to transform it to:

int b = 4 + 5; 

But the first segment of code will generate an instruction for int a:

store i32 4, i32* %a, align 4 

How can I get the Value "%a" from this pointer "i32* %a" in my Pass? So that I can replace all use of the Value %a to the ConstantInt ?

2
  • Are you attempting to modify the GlobalVariable "a" at runtime or during your pass? Commented Jan 28, 2016 at 0:47
  • No, "a" is a stack memory location, allocated by alloca. Commented Jan 28, 2016 at 2:26

2 Answers 2

3

Use the load instruction:

%1 = load i32* %a, align 4 
Sign up to request clarification or add additional context in comments.

4 Comments

How can I load the address in my Pass ?
The value of %a is unknown unless you run the program. A Pass doesn't run the program. It simply inspects and/or transform your program.
Oh I see. But actually %a is a "constant". So is there any other method to do this constant folding ? I know a constant 4 is stored into the address, I want to replace all the use of %a to 4 .
I guess you might have to implement that yourself. Memorize the value from store and use it as a replacement in load. This might get complicated though, because %a could be loaded into %1, %2, ... and chains of other variables.
0

For that, first you need to get all the uses of Value %a

Val.user_begin() to val.user_end() via Value::const_user_iterator it 

and check if there Stored instruction is there and only const is stored

 if (const StoreInst* store = dyn_cast<StoreInst>(*it)) 

then you can replace all instances with that const. Note: this is vary simple algo for inst that you have given

a = 5; b = a +4;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.