LLVM 23.0.0git
RISCVAsmPrinter.cpp
Go to the documentation of this file.
1//===-- RISCVAsmPrinter.cpp - RISC-V LLVM assembly writer -----------------===//
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 contains a printer that converts from our internal representation
10// of machine-dependent LLVM code to the RISC-V assembly language.
11//
12//===----------------------------------------------------------------------===//
13
20#include "RISCV.h"
23#include "RISCVRegisterInfo.h"
25#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/Statistic.h"
32#include "llvm/IR/Module.h"
33#include "llvm/MC/MCAsmInfo.h"
34#include "llvm/MC/MCContext.h"
35#include "llvm/MC/MCInst.h"
39#include "llvm/MC/MCStreamer.h"
40#include "llvm/MC/MCSymbol.h"
46
47using namespace llvm;
48
49#define DEBUG_TYPE "asm-printer"
50
51STATISTIC(RISCVNumInstrsCompressed,
52 "Number of RISC-V Compressed instructions emitted");
53
54namespace llvm {
55extern const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures];
56} // namespace llvm
57
58namespace {
59class RISCVAsmPrinter : public AsmPrinter {
60public:
61 static char ID;
62
63private:
64 const RISCVSubtarget *STI;
65
66public:
67 explicit RISCVAsmPrinter(TargetMachine &TM,
68 std::unique_ptr<MCStreamer> Streamer)
69 : AsmPrinter(TM, std::move(Streamer), ID) {}
70
71 StringRef getPassName() const override { return "RISC-V Assembly Printer"; }
72
73 RISCVTargetStreamer &getTargetStreamer() const {
74 return static_cast<RISCVTargetStreamer &>(
75 *OutStreamer->getTargetStreamer());
76 }
77
78 void LowerSTACKMAP(MCStreamer &OutStreamer, StackMaps &SM,
79 const MachineInstr &MI);
80
81 void LowerPATCHPOINT(MCStreamer &OutStreamer, StackMaps &SM,
82 const MachineInstr &MI);
83
84 void LowerSTATEPOINT(MCStreamer &OutStreamer, StackMaps &SM,
85 const MachineInstr &MI);
86
87 bool runOnMachineFunction(MachineFunction &MF) override;
88
89 void emitInstruction(const MachineInstr *MI) override;
90
91 void emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) override;
92
93 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
94 const char *ExtraCode, raw_ostream &OS) override;
95 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
96 const char *ExtraCode, raw_ostream &OS) override;
97
98 // Returns whether Inst is compressed.
99 bool EmitToStreamer(MCStreamer &S, const MCInst &Inst,
100 const MCSubtargetInfo &SubtargetInfo);
101 bool EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
102 return EmitToStreamer(S, Inst, *STI);
103 }
104
105 bool lowerPseudoInstExpansion(const MachineInstr *MI, MCInst &Inst);
106
107 typedef std::tuple<unsigned, uint32_t> HwasanMemaccessTuple;
108 std::map<HwasanMemaccessTuple, MCSymbol *> HwasanMemaccessSymbols;
109 void LowerHWASAN_CHECK_MEMACCESS(const MachineInstr &MI);
110 void LowerKCFI_CHECK(const MachineInstr &MI);
111 void EmitHwasanMemaccessSymbols(Module &M);
112
113 // Wrapper needed for tblgenned pseudo lowering.
114 bool lowerOperand(const MachineOperand &MO, MCOperand &MCOp) const;
115
116 void emitStartOfAsmFile(Module &M) override;
117 void emitEndOfAsmFile(Module &M) override;
118
119 void emitFunctionEntryLabel() override;
120 bool emitDirectiveOptionArch();
121
122 void emitNoteGnuProperty(const Module &M);
123
124private:
125 void emitAttributes(const MCSubtargetInfo &SubtargetInfo);
126
127 void emitNTLHint(const MachineInstr *MI);
128
129 // XRay Support
130 void LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr *MI);
131 void LowerPATCHABLE_FUNCTION_EXIT(const MachineInstr *MI);
132 void LowerPATCHABLE_TAIL_CALL(const MachineInstr *MI);
133 void emitSled(const MachineInstr *MI, SledKind Kind);
134
135 void lowerToMCInst(const MachineInstr *MI, MCInst &OutMI);
136};
137}
138
139void RISCVAsmPrinter::LowerSTACKMAP(MCStreamer &OutStreamer, StackMaps &SM,
140 const MachineInstr &MI) {
141 unsigned NOPBytes = STI->hasStdExtZca() ? 2 : 4;
142 unsigned NumNOPBytes = StackMapOpers(&MI).getNumPatchBytes();
143
144 auto &Ctx = OutStreamer.getContext();
145 MCSymbol *MILabel = Ctx.createTempSymbol();
146 OutStreamer.emitLabel(MILabel);
147
148 SM.recordStackMap(*MILabel, MI);
149 assert(NumNOPBytes % NOPBytes == 0 &&
150 "Invalid number of NOP bytes requested!");
151
152 // Scan ahead to trim the shadow.
153 const MachineBasicBlock &MBB = *MI.getParent();
155 ++MII;
156 while (NumNOPBytes > 0) {
157 if (MII == MBB.end() || MII->isCall() ||
158 MII->getOpcode() == RISCV::DBG_VALUE ||
159 MII->getOpcode() == TargetOpcode::PATCHPOINT ||
160 MII->getOpcode() == TargetOpcode::STACKMAP)
161 break;
162 ++MII;
163 NumNOPBytes -= NOPBytes;
164 }
165
166 // Emit nops.
167 emitNops(NumNOPBytes / NOPBytes);
168}
169
170// Lower a patchpoint of the form:
171// [<def>], <id>, <numBytes>, <target>, <numArgs>
172void RISCVAsmPrinter::LowerPATCHPOINT(MCStreamer &OutStreamer, StackMaps &SM,
173 const MachineInstr &MI) {
174 unsigned NOPBytes = STI->hasStdExtZca() ? 2 : 4;
175
176 auto &Ctx = OutStreamer.getContext();
177 MCSymbol *MILabel = Ctx.createTempSymbol();
178 OutStreamer.emitLabel(MILabel);
179 SM.recordPatchPoint(*MILabel, MI);
180
181 PatchPointOpers Opers(&MI);
182
183 const MachineOperand &CalleeMO = Opers.getCallTarget();
184 unsigned EncodedBytes = 0;
185
186 if (CalleeMO.isImm()) {
187 uint64_t CallTarget = CalleeMO.getImm();
188 if (CallTarget) {
189 assert((CallTarget & 0xFFFF'FFFF'FFFF) == CallTarget &&
190 "High 16 bits of call target should be zero.");
191 // Materialize the jump address:
193 RISCVMatInt::generateMCInstSeq(CallTarget, *STI, RISCV::X1, Seq);
194 for (MCInst &Inst : Seq) {
195 bool Compressed = EmitToStreamer(OutStreamer, Inst);
196 EncodedBytes += Compressed ? 2 : 4;
197 }
198 bool Compressed = EmitToStreamer(OutStreamer, MCInstBuilder(RISCV::JALR)
199 .addReg(RISCV::X1)
200 .addReg(RISCV::X1)
201 .addImm(0));
202 EncodedBytes += Compressed ? 2 : 4;
203 }
204 } else if (CalleeMO.isGlobal()) {
205 MCOperand CallTargetMCOp;
206 lowerOperand(CalleeMO, CallTargetMCOp);
207 EmitToStreamer(OutStreamer,
208 MCInstBuilder(RISCV::PseudoCALL).addOperand(CallTargetMCOp));
209 EncodedBytes += 8;
210 }
211
212 // Emit padding.
213 unsigned NumBytes = Opers.getNumPatchBytes();
214 assert(NumBytes >= EncodedBytes &&
215 "Patchpoint can't request size less than the length of a call.");
216 assert((NumBytes - EncodedBytes) % NOPBytes == 0 &&
217 "Invalid number of NOP bytes requested!");
218 emitNops((NumBytes - EncodedBytes) / NOPBytes);
219}
220
221void RISCVAsmPrinter::LowerSTATEPOINT(MCStreamer &OutStreamer, StackMaps &SM,
222 const MachineInstr &MI) {
223 unsigned NOPBytes = STI->hasStdExtZca() ? 2 : 4;
224
225 StatepointOpers SOpers(&MI);
226 if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
227 assert(PatchBytes % NOPBytes == 0 &&
228 "Invalid number of NOP bytes requested!");
229 emitNops(PatchBytes / NOPBytes);
230 } else {
231 // Lower call target and choose correct opcode
232 const MachineOperand &CallTarget = SOpers.getCallTarget();
233 MCOperand CallTargetMCOp;
234 switch (CallTarget.getType()) {
237 lowerOperand(CallTarget, CallTargetMCOp);
238 EmitToStreamer(
239 OutStreamer,
240 MCInstBuilder(RISCV::PseudoCALL).addOperand(CallTargetMCOp));
241 break;
243 CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
244 EmitToStreamer(OutStreamer, MCInstBuilder(RISCV::JAL)
245 .addReg(RISCV::X1)
246 .addOperand(CallTargetMCOp));
247 break;
249 CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
250 EmitToStreamer(OutStreamer, MCInstBuilder(RISCV::JALR)
251 .addReg(RISCV::X1)
252 .addOperand(CallTargetMCOp)
253 .addImm(0));
254 break;
255 default:
256 llvm_unreachable("Unsupported operand type in statepoint call target");
257 break;
258 }
259 }
260
261 auto &Ctx = OutStreamer.getContext();
262 MCSymbol *MILabel = Ctx.createTempSymbol();
263 OutStreamer.emitLabel(MILabel);
264 SM.recordStatepoint(*MILabel, MI);
265}
266
267bool RISCVAsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst,
268 const MCSubtargetInfo &SubtargetInfo) {
269 MCInst CInst;
270 bool Res = RISCVRVC::compress(CInst, Inst, SubtargetInfo);
271 if (Res)
272 ++RISCVNumInstrsCompressed;
273 S.emitInstruction(Res ? CInst : Inst, SubtargetInfo);
274 return Res;
275}
276
277// Simple pseudo-instructions have their lowering (with expansion to real
278// instructions) auto-generated.
279#include "RISCVGenMCPseudoLowering.inc"
280
281// If the instruction has a nontemporal MachineMemOperand, emit an NTL hint
282// instruction before it. NTL hints are always safe to emit since they use
283// HINT encodings that are guaranteed not to trap
284// (riscv-non-isa/riscv-elf-psabi-doc#474).
285void RISCVAsmPrinter::emitNTLHint(const MachineInstr *MI) {
286 if (!STI->getInstrInfo()->requiresNTLHint(*MI))
287 return;
288
289 assert(!MI->memoperands_empty());
290
291 MachineMemOperand *MMO = *(MI->memoperands_begin());
292
293 assert(MMO->isNonTemporal());
294
295 unsigned NontemporalMode = 0;
296 if (MMO->getFlags() & MONontemporalBit0)
297 NontemporalMode += 0b1;
298 if (MMO->getFlags() & MONontemporalBit1)
299 NontemporalMode += 0b10;
300
301 MCInst Hint;
302 if (STI->hasStdExtZca())
303 Hint.setOpcode(RISCV::C_ADD);
304 else
305 Hint.setOpcode(RISCV::ADD);
306
307 Hint.addOperand(MCOperand::createReg(RISCV::X0));
308 Hint.addOperand(MCOperand::createReg(RISCV::X0));
309 Hint.addOperand(MCOperand::createReg(RISCV::X2 + NontemporalMode));
310
311 EmitToStreamer(*OutStreamer, Hint);
312}
313
314void RISCVAsmPrinter::emitInstruction(const MachineInstr *MI) {
315 RISCV_MC::verifyInstructionPredicates(MI->getOpcode(), STI->getFeatureBits());
316
317 emitNTLHint(MI);
318
319 // Do any auto-generated pseudo lowerings.
320 if (MCInst OutInst; lowerPseudoInstExpansion(MI, OutInst)) {
321 EmitToStreamer(*OutStreamer, OutInst);
322 return;
323 }
324
325 switch (MI->getOpcode()) {
326 case RISCV::HWASAN_CHECK_MEMACCESS_SHORTGRANULES:
327 LowerHWASAN_CHECK_MEMACCESS(*MI);
328 return;
329 case RISCV::KCFI_CHECK:
330 LowerKCFI_CHECK(*MI);
331 return;
332 case TargetOpcode::STACKMAP:
333 return LowerSTACKMAP(*OutStreamer, SM, *MI);
334 case TargetOpcode::PATCHPOINT:
335 return LowerPATCHPOINT(*OutStreamer, SM, *MI);
336 case TargetOpcode::STATEPOINT:
337 return LowerSTATEPOINT(*OutStreamer, SM, *MI);
338 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
339 const Function &F = MI->getParent()->getParent()->getFunction();
340 if (F.hasFnAttribute("patchable-function-entry")) {
341 unsigned Num =
342 F.getFnAttributeAsParsedInteger("patchable-function-entry");
343 emitNops(Num);
344 return;
345 }
346 LowerPATCHABLE_FUNCTION_ENTER(MI);
347 return;
348 }
349 case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
350 LowerPATCHABLE_FUNCTION_EXIT(MI);
351 return;
352 case TargetOpcode::PATCHABLE_TAIL_CALL:
353 LowerPATCHABLE_TAIL_CALL(MI);
354 return;
355 }
356
357 MCInst OutInst;
358 lowerToMCInst(MI, OutInst);
359 EmitToStreamer(*OutStreamer, OutInst);
360}
361
362bool RISCVAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
363 const char *ExtraCode, raw_ostream &OS) {
364 // First try the generic code, which knows about modifiers like 'c' and 'n'.
365 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS))
366 return false;
367
368 const MachineOperand &MO = MI->getOperand(OpNo);
369 if (ExtraCode && ExtraCode[0]) {
370 if (ExtraCode[1] != 0)
371 return true; // Unknown modifier.
372
373 switch (ExtraCode[0]) {
374 default:
375 return true; // Unknown modifier.
376 case 'z': // Print zero register if zero, regular printing otherwise.
377 if (MO.isImm() && MO.getImm() == 0) {
378 OS << RISCVInstPrinter::getRegisterName(RISCV::X0);
379 return false;
380 }
381 break;
382 case 'i': // Literal 'i' if operand is not a register.
383 if (!MO.isReg())
384 OS << 'i';
385 return false;
386 case 'N': // Print the register encoding as an integer (0-31)
387 if (!MO.isReg())
388 return true;
389
390 const RISCVRegisterInfo *TRI = STI->getRegisterInfo();
391 OS << TRI->getEncodingValue(MO.getReg());
392 return false;
393 }
394 }
395
396 switch (MO.getType()) {
398 OS << MO.getImm();
399 return false;
402 return false;
404 PrintSymbolOperand(MO, OS);
405 return false;
407 MCSymbol *Sym = GetBlockAddressSymbol(MO.getBlockAddress());
408 Sym->print(OS, MAI);
409 return false;
410 }
411 default:
412 break;
413 }
414
415 return true;
416}
417
418bool RISCVAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
419 unsigned OpNo,
420 const char *ExtraCode,
421 raw_ostream &OS) {
422 if (ExtraCode)
423 return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, ExtraCode, OS);
424
425 const MachineOperand &AddrReg = MI->getOperand(OpNo);
426 assert(MI->getNumOperands() > OpNo + 1 && "Expected additional operand");
427 const MachineOperand &Offset = MI->getOperand(OpNo + 1);
428 // All memory operands should have a register and an immediate operand (see
429 // RISCVDAGToDAGISel::SelectInlineAsmMemoryOperand).
430 if (!AddrReg.isReg())
431 return true;
432 if (!Offset.isImm() && !Offset.isGlobal() && !Offset.isBlockAddress() &&
433 !Offset.isMCSymbol())
434 return true;
435
436 MCOperand MCO;
437 if (!lowerOperand(Offset, MCO))
438 return true;
439
440 if (Offset.isImm())
441 OS << MCO.getImm();
442 else if (Offset.isGlobal() || Offset.isBlockAddress() || Offset.isMCSymbol())
443 MAI.printExpr(OS, *MCO.getExpr());
444
445 if (Offset.isMCSymbol())
446 MMI->getContext().registerInlineAsmLabel(Offset.getMCSymbol());
447 if (Offset.isBlockAddress()) {
448 const BlockAddress *BA = Offset.getBlockAddress();
449 MCSymbol *Sym = GetBlockAddressSymbol(BA);
450 MMI->getContext().registerInlineAsmLabel(Sym);
451 }
452
453 OS << "(" << RISCVInstPrinter::getRegisterName(AddrReg.getReg()) << ")";
454 return false;
455}
456
457bool RISCVAsmPrinter::emitDirectiveOptionArch() {
458 RISCVTargetStreamer &RTS = getTargetStreamer();
459 SmallVector<RISCVOptionArchArg> NeedEmitStdOptionArgs;
460 const MCSubtargetInfo &MCSTI = *TM.getMCSubtargetInfo();
461 for (const auto &Feature : RISCVFeatureKV) {
462 if (STI->hasFeature(Feature.Value) == MCSTI.hasFeature(Feature.Value))
463 continue;
464
466 continue;
467
468 auto Delta = STI->hasFeature(Feature.Value) ? RISCVOptionArchArgType::Plus
469 : RISCVOptionArchArgType::Minus;
470 NeedEmitStdOptionArgs.emplace_back(Delta, Feature.Key);
471 }
472 if (!NeedEmitStdOptionArgs.empty()) {
474 RTS.emitDirectiveOptionArch(NeedEmitStdOptionArgs);
475 return true;
476 }
477
478 return false;
479}
480
481bool RISCVAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
482 STI = &MF.getSubtarget<RISCVSubtarget>();
483 RISCVTargetStreamer &RTS = getTargetStreamer();
484
485 bool EmittedOptionArch = emitDirectiveOptionArch();
486
487 SetupMachineFunction(MF);
488 emitFunctionBody();
489
490 // Emit the XRay table
491 emitXRayTable();
492
493 if (EmittedOptionArch)
494 RTS.emitDirectiveOptionPop();
495 return false;
496}
497
498void RISCVAsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr *MI) {
499 emitSled(MI, SledKind::FUNCTION_ENTER);
500}
501
502void RISCVAsmPrinter::LowerPATCHABLE_FUNCTION_EXIT(const MachineInstr *MI) {
503 emitSled(MI, SledKind::FUNCTION_EXIT);
504}
505
506void RISCVAsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr *MI) {
507 emitSled(MI, SledKind::TAIL_CALL);
508}
509
510void RISCVAsmPrinter::emitSled(const MachineInstr *MI, SledKind Kind) {
511 // We want to emit the jump instruction and the nops constituting the sled.
512 // The format is as follows:
513 // .Lxray_sled_N
514 // ALIGN
515 // J .tmpN
516 // 21 or 33 C.NOP instructions
517 // .tmpN
518
519 // The following variable holds the count of the number of NOPs to be patched
520 // in for XRay instrumentation during compilation.
521 // Note that RV64 and RV32 each has a sled of 68 and 44 bytes, respectively.
522 // Assuming we're using JAL to jump to .tmpN, then we only need
523 // (68 - 4)/2 = 32 NOPs for RV64 and (44 - 4)/2 = 20 for RV32. However, there
524 // is a chance that we'll use C.JAL instead, so an additional NOP is needed.
525 const uint8_t NoopsInSledCount = STI->is64Bit() ? 33 : 21;
526
527 OutStreamer->emitCodeAlignment(Align(4), STI);
528 auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
529 OutStreamer->emitLabel(CurSled);
530 auto Target = OutContext.createTempSymbol();
531
532 const MCExpr *TargetExpr = MCSymbolRefExpr::create(Target, OutContext);
533
534 // Emit "J bytes" instruction, which jumps over the nop sled to the actual
535 // start of function.
536 EmitToStreamer(
537 *OutStreamer,
538 MCInstBuilder(RISCV::JAL).addReg(RISCV::X0).addExpr(TargetExpr));
539
540 // Emit NOP instructions
541 for (int8_t I = 0; I < NoopsInSledCount; ++I)
542 EmitToStreamer(*OutStreamer, MCInstBuilder(RISCV::ADDI)
543 .addReg(RISCV::X0)
544 .addReg(RISCV::X0)
545 .addImm(0));
546
547 OutStreamer->emitLabel(Target);
548 recordSled(CurSled, *MI, Kind, 2);
549}
550
551void RISCVAsmPrinter::emitStartOfAsmFile(Module &M) {
552 assert(OutStreamer->getTargetStreamer() &&
553 "target streamer is uninitialized");
554 RISCVTargetStreamer &RTS = getTargetStreamer();
555 if (const MDString *ModuleTargetABI =
556 dyn_cast_or_null<MDString>(M.getModuleFlag("target-abi")))
557 RTS.setTargetABI(RISCVABI::getTargetABI(ModuleTargetABI->getString()));
558
559 MCSubtargetInfo SubtargetInfo = *TM.getMCSubtargetInfo();
560
561 // Use module flag to update feature bits.
562 if (auto *MD = dyn_cast_or_null<MDNode>(M.getModuleFlag("riscv-isa"))) {
563 for (auto &ISA : MD->operands()) {
564 if (auto *ISAString = dyn_cast_or_null<MDString>(ISA)) {
565 auto ParseResult = llvm::RISCVISAInfo::parseArchString(
566 ISAString->getString(), /*EnableExperimentalExtension=*/true,
567 /*ExperimentalExtensionVersionCheck=*/true);
568 if (!errorToBool(ParseResult.takeError())) {
569 auto &ISAInfo = *ParseResult;
570 for (const auto &Feature : RISCVFeatureKV) {
571 if (ISAInfo->hasExtension(Feature.Key) &&
572 !SubtargetInfo.hasFeature(Feature.Value))
573 SubtargetInfo.ToggleFeature(Feature.Key);
574 }
575 }
576 }
577 }
578
579 RTS.setFlagsFromFeatures(SubtargetInfo);
580 }
581
582 if (TM.getTargetTriple().isOSBinFormatELF())
583 emitAttributes(SubtargetInfo);
584}
585
586void RISCVAsmPrinter::emitEndOfAsmFile(Module &M) {
587 RISCVTargetStreamer &RTS = getTargetStreamer();
588
589 if (TM.getTargetTriple().isOSBinFormatELF()) {
591 emitNoteGnuProperty(M);
592 }
593 EmitHwasanMemaccessSymbols(M);
594}
595
596void RISCVAsmPrinter::emitAttributes(const MCSubtargetInfo &SubtargetInfo) {
597 RISCVTargetStreamer &RTS = getTargetStreamer();
598 // Use MCSubtargetInfo from TargetMachine. Individual functions may have
599 // attributes that differ from other functions in the module and we have no
600 // way to know which function is correct.
601 RTS.emitTargetAttributes(SubtargetInfo, /*EmitStackAlign*/ true);
602}
603
604void RISCVAsmPrinter::emitFunctionEntryLabel() {
605 const auto *RMFI = MF->getInfo<RISCVMachineFunctionInfo>();
606 if (RMFI->isVectorCall()) {
607 RISCVTargetStreamer &RTS = getTargetStreamer();
608 RTS.emitDirectiveVariantCC(*CurrentFnSym);
609 }
611}
612
613// Force static initialization.
621
622void RISCVAsmPrinter::LowerHWASAN_CHECK_MEMACCESS(const MachineInstr &MI) {
623 Register Reg = MI.getOperand(0).getReg();
624 uint32_t AccessInfo = MI.getOperand(1).getImm();
625 MCSymbol *&Sym =
626 HwasanMemaccessSymbols[HwasanMemaccessTuple(Reg, AccessInfo)];
627 if (!Sym) {
628 // FIXME: Make this work on non-ELF.
629 if (!TM.getTargetTriple().isOSBinFormatELF())
630 report_fatal_error("llvm.hwasan.check.memaccess only supported on ELF");
631
632 std::string SymName = "__hwasan_check_x" + utostr(Reg - RISCV::X0) + "_" +
633 utostr(AccessInfo) + "_short";
634 Sym = OutContext.getOrCreateSymbol(SymName);
635 }
636 auto Res = MCSymbolRefExpr::create(Sym, OutContext);
637 auto Expr = MCSpecifierExpr::create(Res, RISCV::S_CALL_PLT, OutContext);
638
639 EmitToStreamer(*OutStreamer, MCInstBuilder(RISCV::PseudoCALL).addExpr(Expr));
640}
641
642void RISCVAsmPrinter::LowerKCFI_CHECK(const MachineInstr &MI) {
643 Register AddrReg = MI.getOperand(0).getReg();
644 assert(std::next(MI.getIterator())->isCall() &&
645 "KCFI_CHECK not followed by a call instruction");
646 assert(std::next(MI.getIterator())->getOperand(0).getReg() == AddrReg &&
647 "KCFI_CHECK call target doesn't match call operand");
648
649 // Temporary registers for comparing the hashes. If a register is used
650 // for the call target, or reserved by the user, we can clobber another
651 // temporary register as the check is immediately followed by the
652 // call. The check defaults to X6/X7, but can fall back to X28-X31 if
653 // needed.
654 unsigned ScratchRegs[] = {RISCV::X6, RISCV::X7};
655 unsigned NextReg = RISCV::X28;
656 auto isRegAvailable = [&](unsigned Reg) {
657 return Reg != AddrReg && !STI->isRegisterReservedByUser(Reg);
658 };
659 for (auto &Reg : ScratchRegs) {
660 if (isRegAvailable(Reg))
661 continue;
662 while (!isRegAvailable(NextReg))
663 ++NextReg;
664 Reg = NextReg++;
665 if (Reg > RISCV::X31)
666 report_fatal_error("Unable to find scratch registers for KCFI_CHECK");
667 }
668
669 if (AddrReg == RISCV::X0) {
670 // Checking X0 makes no sense. Instead of emitting a load, zero
671 // ScratchRegs[0].
672 EmitToStreamer(*OutStreamer, MCInstBuilder(RISCV::ADDI)
673 .addReg(ScratchRegs[0])
674 .addReg(RISCV::X0)
675 .addImm(0));
676 } else {
677 // Adjust the offset for patchable-function-prefix. This assumes that
678 // patchable-function-prefix is the same for all functions.
679 int NopSize = STI->hasStdExtZca() ? 2 : 4;
680 int64_t PrefixNops =
681 MI.getMF()->getFunction().getFnAttributeAsParsedInteger(
682 "patchable-function-prefix");
683
684 // Load the target function type hash.
685 EmitToStreamer(*OutStreamer, MCInstBuilder(RISCV::LW)
686 .addReg(ScratchRegs[0])
687 .addReg(AddrReg)
688 .addImm(-(PrefixNops * NopSize + 4)));
689 }
690
691 // Load the expected 32-bit type hash.
692 const int64_t Type = MI.getOperand(1).getImm();
693 const int64_t Hi20 = ((Type + 0x800) >> 12) & 0xFFFFF;
694 const int64_t Lo12 = SignExtend64<12>(Type);
695 if (Hi20) {
696 EmitToStreamer(
697 *OutStreamer,
698 MCInstBuilder(RISCV::LUI).addReg(ScratchRegs[1]).addImm(Hi20));
699 }
700 if (Lo12 || Hi20 == 0) {
701 EmitToStreamer(*OutStreamer,
702 MCInstBuilder((STI->hasFeature(RISCV::Feature64Bit) && Hi20)
703 ? RISCV::ADDIW
704 : RISCV::ADDI)
705 .addReg(ScratchRegs[1])
706 .addReg(ScratchRegs[1])
707 .addImm(Lo12));
708 }
709
710 // Compare the hashes and trap if there's a mismatch.
711 MCSymbol *Pass = OutContext.createTempSymbol();
712 EmitToStreamer(*OutStreamer,
713 MCInstBuilder(RISCV::BEQ)
714 .addReg(ScratchRegs[0])
715 .addReg(ScratchRegs[1])
716 .addExpr(MCSymbolRefExpr::create(Pass, OutContext)));
717
718 MCSymbol *Trap = OutContext.createTempSymbol();
719 OutStreamer->emitLabel(Trap);
720 EmitToStreamer(*OutStreamer, MCInstBuilder(RISCV::EBREAK));
721 emitKCFITrapEntry(*MI.getMF(), Trap);
722 OutStreamer->emitLabel(Pass);
723}
724
725void RISCVAsmPrinter::EmitHwasanMemaccessSymbols(Module &M) {
726 if (HwasanMemaccessSymbols.empty())
727 return;
728
729 assert(TM.getTargetTriple().isOSBinFormatELF());
730 // Use MCSubtargetInfo from TargetMachine. Individual functions may have
731 // attributes that differ from other functions in the module and we have no
732 // way to know which function is correct.
733 const MCSubtargetInfo &MCSTI = *TM.getMCSubtargetInfo();
734
735 MCSymbol *HwasanTagMismatchV2Sym =
736 OutContext.getOrCreateSymbol("__hwasan_tag_mismatch_v2");
737 // Annotate symbol as one having incompatible calling convention, so
738 // run-time linkers can instead eagerly bind this function.
739 RISCVTargetStreamer &RTS = getTargetStreamer();
740 RTS.emitDirectiveVariantCC(*HwasanTagMismatchV2Sym);
741
742 const MCSymbolRefExpr *HwasanTagMismatchV2Ref =
743 MCSymbolRefExpr::create(HwasanTagMismatchV2Sym, OutContext);
744 auto Expr = MCSpecifierExpr::create(HwasanTagMismatchV2Ref, RISCV::S_CALL_PLT,
745 OutContext);
746
747 for (auto &P : HwasanMemaccessSymbols) {
748 unsigned Reg = std::get<0>(P.first);
749 uint32_t AccessInfo = std::get<1>(P.first);
750 MCSymbol *Sym = P.second;
751
752 unsigned Size =
753 1 << ((AccessInfo >> HWASanAccessInfo::AccessSizeShift) & 0xf);
754 OutStreamer->switchSection(OutContext.getELFSection(
755 ".text.hot", ELF::SHT_PROGBITS,
757 /*IsComdat=*/true));
758
760 OutStreamer->emitSymbolAttribute(Sym, MCSA_Weak);
761 OutStreamer->emitSymbolAttribute(Sym, MCSA_Hidden);
762 OutStreamer->emitLabel(Sym);
763
764 // Extract shadow offset from ptr
765 EmitToStreamer(
766 *OutStreamer,
767 MCInstBuilder(RISCV::SLLI).addReg(RISCV::X6).addReg(Reg).addImm(8),
768 MCSTI);
769 EmitToStreamer(*OutStreamer,
770 MCInstBuilder(RISCV::SRLI)
771 .addReg(RISCV::X6)
772 .addReg(RISCV::X6)
773 .addImm(12),
774 MCSTI);
775 // load shadow tag in X6, X5 contains shadow base
776 EmitToStreamer(*OutStreamer,
777 MCInstBuilder(RISCV::ADD)
778 .addReg(RISCV::X6)
779 .addReg(RISCV::X5)
780 .addReg(RISCV::X6),
781 MCSTI);
782 EmitToStreamer(
783 *OutStreamer,
784 MCInstBuilder(RISCV::LBU).addReg(RISCV::X6).addReg(RISCV::X6).addImm(0),
785 MCSTI);
786 // Extract tag from pointer and compare it with loaded tag from shadow
787 EmitToStreamer(
788 *OutStreamer,
789 MCInstBuilder(RISCV::SRLI).addReg(RISCV::X7).addReg(Reg).addImm(56),
790 MCSTI);
791 MCSymbol *HandleMismatchOrPartialSym = OutContext.createTempSymbol();
792 // X7 contains tag from the pointer, while X6 contains tag from memory
793 EmitToStreamer(*OutStreamer,
794 MCInstBuilder(RISCV::BNE)
795 .addReg(RISCV::X7)
796 .addReg(RISCV::X6)
798 HandleMismatchOrPartialSym, OutContext)),
799 MCSTI);
800 MCSymbol *ReturnSym = OutContext.createTempSymbol();
801 OutStreamer->emitLabel(ReturnSym);
802 EmitToStreamer(*OutStreamer,
803 MCInstBuilder(RISCV::JALR)
804 .addReg(RISCV::X0)
805 .addReg(RISCV::X1)
806 .addImm(0),
807 MCSTI);
808 OutStreamer->emitLabel(HandleMismatchOrPartialSym);
809
810 EmitToStreamer(*OutStreamer,
811 MCInstBuilder(RISCV::ADDI)
812 .addReg(RISCV::X28)
813 .addReg(RISCV::X0)
814 .addImm(16),
815 MCSTI);
816 MCSymbol *HandleMismatchSym = OutContext.createTempSymbol();
817 EmitToStreamer(
818 *OutStreamer,
819 MCInstBuilder(RISCV::BGEU)
820 .addReg(RISCV::X6)
821 .addReg(RISCV::X28)
822 .addExpr(MCSymbolRefExpr::create(HandleMismatchSym, OutContext)),
823 MCSTI);
824
825 EmitToStreamer(
826 *OutStreamer,
827 MCInstBuilder(RISCV::ANDI).addReg(RISCV::X28).addReg(Reg).addImm(0xF),
828 MCSTI);
829
830 if (Size != 1)
831 EmitToStreamer(*OutStreamer,
832 MCInstBuilder(RISCV::ADDI)
833 .addReg(RISCV::X28)
834 .addReg(RISCV::X28)
835 .addImm(Size - 1),
836 MCSTI);
837 EmitToStreamer(
838 *OutStreamer,
839 MCInstBuilder(RISCV::BGE)
840 .addReg(RISCV::X28)
841 .addReg(RISCV::X6)
842 .addExpr(MCSymbolRefExpr::create(HandleMismatchSym, OutContext)),
843 MCSTI);
844
845 EmitToStreamer(
846 *OutStreamer,
847 MCInstBuilder(RISCV::ORI).addReg(RISCV::X6).addReg(Reg).addImm(0xF),
848 MCSTI);
849 EmitToStreamer(
850 *OutStreamer,
851 MCInstBuilder(RISCV::LBU).addReg(RISCV::X6).addReg(RISCV::X6).addImm(0),
852 MCSTI);
853 EmitToStreamer(*OutStreamer,
854 MCInstBuilder(RISCV::BEQ)
855 .addReg(RISCV::X6)
856 .addReg(RISCV::X7)
857 .addExpr(MCSymbolRefExpr::create(ReturnSym, OutContext)),
858 MCSTI);
859
860 OutStreamer->emitLabel(HandleMismatchSym);
861
862 // | Previous stack frames... |
863 // +=================================+ <-- [SP + 256]
864 // | ... |
865 // | |
866 // | Stack frame space for x12 - x31.|
867 // | |
868 // | ... |
869 // +---------------------------------+ <-- [SP + 96]
870 // | Saved x11(arg1), as |
871 // | __hwasan_check_* clobbers it. |
872 // +---------------------------------+ <-- [SP + 88]
873 // | Saved x10(arg0), as |
874 // | __hwasan_check_* clobbers it. |
875 // +---------------------------------+ <-- [SP + 80]
876 // | |
877 // | Stack frame space for x9. |
878 // +---------------------------------+ <-- [SP + 72]
879 // | |
880 // | Saved x8(fp), as |
881 // | __hwasan_check_* clobbers it. |
882 // +---------------------------------+ <-- [SP + 64]
883 // | ... |
884 // | |
885 // | Stack frame space for x2 - x7. |
886 // | |
887 // | ... |
888 // +---------------------------------+ <-- [SP + 16]
889 // | Return address (x1) for caller |
890 // | of __hwasan_check_*. |
891 // +---------------------------------+ <-- [SP + 8]
892 // | Reserved place for x0, possibly |
893 // | junk, since we don't save it. |
894 // +---------------------------------+ <-- [x2 / SP]
895
896 // Adjust sp
897 EmitToStreamer(*OutStreamer,
898 MCInstBuilder(RISCV::ADDI)
899 .addReg(RISCV::X2)
900 .addReg(RISCV::X2)
901 .addImm(-256),
902 MCSTI);
903
904 // store x10(arg0) by new sp
905 EmitToStreamer(*OutStreamer,
906 MCInstBuilder(RISCV::SD)
907 .addReg(RISCV::X10)
908 .addReg(RISCV::X2)
909 .addImm(8 * 10),
910 MCSTI);
911 // store x11(arg1) by new sp
912 EmitToStreamer(*OutStreamer,
913 MCInstBuilder(RISCV::SD)
914 .addReg(RISCV::X11)
915 .addReg(RISCV::X2)
916 .addImm(8 * 11),
917 MCSTI);
918
919 // store x8(fp) by new sp
920 EmitToStreamer(
921 *OutStreamer,
922 MCInstBuilder(RISCV::SD).addReg(RISCV::X8).addReg(RISCV::X2).addImm(8 *
923 8),
924 MCSTI);
925 // store x1(ra) by new sp
926 EmitToStreamer(
927 *OutStreamer,
928 MCInstBuilder(RISCV::SD).addReg(RISCV::X1).addReg(RISCV::X2).addImm(1 *
929 8),
930 MCSTI);
931 if (Reg != RISCV::X10)
932 EmitToStreamer(
933 *OutStreamer,
934 MCInstBuilder(RISCV::ADDI).addReg(RISCV::X10).addReg(Reg).addImm(0),
935 MCSTI);
936 EmitToStreamer(*OutStreamer,
937 MCInstBuilder(RISCV::ADDI)
938 .addReg(RISCV::X11)
939 .addReg(RISCV::X0)
940 .addImm(AccessInfo & HWASanAccessInfo::RuntimeMask),
941 MCSTI);
942
943 EmitToStreamer(*OutStreamer, MCInstBuilder(RISCV::PseudoCALL).addExpr(Expr),
944 MCSTI);
945 }
946}
947
948void RISCVAsmPrinter::emitNoteGnuProperty(const Module &M) {
949 assert(TM.getTargetTriple().isOSBinFormatELF() && "invalid binary format");
950 if (const Metadata *const Flag = M.getModuleFlag("cf-protection-return");
951 Flag && !mdconst::extract<ConstantInt>(Flag)->isZero()) {
952 auto &RTS = static_cast<RISCVTargetELFStreamer &>(getTargetStreamer());
953 RTS.emitNoteGnuPropertySection(ELF::GNU_PROPERTY_RISCV_FEATURE_1_CFI_SS);
954 }
955}
956
958 const AsmPrinter &AP) {
959 MCContext &Ctx = AP.OutContext;
960 RISCV::Specifier Kind;
961
962 switch (MO.getTargetFlags()) {
963 default:
964 llvm_unreachable("Unknown target flag on GV operand");
965 case RISCVII::MO_None:
966 Kind = RISCV::S_None;
967 break;
968 case RISCVII::MO_CALL:
969 Kind = RISCV::S_CALL_PLT;
970 break;
971 case RISCVII::MO_LO:
972 Kind = RISCV::S_LO;
973 break;
974 case RISCVII::MO_HI:
975 Kind = ELF::R_RISCV_HI20;
976 break;
978 Kind = RISCV::S_PCREL_LO;
979 break;
981 Kind = RISCV::S_PCREL_HI;
982 break;
984 Kind = RISCV::S_GOT_HI;
985 break;
987 Kind = RISCV::S_TPREL_LO;
988 break;
990 Kind = ELF::R_RISCV_TPREL_HI20;
991 break;
993 Kind = ELF::R_RISCV_TPREL_ADD;
994 break;
996 Kind = ELF::R_RISCV_TLS_GOT_HI20;
997 break;
999 Kind = ELF::R_RISCV_TLS_GD_HI20;
1000 break;
1002 Kind = ELF::R_RISCV_TLSDESC_HI20;
1003 break;
1005 Kind = ELF::R_RISCV_TLSDESC_LOAD_LO12;
1006 break;
1008 Kind = ELF::R_RISCV_TLSDESC_ADD_LO12;
1009 break;
1011 Kind = ELF::R_RISCV_TLSDESC_CALL;
1012 break;
1013 }
1014
1015 const MCExpr *ME = MCSymbolRefExpr::create(Sym, Ctx);
1016
1017 if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
1019 ME, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
1020
1021 if (Kind != RISCV::S_None)
1022 ME = MCSpecifierExpr::create(ME, Kind, Ctx);
1023 return MCOperand::createExpr(ME);
1024}
1025
1026bool RISCVAsmPrinter::lowerOperand(const MachineOperand &MO,
1027 MCOperand &MCOp) const {
1028 switch (MO.getType()) {
1029 default:
1030 report_fatal_error("lowerOperand: unknown operand type");
1032 // Ignore all implicit register operands.
1033 if (MO.isImplicit())
1034 return false;
1035 MCOp = MCOperand::createReg(MO.getReg());
1036 break;
1038 // Regmasks are like implicit defs.
1039 return false;
1041 MCOp = MCOperand::createImm(MO.getImm());
1042 break;
1044 MCOp = lowerSymbolOperand(MO, MO.getMBB()->getSymbol(), *this);
1045 break;
1047 MCOp = lowerSymbolOperand(MO, getSymbolPreferLocal(*MO.getGlobal()), *this);
1048 break;
1050 MCOp = lowerSymbolOperand(MO, GetBlockAddressSymbol(MO.getBlockAddress()),
1051 *this);
1052 break;
1054 MCOp = lowerSymbolOperand(MO, GetExternalSymbolSymbol(MO.getSymbolName()),
1055 *this);
1056 break;
1058 MCOp = lowerSymbolOperand(MO, GetCPISymbol(MO.getIndex()), *this);
1059 break;
1061 MCOp = lowerSymbolOperand(MO, GetJTISymbol(MO.getIndex()), *this);
1062 break;
1064 MCOp = lowerSymbolOperand(MO, MO.getMCSymbol(), *this);
1065 break;
1066 }
1067 return true;
1068}
1069
1071 MCInst &OutMI,
1072 const RISCVSubtarget *STI) {
1074 RISCVVPseudosTable::getPseudoInfo(MI->getOpcode());
1075 if (!RVV)
1076 return false;
1077
1078 OutMI.setOpcode(RVV->BaseInstr);
1079
1080 const TargetInstrInfo *TII = STI->getInstrInfo();
1081 const TargetRegisterInfo *TRI = STI->getRegisterInfo();
1082 assert(TRI && "TargetRegisterInfo expected");
1083
1084 const MCInstrDesc &MCID = MI->getDesc();
1085 uint64_t TSFlags = MCID.TSFlags;
1086 unsigned NumOps = MI->getNumExplicitOperands();
1087
1088 // Skip policy, SEW, VL, VXRM/FRM operands which are the last operands if
1089 // present.
1090 if (RISCVII::hasVecPolicyOp(TSFlags))
1091 --NumOps;
1092 if (RISCVII::hasSEWOp(TSFlags))
1093 --NumOps;
1094 if (RISCVII::hasVLOp(TSFlags))
1095 --NumOps;
1096 if (RISCVII::hasRoundModeOp(TSFlags))
1097 --NumOps;
1098 if (RISCVII::hasTWidenOp(TSFlags))
1099 --NumOps;
1100 if (RISCVII::hasTMOp(TSFlags))
1101 --NumOps;
1102 if (RISCVII::hasTKOp(TSFlags))
1103 --NumOps;
1104
1105 bool hasVLOutput = RISCVInstrInfo::isFaultOnlyFirstLoad(*MI);
1106 for (unsigned OpNo = 0; OpNo != NumOps; ++OpNo) {
1107 const MachineOperand &MO = MI->getOperand(OpNo);
1108 // Skip vl output. It should be the second output.
1109 if (hasVLOutput && OpNo == 1)
1110 continue;
1111
1112 // Skip passthru op. It should be the first operand after the defs.
1113 if (OpNo == MI->getNumExplicitDefs() && MO.isReg() && MO.isTied()) {
1114 assert(MCID.getOperandConstraint(OpNo, MCOI::TIED_TO) == 0 &&
1115 "Expected tied to first def.");
1116 const MCInstrDesc &OutMCID = TII->get(OutMI.getOpcode());
1117 // Skip if the next operand in OutMI is not supposed to be tied. Unless it
1118 // is a _TIED instruction.
1119 if (OutMCID.getOperandConstraint(OutMI.getNumOperands(), MCOI::TIED_TO) <
1120 0 &&
1121 !RISCVII::isTiedPseudo(TSFlags))
1122 continue;
1123 }
1124
1125 MCOperand MCOp;
1126 switch (MO.getType()) {
1127 default:
1128 llvm_unreachable("Unknown operand type");
1130 Register Reg = MO.getReg();
1131
1132 if (RISCV::VRM2RegClass.contains(Reg) ||
1133 RISCV::VRM4RegClass.contains(Reg) ||
1134 RISCV::VRM8RegClass.contains(Reg)) {
1135 Reg = TRI->getSubReg(Reg, RISCV::sub_vrm1_0);
1136 assert(Reg && "Subregister does not exist");
1137 } else if (RISCV::FPR16RegClass.contains(Reg)) {
1138 Reg =
1139 TRI->getMatchingSuperReg(Reg, RISCV::sub_16, &RISCV::FPR32RegClass);
1140 assert(Reg && "Subregister does not exist");
1141 } else if (RISCV::FPR64RegClass.contains(Reg)) {
1142 Reg = TRI->getSubReg(Reg, RISCV::sub_32);
1143 assert(Reg && "Superregister does not exist");
1144 } else if (RISCV::VRN2M1RegClass.contains(Reg) ||
1145 RISCV::VRN2M2RegClass.contains(Reg) ||
1146 RISCV::VRN2M4RegClass.contains(Reg) ||
1147 RISCV::VRN3M1RegClass.contains(Reg) ||
1148 RISCV::VRN3M2RegClass.contains(Reg) ||
1149 RISCV::VRN4M1RegClass.contains(Reg) ||
1150 RISCV::VRN4M2RegClass.contains(Reg) ||
1151 RISCV::VRN5M1RegClass.contains(Reg) ||
1152 RISCV::VRN6M1RegClass.contains(Reg) ||
1153 RISCV::VRN7M1RegClass.contains(Reg) ||
1154 RISCV::VRN8M1RegClass.contains(Reg)) {
1155 Reg = TRI->getSubReg(Reg, RISCV::sub_vrm1_0);
1156 assert(Reg && "Subregister does not exist");
1157 }
1158
1159 MCOp = MCOperand::createReg(Reg);
1160 break;
1161 }
1163 MCOp = MCOperand::createImm(MO.getImm());
1164 break;
1165 }
1166 OutMI.addOperand(MCOp);
1167 }
1168
1169 // Unmasked pseudo instructions need to append dummy mask operand to
1170 // V instructions. All V instructions are modeled as the masked version.
1171 const MCInstrDesc &OutMCID = TII->get(OutMI.getOpcode());
1172 if (OutMI.getNumOperands() < OutMCID.getNumOperands()) {
1173 assert(OutMCID.operands()[OutMI.getNumOperands()].OperandType ==
1175 "Expected only mask operand to be missing");
1176 OutMI.addOperand(MCOperand::createReg(RISCV::NoRegister));
1177 }
1178
1179 assert(OutMI.getNumOperands() == OutMCID.getNumOperands());
1180 return true;
1181}
1182
1183void RISCVAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
1184 if (lowerRISCVVMachineInstrToMCInst(MI, OutMI, STI))
1185 return;
1186
1187 OutMI.setOpcode(MI->getOpcode());
1188
1189 for (const MachineOperand &MO : MI->operands()) {
1190 MCOperand MCOp;
1191 if (lowerOperand(MO, MCOp))
1192 OutMI.addOperand(MCOp);
1193 }
1194}
1195
1196void RISCVAsmPrinter::emitMachineConstantPoolValue(
1197 MachineConstantPoolValue *MCPV) {
1198 auto *RCPV = static_cast<RISCVConstantPoolValue *>(MCPV);
1199 MCSymbol *MCSym;
1200
1201 if (RCPV->isGlobalValue()) {
1202 auto *GV = RCPV->getGlobalValue();
1203 MCSym = getSymbol(GV);
1204 } else {
1205 assert(RCPV->isExtSymbol() && "unrecognized constant pool type");
1206 auto Sym = RCPV->getSymbol();
1207 MCSym = GetExternalSymbolSymbol(Sym);
1208 }
1209
1210 const MCExpr *Expr = MCSymbolRefExpr::create(MCSym, OutContext);
1211 uint64_t Size = getDataLayout().getTypeAllocSize(RCPV->getType());
1212 OutStreamer->emitValue(Expr, Size);
1213}
1214
1215char RISCVAsmPrinter::ID = 0;
1216
1217INITIALIZE_PASS(RISCVAsmPrinter, "riscv-asm-printer", "RISC-V Assembly Printer",
1218 false, false)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
dxil translate DXIL Translate Metadata
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
static MCOperand lowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym, const AsmPrinter &AP)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:598
Machine Check Debug Module
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static constexpr unsigned SM(unsigned Version)
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool lowerRISCVVMachineInstrToMCInst(const MachineInstr *MI, MCInst &OutMI, const RISCVSubtarget *STI)
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVAsmPrinter()
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:483
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:91
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition AsmPrinter.h:101
virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
virtual void emitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:343
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Context object for machine code objects.
Definition MCContext.h:83
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
unsigned getNumOperands() const
Definition MCInst.h:212
unsigned getOpcode() const
Definition MCInst.h:202
void addOperand(const MCOperand Op)
Definition MCInst.h:215
void setOpcode(unsigned Op)
Definition MCInst.h:201
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
ArrayRef< MCOperandInfo > operands() const
int getOperandConstraint(unsigned OpNum, MCOI::OperandConstraint Constraint) const
Returns the value of the specified operand constraint if it is present.
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:40
static MCOperand createExpr(const MCExpr *Val)
Definition MCInst.h:166
int64_t getImm() const
Definition MCInst.h:84
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:138
static MCOperand createImm(int64_t Val)
Definition MCInst.h:145
const MCExpr * getExpr() const
Definition MCInst.h:118
static const MCSpecifierExpr * create(const MCExpr *Expr, Spec S, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.cpp:743
Streaming machine code generation interface.
Definition MCStreamer.h:222
virtual void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
virtual bool emitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute)=0
Add the given Attribute to Symbol.
MCContext & getContext() const
Definition MCStreamer.h:323
void emitValue(const MCExpr *Value, unsigned Size, SMLoc Loc=SMLoc())
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
MCTargetStreamer * getTargetStreamer()
Definition MCStreamer.h:333
virtual void emitCodeAlignment(Align Alignment, const MCSubtargetInfo *STI, unsigned MaxBytesToEmit=0)
Emit nops until the byte alignment ByteAlignment is reached.
virtual void switchSection(MCSection *Section, uint32_t Subsec=0)
Set the current section where code is being emitted to Section.
bool hasFeature(unsigned Feature) const
const FeatureBitset & ToggleFeature(uint64_t FB)
Toggle a feature and return the re-computed feature bits.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:214
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
LLVM_ABI void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition MCSymbol.cpp:59
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Representation of each machine instruction.
Flags getFlags() const
Return the raw flags of the source value,.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isJTI() const
isJTI - Tests if this is a MO_JumpTableIndex operand.
const BlockAddress * getBlockAddress() const
unsigned getTargetFlags() const
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
MCSymbol * getMCSymbol() const
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_MCSymbol
MCSymbol reference (for debug/eh info)
@ MO_GlobalAddress
Address of a global value.
@ MO_RegisterMask
Mask of preserved registers.
@ MO_BlockAddress
Address of a basic block.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
int64_t getOffset() const
Return the offset from the symbol in this operand.
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
static LLVM_ABI bool isSupportedExtensionFeature(StringRef Ext)
static LLVM_ABI llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseArchString(StringRef Arch, bool EnableExperimentalExtension, bool ExperimentalExtensionVersionCheck=true)
Parse RISC-V ISA info from arch string.
static const char * getRegisterName(MCRegister Reg)
bool requiresNTLHint(const MachineInstr &MI) const
Return true if the instruction requires an NTL hint to be emitted.
bool isRegisterReservedByUser(Register i) const override
const RISCVRegisterInfo * getRegisterInfo() const override
const RISCVInstrInfo * getInstrInfo() const override
virtual void emitDirectiveVariantCC(MCSymbol &Symbol)
void emitTargetAttributes(const MCSubtargetInfo &STI, bool EmitStackAlign)
void setFlagsFromFeatures(const MCSubtargetInfo &STI)
void setTargetABI(RISCVABI::ABI ABI)
virtual void emitDirectiveOptionArch(ArrayRef< RISCVOptionArchArg > Args)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
reference emplace_back(ArgTypes &&... Args)
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ SHF_ALLOC
Definition ELF.h:1249
@ SHF_GROUP
Definition ELF.h:1271
@ SHF_EXECINSTR
Definition ELF.h:1252
@ SHT_PROGBITS
Definition ELF.h:1148
@ GNU_PROPERTY_RISCV_FEATURE_1_CFI_SS
Definition ELF.h:1915
ABI getTargetABI(StringRef ABIName)
static bool hasRoundModeOp(uint64_t TSFlags)
static bool hasTWidenOp(uint64_t TSFlags)
static bool isTiedPseudo(uint64_t TSFlags)
static bool hasTKOp(uint64_t TSFlags)
static bool hasVLOp(uint64_t TSFlags)
static bool hasTMOp(uint64_t TSFlags)
static bool hasVecPolicyOp(uint64_t TSFlags)
static bool hasSEWOp(uint64_t TSFlags)
void generateMCInstSeq(int64_t Val, const MCSubtargetInfo &STI, MCRegister DestReg, SmallVectorImpl< MCInst > &Insts)
bool compress(MCInst &OutInst, const MCInst &MI, const MCSubtargetInfo &STI)
uint16_t Specifier
void emitInstruction(MCObjectStreamer &, const MCInst &Inst, const MCSubtargetInfo &STI)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
This is an optimization pass for GlobalISel generic memory operations.
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
Definition Error.h:1129
@ Offset
Definition DWP.cpp:557
static const MachineMemOperand::Flags MONontemporalBit1
Target & getTheRISCV32Target()
static const MachineMemOperand::Flags MONontemporalBit0
std::string utostr(uint64_t X, bool isNeg=false)
Target & getTheRISCV64beTarget()
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
Target & getTheRISCV64Target()
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1916
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:572
const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures]
@ MCSA_Weak
.weak
@ MCSA_ELF_TypeFunction
.type _foo, STT_FUNC # aka @function
@ MCSA_Hidden
.hidden (ELF)
Target & getTheRISCV32beTarget()
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...
Used to provide key value pairs for feature and CPU bit flags.