1//===-- RISCVSubtarget.cpp - RISC-V Subtarget Information -----------------===//
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 implements the RISC-V specific subclass of TargetSubtargetInfo.
10//
11//===----------------------------------------------------------------------===//
12
13#include "RISCVSubtarget.h"
14#include "GISel/RISCVCallLowering.h"
15#include "GISel/RISCVInlineAsmLowering.h"
16#include "GISel/RISCVLegalizerInfo.h"
17#include "RISCV.h"
18#include "RISCVFrameLowering.h"
19#include "RISCVSelectionDAGInfo.h"
20#include "RISCVTargetMachine.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/MC/MCSchedule.h"
24#include "llvm/MC/TargetRegistry.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/ErrorHandling.h"
27
28using namespace llvm;
29
30static cl::opt<unsigned> SchedMispredictPenalty(
31 "riscv-sched-mispredict-penalty", cl::Hidden,
32 cl::init(Val: MCSchedModel::DefaultMispredictPenalty),
33 cl::cat(MCScheduleOptions),
34 cl::desc("Override the mispredict penalty (in cycles) in the scheduler "
35 "model. A non-negative value overrides the target default."));
36
37static cl::opt<unsigned> SchedLoadLatency(
38 "riscv-sched-load-latency", cl::Hidden,
39 cl::init(Val: MCSchedModel::DefaultLoadLatency), cl::cat(MCScheduleOptions),
40 cl::desc("Override the load latency (in cycles) in the scheduler model. "
41 "A non-negative value overrides the target default."));
42
43#define DEBUG_TYPE "riscv-macro-fusion"
44
45#define GET_RISCV_MACRO_FUSION_PRED_IMPL
46#include "RISCVGenMacroFusion.inc"
47
48#undef DEBUG_TYPE
49#define DEBUG_TYPE "riscv-subtarget"
50
51#define GET_SUBTARGETINFO_TARGET_DESC
52#define GET_SUBTARGETINFO_CTOR
53#include "RISCVGenSubtargetInfo.inc"
54
55namespace llvm::RISCVTuneInfoTable {
56
57#define GET_RISCVTuneInfoTable_IMPL
58#include "RISCVGenSearchableTables.inc"
59} // namespace llvm::RISCVTuneInfoTable
60
61static cl::opt<bool> RISCVDisableUsingConstantPoolForLargeInts(
62 "riscv-disable-using-constant-pool-for-large-ints",
63 cl::desc("Disable using constant pool for large integers."),
64 cl::init(Val: false), cl::Hidden);
65
66static cl::opt<unsigned> RISCVMaxBuildIntsCost(
67 "riscv-max-build-ints-cost",
68 cl::desc("The maximum cost used for building integers."), cl::init(Val: 0),
69 cl::Hidden);
70
71static cl::opt<bool> UseAA("riscv-use-aa", cl::init(Val: true),
72 cl::desc("Enable the use of AA during codegen."));
73
74static cl::opt<unsigned> RISCVMinimumJumpTableEntries(
75 "riscv-min-jump-table-entries", cl::Hidden,
76 cl::desc("Set minimum number of entries to use a jump table on RISCV"));
77
78static cl::opt<bool> UseMIPSLoadStorePairsOpt(
79 "use-riscv-mips-load-store-pairs",
80 cl::desc("Enable the load/store pair optimization pass"), cl::init(Val: false),
81 cl::Hidden);
82
83static cl::opt<bool> UseMIPSCCMovInsn("use-riscv-mips-ccmov",
84 cl::desc("Use 'mips.ccmov' instruction"),
85 cl::init(Val: true), cl::Hidden);
86
87void RISCVSubtarget::anchor() {}
88
89RISCVSubtarget &
90RISCVSubtarget::initializeSubtargetDependencies(const Triple &TT, StringRef CPU,
91 StringRef TuneCPU, StringRef FS,
92 StringRef ABIName) {
93 // Determine default and user-specified characteristics
94 bool Is64Bit = TT.isArch64Bit();
95 if (CPU.empty() || CPU == "generic")
96 CPU = Is64Bit ? "generic-rv64" : "generic-rv32";
97
98 if (TuneCPU.empty())
99 TuneCPU = CPU;
100 if (TuneCPU == "generic")
101 TuneCPU = Is64Bit ? "generic-rv64" : "generic-rv32";
102
103 TuneInfo = RISCVTuneInfoTable::getRISCVTuneInfo(Name: TuneCPU);
104 // If there is no TuneInfo for this CPU, we fail back to generic.
105 if (!TuneInfo)
106 TuneInfo = RISCVTuneInfoTable::getRISCVTuneInfo(Name: "generic");
107 assert(TuneInfo && "TuneInfo shouldn't be nullptr!");
108
109 ParseSubtargetFeatures(CPU, TuneCPU, FS);
110
111 RISCV::updateCZceFeatureImplications(STI&: *this);
112
113 // Re-sync the flags.
114 HasStdExtZcd = hasFeature(Feature: RISCV::FeatureStdExtZcd);
115 HasStdExtZcf = hasFeature(Feature: RISCV::FeatureStdExtZcf);
116 HasStdExtC = hasFeature(Feature: RISCV::FeatureStdExtC);
117 HasStdExtZce = hasFeature(Feature: RISCV::FeatureStdExtZce);
118
119 TargetABI = RISCVABI::computeTargetABI(STI: *this, ABIName);
120 RISCVFeatures::validate(TT, FeatureBits: getFeatureBits());
121 return *this;
122}
123
124RISCVSubtarget::RISCVSubtarget(const Triple &TT, StringRef CPU,
125 StringRef TuneCPU, StringRef FS,
126 StringRef ABIName, unsigned RVVVectorBitsMin,
127 unsigned RVVVectorBitsMax,
128 const TargetMachine &TM)
129 : RISCVGenSubtargetInfo(TT, CPU, TuneCPU, FS),
130 IsLittleEndian(TT.isLittleEndian()), RVVVectorBitsMin(RVVVectorBitsMin),
131 RVVVectorBitsMax(RVVVectorBitsMax),
132 FrameLowering(
133 initializeSubtargetDependencies(TT, CPU, TuneCPU, FS, ABIName)),
134 InstrInfo(*this), TLInfo(TM, *this) {
135 TSInfo = std::make_unique<RISCVSelectionDAGInfo>();
136}
137
138RISCVSubtarget::~RISCVSubtarget() = default;
139
140const SelectionDAGTargetInfo *RISCVSubtarget::getSelectionDAGInfo() const {
141 return TSInfo.get();
142}
143
144const InlineAsmLowering *RISCVSubtarget::getInlineAsmLowering() const {
145 if (!InlineAsmLoweringInfo)
146 InlineAsmLoweringInfo.reset(
147 p: new RISCVInlineAsmLowering(getTargetLowering()));
148 return InlineAsmLoweringInfo.get();
149}
150
151const CallLowering *RISCVSubtarget::getCallLowering() const {
152 if (!CallLoweringInfo)
153 CallLoweringInfo.reset(p: new RISCVCallLowering(*getTargetLowering()));
154 return CallLoweringInfo.get();
155}
156
157InstructionSelector *RISCVSubtarget::getInstructionSelector() const {
158 if (!InstSelector) {
159 InstSelector.reset(p: createRISCVInstructionSelector(
160 *static_cast<const RISCVTargetMachine *>(&TLInfo.getTargetMachine()),
161 *this, *getRegBankInfo()));
162 }
163 return InstSelector.get();
164}
165
166const LegalizerInfo *RISCVSubtarget::getLegalizerInfo() const {
167 if (!Legalizer)
168 Legalizer.reset(p: new RISCVLegalizerInfo(*this));
169 return Legalizer.get();
170}
171
172const RISCVRegisterBankInfo *RISCVSubtarget::getRegBankInfo() const {
173 if (!RegBankInfo)
174 RegBankInfo.reset(p: new RISCVRegisterBankInfo(getHwMode()));
175 return RegBankInfo.get();
176}
177
178bool RISCVSubtarget::useConstantPoolForLargeInts() const {
179 return !RISCVDisableUsingConstantPoolForLargeInts;
180}
181
182// Returns true if VT is a P extension packed SIMD type.
183bool RISCVSubtarget::isPExtPackedType(MVT VT) const {
184 if (!HasStdExtP)
185 return false;
186
187 // RV32 supports 32-bit and 64-bit vectors. RV64 only support 64-bit vectors.
188 if (!is64Bit() && (VT == MVT::v4i8 || VT == MVT::v2i16))
189 return true;
190
191 return VT == MVT::v8i8 || VT == MVT::v4i16 || VT == MVT::v2i32;
192}
193
194// Returns true if VT is a P extension packed double-wide SIMD type.
195bool RISCVSubtarget::isPExtPackedDoubleType(MVT VT) const {
196 if (!HasStdExtP || is64Bit())
197 return false;
198
199 return VT == MVT::v8i8 || VT == MVT::v4i16 || VT == MVT::v2i32;
200}
201
202unsigned RISCVSubtarget::getMaxBuildIntsCost() const {
203 // Loading integer from constant pool needs two instructions (the reason why
204 // the minimum cost is 2): an address calculation instruction and a load
205 // instruction. Usually, address calculation and instructions used for
206 // building integers (addi, slli, etc.) can be done in one cycle, so here we
207 // set the default cost to (LoadLatency + 1) if no threshold is provided.
208 return RISCVMaxBuildIntsCost == 0
209 ? getLoadLatency() + 1
210 : std::max<unsigned>(a: 2, b: RISCVMaxBuildIntsCost);
211}
212
213unsigned RISCVSubtarget::getMispredictionPenalty() const {
214 if (SchedMispredictPenalty.getNumOccurrences() > 0)
215 return SchedMispredictPenalty;
216 return getSchedModel().MispredictPenalty;
217}
218
219unsigned RISCVSubtarget::getLoadLatency() const {
220 if (SchedLoadLatency.getNumOccurrences() > 0)
221 return SchedLoadLatency;
222 return getSchedModel().LoadLatency;
223}
224
225unsigned RISCVSubtarget::getMaxRVVVectorSizeInBits() const {
226 assert(hasVInstructions() &&
227 "Tried to get vector length without Zve or V extension support!");
228
229 // ZvlLen specifies the minimum required vlen. The upper bound provided by
230 // riscv-v-vector-bits-max should be no less than it.
231 if (RVVVectorBitsMax != 0 && RVVVectorBitsMax < ZvlLen)
232 report_fatal_error(reason: "riscv-v-vector-bits-max specified is lower "
233 "than the Zvl*b limitation");
234
235 return RVVVectorBitsMax;
236}
237
238unsigned RISCVSubtarget::getMinRVVVectorSizeInBits() const {
239 assert(hasVInstructions() &&
240 "Tried to get vector length without Zve or V extension support!");
241
242 if (RVVVectorBitsMin == -1U)
243 return ZvlLen;
244
245 // ZvlLen specifies the minimum required vlen. The lower bound provided by
246 // riscv-v-vector-bits-min should be no less than it.
247 if (RVVVectorBitsMin != 0 && RVVVectorBitsMin < ZvlLen)
248 report_fatal_error(reason: "riscv-v-vector-bits-min specified is lower "
249 "than the Zvl*b limitation");
250
251 return RVVVectorBitsMin;
252}
253
254unsigned RISCVSubtarget::getMaxLMULForFixedLengthVectors() const {
255 assert(hasVInstructions() &&
256 "Tried to get vector length without Zve or V extension support!");
257 return 8;
258}
259
260bool RISCVSubtarget::useRVVForFixedLengthVectors() const {
261 return hasVInstructions() &&
262 getMinRVVVectorSizeInBits() >= RISCV::RVVBitsPerBlock;
263}
264
265bool RISCVSubtarget::enableSubRegLiveness() const { return true; }
266
267bool RISCVSubtarget::enableMachinePipeliner() const {
268 return getSchedModel().hasInstrSchedModel();
269}
270
271void RISCVSubtarget::mirFileLoaded(MachineFunction &MF) const {
272 // We usually compute max call frame size after ISel. Do the computation now
273 // if the .mir file didn't specify it. Note that this will probably give you
274 // bogus values after PEI has eliminated the callframe setup/destroy pseudo
275 // instructions, specify explicitly if you need it to be correct.
276 MachineFrameInfo &MFI = MF.getFrameInfo();
277 if (!MFI.isMaxCallFrameSizeComputed())
278 MFI.computeMaxCallFrameSize(MF);
279}
280
281 /// Enable use of alias analysis during code generation (during MI
282 /// scheduling, DAGCombine, etc.).
283bool RISCVSubtarget::useAA() const { return UseAA; }
284
285unsigned RISCVSubtarget::getMinimumJumpTableEntries() const {
286 return RISCVMinimumJumpTableEntries.getNumOccurrences() > 0
287 ? RISCVMinimumJumpTableEntries
288 : TuneInfo->MinimumJumpTableEntries;
289}
290
291void RISCVSubtarget::overrideSchedPolicy(MachineSchedPolicy &Policy,
292 const SchedRegion &Region) const {
293 // Do bidirectional scheduling since it provides a more balanced scheduling
294 // leading to better performance. This will increase compile time.
295 Policy.OnlyTopDown = false;
296 Policy.OnlyBottomUp = false;
297
298 // Disabling the latency heuristic can reduce the number of spills/reloads but
299 // will cause some regressions on some cores.
300 Policy.DisableLatencyHeuristic = DisableLatencySchedHeuristic;
301
302 // Spilling is generally expensive on all RISC-V cores, so always enable
303 // register-pressure tracking. This will increase compile time.
304 Policy.ShouldTrackPressure = true;
305}
306
307void RISCVSubtarget::overridePostRASchedPolicy(
308 MachineSchedPolicy &Policy, const SchedRegion &Region) const {
309 MISched::Direction PostRASchedDirection = getPostRASchedDirection();
310 if (PostRASchedDirection == MISched::TopDown) {
311 Policy.OnlyTopDown = true;
312 Policy.OnlyBottomUp = false;
313 } else if (PostRASchedDirection == MISched::BottomUp) {
314 Policy.OnlyTopDown = false;
315 Policy.OnlyBottomUp = true;
316 } else if (PostRASchedDirection == MISched::Bidirectional) {
317 Policy.OnlyTopDown = false;
318 Policy.OnlyBottomUp = false;
319 }
320}
321
322bool RISCVSubtarget::useMIPSLoadStorePairs() const {
323 return UseMIPSLoadStorePairsOpt && HasVendorXMIPSLSP;
324}
325
326bool RISCVSubtarget::useMIPSCCMovInsn() const {
327 return UseMIPSCCMovInsn && HasVendorXMIPSCMov;
328}
329