KiteRunner
KiteRunner

Reputation: 23

How to get class pointer.instance from llvm instruction iterator?

I am writing llvm pass and my goal is to check if instruction is signed division instruction. I am doing something like that to get instructions in the function:

for (inst_iterator I = inst_begin(&function), E = inst_end(&function); I != E; ++I) {
  errs() << *I << "\n";
};

Above gives me printout like that, example:

 %retval = alloca i32, align 4
  %a = alloca i32, align 4
  %b = alloca i32, align 4
  %c = alloca i32, align 4
  %d = alloca i32, align 4
  %a1 = alloca i32, align 4

How do I get class instance for each instruction so I can check for opCode and compare if it is sDiv? Something like that: I.getOpCode() == SDiv. Thanks!

Upvotes: 0

Views: 700

Answers (1)

jmmartinez
jmmartinez

Reputation: 343

There are several ways to achieve this.

Using Instruction::getOpcode (https://llvm.org/doxygen/classllvm_1_1Instruction.html#ab4e05d690df389b8b1477c90387b575f) as you suggested:

for(auto I = inst_begin(F), E = inst_end(F); I != E; ++I) {
  Instruction &Inst = *I;
  if(Inst.getOpcode() == Instruction::SDiv) {
    errs() << "wahou!\n"; 
  }
}

You could match SDivOperator (https://llvm.org/doxygen/classllvm_1_1SDivOperator.html) using isa or dyn_cast (https://llvm.org/docs/ProgrammersManual.html#the-isa-cast-and-dyn-cast-templates).

for(auto I = inst_begin(F), E = inst_end(F); I != E; ++I) {
  Instruction &Inst = *I;
  if(isa<SDivOperator>(Inst)) {
    errs() << "wahou!\n"; 
  }
}

or

for(auto I = inst_begin(F), E = inst_end(F); I != E; ++I) {
  Instruction &Inst = *I;
  if(SDivOperator *SDiv = dyn_cast<SDivOperator>(&Inst)) {
    errs() << "wahou!\n"; 
  }
}

Be aware that SDivOperator would match both sdiv instructions and constant expressions. However, since you're iterating over the instructions of a function, you will only find the former.

Upvotes: 1

Related Questions