LLVM  15.0.0git
CostModel.cpp
Go to the documentation of this file.
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 
20 #include "llvm/Analysis/Passes.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/PassManager.h"
24 #include "llvm/InitializePasses.h"
25 #include "llvm/Pass.h"
28 using namespace llvm;
29 
31  "cost-kind", cl::desc("Target cost kind"),
34  "throughput", "Reciprocal throughput"),
36  "latency", "Instruction latency"),
38  "code-size", "Code size"),
40  "size-latency", "Code size and latency")));
41 
42 
43 #define CM_NAME "cost-model"
44 #define DEBUG_TYPE CM_NAME
45 
46 namespace {
47  class CostModelAnalysis : public FunctionPass {
48 
49  public:
50  static char ID; // Class identification, replacement for typeinfo
51  CostModelAnalysis() : FunctionPass(ID) {
54  }
55 
56  /// Returns the expected cost of the instruction.
57  /// Returns -1 if the cost is unknown.
58  /// Note, this method does not cache the cost calculation and it
59  /// can be expensive in some cases.
60  InstructionCost getInstructionCost(const Instruction *I) const {
62  }
63 
64  private:
65  void getAnalysisUsage(AnalysisUsage &AU) const override;
66  bool runOnFunction(Function &F) override;
67  void print(raw_ostream &OS, const Module*) const override;
68 
69  /// The function that we analyze.
70  Function *F = nullptr;
71  /// Target information.
72  const TargetTransformInfo *TTI = nullptr;
73  };
74 } // End of anonymous namespace
75 
76 // Register this pass.
77 char CostModelAnalysis::ID = 0;
78 static const char cm_name[] = "Cost Model Analysis";
79 INITIALIZE_PASS_BEGIN(CostModelAnalysis, CM_NAME, cm_name, false, true)
80 INITIALIZE_PASS_END (CostModelAnalysis, CM_NAME, cm_name, false, true)
81 
83  return new CostModelAnalysis();
84 }
85 
86 void
87 CostModelAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
88  AU.setPreservesAll();
89 }
90 
91 bool
93  this->F = &F;
94  auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
95  TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr;
96 
97  return false;
98 }
99 
100 void CostModelAnalysis::print(raw_ostream &OS, const Module*) const {
101  if (!F)
102  return;
103 
104  for (BasicBlock &B : *F) {
105  for (Instruction &Inst : B) {
107  if (auto CostVal = Cost.getValue())
108  OS << "Cost Model: Found an estimated cost of " << *CostVal;
109  else
110  OS << "Cost Model: Invalid cost";
111 
112  OS << " for instruction: " << Inst << "\n";
113  }
114  }
115 }
116 
119  auto &TTI = AM.getResult<TargetIRAnalysis>(F);
120  OS << "Printing analysis 'Cost Model Analysis' for function '" << F.getName() << "':\n";
121  for (BasicBlock &B : F) {
122  for (Instruction &Inst : B) {
123  // TODO: Use a pass parameter instead of cl::opt CostKind to determine
124  // which cost kind to print.
126  if (auto CostVal = Cost.getValue())
127  OS << "Cost Model: Found an estimated cost of " << *CostVal;
128  else
129  OS << "Cost Model: Invalid cost";
130 
131  OS << " for instruction: " << Inst << "\n";
132  }
133  }
134  return PreservedAnalyses::all();
135 }
llvm::InstructionCost
Definition: InstructionCost.h:29
llvm::PreservedAnalyses
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
llvm::TargetIRAnalysis
Analysis pass providing the TargetTransformInfo.
Definition: TargetTransformInfo.h:2461
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:17
llvm::InstructionCost::getValue
Optional< CostType > getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
Definition: InstructionCost.h:87
llvm::TargetTransformInfo::TCK_Latency
@ TCK_Latency
The latency of instruction.
Definition: TargetTransformInfo.h:212
print
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Definition: ArchiveWriter.cpp:189
llvm::AnalysisManager::getResult
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:780
llvm::Function
Definition: Function.h:60
Pass.h
llvm::TargetTransformInfo
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Definition: TargetTransformInfo.h:167
llvm::TargetTransformInfo::TCK_CodeSize
@ TCK_CodeSize
Instruction code size.
Definition: TargetTransformInfo.h:213
true
basic Basic Alias true
Definition: BasicAliasAnalysis.cpp:1909
F
#define F(x, y, z)
Definition: MD5.cpp:55
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:55
CommandLine.h
llvm::PassRegistry::getPassRegistry
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Definition: PassRegistry.cpp:31
llvm::CostModelPrinterPass::run
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: CostModel.cpp:117
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
false
Definition: StackSlotColoring.cpp:141
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
llvm::Instruction
Definition: Instruction.h:42
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:54
llvm::createCostModelAnalysisPass
FunctionPass * createCostModelAnalysisPass()
Definition: CostModel.cpp:82
llvm::CallingConv::ID
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
INITIALIZE_PASS_END
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:58
llvm::cl::opt
Definition: CommandLine.h:1392
llvm::cl::values
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:685
cm_name
static const char cm_name[]
Definition: CostModel.cpp:78
I
#define I(x, y, z)
Definition: MD5.cpp:58
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
llvm::TargetTransformInfo::TCK_SizeAndLatency
@ TCK_SizeAndLatency
The weighted sum of size and latency.
Definition: TargetTransformInfo.h:214
CostKind
static cl::opt< TargetTransformInfo::TargetCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(TargetTransformInfo::TCK_RecipThroughput), cl::values(clEnumValN(TargetTransformInfo::TCK_RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(TargetTransformInfo::TCK_Latency, "latency", "Instruction latency"), clEnumValN(TargetTransformInfo::TCK_CodeSize, "code-size", "Code size"), clEnumValN(TargetTransformInfo::TCK_SizeAndLatency, "size-latency", "Code size and latency")))
clEnumValN
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:660
CostModel.h
runOnFunction
static bool runOnFunction(Function &F, bool PostInlining)
Definition: EntryExitInstrumenter.cpp:69
llvm::AnalysisUsage::setPreservesAll
void setPreservesAll()
Set by analyses that do not transform their input at all.
Definition: PassAnalysisSupport.h:130
llvm::PreservedAnalyses::all
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
Function.h
PassManager.h
llvm::TargetTransformInfo::getInstructionCost
InstructionCost getInstructionCost(const Instruction *I, enum TargetCostKind kind) const
Query the cost of a specified instruction.
Definition: TargetTransformInfo.h:224
INITIALIZE_PASS_BEGIN
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:51
TargetTransformInfo.h
llvm::AnalysisManager
A container for analyses that lazily runs them and caches their results.
Definition: InstructionSimplify.h:42
llvm::FunctionPass
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:308
llvm::cl::desc
Definition: CommandLine.h:405
raw_ostream.h
llvm::initializeCostModelAnalysisPass
void initializeCostModelAnalysisPass(PassRegistry &)
CM_NAME
#define CM_NAME
Definition: CostModel.cpp:43
InitializePasses.h
llvm::TargetTransformInfo::TCK_RecipThroughput
@ TCK_RecipThroughput
Reciprocal throughput.
Definition: TargetTransformInfo.h:211
Passes.h
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:37