Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly iterate over llvm::Instructions in a function

Tags:

llvm

llvm-ir

Is there a way to randomly iterate over llvm::Instructions in a function? Say a function has several branches. I'd like to randomly follow different paths each time I iterate over the function's instructions.

like image 559
Chris Smyth Avatar asked Jun 12 '26 08:06

Chris Smyth


1 Answers

First, make a function to return a random iterator:

template<typename T>
typename T::iterator getRandomIterator(T& t)
{
    if(!t.size())
        return t.end();
    size_t randIdx = ::rand() % t.size();
    auto i = t.begin();
    std::advance(i, randIdx);
    return i;
}

Then copy all instructions you want to work on into a temporary vector:

#include <llvm/IR/InstIterator.h>

std::vector<Instruction*> insts;
std::copy(inst_begin(F), inst_end(F), insts);

Then walk over them, until you visit every instruction:

while(!insts.empty())
{
  auto It = getRandomIterator(insts);
  // do something
  insts.erase(It);
}
like image 198
arrowd Avatar answered Jun 17 '26 08:06

arrowd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!