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