LLVM 24.0.0git
RISCVMCTargetDesc.cpp
Go to the documentation of this file.
1//===-- RISCVMCTargetDesc.cpp - RISC-V Target Descriptions ----------------===//
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 provides RISC-V specific target descriptions.
10///
11//===----------------------------------------------------------------------===//
12
13#include "RISCVMCTargetDesc.h"
14#include "RISCVELFStreamer.h"
15#include "RISCVInstPrinter.h"
16#include "RISCVMCAsmInfo.h"
18#include "RISCVMCOptions.h"
19#include "RISCVTargetStreamer.h"
22#include "llvm/MC/MCAsmInfo.h"
25#include "llvm/MC/MCInstrInfo.h"
29#include "llvm/MC/MCStreamer.h"
36#include <bitset>
37
38#define GET_INSTRINFO_MC_DESC
39#define ENABLE_INSTR_PREDICATE_VERIFIER
40#define GET_INSTRINFO_NAMED_OPS
41#include "RISCVGenInstrInfo.inc"
42
43#define GET_REGINFO_MC_DESC
44#include "RISCVGenRegisterInfo.inc"
45
46#define GET_SUBTARGETINFO_MC_DESC
47#include "RISCVGenSubtargetInfo.inc"
48
49#define OPTIONS_STRUCT_DEFS
50#include "RISCVMCOptions.inc"
51
52using namespace llvm;
53
55 MCInstrInfo *X = new MCInstrInfo();
56 InitRISCVMCInstrInfo(X);
57 return X;
58}
59
62 InitRISCVMCRegisterInfo(X, RISCV::X1);
63 return X;
64}
65
67 const Triple &TT,
68 const MCTargetOptions &Options) {
69 MCAsmInfo *MAI = nullptr;
70 if (TT.isOSBinFormatELF())
71 MAI = new RISCVMCAsmInfo(TT, Options);
72 else if (TT.isOSBinFormatMachO())
74 else
75 reportFatalUsageError("unsupported object format");
76
77 unsigned SP = MRI.getDwarfRegNum(RISCV::X2, true);
78 MCCFIInstruction Inst = MCCFIInstruction::cfiDefCfa(nullptr, SP, 0);
79 MAI->addInitialFrameState(Inst);
80
81 return MAI;
82}
83
84static MCObjectFileInfo *
86 bool LargeCodeModel = false) {
88 MOFI->initMCObjectFileInfo(Ctx, PIC, LargeCodeModel);
89 return MOFI;
90}
91
93 // Add Zcd if C and D are enabled and we aren't targeting 64-bit RVY.
94 if (STI.hasFeature(RISCV::FeatureStdExtC) &&
95 STI.hasFeature(RISCV::FeatureStdExtD) &&
96 !STI.hasFeature(RISCV::FeatureStdExtZcd) &&
97 !(STI.hasFeature(RISCV::Feature64Bit) &&
98 STI.hasFeature(RISCV::FeatureStdExtY)))
99 STI.ToggleFeature(RISCV::FeatureStdExtZcd);
100
101 // Add Zcf if F and C or Zce are enabled on RV32 and Y is not enabled.
102 if (!STI.hasFeature(RISCV::FeatureStdExtZcf) &&
103 !STI.hasFeature(RISCV::Feature64Bit) &&
104 !STI.hasFeature(RISCV::FeatureStdExtY) &&
105 STI.hasFeature(RISCV::FeatureStdExtF) &&
106 (STI.hasFeature(RISCV::FeatureStdExtC) ||
107 STI.hasFeature(RISCV::FeatureStdExtZce)))
108 STI.ToggleFeature(RISCV::FeatureStdExtZcf);
109
110 // We don't infer C or Zce because no code should be looking at those
111 // subtarget feature flags and they can cause issues like #229758.
112}
113
114static MCSubtargetInfo *
116 if (CPU.empty() || CPU == "generic")
117 CPU = TT.isArch64Bit() ? "generic-rv64" : "generic-rv32";
118
120 createRISCVMCSubtargetInfoImpl(TT, CPU, /*TuneCPU*/ CPU, FS);
121
122 // If the CPU is "help" fill in 64 or 32 bit feature so we can pass
123 // RISCVFeatures::validate.
124 // FIXME: Why does llvm-mc still expect a source file with -mcpu=help?
125 if (CPU == "help") {
126 llvm::FeatureBitset Features = X->getFeatureBits();
127 if (TT.isArch64Bit())
128 Features.set(RISCV::Feature64Bit);
129 else
130 Features.set(RISCV::Feature32Bit);
131 X->setFeatureBits(Features);
132 }
133
135
136 return X;
137}
138
140 unsigned SyntaxVariant,
141 const MCAsmInfo &MAI,
142 const MCInstrInfo &MII,
143 const MCRegisterInfo &MRI) {
144 return new RISCVInstPrinter(MAI, MII, MRI);
145}
146
147static MCTargetStreamer *
149 const Triple &TT = STI.getTargetTriple();
150 if (TT.isOSBinFormatELF())
151 return new RISCVTargetELFStreamer(S, STI);
152 return new RISCVTargetStreamer(S);
153}
154
155static MCStreamer *
156createMachOStreamer(MCContext &Ctx, std::unique_ptr<MCAsmBackend> &&TAB,
157 std::unique_ptr<MCObjectWriter> &&OW,
158 std::unique_ptr<MCCodeEmitter> &&Emitter) {
159 return createMachOStreamer(Ctx, std::move(TAB), std::move(OW),
160 std::move(Emitter),
161 /*DWARFMustBeAtTheEnd*/ false,
162 /*LabelSections*/ true);
163}
164
165static MCTargetStreamer *
170
174
175namespace {
176
177class RISCVMCInstrAnalysis : public MCInstrAnalysis {
178 int64_t GPRState[31] = {};
179 std::bitset<31> GPRValidMask;
180
181 static bool isGPR(MCRegister Reg) {
182 return Reg >= RISCV::X0 && Reg <= RISCV::X31;
183 }
184 static bool isYGPR(MCRegister Reg) {
185 return Reg >= RISCV::X0_Y && Reg <= RISCV::X31_Y;
186 }
187 static bool isZeroReg(MCRegister Reg) {
188 return Reg == RISCV::X0 || Reg == RISCV::X0_Y;
189 }
190
191 static unsigned getRegIndex(MCRegister Reg) {
192 if (isYGPR(Reg)) {
193 assert(Reg != RISCV::X0_Y && "Invalid GPR reg");
194 return Reg - RISCV::X1_Y;
195 }
196 assert(isGPR(Reg) && Reg != RISCV::X0 && "Invalid GPR reg");
197 return Reg - RISCV::X1;
198 }
199
200 void setGPRState(MCRegister Reg, std::optional<int64_t> Value) {
201 if (isZeroReg(Reg))
202 return;
203
204 auto Index = getRegIndex(Reg);
205
206 if (Value) {
207 GPRState[Index] = *Value;
208 GPRValidMask.set(Index);
209 } else {
210 GPRValidMask.reset(Index);
211 }
212 }
213
214 std::optional<int64_t> getGPRState(MCRegister Reg) const {
215 if (isZeroReg(Reg))
216 return 0;
217
218 auto Index = getRegIndex(Reg);
219
220 if (GPRValidMask.test(Index))
221 return GPRState[Index];
222 return std::nullopt;
223 }
224
225public:
226 explicit RISCVMCInstrAnalysis(const MCInstrInfo *Info)
227 : MCInstrAnalysis(Info) {}
228
229 void resetState() override { GPRValidMask.reset(); }
230
231 void updateState(const MCInst &Inst, const MCSubtargetInfo *STI,
232 uint64_t Addr) override {
233 // Terminators mark the end of a basic block which means the sequentially
234 // next instruction will be the first of another basic block and the current
235 // state will typically not be valid anymore. For calls, we assume all
236 // registers may be clobbered by the callee (TODO: should we take the
237 // calling convention into account?).
238 if (isTerminator(Inst) || isCall(Inst)) {
239 resetState();
240 return;
241 }
242
243 switch (Inst.getOpcode()) {
244 default: {
245 // Clear the state of all defined registers for instructions that we don't
246 // explicitly support.
247 auto NumDefs = Info->get(Inst.getOpcode()).getNumDefs();
248 for (unsigned I = 0; I < NumDefs; ++I) {
249 auto DefReg = Inst.getOperand(I).getReg();
250 if (isGPR(DefReg))
251 setGPRState(DefReg, std::nullopt);
252 }
253 break;
254 }
255 case RISCV::AUIPC:
256 setGPRState(Inst.getOperand(0).getReg(),
257 Addr + SignExtend64<32>(Inst.getOperand(1).getImm() << 12));
258 break;
259 }
260 }
261
262 bool evaluateBranch(const MCInst &Inst, uint64_t Addr, uint64_t Size,
263 uint64_t &Target) const override {
264 if (isConditionalBranch(Inst)) {
265 int64_t Imm;
266 if (Size == 2)
267 Imm = Inst.getOperand(1).getImm();
268 else
269 Imm = Inst.getOperand(2).getImm();
270 Target = Addr + Imm;
271 return true;
272 }
273
274 switch (Inst.getOpcode()) {
275 case RISCV::C_J:
276 case RISCV::C_JAL:
277 case RISCV::QC_E_J:
278 case RISCV::QC_E_JAL:
279 Target = Addr + Inst.getOperand(0).getImm();
280 return true;
281 case RISCV::JAL:
282 Target = Addr + Inst.getOperand(1).getImm();
283 return true;
284 case RISCV::JALR: {
285 if (auto TargetRegState = getGPRState(Inst.getOperand(1).getReg())) {
286 Target = *TargetRegState + Inst.getOperand(2).getImm();
287 return true;
288 }
289 return false;
290 }
291 }
292
293 return false;
294 }
295
296 bool isTerminator(const MCInst &Inst) const override {
298 return true;
299
300 switch (Inst.getOpcode()) {
301 default:
302 return false;
303 case RISCV::JAL:
304 case RISCV::JALR:
305 return Inst.getOperand(0).getReg() == RISCV::X0;
306 }
307 }
308
309 bool isCall(const MCInst &Inst) const override {
310 if (MCInstrAnalysis::isCall(Inst))
311 return true;
312
313 switch (Inst.getOpcode()) {
314 default:
315 return false;
316 case RISCV::JAL:
317 case RISCV::JALR:
318 return Inst.getOperand(0).getReg() != RISCV::X0;
319 }
320 }
321
322 bool isReturn(const MCInst &Inst) const override {
324 return true;
325
326 switch (Inst.getOpcode()) {
327 default:
328 return false;
329 case RISCV::JALR:
330 return Inst.getOperand(0).getReg() == RISCV::X0 &&
331 maybeReturnAddress(Inst.getOperand(1).getReg());
332 case RISCV::C_JR:
333 return maybeReturnAddress(Inst.getOperand(0).getReg());
334 }
335 }
336
337 bool isBranch(const MCInst &Inst) const override {
339 return true;
340
341 return isBranchImpl(Inst);
342 }
343
344 bool isUnconditionalBranch(const MCInst &Inst) const override {
346 return true;
347
348 return isBranchImpl(Inst);
349 }
350
351 bool isIndirectBranch(const MCInst &Inst) const override {
353 return true;
354
355 switch (Inst.getOpcode()) {
356 default:
357 return false;
358 case RISCV::JALR:
359 return Inst.getOperand(0).getReg() == RISCV::X0 &&
360 !maybeReturnAddress(Inst.getOperand(1).getReg());
361 case RISCV::C_JR:
362 return !maybeReturnAddress(Inst.getOperand(0).getReg());
363 }
364 }
365
366 /// Returns (PLT virtual address, GOT virtual address) pairs for PLT entries.
367 std::vector<std::pair<uint64_t, uint64_t>>
368 findPltEntries(uint64_t PltSectionVA, ArrayRef<uint8_t> PltContents,
369 const MCSubtargetInfo &STI) const override {
370 uint32_t LoadInsnOpCode;
371 if (const Triple &T = STI.getTargetTriple(); T.isRISCV64())
372 LoadInsnOpCode = 0x3003; // ld
373 else if (T.isRISCV32())
374 LoadInsnOpCode = 0x2003; // lw
375 else
376 return {};
377
378 constexpr uint64_t FirstEntryAt = 32, EntrySize = 16;
379 if (PltContents.size() < FirstEntryAt + EntrySize)
380 return {};
381
382 std::vector<std::pair<uint64_t, uint64_t>> Results;
383 for (uint64_t EntryStart = FirstEntryAt,
384 EntryStartEnd = PltContents.size() - EntrySize;
385 EntryStart <= EntryStartEnd; EntryStart += EntrySize) {
386 const uint32_t AuipcInsn =
387 support::endian::read32le(PltContents.data() + EntryStart);
388 const bool IsAuipc = (AuipcInsn & 0x7F) == 0x17;
389 if (!IsAuipc)
390 continue;
391
392 const uint32_t LoadInsn =
393 support::endian::read32le(PltContents.data() + EntryStart + 4);
394 const bool IsLoad = (LoadInsn & 0x707F) == LoadInsnOpCode;
395 if (!IsLoad)
396 continue;
397
398 const uint64_t GotPltSlotVA = PltSectionVA + EntryStart +
399 (AuipcInsn & 0xFFFFF000) +
400 SignExtend64<12>(LoadInsn >> 20);
401 Results.emplace_back(PltSectionVA + EntryStart, GotPltSlotVA);
402 }
403
404 return Results;
405 }
406
407private:
408 static bool maybeReturnAddress(MCRegister Reg) {
409 // X1 is used for normal returns, X5 for returns from outlined functions.
410 return Reg == RISCV::X1 || Reg == RISCV::X5;
411 }
412
413 static bool isBranchImpl(const MCInst &Inst) {
414 switch (Inst.getOpcode()) {
415 default:
416 return false;
417 case RISCV::JAL:
418 return Inst.getOperand(0).getReg() == RISCV::X0;
419 case RISCV::JALR:
420 return Inst.getOperand(0).getReg() == RISCV::X0 &&
421 !maybeReturnAddress(Inst.getOperand(1).getReg());
422 case RISCV::C_JR:
423 return !maybeReturnAddress(Inst.getOperand(0).getReg());
424 }
425 }
426};
427
428} // end anonymous namespace
429
431 return new RISCVMCInstrAnalysis(Info);
432}
433
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
dxil DXContainer Global Emitter
static LVOptions Options
Definition LVOptions.cpp:25
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
#define T
PassInstrumentationCallbacks PIC
static bool isBranch(unsigned Opcode)
static MCRegisterInfo * createRISCVMCRegisterInfo(const Triple &TT)
static MCInstPrinter * createRISCVMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI)
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVTargetMC()
static MCObjectFileInfo * createRISCVMCObjectFileInfo(MCContext &Ctx, bool PIC, bool LargeCodeModel=false)
static MCTargetStreamer * createRISCVNullTargetStreamer(MCStreamer &S)
static MCSubtargetInfo * createRISCVMCSubtargetInfo(const Triple &TT, StringRef CPU, StringRef FS)
static MCTargetStreamer * createRISCVObjectTargetStreamer(MCStreamer &S, const MCSubtargetInfo &STI)
static MCInstrAnalysis * createRISCVInstrAnalysis(const MCInstrInfo *Info)
static MCTargetStreamer * createRISCVAsmTargetStreamer(MCStreamer &S, formatted_raw_ostream &OS, MCInstPrinter *InstPrint)
static MCInstrInfo * createRISCVMCInstrInfo()
static MCAsmInfo * createRISCVMCAsmInfo(const MCRegisterInfo &MRI, const Triple &TT, const MCTargetOptions &Options)
size_t size() const
Get the array size.
Definition ArrayRef.h:141
const T * data() const
Definition ArrayRef.h:138
Container class for subtarget features.
FeatureBitset & set()
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition MCAsmInfo.h:67
void addInitialFrameState(const MCCFIInstruction &Inst)
Definition MCAsmInfo.cpp:39
static MCCFIInstruction cfiDefCfa(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it.
Definition MCDwarf.h:628
Context object for machine code objects.
Definition MCContext.h:83
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
unsigned getOpcode() const
Definition MCInst.h:202
const MCOperand & getOperand(unsigned i) const
Definition MCInst.h:210
virtual bool isCall(const MCInst &Inst) const
virtual bool isBranch(const MCInst &Inst) const
virtual bool isUnconditionalBranch(const MCInst &Inst) const
virtual bool isTerminator(const MCInst &Inst) const
virtual bool isReturn(const MCInst &Inst) const
virtual bool isIndirectBranch(const MCInst &Inst) const
Interface to description of machine instruction set.
Definition MCInstrInfo.h:27
void initMCObjectFileInfo(MCContext &MCCtx, bool PIC, bool LargeCodeModel=false)
int64_t getImm() const
Definition MCInst.h:84
MCRegister getReg() const
Returns the register number.
Definition MCInst.h:73
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
virtual int64_t getDwarfRegNum(MCRegister Reg, bool isEH) const
Map a target register to an equivalent dwarf register number.
Streaming machine code generation interface.
Definition MCStreamer.h:222
Generic base class for all target subtargets.
bool hasFeature(unsigned Feature) const
const Triple & getTargetTriple() const
const FeatureBitset & ToggleFeature(uint64_t FB)
Toggle a feature and return the re-computed feature bits.
Target specific streamer interface.
Definition MCStreamer.h:95
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isRISCV64() const
Tests whether the target is 64-bit RISC-V.
Definition Triple.h:1179
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
Registers T::Global with cl::ParseCommandLineOptions.
void updateCZceFeatureImplications(MCSubtargetInfo &STI)
uint32_t read32le(const void *P)
Definition Endian.h:412
This is an optimization pass for GlobalISel generic memory operations.
MCCodeEmitter * createRISCVMCCodeEmitter(const MCInstrInfo &MCII, MCContext &Ctx)
Target & getTheRISCV32Target()
Target & getTheRISCV64beTarget()
MCStreamer * createRISCVELFStreamer(const Triple &, MCContext &C, std::unique_ptr< MCAsmBackend > &&MAB, std::unique_ptr< MCObjectWriter > &&MOW, std::unique_ptr< MCCodeEmitter > &&MCE)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI MCStreamer * createMachOStreamer(MCContext &Ctx, std::unique_ptr< MCAsmBackend > &&TAB, std::unique_ptr< MCObjectWriter > &&OW, std::unique_ptr< MCCodeEmitter > &&CE, bool DWARFMustBeAtTheEnd, bool LabelSections=false)
MCAsmBackend * createRISCVAsmBackend(const Target &T, const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options)
Target & getTheRISCV64Target()
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:567
Target & getTheRISCV32beTarget()
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
static void RegisterMCRegInfo(Target &T, Target::MCRegInfoCtorFnTy Fn)
RegisterMCRegInfo - Register a MCRegisterInfo implementation for the given target.
static void RegisterMCAsmBackend(Target &T, Target::MCAsmBackendCtorTy Fn)
RegisterMCAsmBackend - Register a MCAsmBackend implementation for the given target.
static void RegisterMCCodeEmitter(Target &T, Target::MCCodeEmitterCtorTy Fn)
RegisterMCCodeEmitter - Register a MCCodeEmitter implementation for the given target.
static void RegisterMCAsmInfo(Target &T, Target::MCAsmInfoCtorFnTy Fn)
RegisterMCAsmInfo - Register a MCAsmInfo implementation for the given target.
static void RegisterMCSubtargetInfo(Target &T, Target::MCSubtargetInfoCtorFnTy Fn)
RegisterMCSubtargetInfo - Register a MCSubtargetInfo implementation for the given target.
static void RegisterObjectTargetStreamer(Target &T, Target::ObjectTargetStreamerCtorTy Fn)
static void RegisterMCInstrAnalysis(Target &T, Target::MCInstrAnalysisCtorFnTy Fn)
RegisterMCInstrAnalysis - Register a MCInstrAnalysis implementation for the given target.
static void RegisterELFStreamer(Target &T, Target::ELFStreamerCtorTy Fn)
static void RegisterNullTargetStreamer(Target &T, Target::NullTargetStreamerCtorTy Fn)
static void RegisterMCInstPrinter(Target &T, Target::MCInstPrinterCtorTy Fn)
RegisterMCInstPrinter - Register a MCInstPrinter implementation for the given target.
static void RegisterMCInstrInfo(Target &T, Target::MCInstrInfoCtorFnTy Fn)
RegisterMCInstrInfo - Register a MCInstrInfo implementation for the given target.
static void RegisterMachOStreamer(Target &T, Target::MachOStreamerCtorTy Fn)
static void RegisterMCObjectFileInfo(Target &T, Target::MCObjectFileInfoCtorFnTy Fn)
Register a MCObjectFileInfo implementation for the given target.
static void RegisterAsmTargetStreamer(Target &T, Target::AsmTargetStreamerCtorTy Fn)