Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a Global Variable in a LLVM module?

Tags:

c++

llvm

clang

I want to add an instruction at the end of a basic block to increment a GlobalVariable (using the LLVM C++ library). I am pretty new to to the LLVM, can I do this directly or does this require loading the global variable, incrementing it by the desired value and writing back to the global variable ?

Even if I load the variable (with LoadInst constructor), How will the "Add" instruction know where is the variable ?

For example, look at this IR ocde :

%cell_index = load i32* %cell_index_ptr
%new_cell_index = add i32 1, %cell_index

the add instruction knows on which variable to operate (cell_index). But since I will create the load instruction from the C++ I don't know where the variable will be created.

like image 366
mdrlol Avatar asked May 14 '15 03:05

mdrlol


People also ask

How to create global variables in LLVM?

Global variables have visibility of all the functions within a given module. LLVM provides the GlobalVariable class to create global variables and set its properties such as linkage type, alignment, and so on. The Module class has the method getOrInsertGlobal () to create a global variable.

What is a globalvalrefmap in LLVM?

A module maintains a GlobalValRefMap object that is used to hold all constant references to global variables in the module. When a global variable is destroyed, it should have no entries in the GlobalValueRefMap. The main container class for the LLVM Intermediate Representation. Definition at line 65 of file Module.h. The Global Alias iterators.

What are modmodules in LLVM?

Modules are the top level container of all other LLVM Intermediate Representation (IR) objects. Each module directly contains a list of globals variables, a list of functions, a list of libraries (or other modules) this module depends on, a symbol table, and various data about the target's characteristics.

How do you create a global variable in a module?

The Module class has the method getOrInsertGlobal () to create a global variable. It takes two arguments—the first is the name of the variable and the second is the data type of the variable. As global variables are part of a module, we create global variables after creating the module.


Video Answer


1 Answers

Yes, you'll have to create load, add, and store instructions.

In LLVM's C++ class hierarchy, Instruction subclasses Value. When you create your LoadInst, you can just refer to it directly when creating new instructions. For example:

IRBuilder<> IR(SomeInsertionPoint);
LoadInst *Load = IR.CreateLoad(MyGlobalVariable);
Value *Inc = IR.CreateAdd(IR.getInt32(1), Load);
StoreInst *Store = IR.CreateStore(Inc, MyGlobalVariable);
like image 197
Ismail Badawi Avatar answered Sep 23 '22 16:09

Ismail Badawi