Instvisitor

Reference 1

Class InstVisitor:

Base class for instruction visitors

Instruction visitors are used when you want to perform different actions for different kinds of instructions without having to use lots of casts and a big switch statement (in your code, that is).

To define your own visitor, inherit from this class, specifying your new type for the ‘SubClass’ template parameter, and “override” visitXXX functions in your class. I say “override” because this class is defined in terms of statically resolved overloading, not virtual functions.

For example, here is a visitor that counts the number of malloc instructions processed:

Declare the class. Note that we derive from InstVisitor instantiated with our new subclasses type.

 struct CountAllocaVisitor : public InstVisitor<CountAllocaVisitor> {
   unsigned Count;
   CountAllocaVisitor() : Count(0) {}

   void visitAllocaInst(AllocaInst &AI) { ++Count; }
 };

 And this class would be used like this:
   CountAllocaVisitor CAV;
   CAV.visit(function);
   NumAllocas = CAV.Count;

The defined has ‘visit’ methods for Instruction, and also for BasicBlock, Function, and Module, which recursively process all contained instructions.

Note that if you don’t implement visitXXX for some instruction type, the visitXXX method for instruction superclass will be invoked. So if instructions are added in the future, they will be automatically supported, if you handle one of their superclasses.

The optional second template argument specifies the type that instruction visitation functions should return. If you specify this, you MUST provide an implementation of visitInstruction though!.

Note that this class is specifically designed as a template to avoid virtual function call overhead. Defining and using an InstVisitor is just as efficient as having your own switch statement over the instruction opcode.

Created Nov 1, 2019 // Last Updated Nov 1, 2019

If you could revise
the fundmental principles of
computer system design
to improve security...

... what would you change?