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/Analysis/Passes.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/PassManager.h"
24 #include "llvm/InitializePasses.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 using namespace llvm;
30 
31 static cl::opt<TargetTransformInfo::TargetCostKind> CostKind(
32     "cost-kind", cl::desc("Target cost kind"),
33     cl::init(TargetTransformInfo::TCK_RecipThroughput),
34     cl::values(clEnumValN(TargetTransformInfo::TCK_RecipThroughput,
35                           "throughput", "Reciprocal throughput"),
36                clEnumValN(TargetTransformInfo::TCK_Latency,
37                           "latency", "Instruction latency"),
38                clEnumValN(TargetTransformInfo::TCK_CodeSize,
39                           "code-size", "Code size"),
40                clEnumValN(TargetTransformInfo::TCK_SizeAndLatency,
41                           "size-latency", "Code size and latency")));
42 
43 static cl::opt<bool> TypeBasedIntrinsicCost("type-based-intrinsic-cost",
44     cl::desc("Calculate intrinsics cost based only on argument types"),
45     cl::init(false));
46 
47 #define CM_NAME "cost-model"
48 #define DEBUG_TYPE CM_NAME
49 
50 namespace {
51   class CostModelAnalysis : public FunctionPass {
52 
53   public:
54     static char ID; // Class identification, replacement for typeinfo
55     CostModelAnalysis() : FunctionPass(ID) {
56       initializeCostModelAnalysisPass(
57         *PassRegistry::getPassRegistry());
58     }
59 
60     /// Returns the expected cost of the instruction.
61     /// Returns -1 if the cost is unknown.
62     /// Note, this method does not cache the cost calculation and it
63     /// can be expensive in some cases.
64     InstructionCost getInstructionCost(const Instruction *I) const {
65       return TTI->getInstructionCost(I, TargetTransformInfo::TCK_RecipThroughput);
66     }
67 
68   private:
69     void getAnalysisUsage(AnalysisUsage &AU) const override;
70     bool runOnFunction(Function &F) override;
71     void print(raw_ostream &OS, const Module*) const override;
72 
73     /// The function that we analyze.
74     Function *F = nullptr;
75     /// Target information.
76     const TargetTransformInfo *TTI = nullptr;
77   };
78 }  // End of anonymous namespace
79 
80 // Register this pass.
81 char CostModelAnalysis::ID = 0;
82 static const char cm_name[] = "Cost Model Analysis";
83 INITIALIZE_PASS_BEGIN(CostModelAnalysis, CM_NAME, cm_name, false, true)
84 INITIALIZE_PASS_END  (CostModelAnalysis, CM_NAME, cm_name, false, true)
85 
86 FunctionPass *llvm::createCostModelAnalysisPass() {
87   return new CostModelAnalysis();
88 }
89 
90 void
91 CostModelAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
92   AU.setPreservesAll();
93 }
94 
95 bool
96 CostModelAnalysis::runOnFunction(Function &F) {
97  this->F = &F;
98  auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
99  TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr;
100 
101  return false;
102 }
103 
104 void CostModelAnalysis::print(raw_ostream &OS, const Module*) const {
105   if (!F)
106     return;
107 
108   for (BasicBlock &B : *F) {
109     for (Instruction &Inst : B) {
110       InstructionCost Cost;
111       if (TypeBasedIntrinsicCost && isa<IntrinsicInst>(&Inst)) {
112         auto *II = dyn_cast<IntrinsicInst>(&Inst);
113         IntrinsicCostAttributes ICA(II->getIntrinsicID(), *II,
114                                     InstructionCost::getInvalid(), true);
115         Cost = TTI->getIntrinsicInstrCost(ICA, CostKind);
116       }
117       else {
118         Cost = TTI->getInstructionCost(&Inst, CostKind);
119       }
120       if (auto CostVal = Cost.getValue())
121         OS << "Cost Model: Found an estimated cost of " << *CostVal;
122       else
123         OS << "Cost Model: Invalid cost";
124 
125       OS << " for instruction: " << Inst << "\n";
126     }
127   }
128 }
129 
130 PreservedAnalyses CostModelPrinterPass::run(Function &F,
131                                             FunctionAnalysisManager &AM) {
132   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
133   OS << "Printing analysis 'Cost Model Analysis' for function '" << F.getName() << "':\n";
134   for (BasicBlock &B : F) {
135     for (Instruction &Inst : B) {
136       // TODO: Use a pass parameter instead of cl::opt CostKind to determine
137       // which cost kind to print.
138       InstructionCost Cost;
139       if (TypeBasedIntrinsicCost && isa<IntrinsicInst>(&Inst)) {
140         auto *II = dyn_cast<IntrinsicInst>(&Inst);
141         IntrinsicCostAttributes ICA(II->getIntrinsicID(), *II,
142                                     InstructionCost::getInvalid(), true);
143         Cost = TTI.getIntrinsicInstrCost(ICA, CostKind);
144       }
145       else {
146         Cost = TTI.getInstructionCost(&Inst, CostKind);
147       }
148       if (auto CostVal = Cost.getValue())
149         OS << "Cost Model: Found an estimated cost of " << *CostVal;
150       else
151         OS << "Cost Model: Invalid cost";
152 
153       OS << " for instruction: " << Inst << "\n";
154     }
155   }
156   return PreservedAnalyses::all();
157 }
158