0

I want to insert an add instruction in LLVM IR format, something like x = x + 1, where x is global variable. I have tried this:

GlobalVariable* x = new GlobalVariable(mod,Type::getInt32Ty(Context),false,GlobalValue::CommonLinkage,0,"xCounter");

Value one =  ConstantInt::get(Type::getInt32Ty(Context),1);
newInst = BinaryOperator::Create(Instruction::Add, , one ,"counter", insertPos);

But an error occurs, it does not accept type GlobalVariable.

How can I define a global variable and set its value?

1
  • Your last line - how to print it - is really its own question. I removed it from this question, you should ask it separately. Commented Mar 12, 2014 at 15:30

1 Answer 1

1

Global variables are always pointers - in your case, its type will be i32*. You need to load from it first before you can add it with anything. You'll then have to store the new value, using the global variable as the store address.

It's the same with local variables, by the way - alloca values are always pointers.

Sign up to request clarification or add additional context in comments.

2 Comments

Why i need to load the global variable from memory before using it, in my case , the initial value is constant number zero, and how can i use it in add instruction ?
@user3411138 when you have a pointer - and as I've written, global variables are always pointers - then you need to load the value from them first before you can use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.