LLVM 17.0.0git
Go to the documentation of this file.
1//===- CostModel.cpp ------ Cost Model Analysis ---------------------------===//
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
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.
22#include "llvm/IR/Function.h"
23#include "llvm/IR/PassManager.h"
25#include "llvm/Pass.h"
29using namespace llvm;
32 "cost-kind", cl::desc("Target cost kind"),
35 "throughput", "Reciprocal throughput"),
37 "latency", "Instruction latency"),
39 "code-size", "Code size"),
41 "size-latency", "Code size and latency")));
43static cl::opt<bool> TypeBasedIntrinsicCost("type-based-intrinsic-cost",
44 cl::desc("Calculate intrinsics cost based only on argument types"),
45 cl::init(false));
47#define CM_NAME "cost-model"
50namespace {
51 class CostModelAnalysis : public FunctionPass {
53 public:
54 static char ID; // Class identification, replacement for typeinfo
55 CostModelAnalysis() : FunctionPass(ID) {
58 }
60 private:
61 void getAnalysisUsage(AnalysisUsage &AU) const override;
62 bool runOnFunction(Function &F) override;
63 void print(raw_ostream &OS, const Module*) const override;
65 /// The function that we analyze.
66 Function *F = nullptr;
67 /// Target information.
68 const TargetTransformInfo *TTI = nullptr;
69 };
70} // End of anonymous namespace
72// Register this pass.
73char CostModelAnalysis::ID = 0;
74static const char cm_name[] = "Cost Model Analysis";
75INITIALIZE_PASS_BEGIN(CostModelAnalysis, CM_NAME, cm_name, false, true)
76INITIALIZE_PASS_END (CostModelAnalysis, CM_NAME, cm_name, false, true)
79 return new CostModelAnalysis();
83CostModelAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.setPreservesAll();
88CostModelAnalysis::runOnFunction(Function &F) {
89 this->F = &F;
90 auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
91 TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr;
93 return false;
96void CostModelAnalysis::print(raw_ostream &OS, const Module*) const {
97 if (!F)
98 return;
100 for (BasicBlock &B : *F) {
101 for (Instruction &Inst : B) {
103 auto *II = dyn_cast<IntrinsicInst>(&Inst);
104 if (II && TypeBasedIntrinsicCost) {
105 IntrinsicCostAttributes ICA(II->getIntrinsicID(), *II,
108 }
109 else {
111 }
113 if (auto CostVal = Cost.getValue())
114 OS << "Cost Model: Found an estimated cost of " << *CostVal;
115 else
116 OS << "Cost Model: Invalid cost";
118 OS << " for instruction: " << Inst << "\n";
119 }
120 }
125 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
126 OS << "Printing analysis 'Cost Model Analysis' for function '" << F.getName() << "':\n";
127 for (BasicBlock &B : F) {
128 for (Instruction &Inst : B) {
129 // TODO: Use a pass parameter instead of cl::opt CostKind to determine
130 // which cost kind to print.
132 auto *II = dyn_cast<IntrinsicInst>(&Inst);
133 if (II && TypeBasedIntrinsicCost) {
134 IntrinsicCostAttributes ICA(II->getIntrinsicID(), *II,
137 }
138 else {
140 }
142 if (auto CostVal = Cost.getValue())
143 OS << "Cost Model: Found an estimated cost of " << *CostVal;
144 else
145 OS << "Cost Model: Invalid cost";
147 OS << " for instruction: " << Inst << "\n";
148 }
149 }
150 return PreservedAnalyses::all();
basic Basic Alias true
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Definition: CommandLine.h:678
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")))
static cl::opt< bool > TypeBasedIntrinsicCost("type-based-intrinsic-cost", cl::desc("Calculate intrinsics cost based only on argument types"), cl::init(false))
static const char cm_name[]
Definition: CostModel.cpp:74
#define CM_NAME
Definition: CostModel.cpp:47
#define F(x, y, z)
Definition: MD5.cpp:55
This header defines various interfaces for pass management in LLVM.
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:59
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
raw_pwrite_stream & OS
This pass exposes codegen information to IR-level passes.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:774
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: CostModel.cpp:123
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:308
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
static InstructionCost getInvalid(CostType Val=0)
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition: Pass.cpp:130
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCK_Latency
The latency of instruction.
InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:703
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void initializeCostModelAnalysisPass(PassRegistry &)
FunctionPass * createCostModelAnalysisPass()
Definition: CostModel.cpp:78