xref: /llvm-project/llvm/lib/Analysis/InstCount.cpp (revision 236fda550d36d35a00785938c3e38b0f402aeda6)
1 //===-- InstCount.cpp - Collects the count of all instructions ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass collects the count of all instructions and reports them
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Analysis/InstCount.h"
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/IR/Function.h"
16 #include "llvm/IR/InstVisitor.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/raw_ostream.h"
20 using namespace llvm;
21 
22 #define DEBUG_TYPE "instcount"
23 
24 STATISTIC(TotalInsts, "Number of instructions (of all types)");
25 STATISTIC(TotalBlocks, "Number of basic blocks");
26 STATISTIC(TotalFuncs, "Number of non-external functions");
27 
28 #define HANDLE_INST(N, OPCODE, CLASS)                                          \
29   STATISTIC(Num##OPCODE##Inst, "Number of " #OPCODE " insts");
30 
31 #include "llvm/IR/Instruction.def"
32 
33 namespace {
34 class InstCount : public InstVisitor<InstCount> {
35   friend class InstVisitor<InstCount>;
36 
37   void visitFunction(Function &F) { ++TotalFuncs; }
38   void visitBasicBlock(BasicBlock &BB) { ++TotalBlocks; }
39 
40 #define HANDLE_INST(N, OPCODE, CLASS)                                          \
41   void visit##OPCODE(CLASS &) {                                                \
42     ++Num##OPCODE##Inst;                                                       \
43     ++TotalInsts;                                                              \
44   }
45 
46 #include "llvm/IR/Instruction.def"
47 
48   void visitInstruction(Instruction &I) {
49     errs() << "Instruction Count does not know about " << I;
50     llvm_unreachable(nullptr);
51   }
52 };
53 } // namespace
54 
55 PreservedAnalyses InstCountPass::run(Function &F,
56                                      FunctionAnalysisManager &FAM) {
57   LLVM_DEBUG(dbgs() << "INSTCOUNT: running on function " << F.getName()
58                     << "\n");
59   InstCount().visit(F);
60 
61   return PreservedAnalyses::all();
62 }
63