1 //===- CostModel.cpp ------ Cost Model Analysis ---------------------------===//
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 file defines the cost model analysis. It provides a very basic cost
10 // estimation for LLVM-IR. This analysis uses the services of the codegen
11 // to approximate the cost of any IR instruction when lowered to machine
12 // instructions. The cost results are unit-less and the cost number represents
13 // the throughput of the machine assuming that all loads hit the cache, all
14 // branches are predicted, etc. The cost numbers can be added in order to
15 // compare two or more transformation alternatives.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Analysis/CostModel.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Analysis/Passes.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/PassManager.h"
25 #include "llvm/InitializePasses.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm;
31 
32 static cl::opt<TargetTransformInfo::TargetCostKind> CostKind(
33     "cost-kind", cl::desc("Target cost kind"),
34     cl::init(TargetTransformInfo::TCK_RecipThroughput),
35     cl::values(clEnumValN(TargetTransformInfo::TCK_RecipThroughput,
36                           "throughput", "Reciprocal throughput"),
37                clEnumValN(TargetTransformInfo::TCK_Latency,
38                           "latency", "Instruction latency"),
39                clEnumValN(TargetTransformInfo::TCK_CodeSize,
40                           "code-size", "Code size"),
41                clEnumValN(TargetTransformInfo::TCK_SizeAndLatency,
42                           "size-latency", "Code size and latency")));
43 
44 
45 #define CM_NAME "cost-model"
46 #define DEBUG_TYPE CM_NAME
47 
48 namespace {
49   class CostModelAnalysis : public FunctionPass {
50 
51   public:
52     static char ID; // Class identification, replacement for typeinfo
CostModelAnalysis()53     CostModelAnalysis() : FunctionPass(ID), F(nullptr), TTI(nullptr) {
54       initializeCostModelAnalysisPass(
55         *PassRegistry::getPassRegistry());
56     }
57 
58     /// Returns the expected cost of the instruction.
59     /// Returns -1 if the cost is unknown.
60     /// Note, this method does not cache the cost calculation and it
61     /// can be expensive in some cases.
getInstructionCost(const Instruction * I) const62     InstructionCost getInstructionCost(const Instruction *I) const {
63       return TTI->getInstructionCost(I, TargetTransformInfo::TCK_RecipThroughput);
64     }
65 
66   private:
67     void getAnalysisUsage(AnalysisUsage &AU) const override;
68     bool runOnFunction(Function &F) override;
69     void print(raw_ostream &OS, const Module*) const override;
70 
71     /// The function that we analyze.
72     Function *F;
73     /// Target information.
74     const TargetTransformInfo *TTI;
75   };
76 }  // End of anonymous namespace
77 
78 // Register this pass.
79 char CostModelAnalysis::ID = 0;
80 static const char cm_name[] = "Cost Model Analysis";
INITIALIZE_PASS_BEGIN(CostModelAnalysis,CM_NAME,cm_name,false,true)81 INITIALIZE_PASS_BEGIN(CostModelAnalysis, CM_NAME, cm_name, false, true)
82 INITIALIZE_PASS_END  (CostModelAnalysis, CM_NAME, cm_name, false, true)
83 
84 FunctionPass *llvm::createCostModelAnalysisPass() {
85   return new CostModelAnalysis();
86 }
87 
88 void
getAnalysisUsage(AnalysisUsage & AU) const89 CostModelAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
90   AU.setPreservesAll();
91 }
92 
93 bool
runOnFunction(Function & F)94 CostModelAnalysis::runOnFunction(Function &F) {
95  this->F = &F;
96  auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
97  TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr;
98 
99  return false;
100 }
101 
print(raw_ostream & OS,const Module *) const102 void CostModelAnalysis::print(raw_ostream &OS, const Module*) const {
103   if (!F)
104     return;
105 
106   for (BasicBlock &B : *F) {
107     for (Instruction &Inst : B) {
108       InstructionCost Cost = TTI->getInstructionCost(&Inst, CostKind);
109       if (auto CostVal = Cost.getValue())
110         OS << "Cost Model: Found an estimated cost of " << *CostVal;
111       else
112         OS << "Cost Model: Invalid cost";
113 
114       OS << " for instruction: " << Inst << "\n";
115     }
116   }
117 }
118 
run(Function & F,FunctionAnalysisManager & AM)119 PreservedAnalyses CostModelPrinterPass::run(Function &F,
120                                             FunctionAnalysisManager &AM) {
121   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
122   OS << "Cost Model for function '" << F.getName() << "'\n";
123   for (BasicBlock &B : F) {
124     for (Instruction &Inst : B) {
125       // TODO: Use a pass parameter instead of cl::opt CostKind to determine
126       // which cost kind to print.
127       InstructionCost Cost = TTI.getInstructionCost(&Inst, CostKind);
128       if (auto CostVal = Cost.getValue())
129         OS << "Cost Model: Found an estimated cost of " << *CostVal;
130       else
131         OS << "Cost Model: Invalid cost";
132 
133       OS << " for instruction: " << Inst << "\n";
134     }
135   }
136   return PreservedAnalyses::all();
137 }
138