Calculating the number of the LLVM instructions in a function

Viewed 3035

I have been using

opt -stats -analyze -instcount file.bc

to get statistic info of code. Now I would like to get the number of the LLVM instructions in a function of a particular name, say, "bar".

Ideally, I would expect an option of opt, which would work in this way

opt -stats -analyze -instcount   funcname="bar"

What would be the right option to use? I googled a lot and have not got an answer yet.

2 Answers

Create a function analysis pass. (llvm::FunctionPass documentation)

Your code would look something like this:

// This is a contrived example.

#include <iterator>
#include <string>

#include "llvm/Pass.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"
#include "llvm/Support/raw_ostream.h"

namespace
{

using namespace llvm;

cl::opt<std::string> functionName("funcname", cl::ValueRequired,
  cl::desc("Function name"), cl::NotHidden);

class FunctionInstCounter : public FunctionPass
{
public:
  static char ID;

  FunctionInstCounter()
    : FunctionPass(ID)
  {
    initializeFunctionInstCounterPass(*PassRegistry::getPassRegistry());
  }

  bool runOnFunction(Function& func) override
  {
    if (func.getName() != functionName)
    {
      return false;
    }

    unsigned int instCount = 0;
    for (BasicBlock& bb : func)
    {
      instCount += std::distance(bb.begin(), bb.end());
    }

    llvm::outs() << "Number of instructions in " << func.getName() << ": "
      << instCount << "\n";
    return false;
  }
};

} // namespace

char FunctionInstCounter::ID = 0;

INITIALIZE_PASS(FunctionInstCounter, "funcinstcount",
  "Function instruction counter", false, true)

llvm::Pass* llvm::createFunctionInstCounterPass()
{
  return new FunctionInstCounter();
}

You would call it like this:

opt -funcinstcount -funcname=NameOfFunctionHere
 bool runOnFunction(Function &F) override {
      outs() << "No of Instructions : " <<F.getInstructionCount() << "\n";
  }

I guess the above snippet is sufficient for finding the no of instructions in a function

Related