LLVM 19.0.0git
RISCVAsmParser.cpp
Go to the documentation of this file.
1//===-- RISCVAsmParser.cpp - Parse RISC-V assembly to MCInst instructions -===//
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
17#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/Statistic.h"
22#include "llvm/MC/MCAssembler.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCExpr.h"
25#include "llvm/MC/MCInst.h"
27#include "llvm/MC/MCInstrInfo.h"
33#include "llvm/MC/MCStreamer.h"
35#include "llvm/MC/MCValue.h"
42
43#include <limits>
44
45using namespace llvm;
46
47#define DEBUG_TYPE "riscv-asm-parser"
48
49STATISTIC(RISCVNumInstrsCompressed,
50 "Number of RISC-V Compressed instructions emitted");
51
52static cl::opt<bool> AddBuildAttributes("riscv-add-build-attributes",
53 cl::init(false));
54
55namespace llvm {
56extern const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures];
57} // namespace llvm
58
59namespace {
60struct RISCVOperand;
61
62struct ParserOptionsSet {
63 bool IsPicEnabled;
64};
65
66class RISCVAsmParser : public MCTargetAsmParser {
67 // This tracks the parsing of the 4 operands that make up the vtype portion
68 // of vset(i)vli instructions which are separated by commas. The state names
69 // represent the next expected operand with Done meaning no other operands are
70 // expected.
71 enum VTypeState {
72 VTypeState_SEW,
73 VTypeState_LMUL,
74 VTypeState_TailPolicy,
75 VTypeState_MaskPolicy,
76 VTypeState_Done,
77 };
78
79 SmallVector<FeatureBitset, 4> FeatureBitStack;
80
81 SmallVector<ParserOptionsSet, 4> ParserOptionsStack;
82 ParserOptionsSet ParserOptions;
83
84 SMLoc getLoc() const { return getParser().getTok().getLoc(); }
85 bool isRV64() const { return getSTI().hasFeature(RISCV::Feature64Bit); }
86 bool isRVE() const { return getSTI().hasFeature(RISCV::FeatureRVE); }
87
88 RISCVTargetStreamer &getTargetStreamer() {
89 assert(getParser().getStreamer().getTargetStreamer() &&
90 "do not have a target streamer");
92 return static_cast<RISCVTargetStreamer &>(TS);
93 }
94
96 unsigned Kind) override;
97 unsigned checkTargetMatchPredicate(MCInst &Inst) override;
98
99 bool generateImmOutOfRangeError(OperandVector &Operands, uint64_t ErrorInfo,
100 int64_t Lower, int64_t Upper,
101 const Twine &Msg);
102 bool generateImmOutOfRangeError(SMLoc ErrorLoc, int64_t Lower, int64_t Upper,
103 const Twine &Msg);
104
105 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
108 bool MatchingInlineAsm) override;
109
111 bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
113 SMLoc &EndLoc) override;
114
116 SMLoc NameLoc, OperandVector &Operands) override;
117
118 ParseStatus parseDirective(AsmToken DirectiveID) override;
119
120 bool parseVTypeToken(StringRef Identifier, VTypeState &State, unsigned &Sew,
121 unsigned &Lmul, bool &Fractional, bool &TailAgnostic,
122 bool &MaskAgnostic);
123 bool generateVTypeError(SMLoc ErrorLoc);
124
125 // Helper to actually emit an instruction to the MCStreamer. Also, when
126 // possible, compression of the instruction is performed.
127 void emitToStreamer(MCStreamer &S, const MCInst &Inst);
128
129 // Helper to emit a combination of LUI, ADDI(W), and SLLI instructions that
130 // synthesize the desired immedate value into the destination register.
131 void emitLoadImm(MCRegister DestReg, int64_t Value, MCStreamer &Out);
132
133 // Helper to emit a combination of AUIPC and SecondOpcode. Used to implement
134 // helpers such as emitLoadLocalAddress and emitLoadAddress.
135 void emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
136 const MCExpr *Symbol, RISCVMCExpr::VariantKind VKHi,
137 unsigned SecondOpcode, SMLoc IDLoc, MCStreamer &Out);
138
139 // Helper to emit pseudo instruction "lla" used in PC-rel addressing.
140 void emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
141
142 // Helper to emit pseudo instruction "lga" used in GOT-rel addressing.
143 void emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
144
145 // Helper to emit pseudo instruction "la" used in GOT/PC-rel addressing.
146 void emitLoadAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
147
148 // Helper to emit pseudo instruction "la.tls.ie" used in initial-exec TLS
149 // addressing.
150 void emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
151
152 // Helper to emit pseudo instruction "la.tls.gd" used in global-dynamic TLS
153 // addressing.
154 void emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
155
156 // Helper to emit pseudo load/store instruction with a symbol.
157 void emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
158 MCStreamer &Out, bool HasTmpReg);
159
160 // Helper to emit pseudo sign/zero extend instruction.
161 void emitPseudoExtend(MCInst &Inst, bool SignExtend, int64_t Width,
162 SMLoc IDLoc, MCStreamer &Out);
163
164 // Helper to emit pseudo vmsge{u}.vx instruction.
165 void emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc, MCStreamer &Out);
166
167 // Checks that a PseudoAddTPRel is using x4/tp in its second input operand.
168 // Enforcing this using a restricted register class for the second input
169 // operand of PseudoAddTPRel results in a poor diagnostic due to the fact
170 // 'add' is an overloaded mnemonic.
171 bool checkPseudoAddTPRel(MCInst &Inst, OperandVector &Operands);
172
173 // Checks that a PseudoTLSDESCCall is using x5/t0 in its output operand.
174 // Enforcing this using a restricted register class for the output
175 // operand of PseudoTLSDESCCall results in a poor diagnostic due to the fact
176 // 'jalr' is an overloaded mnemonic.
177 bool checkPseudoTLSDESCCall(MCInst &Inst, OperandVector &Operands);
178
179 // Check instruction constraints.
180 bool validateInstruction(MCInst &Inst, OperandVector &Operands);
181
182 /// Helper for processing MC instructions that have been successfully matched
183 /// by MatchAndEmitInstruction. Modifications to the emitted instructions,
184 /// like the expansion of pseudo instructions (e.g., "li"), can be performed
185 /// in this method.
186 bool processInstruction(MCInst &Inst, SMLoc IDLoc, OperandVector &Operands,
187 MCStreamer &Out);
188
189// Auto-generated instruction matching functions
190#define GET_ASSEMBLER_HEADER
191#include "RISCVGenAsmMatcher.inc"
192
193 ParseStatus parseCSRSystemRegister(OperandVector &Operands);
196 ParseStatus parseRegister(OperandVector &Operands, bool AllowParens = false);
197 ParseStatus parseMemOpBaseReg(OperandVector &Operands);
198 ParseStatus parseZeroOffsetMemOp(OperandVector &Operands);
199 ParseStatus parseOperandWithModifier(OperandVector &Operands);
200 ParseStatus parseBareSymbol(OperandVector &Operands);
201 ParseStatus parseCallSymbol(OperandVector &Operands);
202 ParseStatus parsePseudoJumpSymbol(OperandVector &Operands);
203 ParseStatus parseJALOffset(OperandVector &Operands);
204 ParseStatus parseVTypeI(OperandVector &Operands);
205 ParseStatus parseMaskReg(OperandVector &Operands);
206 ParseStatus parseInsnDirectiveOpcode(OperandVector &Operands);
207 ParseStatus parseInsnCDirectiveOpcode(OperandVector &Operands);
208 ParseStatus parseGPRAsFPR(OperandVector &Operands);
209 template <bool IsRV64Inst> ParseStatus parseGPRPair(OperandVector &Operands);
210 ParseStatus parseGPRPair(OperandVector &Operands, bool IsRV64Inst);
211 ParseStatus parseFRMArg(OperandVector &Operands);
212 ParseStatus parseFenceArg(OperandVector &Operands);
213 ParseStatus parseReglist(OperandVector &Operands);
214 ParseStatus parseRegReg(OperandVector &Operands);
215 ParseStatus parseRetval(OperandVector &Operands);
216 ParseStatus parseZcmpSpimm(OperandVector &Operands);
217
218 bool parseOperand(OperandVector &Operands, StringRef Mnemonic);
219
220 bool parseDirectiveOption();
221 bool parseDirectiveAttribute();
222 bool parseDirectiveInsn(SMLoc L);
223 bool parseDirectiveVariantCC();
224
225 /// Helper to reset target features for a new arch string. It
226 /// also records the new arch string that is expanded by RISCVISAInfo
227 /// and reports error for invalid arch string.
228 bool resetToArch(StringRef Arch, SMLoc Loc, std::string &Result,
229 bool FromOptionDirective);
230
231 void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
232 if (!(getSTI().hasFeature(Feature))) {
233 MCSubtargetInfo &STI = copySTI();
235 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
236 }
237 }
238
239 void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
240 if (getSTI().hasFeature(Feature)) {
241 MCSubtargetInfo &STI = copySTI();
243 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
244 }
245 }
246
247 void pushFeatureBits() {
248 assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
249 "These two stacks must be kept synchronized");
250 FeatureBitStack.push_back(getSTI().getFeatureBits());
251 ParserOptionsStack.push_back(ParserOptions);
252 }
253
254 bool popFeatureBits() {
255 assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
256 "These two stacks must be kept synchronized");
257 if (FeatureBitStack.empty())
258 return true;
259
260 FeatureBitset FeatureBits = FeatureBitStack.pop_back_val();
261 copySTI().setFeatureBits(FeatureBits);
262 setAvailableFeatures(ComputeAvailableFeatures(FeatureBits));
263
264 ParserOptions = ParserOptionsStack.pop_back_val();
265
266 return false;
267 }
268
269 std::unique_ptr<RISCVOperand> defaultMaskRegOp() const;
270 std::unique_ptr<RISCVOperand> defaultFRMArgOp() const;
271 std::unique_ptr<RISCVOperand> defaultFRMArgLegacyOp() const;
272
273public:
274 enum RISCVMatchResultTy {
275 Match_Dummy = FIRST_TARGET_MATCH_RESULT_TY,
276 Match_RequiresEvenGPRs,
277#define GET_OPERAND_DIAGNOSTIC_TYPES
278#include "RISCVGenAsmMatcher.inc"
279#undef GET_OPERAND_DIAGNOSTIC_TYPES
280 };
281
282 static bool classifySymbolRef(const MCExpr *Expr,
284 static bool isSymbolDiff(const MCExpr *Expr);
285
286 RISCVAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
287 const MCInstrInfo &MII, const MCTargetOptions &Options)
288 : MCTargetAsmParser(Options, STI, MII) {
290
291 Parser.addAliasForDirective(".half", ".2byte");
292 Parser.addAliasForDirective(".hword", ".2byte");
293 Parser.addAliasForDirective(".word", ".4byte");
294 Parser.addAliasForDirective(".dword", ".8byte");
295 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
296
297 auto ABIName = StringRef(Options.ABIName);
298 if (ABIName.ends_with("f") && !getSTI().hasFeature(RISCV::FeatureStdExtF)) {
299 errs() << "Hard-float 'f' ABI can't be used for a target that "
300 "doesn't support the F instruction set extension (ignoring "
301 "target-abi)\n";
302 } else if (ABIName.ends_with("d") &&
303 !getSTI().hasFeature(RISCV::FeatureStdExtD)) {
304 errs() << "Hard-float 'd' ABI can't be used for a target that "
305 "doesn't support the D instruction set extension (ignoring "
306 "target-abi)\n";
307 }
308
309 // Use computeTargetABI to check if ABIName is valid. If invalid, output
310 // error message.
312 ABIName);
313
314 const MCObjectFileInfo *MOFI = Parser.getContext().getObjectFileInfo();
315 ParserOptions.IsPicEnabled = MOFI->isPositionIndependent();
316
318 getTargetStreamer().emitTargetAttributes(STI, /*EmitStackAlign*/ false);
319 }
320};
321
322/// RISCVOperand - Instances of this class represent a parsed machine
323/// instruction
324struct RISCVOperand final : public MCParsedAsmOperand {
325
326 enum class KindTy {
327 Token,
328 Register,
329 Immediate,
330 FPImmediate,
331 SystemRegister,
332 VType,
333 FRM,
334 Fence,
335 Rlist,
336 Spimm,
337 RegReg,
338 } Kind;
339
340 struct RegOp {
341 MCRegister RegNum;
342 bool IsGPRAsFPR;
343 };
344
345 struct ImmOp {
346 const MCExpr *Val;
347 bool IsRV64;
348 };
349
350 struct FPImmOp {
351 uint64_t Val;
352 };
353
354 struct SysRegOp {
355 const char *Data;
356 unsigned Length;
357 unsigned Encoding;
358 // FIXME: Add the Encoding parsed fields as needed for checks,
359 // e.g.: read/write or user/supervisor/machine privileges.
360 };
361
362 struct VTypeOp {
363 unsigned Val;
364 };
365
366 struct FRMOp {
368 };
369
370 struct FenceOp {
371 unsigned Val;
372 };
373
374 struct RlistOp {
375 unsigned Val;
376 };
377
378 struct SpimmOp {
379 unsigned Val;
380 };
381
382 struct RegRegOp {
383 MCRegister Reg1;
384 MCRegister Reg2;
385 };
386
387 SMLoc StartLoc, EndLoc;
388 union {
389 StringRef Tok;
390 RegOp Reg;
391 ImmOp Imm;
392 FPImmOp FPImm;
393 struct SysRegOp SysReg;
394 struct VTypeOp VType;
395 struct FRMOp FRM;
396 struct FenceOp Fence;
397 struct RlistOp Rlist;
398 struct SpimmOp Spimm;
399 struct RegRegOp RegReg;
400 };
401
402 RISCVOperand(KindTy K) : Kind(K) {}
403
404public:
405 RISCVOperand(const RISCVOperand &o) : MCParsedAsmOperand() {
406 Kind = o.Kind;
407 StartLoc = o.StartLoc;
408 EndLoc = o.EndLoc;
409 switch (Kind) {
410 case KindTy::Register:
411 Reg = o.Reg;
412 break;
413 case KindTy::Immediate:
414 Imm = o.Imm;
415 break;
416 case KindTy::FPImmediate:
417 FPImm = o.FPImm;
418 break;
419 case KindTy::Token:
420 Tok = o.Tok;
421 break;
422 case KindTy::SystemRegister:
423 SysReg = o.SysReg;
424 break;
425 case KindTy::VType:
426 VType = o.VType;
427 break;
428 case KindTy::FRM:
429 FRM = o.FRM;
430 break;
431 case KindTy::Fence:
432 Fence = o.Fence;
433 break;
434 case KindTy::Rlist:
435 Rlist = o.Rlist;
436 break;
437 case KindTy::Spimm:
438 Spimm = o.Spimm;
439 break;
440 case KindTy::RegReg:
441 RegReg = o.RegReg;
442 break;
443 }
444 }
445
446 bool isToken() const override { return Kind == KindTy::Token; }
447 bool isReg() const override { return Kind == KindTy::Register; }
448 bool isV0Reg() const {
449 return Kind == KindTy::Register && Reg.RegNum == RISCV::V0;
450 }
451 bool isAnyReg() const {
452 return Kind == KindTy::Register &&
453 (RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg.RegNum) ||
454 RISCVMCRegisterClasses[RISCV::FPR64RegClassID].contains(Reg.RegNum) ||
455 RISCVMCRegisterClasses[RISCV::VRRegClassID].contains(Reg.RegNum));
456 }
457 bool isAnyRegC() const {
458 return Kind == KindTy::Register &&
459 (RISCVMCRegisterClasses[RISCV::GPRCRegClassID].contains(
460 Reg.RegNum) ||
461 RISCVMCRegisterClasses[RISCV::FPR64CRegClassID].contains(
462 Reg.RegNum));
463 }
464 bool isImm() const override { return Kind == KindTy::Immediate; }
465 bool isMem() const override { return false; }
466 bool isSystemRegister() const { return Kind == KindTy::SystemRegister; }
467 bool isRegReg() const { return Kind == KindTy::RegReg; }
468 bool isRlist() const { return Kind == KindTy::Rlist; }
469 bool isSpimm() const { return Kind == KindTy::Spimm; }
470
471 bool isGPR() const {
472 return Kind == KindTy::Register &&
473 RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg.RegNum);
474 }
475
476 bool isGPRAsFPR() const { return isGPR() && Reg.IsGPRAsFPR; }
477
478 bool isGPRPair() const {
479 return Kind == KindTy::Register &&
480 RISCVMCRegisterClasses[RISCV::GPRPairRegClassID].contains(
481 Reg.RegNum);
482 }
483
484 static bool evaluateConstantImm(const MCExpr *Expr, int64_t &Imm,
486 if (auto *RE = dyn_cast<RISCVMCExpr>(Expr)) {
487 VK = RE->getKind();
488 return RE->evaluateAsConstant(Imm);
489 }
490
491 if (auto CE = dyn_cast<MCConstantExpr>(Expr)) {
493 Imm = CE->getValue();
494 return true;
495 }
496
497 return false;
498 }
499
500 // True if operand is a symbol with no modifiers, or a constant with no
501 // modifiers and isShiftedInt<N-1, 1>(Op).
502 template <int N> bool isBareSimmNLsb0() const {
503 int64_t Imm;
505 if (!isImm())
506 return false;
507 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
508 bool IsValid;
509 if (!IsConstantImm)
510 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
511 else
512 IsValid = isShiftedInt<N - 1, 1>(Imm);
513 return IsValid && VK == RISCVMCExpr::VK_RISCV_None;
514 }
515
516 // Predicate methods for AsmOperands defined in RISCVInstrInfo.td
517
518 bool isBareSymbol() const {
519 int64_t Imm;
521 // Must be of 'immediate' type but not a constant.
522 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
523 return false;
524 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
526 }
527
528 bool isCallSymbol() const {
529 int64_t Imm;
531 // Must be of 'immediate' type but not a constant.
532 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
533 return false;
534 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
537 }
538
539 bool isPseudoJumpSymbol() const {
540 int64_t Imm;
542 // Must be of 'immediate' type but not a constant.
543 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
544 return false;
545 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
547 }
548
549 bool isTPRelAddSymbol() const {
550 int64_t Imm;
552 // Must be of 'immediate' type but not a constant.
553 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
554 return false;
555 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
557 }
558
559 bool isTLSDESCCallSymbol() const {
560 int64_t Imm;
562 // Must be of 'immediate' type but not a constant.
563 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
564 return false;
565 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
567 }
568
569 bool isCSRSystemRegister() const { return isSystemRegister(); }
570
571 bool isVTypeImm(unsigned N) const {
572 int64_t Imm;
574 if (!isImm())
575 return false;
576 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
577 return IsConstantImm && isUIntN(N, Imm) && VK == RISCVMCExpr::VK_RISCV_None;
578 }
579
580 // If the last operand of the vsetvli/vsetvli instruction is a constant
581 // expression, KindTy is Immediate.
582 bool isVTypeI10() const {
583 if (Kind == KindTy::Immediate)
584 return isVTypeImm(10);
585 return Kind == KindTy::VType;
586 }
587 bool isVTypeI11() const {
588 if (Kind == KindTy::Immediate)
589 return isVTypeImm(11);
590 return Kind == KindTy::VType;
591 }
592
593 /// Return true if the operand is a valid for the fence instruction e.g.
594 /// ('iorw').
595 bool isFenceArg() const { return Kind == KindTy::Fence; }
596
597 /// Return true if the operand is a valid floating point rounding mode.
598 bool isFRMArg() const { return Kind == KindTy::FRM; }
599 bool isFRMArgLegacy() const { return Kind == KindTy::FRM; }
600 bool isRTZArg() const { return isFRMArg() && FRM.FRM == RISCVFPRndMode::RTZ; }
601
602 /// Return true if the operand is a valid fli.s floating-point immediate.
603 bool isLoadFPImm() const {
604 if (isImm())
605 return isUImm5();
606 if (Kind != KindTy::FPImmediate)
607 return false;
609 APFloat(APFloat::IEEEdouble(), APInt(64, getFPConst())));
610 // Don't allow decimal version of the minimum value. It is a different value
611 // for each supported data type.
612 return Idx >= 0 && Idx != 1;
613 }
614
615 bool isImmXLenLI() const {
616 int64_t Imm;
618 if (!isImm())
619 return false;
620 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
621 if (VK == RISCVMCExpr::VK_RISCV_LO ||
625 return true;
626 // Given only Imm, ensuring that the actually specified constant is either
627 // a signed or unsigned 64-bit number is unfortunately impossible.
628 if (IsConstantImm) {
629 return VK == RISCVMCExpr::VK_RISCV_None &&
630 (isRV64Imm() || (isInt<32>(Imm) || isUInt<32>(Imm)));
631 }
632
633 return RISCVAsmParser::isSymbolDiff(getImm());
634 }
635
636 bool isImmXLenLI_Restricted() const {
637 int64_t Imm;
639 if (!isImm())
640 return false;
641 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
642 // 'la imm' supports constant immediates only.
643 return IsConstantImm && (VK == RISCVMCExpr::VK_RISCV_None) &&
644 (isRV64Imm() || (isInt<32>(Imm) || isUInt<32>(Imm)));
645 }
646
647 bool isUImmLog2XLen() const {
648 int64_t Imm;
650 if (!isImm())
651 return false;
652 if (!evaluateConstantImm(getImm(), Imm, VK) ||
654 return false;
655 return (isRV64Imm() && isUInt<6>(Imm)) || isUInt<5>(Imm);
656 }
657
658 bool isUImmLog2XLenNonZero() const {
659 int64_t Imm;
661 if (!isImm())
662 return false;
663 if (!evaluateConstantImm(getImm(), Imm, VK) ||
665 return false;
666 if (Imm == 0)
667 return false;
668 return (isRV64Imm() && isUInt<6>(Imm)) || isUInt<5>(Imm);
669 }
670
671 bool isUImmLog2XLenHalf() const {
672 int64_t Imm;
674 if (!isImm())
675 return false;
676 if (!evaluateConstantImm(getImm(), Imm, VK) ||
678 return false;
679 return (isRV64Imm() && isUInt<5>(Imm)) || isUInt<4>(Imm);
680 }
681
682 template <unsigned N> bool IsUImm() const {
683 int64_t Imm;
685 if (!isImm())
686 return false;
687 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
688 return IsConstantImm && isUInt<N>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
689 }
690
691 bool isUImm1() const { return IsUImm<1>(); }
692 bool isUImm2() const { return IsUImm<2>(); }
693 bool isUImm3() const { return IsUImm<3>(); }
694 bool isUImm4() const { return IsUImm<4>(); }
695 bool isUImm5() const { return IsUImm<5>(); }
696 bool isUImm6() const { return IsUImm<6>(); }
697 bool isUImm7() const { return IsUImm<7>(); }
698 bool isUImm8() const { return IsUImm<8>(); }
699 bool isUImm20() const { return IsUImm<20>(); }
700
701 bool isUImm8GE32() const {
702 int64_t Imm;
704 if (!isImm())
705 return false;
706 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
707 return IsConstantImm && isUInt<8>(Imm) && Imm >= 32 &&
709 }
710
711 bool isRnumArg() const {
712 int64_t Imm;
714 if (!isImm())
715 return false;
716 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
717 return IsConstantImm && Imm >= INT64_C(0) && Imm <= INT64_C(10) &&
719 }
720
721 bool isRnumArg_0_7() const {
722 int64_t Imm;
724 if (!isImm())
725 return false;
726 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
727 return IsConstantImm && Imm >= INT64_C(0) && Imm <= INT64_C(7) &&
729 }
730
731 bool isRnumArg_1_10() const {
732 int64_t Imm;
734 if (!isImm())
735 return false;
736 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
737 return IsConstantImm && Imm >= INT64_C(1) && Imm <= INT64_C(10) &&
739 }
740
741 bool isRnumArg_2_14() const {
742 int64_t Imm;
744 if (!isImm())
745 return false;
746 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
747 return IsConstantImm && Imm >= INT64_C(2) && Imm <= INT64_C(14) &&
749 }
750
751 bool isSImm5() const {
752 if (!isImm())
753 return false;
755 int64_t Imm;
756 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
757 return IsConstantImm && isInt<5>(fixImmediateForRV32(Imm, isRV64Imm())) &&
759 }
760
761 bool isSImm6() const {
762 if (!isImm())
763 return false;
765 int64_t Imm;
766 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
767 return IsConstantImm && isInt<6>(fixImmediateForRV32(Imm, isRV64Imm())) &&
769 }
770
771 bool isSImm6NonZero() const {
772 if (!isImm())
773 return false;
775 int64_t Imm;
776 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
777 return IsConstantImm && Imm != 0 &&
778 isInt<6>(fixImmediateForRV32(Imm, isRV64Imm())) &&
780 }
781
782 bool isCLUIImm() const {
783 if (!isImm())
784 return false;
785 int64_t Imm;
787 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
788 return IsConstantImm && (Imm != 0) &&
789 (isUInt<5>(Imm) || (Imm >= 0xfffe0 && Imm <= 0xfffff)) &&
791 }
792
793 bool isUImm2Lsb0() const {
794 if (!isImm())
795 return false;
796 int64_t Imm;
798 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
799 return IsConstantImm && isShiftedUInt<1, 1>(Imm) &&
801 }
802
803 bool isUImm7Lsb00() const {
804 if (!isImm())
805 return false;
806 int64_t Imm;
808 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
809 return IsConstantImm && isShiftedUInt<5, 2>(Imm) &&
811 }
812
813 bool isUImm8Lsb00() const {
814 if (!isImm())
815 return false;
816 int64_t Imm;
818 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
819 return IsConstantImm && isShiftedUInt<6, 2>(Imm) &&
821 }
822
823 bool isUImm8Lsb000() const {
824 if (!isImm())
825 return false;
826 int64_t Imm;
828 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
829 return IsConstantImm && isShiftedUInt<5, 3>(Imm) &&
831 }
832
833 bool isSImm9Lsb0() const { return isBareSimmNLsb0<9>(); }
834
835 bool isUImm9Lsb000() const {
836 if (!isImm())
837 return false;
838 int64_t Imm;
840 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
841 return IsConstantImm && isShiftedUInt<6, 3>(Imm) &&
843 }
844
845 bool isUImm10Lsb00NonZero() const {
846 if (!isImm())
847 return false;
848 int64_t Imm;
850 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
851 return IsConstantImm && isShiftedUInt<8, 2>(Imm) && (Imm != 0) &&
853 }
854
855 // If this a RV32 and the immediate is a uimm32, sign extend it to 32 bits.
856 // This allows writing 'addi a0, a0, 0xffffffff'.
857 static int64_t fixImmediateForRV32(int64_t Imm, bool IsRV64Imm) {
858 if (IsRV64Imm || !isUInt<32>(Imm))
859 return Imm;
860 return SignExtend64<32>(Imm);
861 }
862
863 bool isSImm12() const {
865 int64_t Imm;
866 bool IsValid;
867 if (!isImm())
868 return false;
869 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
870 if (!IsConstantImm)
871 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
872 else
873 IsValid = isInt<12>(fixImmediateForRV32(Imm, isRV64Imm()));
874 return IsValid && ((IsConstantImm && VK == RISCVMCExpr::VK_RISCV_None) ||
880 }
881
882 bool isSImm12Lsb0() const { return isBareSimmNLsb0<12>(); }
883
884 bool isSImm12Lsb00000() const {
885 if (!isImm())
886 return false;
888 int64_t Imm;
889 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
890 return IsConstantImm && isShiftedInt<7, 5>(Imm) &&
892 }
893
894 bool isSImm13Lsb0() const { return isBareSimmNLsb0<13>(); }
895
896 bool isSImm10Lsb0000NonZero() const {
897 if (!isImm())
898 return false;
899 int64_t Imm;
901 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
902 return IsConstantImm && (Imm != 0) && isShiftedInt<6, 4>(Imm) &&
904 }
905
906 bool isUImm20LUI() const {
908 int64_t Imm;
909 bool IsValid;
910 if (!isImm())
911 return false;
912 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
913 if (!IsConstantImm) {
914 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
915 return IsValid && (VK == RISCVMCExpr::VK_RISCV_HI ||
917 } else {
918 return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
921 }
922 }
923
924 bool isUImm20AUIPC() const {
926 int64_t Imm;
927 bool IsValid;
928 if (!isImm())
929 return false;
930 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
931 if (!IsConstantImm) {
932 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
933 return IsValid && (VK == RISCVMCExpr::VK_RISCV_PCREL_HI ||
938 }
939
940 return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
946 }
947
948 bool isSImm21Lsb0JAL() const { return isBareSimmNLsb0<21>(); }
949
950 bool isImmZero() const {
951 if (!isImm())
952 return false;
953 int64_t Imm;
955 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
956 return IsConstantImm && (Imm == 0) && VK == RISCVMCExpr::VK_RISCV_None;
957 }
958
959 bool isSImm5Plus1() const {
960 if (!isImm())
961 return false;
963 int64_t Imm;
964 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
965 return IsConstantImm &&
966 isInt<5>(fixImmediateForRV32(Imm, isRV64Imm()) - 1) &&
968 }
969
970 /// getStartLoc - Gets location of the first token of this operand
971 SMLoc getStartLoc() const override { return StartLoc; }
972 /// getEndLoc - Gets location of the last token of this operand
973 SMLoc getEndLoc() const override { return EndLoc; }
974 /// True if this operand is for an RV64 instruction
975 bool isRV64Imm() const {
976 assert(Kind == KindTy::Immediate && "Invalid type access!");
977 return Imm.IsRV64;
978 }
979
980 unsigned getReg() const override {
981 assert(Kind == KindTy::Register && "Invalid type access!");
982 return Reg.RegNum.id();
983 }
984
985 StringRef getSysReg() const {
986 assert(Kind == KindTy::SystemRegister && "Invalid type access!");
987 return StringRef(SysReg.Data, SysReg.Length);
988 }
989
990 const MCExpr *getImm() const {
991 assert(Kind == KindTy::Immediate && "Invalid type access!");
992 return Imm.Val;
993 }
994
995 uint64_t getFPConst() const {
996 assert(Kind == KindTy::FPImmediate && "Invalid type access!");
997 return FPImm.Val;
998 }
999
1000 StringRef getToken() const {
1001 assert(Kind == KindTy::Token && "Invalid type access!");
1002 return Tok;
1003 }
1004
1005 unsigned getVType() const {
1006 assert(Kind == KindTy::VType && "Invalid type access!");
1007 return VType.Val;
1008 }
1009
1010 RISCVFPRndMode::RoundingMode getFRM() const {
1011 assert(Kind == KindTy::FRM && "Invalid type access!");
1012 return FRM.FRM;
1013 }
1014
1015 unsigned getFence() const {
1016 assert(Kind == KindTy::Fence && "Invalid type access!");
1017 return Fence.Val;
1018 }
1019
1020 void print(raw_ostream &OS) const override {
1021 auto RegName = [](MCRegister Reg) {
1022 if (Reg)
1024 else
1025 return "noreg";
1026 };
1027
1028 switch (Kind) {
1029 case KindTy::Immediate:
1030 OS << *getImm();
1031 break;
1032 case KindTy::FPImmediate:
1033 break;
1034 case KindTy::Register:
1035 OS << "<register " << RegName(getReg()) << ">";
1036 break;
1037 case KindTy::Token:
1038 OS << "'" << getToken() << "'";
1039 break;
1040 case KindTy::SystemRegister:
1041 OS << "<sysreg: " << getSysReg() << '>';
1042 break;
1043 case KindTy::VType:
1044 OS << "<vtype: ";
1045 RISCVVType::printVType(getVType(), OS);
1046 OS << '>';
1047 break;
1048 case KindTy::FRM:
1049 OS << "<frm: ";
1050 roundingModeToString(getFRM());
1051 OS << '>';
1052 break;
1053 case KindTy::Fence:
1054 OS << "<fence: ";
1055 OS << getFence();
1056 OS << '>';
1057 break;
1058 case KindTy::Rlist:
1059 OS << "<rlist: ";
1060 RISCVZC::printRlist(Rlist.Val, OS);
1061 OS << '>';
1062 break;
1063 case KindTy::Spimm:
1064 OS << "<Spimm: ";
1065 RISCVZC::printSpimm(Spimm.Val, OS);
1066 OS << '>';
1067 break;
1068 case KindTy::RegReg:
1069 OS << "<RegReg: Reg1 " << RegName(RegReg.Reg1);
1070 OS << " Reg2 " << RegName(RegReg.Reg2);
1071 break;
1072 }
1073 }
1074
1075 static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S) {
1076 auto Op = std::make_unique<RISCVOperand>(KindTy::Token);
1077 Op->Tok = Str;
1078 Op->StartLoc = S;
1079 Op->EndLoc = S;
1080 return Op;
1081 }
1082
1083 static std::unique_ptr<RISCVOperand>
1084 createReg(unsigned RegNo, SMLoc S, SMLoc E, bool IsGPRAsFPR = false) {
1085 auto Op = std::make_unique<RISCVOperand>(KindTy::Register);
1086 Op->Reg.RegNum = RegNo;
1087 Op->Reg.IsGPRAsFPR = IsGPRAsFPR;
1088 Op->StartLoc = S;
1089 Op->EndLoc = E;
1090 return Op;
1091 }
1092
1093 static std::unique_ptr<RISCVOperand> createImm(const MCExpr *Val, SMLoc S,
1094 SMLoc E, bool IsRV64) {
1095 auto Op = std::make_unique<RISCVOperand>(KindTy::Immediate);
1096 Op->Imm.Val = Val;
1097 Op->Imm.IsRV64 = IsRV64;
1098 Op->StartLoc = S;
1099 Op->EndLoc = E;
1100 return Op;
1101 }
1102
1103 static std::unique_ptr<RISCVOperand> createFPImm(uint64_t Val, SMLoc S) {
1104 auto Op = std::make_unique<RISCVOperand>(KindTy::FPImmediate);
1105 Op->FPImm.Val = Val;
1106 Op->StartLoc = S;
1107 Op->EndLoc = S;
1108 return Op;
1109 }
1110
1111 static std::unique_ptr<RISCVOperand> createSysReg(StringRef Str, SMLoc S,
1112 unsigned Encoding) {
1113 auto Op = std::make_unique<RISCVOperand>(KindTy::SystemRegister);
1114 Op->SysReg.Data = Str.data();
1115 Op->SysReg.Length = Str.size();
1116 Op->SysReg.Encoding = Encoding;
1117 Op->StartLoc = S;
1118 Op->EndLoc = S;
1119 return Op;
1120 }
1121
1122 static std::unique_ptr<RISCVOperand>
1123 createFRMArg(RISCVFPRndMode::RoundingMode FRM, SMLoc S) {
1124 auto Op = std::make_unique<RISCVOperand>(KindTy::FRM);
1125 Op->FRM.FRM = FRM;
1126 Op->StartLoc = S;
1127 Op->EndLoc = S;
1128 return Op;
1129 }
1130
1131 static std::unique_ptr<RISCVOperand> createFenceArg(unsigned Val, SMLoc S) {
1132 auto Op = std::make_unique<RISCVOperand>(KindTy::Fence);
1133 Op->Fence.Val = Val;
1134 Op->StartLoc = S;
1135 Op->EndLoc = S;
1136 return Op;
1137 }
1138
1139 static std::unique_ptr<RISCVOperand> createVType(unsigned VTypeI, SMLoc S) {
1140 auto Op = std::make_unique<RISCVOperand>(KindTy::VType);
1141 Op->VType.Val = VTypeI;
1142 Op->StartLoc = S;
1143 Op->EndLoc = S;
1144 return Op;
1145 }
1146
1147 static std::unique_ptr<RISCVOperand> createRlist(unsigned RlistEncode,
1148 SMLoc S) {
1149 auto Op = std::make_unique<RISCVOperand>(KindTy::Rlist);
1150 Op->Rlist.Val = RlistEncode;
1151 Op->StartLoc = S;
1152 return Op;
1153 }
1154
1155 static std::unique_ptr<RISCVOperand> createRegReg(unsigned Reg1No,
1156 unsigned Reg2No, SMLoc S) {
1157 auto Op = std::make_unique<RISCVOperand>(KindTy::RegReg);
1158 Op->RegReg.Reg1 = Reg1No;
1159 Op->RegReg.Reg2 = Reg2No;
1160 Op->StartLoc = S;
1161 Op->EndLoc = S;
1162 return Op;
1163 }
1164
1165 static std::unique_ptr<RISCVOperand> createSpimm(unsigned Spimm, SMLoc S) {
1166 auto Op = std::make_unique<RISCVOperand>(KindTy::Spimm);
1167 Op->Spimm.Val = Spimm;
1168 Op->StartLoc = S;
1169 return Op;
1170 }
1171
1172 static void addExpr(MCInst &Inst, const MCExpr *Expr, bool IsRV64Imm) {
1173 assert(Expr && "Expr shouldn't be null!");
1174 int64_t Imm = 0;
1176 bool IsConstant = evaluateConstantImm(Expr, Imm, VK);
1177
1178 if (IsConstant)
1179 Inst.addOperand(
1180 MCOperand::createImm(fixImmediateForRV32(Imm, IsRV64Imm)));
1181 else
1183 }
1184
1185 // Used by the TableGen Code
1186 void addRegOperands(MCInst &Inst, unsigned N) const {
1187 assert(N == 1 && "Invalid number of operands!");
1189 }
1190
1191 void addImmOperands(MCInst &Inst, unsigned N) const {
1192 assert(N == 1 && "Invalid number of operands!");
1193 addExpr(Inst, getImm(), isRV64Imm());
1194 }
1195
1196 void addFPImmOperands(MCInst &Inst, unsigned N) const {
1197 assert(N == 1 && "Invalid number of operands!");
1198 if (isImm()) {
1199 addExpr(Inst, getImm(), isRV64Imm());
1200 return;
1201 }
1202
1204 APFloat(APFloat::IEEEdouble(), APInt(64, getFPConst())));
1206 }
1207
1208 void addFenceArgOperands(MCInst &Inst, unsigned N) const {
1209 assert(N == 1 && "Invalid number of operands!");
1210 Inst.addOperand(MCOperand::createImm(Fence.Val));
1211 }
1212
1213 void addCSRSystemRegisterOperands(MCInst &Inst, unsigned N) const {
1214 assert(N == 1 && "Invalid number of operands!");
1215 Inst.addOperand(MCOperand::createImm(SysReg.Encoding));
1216 }
1217
1218 // Support non-canonical syntax:
1219 // "vsetivli rd, uimm, 0xabc" or "vsetvli rd, rs1, 0xabc"
1220 // "vsetivli rd, uimm, (0xc << N)" or "vsetvli rd, rs1, (0xc << N)"
1221 void addVTypeIOperands(MCInst &Inst, unsigned N) const {
1222 assert(N == 1 && "Invalid number of operands!");
1223 int64_t Imm = 0;
1224 if (Kind == KindTy::Immediate) {
1226 [[maybe_unused]] bool IsConstantImm =
1227 evaluateConstantImm(getImm(), Imm, VK);
1228 assert(IsConstantImm && "Invalid VTypeI Operand!");
1229 } else {
1230 Imm = getVType();
1231 }
1233 }
1234
1235 void addRlistOperands(MCInst &Inst, unsigned N) const {
1236 assert(N == 1 && "Invalid number of operands!");
1237 Inst.addOperand(MCOperand::createImm(Rlist.Val));
1238 }
1239
1240 void addRegRegOperands(MCInst &Inst, unsigned N) const {
1241 assert(N == 1 && "Invalid number of operands!");
1244 }
1245
1246 void addSpimmOperands(MCInst &Inst, unsigned N) const {
1247 assert(N == 1 && "Invalid number of operands!");
1248 Inst.addOperand(MCOperand::createImm(Spimm.Val));
1249 }
1250
1251 void addFRMArgOperands(MCInst &Inst, unsigned N) const {
1252 assert(N == 1 && "Invalid number of operands!");
1253 Inst.addOperand(MCOperand::createImm(getFRM()));
1254 }
1255};
1256} // end anonymous namespace.
1257
1258#define GET_REGISTER_MATCHER
1259#define GET_SUBTARGET_FEATURE_NAME
1260#define GET_MATCHER_IMPLEMENTATION
1261#define GET_MNEMONIC_SPELL_CHECKER
1262#include "RISCVGenAsmMatcher.inc"
1263
1265 assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
1266 return Reg - RISCV::F0_D + RISCV::F0_H;
1267}
1268
1270 assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
1271 return Reg - RISCV::F0_D + RISCV::F0_F;
1272}
1273
1275 unsigned Kind) {
1276 unsigned RegClassID;
1277 if (Kind == MCK_VRM2)
1278 RegClassID = RISCV::VRM2RegClassID;
1279 else if (Kind == MCK_VRM4)
1280 RegClassID = RISCV::VRM4RegClassID;
1281 else if (Kind == MCK_VRM8)
1282 RegClassID = RISCV::VRM8RegClassID;
1283 else
1284 return 0;
1285 return RI.getMatchingSuperReg(Reg, RISCV::sub_vrm1_0,
1286 &RISCVMCRegisterClasses[RegClassID]);
1287}
1288
1289unsigned RISCVAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
1290 unsigned Kind) {
1291 RISCVOperand &Op = static_cast<RISCVOperand &>(AsmOp);
1292 if (!Op.isReg())
1293 return Match_InvalidOperand;
1294
1295 MCRegister Reg = Op.getReg();
1296 bool IsRegFPR64 =
1297 RISCVMCRegisterClasses[RISCV::FPR64RegClassID].contains(Reg);
1298 bool IsRegFPR64C =
1299 RISCVMCRegisterClasses[RISCV::FPR64CRegClassID].contains(Reg);
1300 bool IsRegVR = RISCVMCRegisterClasses[RISCV::VRRegClassID].contains(Reg);
1301
1302 // As the parser couldn't differentiate an FPR32 from an FPR64, coerce the
1303 // register from FPR64 to FPR32 or FPR64C to FPR32C if necessary.
1304 if ((IsRegFPR64 && Kind == MCK_FPR32) ||
1305 (IsRegFPR64C && Kind == MCK_FPR32C)) {
1306 Op.Reg.RegNum = convertFPR64ToFPR32(Reg);
1307 return Match_Success;
1308 }
1309 // As the parser couldn't differentiate an FPR16 from an FPR64, coerce the
1310 // register from FPR64 to FPR16 if necessary.
1311 if (IsRegFPR64 && Kind == MCK_FPR16) {
1312 Op.Reg.RegNum = convertFPR64ToFPR16(Reg);
1313 return Match_Success;
1314 }
1315 // As the parser couldn't differentiate an VRM2/VRM4/VRM8 from an VR, coerce
1316 // the register from VR to VRM2/VRM4/VRM8 if necessary.
1317 if (IsRegVR && (Kind == MCK_VRM2 || Kind == MCK_VRM4 || Kind == MCK_VRM8)) {
1318 Op.Reg.RegNum = convertVRToVRMx(*getContext().getRegisterInfo(), Reg, Kind);
1319 if (Op.Reg.RegNum == 0)
1320 return Match_InvalidOperand;
1321 return Match_Success;
1322 }
1323 return Match_InvalidOperand;
1324}
1325
1326unsigned RISCVAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
1327 const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
1328
1329 for (unsigned I = 0; I < MCID.NumOperands; ++I) {
1330 if (MCID.operands()[I].RegClass == RISCV::GPRPairRegClassID) {
1331 const auto &Op = Inst.getOperand(I);
1332 assert(Op.isReg());
1333
1334 MCRegister Reg = Op.getReg();
1335 if (RISCVMCRegisterClasses[RISCV::GPRPairRegClassID].contains(Reg))
1336 continue;
1337
1338 // FIXME: We should form a paired register during parsing/matching.
1339 if (((Reg.id() - RISCV::X0) & 1) != 0)
1340 return Match_RequiresEvenGPRs;
1341 }
1342 }
1343
1344 return Match_Success;
1345}
1346
1347bool RISCVAsmParser::generateImmOutOfRangeError(
1348 SMLoc ErrorLoc, int64_t Lower, int64_t Upper,
1349 const Twine &Msg = "immediate must be an integer in the range") {
1350 return Error(ErrorLoc, Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
1351}
1352
1353bool RISCVAsmParser::generateImmOutOfRangeError(
1354 OperandVector &Operands, uint64_t ErrorInfo, int64_t Lower, int64_t Upper,
1355 const Twine &Msg = "immediate must be an integer in the range") {
1356 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1357 return generateImmOutOfRangeError(ErrorLoc, Lower, Upper, Msg);
1358}
1359
1360bool RISCVAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1362 MCStreamer &Out,
1364 bool MatchingInlineAsm) {
1365 MCInst Inst;
1366 FeatureBitset MissingFeatures;
1367
1368 auto Result = MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,
1369 MatchingInlineAsm);
1370 switch (Result) {
1371 default:
1372 break;
1373 case Match_Success:
1374 if (validateInstruction(Inst, Operands))
1375 return true;
1376 return processInstruction(Inst, IDLoc, Operands, Out);
1377 case Match_MissingFeature: {
1378 assert(MissingFeatures.any() && "Unknown missing features!");
1379 bool FirstFeature = true;
1380 std::string Msg = "instruction requires the following:";
1381 for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i) {
1382 if (MissingFeatures[i]) {
1383 Msg += FirstFeature ? " " : ", ";
1385 FirstFeature = false;
1386 }
1387 }
1388 return Error(IDLoc, Msg);
1389 }
1390 case Match_MnemonicFail: {
1391 FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
1392 std::string Suggestion = RISCVMnemonicSpellCheck(
1393 ((RISCVOperand &)*Operands[0]).getToken(), FBS, 0);
1394 return Error(IDLoc, "unrecognized instruction mnemonic" + Suggestion);
1395 }
1396 case Match_InvalidOperand: {
1397 SMLoc ErrorLoc = IDLoc;
1398 if (ErrorInfo != ~0ULL) {
1399 if (ErrorInfo >= Operands.size())
1400 return Error(ErrorLoc, "too few operands for instruction");
1401
1402 ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1403 if (ErrorLoc == SMLoc())
1404 ErrorLoc = IDLoc;
1405 }
1406 return Error(ErrorLoc, "invalid operand for instruction");
1407 }
1408 }
1409
1410 // Handle the case when the error message is of specific type
1411 // other than the generic Match_InvalidOperand, and the
1412 // corresponding operand is missing.
1413 if (Result > FIRST_TARGET_MATCH_RESULT_TY) {
1414 SMLoc ErrorLoc = IDLoc;
1415 if (ErrorInfo != ~0ULL && ErrorInfo >= Operands.size())
1416 return Error(ErrorLoc, "too few operands for instruction");
1417 }
1418
1419 switch (Result) {
1420 default:
1421 break;
1422 case Match_RequiresEvenGPRs:
1423 return Error(IDLoc,
1424 "double precision floating point operands must use even "
1425 "numbered X register");
1426 case Match_InvalidImmXLenLI:
1427 if (isRV64()) {
1428 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1429 return Error(ErrorLoc, "operand must be a constant 64-bit integer");
1430 }
1431 return generateImmOutOfRangeError(Operands, ErrorInfo,
1432 std::numeric_limits<int32_t>::min(),
1433 std::numeric_limits<uint32_t>::max());
1434 case Match_InvalidImmXLenLI_Restricted:
1435 if (isRV64()) {
1436 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1437 return Error(ErrorLoc, "operand either must be a constant 64-bit integer "
1438 "or a bare symbol name");
1439 }
1440 return generateImmOutOfRangeError(
1441 Operands, ErrorInfo, std::numeric_limits<int32_t>::min(),
1442 std::numeric_limits<uint32_t>::max(),
1443 "operand either must be a bare symbol name or an immediate integer in "
1444 "the range");
1445 case Match_InvalidImmZero: {
1446 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1447 return Error(ErrorLoc, "immediate must be zero");
1448 }
1449 case Match_InvalidUImmLog2XLen:
1450 if (isRV64())
1451 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
1452 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1453 case Match_InvalidUImmLog2XLenNonZero:
1454 if (isRV64())
1455 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 6) - 1);
1456 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5) - 1);
1457 case Match_InvalidUImmLog2XLenHalf:
1458 if (isRV64())
1459 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1460 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 4) - 1);
1461 case Match_InvalidUImm1:
1462 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 1) - 1);
1463 case Match_InvalidUImm2:
1464 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 2) - 1);
1465 case Match_InvalidUImm2Lsb0:
1466 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, 2,
1467 "immediate must be one of");
1468 case Match_InvalidUImm3:
1469 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 3) - 1);
1470 case Match_InvalidUImm4:
1471 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 4) - 1);
1472 case Match_InvalidUImm5:
1473 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1474 case Match_InvalidUImm6:
1475 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
1476 case Match_InvalidUImm7:
1477 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 7) - 1);
1478 case Match_InvalidUImm8:
1479 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 8) - 1);
1480 case Match_InvalidUImm8GE32:
1481 return generateImmOutOfRangeError(Operands, ErrorInfo, 32, (1 << 8) - 1);
1482 case Match_InvalidSImm5:
1483 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 4),
1484 (1 << 4) - 1);
1485 case Match_InvalidSImm6:
1486 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
1487 (1 << 5) - 1);
1488 case Match_InvalidSImm6NonZero:
1489 return generateImmOutOfRangeError(
1490 Operands, ErrorInfo, -(1 << 5), (1 << 5) - 1,
1491 "immediate must be non-zero in the range");
1492 case Match_InvalidCLUIImm:
1493 return generateImmOutOfRangeError(
1494 Operands, ErrorInfo, 1, (1 << 5) - 1,
1495 "immediate must be in [0xfffe0, 0xfffff] or");
1496 case Match_InvalidUImm7Lsb00:
1497 return generateImmOutOfRangeError(
1498 Operands, ErrorInfo, 0, (1 << 7) - 4,
1499 "immediate must be a multiple of 4 bytes in the range");
1500 case Match_InvalidUImm8Lsb00:
1501 return generateImmOutOfRangeError(
1502 Operands, ErrorInfo, 0, (1 << 8) - 4,
1503 "immediate must be a multiple of 4 bytes in the range");
1504 case Match_InvalidUImm8Lsb000:
1505 return generateImmOutOfRangeError(
1506 Operands, ErrorInfo, 0, (1 << 8) - 8,
1507 "immediate must be a multiple of 8 bytes in the range");
1508 case Match_InvalidSImm9Lsb0:
1509 return generateImmOutOfRangeError(
1510 Operands, ErrorInfo, -(1 << 8), (1 << 8) - 2,
1511 "immediate must be a multiple of 2 bytes in the range");
1512 case Match_InvalidUImm9Lsb000:
1513 return generateImmOutOfRangeError(
1514 Operands, ErrorInfo, 0, (1 << 9) - 8,
1515 "immediate must be a multiple of 8 bytes in the range");
1516 case Match_InvalidUImm10Lsb00NonZero:
1517 return generateImmOutOfRangeError(
1518 Operands, ErrorInfo, 4, (1 << 10) - 4,
1519 "immediate must be a multiple of 4 bytes in the range");
1520 case Match_InvalidSImm10Lsb0000NonZero:
1521 return generateImmOutOfRangeError(
1522 Operands, ErrorInfo, -(1 << 9), (1 << 9) - 16,
1523 "immediate must be a multiple of 16 bytes and non-zero in the range");
1524 case Match_InvalidSImm12:
1525 return generateImmOutOfRangeError(
1526 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 1,
1527 "operand must be a symbol with %lo/%pcrel_lo/%tprel_lo modifier or an "
1528 "integer in the range");
1529 case Match_InvalidSImm12Lsb0:
1530 return generateImmOutOfRangeError(
1531 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 2,
1532 "immediate must be a multiple of 2 bytes in the range");
1533 case Match_InvalidSImm12Lsb00000:
1534 return generateImmOutOfRangeError(
1535 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 32,
1536 "immediate must be a multiple of 32 bytes in the range");
1537 case Match_InvalidSImm13Lsb0:
1538 return generateImmOutOfRangeError(
1539 Operands, ErrorInfo, -(1 << 12), (1 << 12) - 2,
1540 "immediate must be a multiple of 2 bytes in the range");
1541 case Match_InvalidUImm20LUI:
1542 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1,
1543 "operand must be a symbol with "
1544 "%hi/%tprel_hi modifier or an integer in "
1545 "the range");
1546 case Match_InvalidUImm20:
1547 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1);
1548 case Match_InvalidUImm20AUIPC:
1549 return generateImmOutOfRangeError(
1550 Operands, ErrorInfo, 0, (1 << 20) - 1,
1551 "operand must be a symbol with a "
1552 "%pcrel_hi/%got_pcrel_hi/%tls_ie_pcrel_hi/%tls_gd_pcrel_hi modifier or "
1553 "an integer in the range");
1554 case Match_InvalidSImm21Lsb0JAL:
1555 return generateImmOutOfRangeError(
1556 Operands, ErrorInfo, -(1 << 20), (1 << 20) - 2,
1557 "immediate must be a multiple of 2 bytes in the range");
1558 case Match_InvalidCSRSystemRegister: {
1559 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 12) - 1,
1560 "operand must be a valid system register "
1561 "name or an integer in the range");
1562 }
1563 case Match_InvalidLoadFPImm: {
1564 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1565 return Error(ErrorLoc, "operand must be a valid floating-point constant");
1566 }
1567 case Match_InvalidBareSymbol: {
1568 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1569 return Error(ErrorLoc, "operand must be a bare symbol name");
1570 }
1571 case Match_InvalidPseudoJumpSymbol: {
1572 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1573 return Error(ErrorLoc, "operand must be a valid jump target");
1574 }
1575 case Match_InvalidCallSymbol: {
1576 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1577 return Error(ErrorLoc, "operand must be a bare symbol name");
1578 }
1579 case Match_InvalidTPRelAddSymbol: {
1580 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1581 return Error(ErrorLoc, "operand must be a symbol with %tprel_add modifier");
1582 }
1583 case Match_InvalidTLSDESCCallSymbol: {
1584 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1585 return Error(ErrorLoc,
1586 "operand must be a symbol with %tlsdesc_call modifier");
1587 }
1588 case Match_InvalidRTZArg: {
1589 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1590 return Error(ErrorLoc, "operand must be 'rtz' floating-point rounding mode");
1591 }
1592 case Match_InvalidVTypeI: {
1593 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1594 return generateVTypeError(ErrorLoc);
1595 }
1596 case Match_InvalidVMaskRegister: {
1597 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1598 return Error(ErrorLoc, "operand must be v0.t");
1599 }
1600 case Match_InvalidSImm5Plus1: {
1601 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 4) + 1,
1602 (1 << 4),
1603 "immediate must be in the range");
1604 }
1605 case Match_InvalidRlist: {
1606 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1607 return Error(
1608 ErrorLoc,
1609 "operand must be {ra [, s0[-sN]]} or {x1 [, x8[-x9][, x18[-xN]]]}");
1610 }
1611 case Match_InvalidSpimm: {
1612 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1613 return Error(
1614 ErrorLoc,
1615 "stack adjustment is invalid for this instruction and register list; "
1616 "refer to Zc spec for a detailed range of stack adjustment");
1617 }
1618 case Match_InvalidRnumArg: {
1619 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, 10);
1620 }
1621 case Match_InvalidRegReg: {
1622 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1623 return Error(ErrorLoc, "operands must be register and register");
1624 }
1625 }
1626
1627 llvm_unreachable("Unknown match type detected!");
1628}
1629
1630// Attempts to match Name as a register (either using the default name or
1631// alternative ABI names), setting RegNo to the matching register. Upon
1632// failure, returns a non-valid MCRegister. If IsRVE, then registers x16-x31
1633// will be rejected.
1634MCRegister RISCVAsmParser::matchRegisterNameHelper(StringRef Name) const {
1636 // The 16-/32- and 64-bit FPRs have the same asm name. Check that the initial
1637 // match always matches the 64-bit variant, and not the 16/32-bit one.
1638 assert(!(Reg >= RISCV::F0_H && Reg <= RISCV::F31_H));
1639 assert(!(Reg >= RISCV::F0_F && Reg <= RISCV::F31_F));
1640 // The default FPR register class is based on the tablegen enum ordering.
1641 static_assert(RISCV::F0_D < RISCV::F0_H, "FPR matching must be updated");
1642 static_assert(RISCV::F0_D < RISCV::F0_F, "FPR matching must be updated");
1643 if (!Reg)
1645 if (isRVE() && Reg >= RISCV::X16 && Reg <= RISCV::X31)
1646 Reg = RISCV::NoRegister;
1647 return Reg;
1648}
1649
1650bool RISCVAsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
1651 SMLoc &EndLoc) {
1652 if (!tryParseRegister(Reg, StartLoc, EndLoc).isSuccess())
1653 return Error(StartLoc, "invalid register name");
1654 return false;
1655}
1656
1657ParseStatus RISCVAsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
1658 SMLoc &EndLoc) {
1659 const AsmToken &Tok = getParser().getTok();
1660 StartLoc = Tok.getLoc();
1661 EndLoc = Tok.getEndLoc();
1662 StringRef Name = getLexer().getTok().getIdentifier();
1663
1665 if (!Reg)
1666 return ParseStatus::NoMatch;
1667
1668 getParser().Lex(); // Eat identifier token.
1669 return ParseStatus::Success;
1670}
1671
1672ParseStatus RISCVAsmParser::parseRegister(OperandVector &Operands,
1673 bool AllowParens) {
1674 SMLoc FirstS = getLoc();
1675 bool HadParens = false;
1676 AsmToken LParen;
1677
1678 // If this is an LParen and a parenthesised register name is allowed, parse it
1679 // atomically.
1680 if (AllowParens && getLexer().is(AsmToken::LParen)) {
1681 AsmToken Buf[2];
1682 size_t ReadCount = getLexer().peekTokens(Buf);
1683 if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
1684 HadParens = true;
1685 LParen = getParser().getTok();
1686 getParser().Lex(); // Eat '('
1687 }
1688 }
1689
1690 switch (getLexer().getKind()) {
1691 default:
1692 if (HadParens)
1693 getLexer().UnLex(LParen);
1694 return ParseStatus::NoMatch;
1696 StringRef Name = getLexer().getTok().getIdentifier();
1698
1699 if (!RegNo) {
1700 if (HadParens)
1701 getLexer().UnLex(LParen);
1702 return ParseStatus::NoMatch;
1703 }
1704 if (HadParens)
1705 Operands.push_back(RISCVOperand::createToken("(", FirstS));
1706 SMLoc S = getLoc();
1708 getLexer().Lex();
1709 Operands.push_back(RISCVOperand::createReg(RegNo, S, E));
1710 }
1711
1712 if (HadParens) {
1713 getParser().Lex(); // Eat ')'
1714 Operands.push_back(RISCVOperand::createToken(")", getLoc()));
1715 }
1716
1717 return ParseStatus::Success;
1718}
1719
1720ParseStatus RISCVAsmParser::parseInsnDirectiveOpcode(OperandVector &Operands) {
1721 SMLoc S = getLoc();
1722 SMLoc E;
1723 const MCExpr *Res;
1724
1725 switch (getLexer().getKind()) {
1726 default:
1727 return ParseStatus::NoMatch;
1728 case AsmToken::LParen:
1729 case AsmToken::Minus:
1730 case AsmToken::Plus:
1731 case AsmToken::Exclaim:
1732 case AsmToken::Tilde:
1733 case AsmToken::Integer:
1734 case AsmToken::String: {
1735 if (getParser().parseExpression(Res, E))
1736 return ParseStatus::Failure;
1737
1738 auto *CE = dyn_cast<MCConstantExpr>(Res);
1739 if (CE) {
1740 int64_t Imm = CE->getValue();
1741 if (isUInt<7>(Imm)) {
1742 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1743 return ParseStatus::Success;
1744 }
1745 }
1746
1747 break;
1748 }
1749 case AsmToken::Identifier: {
1751 if (getParser().parseIdentifier(Identifier))
1752 return ParseStatus::Failure;
1753
1754 auto Opcode = RISCVInsnOpcode::lookupRISCVOpcodeByName(Identifier);
1755 if (Opcode) {
1756 assert(isUInt<7>(Opcode->Value) && (Opcode->Value & 0x3) == 3 &&
1757 "Unexpected opcode");
1758 Res = MCConstantExpr::create(Opcode->Value, getContext());
1760 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1761 return ParseStatus::Success;
1762 }
1763
1764 break;
1765 }
1766 case AsmToken::Percent:
1767 break;
1768 }
1769
1770 return generateImmOutOfRangeError(
1771 S, 0, 127,
1772 "opcode must be a valid opcode name or an immediate in the range");
1773}
1774
1775ParseStatus RISCVAsmParser::parseInsnCDirectiveOpcode(OperandVector &Operands) {
1776 SMLoc S = getLoc();
1777 SMLoc E;
1778 const MCExpr *Res;
1779
1780 switch (getLexer().getKind()) {
1781 default:
1782 return ParseStatus::NoMatch;
1783 case AsmToken::LParen:
1784 case AsmToken::Minus:
1785 case AsmToken::Plus:
1786 case AsmToken::Exclaim:
1787 case AsmToken::Tilde:
1788 case AsmToken::Integer:
1789 case AsmToken::String: {
1790 if (getParser().parseExpression(Res, E))
1791 return ParseStatus::Failure;
1792
1793 auto *CE = dyn_cast<MCConstantExpr>(Res);
1794 if (CE) {
1795 int64_t Imm = CE->getValue();
1796 if (Imm >= 0 && Imm <= 2) {
1797 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1798 return ParseStatus::Success;
1799 }
1800 }
1801
1802 break;
1803 }
1804 case AsmToken::Identifier: {
1806 if (getParser().parseIdentifier(Identifier))
1807 return ParseStatus::Failure;
1808
1809 unsigned Opcode;
1810 if (Identifier == "C0")
1811 Opcode = 0;
1812 else if (Identifier == "C1")
1813 Opcode = 1;
1814 else if (Identifier == "C2")
1815 Opcode = 2;
1816 else
1817 break;
1818
1819 Res = MCConstantExpr::create(Opcode, getContext());
1821 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1822 return ParseStatus::Success;
1823 }
1824 case AsmToken::Percent: {
1825 // Discard operand with modifier.
1826 break;
1827 }
1828 }
1829
1830 return generateImmOutOfRangeError(
1831 S, 0, 2,
1832 "opcode must be a valid opcode name or an immediate in the range");
1833}
1834
1835ParseStatus RISCVAsmParser::parseCSRSystemRegister(OperandVector &Operands) {
1836 SMLoc S = getLoc();
1837 const MCExpr *Res;
1838
1839 switch (getLexer().getKind()) {
1840 default:
1841 return ParseStatus::NoMatch;
1842 case AsmToken::LParen:
1843 case AsmToken::Minus:
1844 case AsmToken::Plus:
1845 case AsmToken::Exclaim:
1846 case AsmToken::Tilde:
1847 case AsmToken::Integer:
1848 case AsmToken::String: {
1849 if (getParser().parseExpression(Res))
1850 return ParseStatus::Failure;
1851
1852 auto *CE = dyn_cast<MCConstantExpr>(Res);
1853 if (CE) {
1854 int64_t Imm = CE->getValue();
1855 if (isUInt<12>(Imm)) {
1856 auto SysReg = RISCVSysReg::lookupSysRegByEncoding(Imm);
1857 // Accept an immediate representing a named or un-named Sys Reg
1858 // if the range is valid, regardless of the required features.
1859 Operands.push_back(
1860 RISCVOperand::createSysReg(SysReg ? SysReg->Name : "", S, Imm));
1861 return ParseStatus::Success;
1862 }
1863 }
1864
1865 return generateImmOutOfRangeError(S, 0, (1 << 12) - 1);
1866 }
1867 case AsmToken::Identifier: {
1869 if (getParser().parseIdentifier(Identifier))
1870 return ParseStatus::Failure;
1871
1872 auto SysReg = RISCVSysReg::lookupSysRegByName(Identifier);
1873 if (!SysReg)
1874 SysReg = RISCVSysReg::lookupSysRegByAltName(Identifier);
1875 if (!SysReg)
1876 if ((SysReg = RISCVSysReg::lookupSysRegByDeprecatedName(Identifier)))
1877 Warning(S, "'" + Identifier + "' is a deprecated alias for '" +
1878 SysReg->Name + "'");
1879
1880 // Accept a named Sys Reg if the required features are present.
1881 if (SysReg) {
1882 if (!SysReg->haveRequiredFeatures(getSTI().getFeatureBits()))
1883 return Error(S, "system register use requires an option to be enabled");
1884 Operands.push_back(
1885 RISCVOperand::createSysReg(Identifier, S, SysReg->Encoding));
1886 return ParseStatus::Success;
1887 }
1888
1889 return generateImmOutOfRangeError(S, 0, (1 << 12) - 1,
1890 "operand must be a valid system register "
1891 "name or an integer in the range");
1892 }
1893 case AsmToken::Percent: {
1894 // Discard operand with modifier.
1895 return generateImmOutOfRangeError(S, 0, (1 << 12) - 1);
1896 }
1897 }
1898
1899 return ParseStatus::NoMatch;
1900}
1901
1902ParseStatus RISCVAsmParser::parseFPImm(OperandVector &Operands) {
1903 SMLoc S = getLoc();
1904
1905 // Parse special floats (inf/nan/min) representation.
1906 if (getTok().is(AsmToken::Identifier)) {
1907 StringRef Identifier = getTok().getIdentifier();
1908 if (Identifier.compare_insensitive("inf") == 0) {
1909 Operands.push_back(
1910 RISCVOperand::createImm(MCConstantExpr::create(30, getContext()), S,
1911 getTok().getEndLoc(), isRV64()));
1912 } else if (Identifier.compare_insensitive("nan") == 0) {
1913 Operands.push_back(
1914 RISCVOperand::createImm(MCConstantExpr::create(31, getContext()), S,
1915 getTok().getEndLoc(), isRV64()));
1916 } else if (Identifier.compare_insensitive("min") == 0) {
1917 Operands.push_back(
1918 RISCVOperand::createImm(MCConstantExpr::create(1, getContext()), S,
1919 getTok().getEndLoc(), isRV64()));
1920 } else {
1921 return TokError("invalid floating point literal");
1922 }
1923
1924 Lex(); // Eat the token.
1925
1926 return ParseStatus::Success;
1927 }
1928
1929 // Handle negation, as that still comes through as a separate token.
1930 bool IsNegative = parseOptionalToken(AsmToken::Minus);
1931
1932 const AsmToken &Tok = getTok();
1933 if (!Tok.is(AsmToken::Real))
1934 return TokError("invalid floating point immediate");
1935
1936 // Parse FP representation.
1937 APFloat RealVal(APFloat::IEEEdouble());
1938 auto StatusOrErr =
1939 RealVal.convertFromString(Tok.getString(), APFloat::rmTowardZero);
1940 if (errorToBool(StatusOrErr.takeError()))
1941 return TokError("invalid floating point representation");
1942
1943 if (IsNegative)
1944 RealVal.changeSign();
1945
1946 Operands.push_back(RISCVOperand::createFPImm(
1947 RealVal.bitcastToAPInt().getZExtValue(), S));
1948
1949 Lex(); // Eat the token.
1950
1951 return ParseStatus::Success;
1952}
1953
1954ParseStatus RISCVAsmParser::parseImmediate(OperandVector &Operands) {
1955 SMLoc S = getLoc();
1956 SMLoc E;
1957 const MCExpr *Res;
1958
1959 switch (getLexer().getKind()) {
1960 default:
1961 return ParseStatus::NoMatch;
1962 case AsmToken::LParen:
1963 case AsmToken::Dot:
1964 case AsmToken::Minus:
1965 case AsmToken::Plus:
1966 case AsmToken::Exclaim:
1967 case AsmToken::Tilde:
1968 case AsmToken::Integer:
1969 case AsmToken::String:
1971 if (getParser().parseExpression(Res, E))
1972 return ParseStatus::Failure;
1973 break;
1974 case AsmToken::Percent:
1975 return parseOperandWithModifier(Operands);
1976 }
1977
1978 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1979 return ParseStatus::Success;
1980}
1981
1982ParseStatus RISCVAsmParser::parseOperandWithModifier(OperandVector &Operands) {
1983 SMLoc S = getLoc();
1984 SMLoc E;
1985
1986 if (parseToken(AsmToken::Percent, "expected '%' for operand modifier"))
1987 return ParseStatus::Failure;
1988
1989 if (getLexer().getKind() != AsmToken::Identifier)
1990 return Error(getLoc(), "expected valid identifier for operand modifier");
1991 StringRef Identifier = getParser().getTok().getIdentifier();
1994 return Error(getLoc(), "unrecognized operand modifier");
1995
1996 getParser().Lex(); // Eat the identifier
1997 if (parseToken(AsmToken::LParen, "expected '('"))
1998 return ParseStatus::Failure;
1999
2000 const MCExpr *SubExpr;
2001 if (getParser().parseParenExpression(SubExpr, E))
2002 return ParseStatus::Failure;
2003
2004 const MCExpr *ModExpr = RISCVMCExpr::create(SubExpr, VK, getContext());
2005 Operands.push_back(RISCVOperand::createImm(ModExpr, S, E, isRV64()));
2006 return ParseStatus::Success;
2007}
2008
2009ParseStatus RISCVAsmParser::parseBareSymbol(OperandVector &Operands) {
2010 SMLoc S = getLoc();
2011 const MCExpr *Res;
2012
2013 if (getLexer().getKind() != AsmToken::Identifier)
2014 return ParseStatus::NoMatch;
2015
2017 AsmToken Tok = getLexer().getTok();
2018
2019 if (getParser().parseIdentifier(Identifier))
2020 return ParseStatus::Failure;
2021
2023
2024 if (Identifier.consume_back("@plt"))
2025 return Error(getLoc(), "'@plt' operand not valid for instruction");
2026
2027 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
2028
2029 if (Sym->isVariable()) {
2030 const MCExpr *V = Sym->getVariableValue(/*SetUsed=*/false);
2031 if (!isa<MCSymbolRefExpr>(V)) {
2032 getLexer().UnLex(Tok); // Put back if it's not a bare symbol.
2033 return ParseStatus::NoMatch;
2034 }
2035 Res = V;
2036 } else
2038
2039 MCBinaryExpr::Opcode Opcode;
2040 switch (getLexer().getKind()) {
2041 default:
2042 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
2043 return ParseStatus::Success;
2044 case AsmToken::Plus:
2045 Opcode = MCBinaryExpr::Add;
2046 getLexer().Lex();
2047 break;
2048 case AsmToken::Minus:
2049 Opcode = MCBinaryExpr::Sub;
2050 getLexer().Lex();
2051 break;
2052 }
2053
2054 const MCExpr *Expr;
2055 if (getParser().parseExpression(Expr, E))
2056 return ParseStatus::Failure;
2057 Res = MCBinaryExpr::create(Opcode, Res, Expr, getContext());
2058 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
2059 return ParseStatus::Success;
2060}
2061
2062ParseStatus RISCVAsmParser::parseCallSymbol(OperandVector &Operands) {
2063 SMLoc S = getLoc();
2064 const MCExpr *Res;
2065
2066 if (getLexer().getKind() != AsmToken::Identifier)
2067 return ParseStatus::NoMatch;
2068
2069 // Avoid parsing the register in `call rd, foo` as a call symbol.
2070 if (getLexer().peekTok().getKind() != AsmToken::EndOfStatement)
2071 return ParseStatus::NoMatch;
2072
2074 if (getParser().parseIdentifier(Identifier))
2075 return ParseStatus::Failure;
2076
2078
2080 (void)Identifier.consume_back("@plt");
2081
2082 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
2084 Res = RISCVMCExpr::create(Res, Kind, getContext());
2085 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
2086 return ParseStatus::Success;
2087}
2088
2089ParseStatus RISCVAsmParser::parsePseudoJumpSymbol(OperandVector &Operands) {
2090 SMLoc S = getLoc();
2091 SMLoc E;
2092 const MCExpr *Res;
2093
2094 if (getParser().parseExpression(Res, E))
2095 return ParseStatus::Failure;
2096
2097 if (Res->getKind() != MCExpr::ExprKind::SymbolRef ||
2098 cast<MCSymbolRefExpr>(Res)->getKind() ==
2099 MCSymbolRefExpr::VariantKind::VK_PLT)
2100 return Error(S, "operand must be a valid jump target");
2101
2102 Res = RISCVMCExpr::create(Res, RISCVMCExpr::VK_RISCV_CALL, getContext());
2103 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
2104 return ParseStatus::Success;
2105}
2106
2107ParseStatus RISCVAsmParser::parseJALOffset(OperandVector &Operands) {
2108 // Parsing jal operands is fiddly due to the `jal foo` and `jal ra, foo`
2109 // both being acceptable forms. When parsing `jal ra, foo` this function
2110 // will be called for the `ra` register operand in an attempt to match the
2111 // single-operand alias. parseJALOffset must fail for this case. It would
2112 // seem logical to try parse the operand using parseImmediate and return
2113 // NoMatch if the next token is a comma (meaning we must be parsing a jal in
2114 // the second form rather than the first). We can't do this as there's no
2115 // way of rewinding the lexer state. Instead, return NoMatch if this operand
2116 // is an identifier and is followed by a comma.
2117 if (getLexer().is(AsmToken::Identifier) &&
2118 getLexer().peekTok().is(AsmToken::Comma))
2119 return ParseStatus::NoMatch;
2120
2121 return parseImmediate(Operands);
2122}
2123
2124bool RISCVAsmParser::parseVTypeToken(StringRef Identifier, VTypeState &State,
2125 unsigned &Sew, unsigned &Lmul,
2126 bool &Fractional, bool &TailAgnostic,
2127 bool &MaskAgnostic) {
2128 switch (State) {
2129 case VTypeState_SEW:
2130 if (!Identifier.consume_front("e"))
2131 break;
2132 if (Identifier.getAsInteger(10, Sew))
2133 break;
2134 if (!RISCVVType::isValidSEW(Sew))
2135 break;
2136 State = VTypeState_LMUL;
2137 return false;
2138 case VTypeState_LMUL: {
2139 if (!Identifier.consume_front("m"))
2140 break;
2141 Fractional = Identifier.consume_front("f");
2142 if (Identifier.getAsInteger(10, Lmul))
2143 break;
2144 if (!RISCVVType::isValidLMUL(Lmul, Fractional))
2145 break;
2146 State = VTypeState_TailPolicy;
2147 return false;
2148 }
2149 case VTypeState_TailPolicy:
2150 if (Identifier == "ta")
2151 TailAgnostic = true;
2152 else if (Identifier == "tu")
2153 TailAgnostic = false;
2154 else
2155 break;
2156 State = VTypeState_MaskPolicy;
2157 return false;
2158 case VTypeState_MaskPolicy:
2159 if (Identifier == "ma")
2160 MaskAgnostic = true;
2161 else if (Identifier == "mu")
2162 MaskAgnostic = false;
2163 else
2164 break;
2165 State = VTypeState_Done;
2166 return false;
2167 case VTypeState_Done:
2168 // Extra token?
2169 break;
2170 }
2171
2172 return true;
2173}
2174
2175ParseStatus RISCVAsmParser::parseVTypeI(OperandVector &Operands) {
2176 SMLoc S = getLoc();
2177
2178 unsigned Sew = 0;
2179 unsigned Lmul = 0;
2180 bool Fractional = false;
2181 bool TailAgnostic = false;
2182 bool MaskAgnostic = false;
2183
2184 VTypeState State = VTypeState_SEW;
2185
2186 if (getLexer().isNot(AsmToken::Identifier))
2187 return ParseStatus::NoMatch;
2188
2189 StringRef Identifier = getTok().getIdentifier();
2190
2191 if (parseVTypeToken(Identifier, State, Sew, Lmul, Fractional, TailAgnostic,
2192 MaskAgnostic))
2193 return ParseStatus::NoMatch;
2194
2195 getLexer().Lex();
2196
2197 while (parseOptionalToken(AsmToken::Comma)) {
2198 if (getLexer().isNot(AsmToken::Identifier))
2199 break;
2200
2201 Identifier = getTok().getIdentifier();
2202
2203 if (parseVTypeToken(Identifier, State, Sew, Lmul, Fractional, TailAgnostic,
2204 MaskAgnostic))
2205 break;
2206
2207 getLexer().Lex();
2208 }
2209
2210 if (getLexer().is(AsmToken::EndOfStatement) && State == VTypeState_Done) {
2211 RISCVII::VLMUL VLMUL = RISCVVType::encodeLMUL(Lmul, Fractional);
2212
2213 unsigned VTypeI =
2214 RISCVVType::encodeVTYPE(VLMUL, Sew, TailAgnostic, MaskAgnostic);
2215 Operands.push_back(RISCVOperand::createVType(VTypeI, S));
2216 return ParseStatus::Success;
2217 }
2218
2219 return generateVTypeError(S);
2220}
2221
2222bool RISCVAsmParser::generateVTypeError(SMLoc ErrorLoc) {
2223 return Error(
2224 ErrorLoc,
2225 "operand must be "
2226 "e[8|16|32|64|128|256|512|1024],m[1|2|4|8|f2|f4|f8],[ta|tu],[ma|mu]");
2227}
2228
2229ParseStatus RISCVAsmParser::parseMaskReg(OperandVector &Operands) {
2230 if (getLexer().isNot(AsmToken::Identifier))
2231 return ParseStatus::NoMatch;
2232
2233 StringRef Name = getLexer().getTok().getIdentifier();
2234 if (!Name.consume_back(".t"))
2235 return Error(getLoc(), "expected '.t' suffix");
2237
2238 if (!RegNo)
2239 return ParseStatus::NoMatch;
2240 if (RegNo != RISCV::V0)
2241 return ParseStatus::NoMatch;
2242 SMLoc S = getLoc();
2244 getLexer().Lex();
2245 Operands.push_back(RISCVOperand::createReg(RegNo, S, E));
2246 return ParseStatus::Success;
2247}
2248
2249ParseStatus RISCVAsmParser::parseGPRAsFPR(OperandVector &Operands) {
2250 if (getLexer().isNot(AsmToken::Identifier))
2251 return ParseStatus::NoMatch;
2252
2253 StringRef Name = getLexer().getTok().getIdentifier();
2255
2256 if (!RegNo)
2257 return ParseStatus::NoMatch;
2258 SMLoc S = getLoc();
2260 getLexer().Lex();
2261 Operands.push_back(RISCVOperand::createReg(
2262 RegNo, S, E, !getSTI().hasFeature(RISCV::FeatureStdExtF)));
2263 return ParseStatus::Success;
2264}
2265
2266template <bool IsRV64>
2267ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands) {
2268 return parseGPRPair(Operands, IsRV64);
2269}
2270
2271ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands,
2272 bool IsRV64Inst) {
2273 // If this is not an RV64 GPRPair instruction, don't parse as a GPRPair on
2274 // RV64 as it will prevent matching the RV64 version of the same instruction
2275 // that doesn't use a GPRPair.
2276 // If this is an RV64 GPRPair instruction, there is no RV32 version so we can
2277 // still parse as a pair.
2278 if (!IsRV64Inst && isRV64())
2279 return ParseStatus::NoMatch;
2280
2281 if (getLexer().isNot(AsmToken::Identifier))
2282 return ParseStatus::NoMatch;
2283
2284 StringRef Name = getLexer().getTok().getIdentifier();
2286
2287 if (!RegNo)
2288 return ParseStatus::NoMatch;
2289
2290 if (!RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(RegNo))
2291 return ParseStatus::NoMatch;
2292
2293 if ((RegNo - RISCV::X0) & 1)
2294 return TokError("register must be even");
2295
2296 SMLoc S = getLoc();
2298 getLexer().Lex();
2299
2300 const MCRegisterInfo *RI = getContext().getRegisterInfo();
2301 unsigned Pair = RI->getMatchingSuperReg(
2302 RegNo, RISCV::sub_gpr_even,
2303 &RISCVMCRegisterClasses[RISCV::GPRPairRegClassID]);
2304 Operands.push_back(RISCVOperand::createReg(Pair, S, E));
2305 return ParseStatus::Success;
2306}
2307
2308ParseStatus RISCVAsmParser::parseFRMArg(OperandVector &Operands) {
2309 if (getLexer().isNot(AsmToken::Identifier))
2310 return TokError(
2311 "operand must be a valid floating point rounding mode mnemonic");
2312
2313 StringRef Str = getLexer().getTok().getIdentifier();
2315
2316 if (FRM == RISCVFPRndMode::Invalid)
2317 return TokError(
2318 "operand must be a valid floating point rounding mode mnemonic");
2319
2320 Operands.push_back(RISCVOperand::createFRMArg(FRM, getLoc()));
2321 Lex(); // Eat identifier token.
2322 return ParseStatus::Success;
2323}
2324
2325ParseStatus RISCVAsmParser::parseFenceArg(OperandVector &Operands) {
2326 const AsmToken &Tok = getLexer().getTok();
2327
2328 if (Tok.is(AsmToken::Integer)) {
2329 if (Tok.getIntVal() != 0)
2330 goto ParseFail;
2331
2332 Operands.push_back(RISCVOperand::createFenceArg(0, getLoc()));
2333 Lex();
2334 return ParseStatus::Success;
2335 }
2336
2337 if (Tok.is(AsmToken::Identifier)) {
2338 StringRef Str = Tok.getIdentifier();
2339
2340 // Letters must be unique, taken from 'iorw', and in ascending order. This
2341 // holds as long as each individual character is one of 'iorw' and is
2342 // greater than the previous character.
2343 unsigned Imm = 0;
2344 bool Valid = true;
2345 char Prev = '\0';
2346 for (char c : Str) {
2347 switch (c) {
2348 default:
2349 Valid = false;
2350 break;
2351 case 'i':
2353 break;
2354 case 'o':
2356 break;
2357 case 'r':
2359 break;
2360 case 'w':
2362 break;
2363 }
2364
2365 if (c <= Prev) {
2366 Valid = false;
2367 break;
2368 }
2369 Prev = c;
2370 }
2371
2372 if (!Valid)
2373 goto ParseFail;
2374
2375 Operands.push_back(RISCVOperand::createFenceArg(Imm, getLoc()));
2376 Lex();
2377 return ParseStatus::Success;
2378 }
2379
2380ParseFail:
2381 return TokError("operand must be formed of letters selected in-order from "
2382 "'iorw' or be 0");
2383}
2384
2385ParseStatus RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
2386 if (parseToken(AsmToken::LParen, "expected '('"))
2387 return ParseStatus::Failure;
2388 Operands.push_back(RISCVOperand::createToken("(", getLoc()));
2389
2390 if (!parseRegister(Operands).isSuccess())
2391 return Error(getLoc(), "expected register");
2392
2393 if (parseToken(AsmToken::RParen, "expected ')'"))
2394 return ParseStatus::Failure;
2395 Operands.push_back(RISCVOperand::createToken(")", getLoc()));
2396
2397 return ParseStatus::Success;
2398}
2399
2400ParseStatus RISCVAsmParser::parseZeroOffsetMemOp(OperandVector &Operands) {
2401 // Atomic operations such as lr.w, sc.w, and amo*.w accept a "memory operand"
2402 // as one of their register operands, such as `(a0)`. This just denotes that
2403 // the register (in this case `a0`) contains a memory address.
2404 //
2405 // Normally, we would be able to parse these by putting the parens into the
2406 // instruction string. However, GNU as also accepts a zero-offset memory
2407 // operand (such as `0(a0)`), and ignores the 0. Normally this would be parsed
2408 // with parseImmediate followed by parseMemOpBaseReg, but these instructions
2409 // do not accept an immediate operand, and we do not want to add a "dummy"
2410 // operand that is silently dropped.
2411 //
2412 // Instead, we use this custom parser. This will: allow (and discard) an
2413 // offset if it is zero; require (and discard) parentheses; and add only the
2414 // parsed register operand to `Operands`.
2415 //
2416 // These operands are printed with RISCVInstPrinter::printZeroOffsetMemOp,
2417 // which will only print the register surrounded by parentheses (which GNU as
2418 // also uses as its canonical representation for these operands).
2419 std::unique_ptr<RISCVOperand> OptionalImmOp;
2420
2421 if (getLexer().isNot(AsmToken::LParen)) {
2422 // Parse an Integer token. We do not accept arbritrary constant expressions
2423 // in the offset field (because they may include parens, which complicates
2424 // parsing a lot).
2425 int64_t ImmVal;
2426 SMLoc ImmStart = getLoc();
2427 if (getParser().parseIntToken(ImmVal,
2428 "expected '(' or optional integer offset"))
2429 return ParseStatus::Failure;
2430
2431 // Create a RISCVOperand for checking later (so the error messages are
2432 // nicer), but we don't add it to Operands.
2433 SMLoc ImmEnd = getLoc();
2434 OptionalImmOp =
2435 RISCVOperand::createImm(MCConstantExpr::create(ImmVal, getContext()),
2436 ImmStart, ImmEnd, isRV64());
2437 }
2438
2439 if (parseToken(AsmToken::LParen,
2440 OptionalImmOp ? "expected '(' after optional integer offset"
2441 : "expected '(' or optional integer offset"))
2442 return ParseStatus::Failure;
2443
2444 if (!parseRegister(Operands).isSuccess())
2445 return Error(getLoc(), "expected register");
2446
2447 if (parseToken(AsmToken::RParen, "expected ')'"))
2448 return ParseStatus::Failure;
2449
2450 // Deferred Handling of non-zero offsets. This makes the error messages nicer.
2451 if (OptionalImmOp && !OptionalImmOp->isImmZero())
2452 return Error(
2453 OptionalImmOp->getStartLoc(), "optional integer offset must be 0",
2454 SMRange(OptionalImmOp->getStartLoc(), OptionalImmOp->getEndLoc()));
2455
2456 return ParseStatus::Success;
2457}
2458
2459ParseStatus RISCVAsmParser::parseRegReg(OperandVector &Operands) {
2460 // RR : a2(a1)
2461 if (getLexer().getKind() != AsmToken::Identifier)
2462 return ParseStatus::NoMatch;
2463
2464 StringRef RegName = getLexer().getTok().getIdentifier();
2466 if (!Reg)
2467 return Error(getLoc(), "invalid register");
2468 getLexer().Lex();
2469
2470 if (parseToken(AsmToken::LParen, "expected '(' or invalid operand"))
2471 return ParseStatus::Failure;
2472
2473 if (getLexer().getKind() != AsmToken::Identifier)
2474 return Error(getLoc(), "expected register");
2475
2476 StringRef Reg2Name = getLexer().getTok().getIdentifier();
2477 MCRegister Reg2 = matchRegisterNameHelper(Reg2Name);
2478 if (!Reg2)
2479 return Error(getLoc(), "invalid register");
2480 getLexer().Lex();
2481
2482 if (parseToken(AsmToken::RParen, "expected ')'"))
2483 return ParseStatus::Failure;
2484
2485 Operands.push_back(RISCVOperand::createRegReg(Reg, Reg2, getLoc()));
2486
2487 return ParseStatus::Success;
2488}
2489
2490ParseStatus RISCVAsmParser::parseReglist(OperandVector &Operands) {
2491 // Rlist: {ra [, s0[-sN]]}
2492 // XRlist: {x1 [, x8[-x9][, x18[-xN]]]}
2493 SMLoc S = getLoc();
2494
2495 if (parseToken(AsmToken::LCurly, "register list must start with '{'"))
2496 return ParseStatus::Failure;
2497
2498 bool IsEABI = isRVE();
2499
2500 if (getLexer().isNot(AsmToken::Identifier))
2501 return Error(getLoc(), "register list must start from 'ra' or 'x1'");
2502
2503 StringRef RegName = getLexer().getTok().getIdentifier();
2505 MCRegister RegEnd;
2506 if (RegStart != RISCV::X1)
2507 return Error(getLoc(), "register list must start from 'ra' or 'x1'");
2508 getLexer().Lex();
2509
2510 // parse case like ,s0
2511 if (parseOptionalToken(AsmToken::Comma)) {
2512 if (getLexer().isNot(AsmToken::Identifier))
2513 return Error(getLoc(), "invalid register");
2514 StringRef RegName = getLexer().getTok().getIdentifier();
2515 RegStart = matchRegisterNameHelper(RegName);
2516 if (!RegStart)
2517 return Error(getLoc(), "invalid register");
2518 if (RegStart != RISCV::X8)
2519 return Error(getLoc(),
2520 "continuous register list must start from 's0' or 'x8'");
2521 getLexer().Lex(); // eat reg
2522 }
2523
2524 // parse case like -s1
2525 if (parseOptionalToken(AsmToken::Minus)) {
2526 StringRef EndName = getLexer().getTok().getIdentifier();
2527 // FIXME: the register mapping and checks of EABI is wrong
2528 RegEnd = matchRegisterNameHelper(EndName);
2529 if (!RegEnd)
2530 return Error(getLoc(), "invalid register");
2531 if (IsEABI && RegEnd != RISCV::X9)
2532 return Error(getLoc(), "contiguous register list of EABI can only be "
2533 "'s0-s1' or 'x8-x9' pair");
2534 getLexer().Lex();
2535 }
2536
2537 if (!IsEABI) {
2538 // parse extra part like ', x18[-x20]' for XRegList
2539 if (parseOptionalToken(AsmToken::Comma)) {
2540 if (RegEnd != RISCV::X9)
2541 return Error(
2542 getLoc(),
2543 "first contiguous registers pair of register list must be 'x8-x9'");
2544
2545 // parse ', x18' for extra part
2546 if (getLexer().isNot(AsmToken::Identifier))
2547 return Error(getLoc(), "invalid register");
2548 StringRef EndName = getLexer().getTok().getIdentifier();
2549 if (MatchRegisterName(EndName) != RISCV::X18)
2550 return Error(getLoc(),
2551 "second contiguous registers pair of register list "
2552 "must start from 'x18'");
2553 getLexer().Lex();
2554
2555 // parse '-x20' for extra part
2556 if (parseOptionalToken(AsmToken::Minus)) {
2557 if (getLexer().isNot(AsmToken::Identifier))
2558 return Error(getLoc(), "invalid register");
2559 EndName = getLexer().getTok().getIdentifier();
2560 if (MatchRegisterName(EndName) == RISCV::NoRegister)
2561 return Error(getLoc(), "invalid register");
2562 getLexer().Lex();
2563 }
2564 RegEnd = MatchRegisterName(EndName);
2565 }
2566 }
2567
2568 if (RegEnd == RISCV::X26)
2569 return Error(getLoc(), "invalid register list, {ra, s0-s10} or {x1, x8-x9, "
2570 "x18-x26} is not supported");
2571
2572 if (parseToken(AsmToken::RCurly, "register list must end with '}'"))
2573 return ParseStatus::Failure;
2574
2575 if (RegEnd == RISCV::NoRegister)
2576 RegEnd = RegStart;
2577
2578 auto Encode = RISCVZC::encodeRlist(RegEnd, IsEABI);
2579 if (Encode == RISCVZC::INVALID_RLIST)
2580 return Error(S, "invalid register list");
2581 Operands.push_back(RISCVOperand::createRlist(Encode, S));
2582
2583 return ParseStatus::Success;
2584}
2585
2586ParseStatus RISCVAsmParser::parseZcmpSpimm(OperandVector &Operands) {
2587 (void)parseOptionalToken(AsmToken::Minus);
2588
2589 SMLoc S = getLoc();
2590 int64_t StackAdjustment = getLexer().getTok().getIntVal();
2591 unsigned Spimm = 0;
2592 unsigned RlistVal = static_cast<RISCVOperand *>(Operands[1].get())->Rlist.Val;
2593
2594 bool IsEABI = isRVE();
2595 if (!RISCVZC::getSpimm(RlistVal, Spimm, StackAdjustment, isRV64(), IsEABI))
2596 return ParseStatus::NoMatch;
2597 Operands.push_back(RISCVOperand::createSpimm(Spimm << 4, S));
2598 getLexer().Lex();
2599 return ParseStatus::Success;
2600}
2601
2602/// Looks at a token type and creates the relevant operand from this
2603/// information, adding to Operands. If operand was parsed, returns false, else
2604/// true.
2605bool RISCVAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
2606 // Check if the current operand has a custom associated parser, if so, try to
2607 // custom parse the operand, or fallback to the general approach.
2609 MatchOperandParserImpl(Operands, Mnemonic, /*ParseForAllFeatures=*/true);
2610 if (Result.isSuccess())
2611 return false;
2612 if (Result.isFailure())
2613 return true;
2614
2615 // Attempt to parse token as a register.
2616 if (parseRegister(Operands, true).isSuccess())
2617 return false;
2618
2619 // Attempt to parse token as an immediate
2620 if (parseImmediate(Operands).isSuccess()) {
2621 // Parse memory base register if present
2622 if (getLexer().is(AsmToken::LParen))
2623 return !parseMemOpBaseReg(Operands).isSuccess();
2624 return false;
2625 }
2626
2627 // Finally we have exhausted all options and must declare defeat.
2628 Error(getLoc(), "unknown operand");
2629 return true;
2630}
2631
2632bool RISCVAsmParser::ParseInstruction(ParseInstructionInfo &Info,
2633 StringRef Name, SMLoc NameLoc,
2635 // Ensure that if the instruction occurs when relaxation is enabled,
2636 // relocations are forced for the file. Ideally this would be done when there
2637 // is enough information to reliably determine if the instruction itself may
2638 // cause relaxations. Unfortunately instruction processing stage occurs in the
2639 // same pass as relocation emission, so it's too late to set a 'sticky bit'
2640 // for the entire file.
2641 if (getSTI().hasFeature(RISCV::FeatureRelax)) {
2642 auto *Assembler = getTargetStreamer().getStreamer().getAssemblerPtr();
2643 if (Assembler != nullptr) {
2644 RISCVAsmBackend &MAB =
2645 static_cast<RISCVAsmBackend &>(Assembler->getBackend());
2646 MAB.setForceRelocs();
2647 }
2648 }
2649
2650 // First operand is token for instruction
2651 Operands.push_back(RISCVOperand::createToken(Name, NameLoc));
2652
2653 // If there are no more operands, then finish
2654 if (getLexer().is(AsmToken::EndOfStatement)) {
2655 getParser().Lex(); // Consume the EndOfStatement.
2656 return false;
2657 }
2658
2659 // Parse first operand
2660 if (parseOperand(Operands, Name))
2661 return true;
2662
2663 // Parse until end of statement, consuming commas between operands
2664 while (parseOptionalToken(AsmToken::Comma)) {
2665 // Parse next operand
2666 if (parseOperand(Operands, Name))
2667 return true;
2668 }
2669
2670 if (getParser().parseEOL("unexpected token")) {
2671 getParser().eatToEndOfStatement();
2672 return true;
2673 }
2674 return false;
2675}
2676
2677bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
2680
2681 if (const RISCVMCExpr *RE = dyn_cast<RISCVMCExpr>(Expr)) {
2682 Kind = RE->getKind();
2683 Expr = RE->getSubExpr();
2684 }
2685
2686 MCValue Res;
2687 MCFixup Fixup;
2688 if (Expr->evaluateAsRelocatable(Res, nullptr, &Fixup))
2689 return Res.getRefKind() == RISCVMCExpr::VK_RISCV_None;
2690 return false;
2691}
2692
2693bool RISCVAsmParser::isSymbolDiff(const MCExpr *Expr) {
2694 MCValue Res;
2695 MCFixup Fixup;
2696 if (Expr->evaluateAsRelocatable(Res, nullptr, &Fixup)) {
2697 return Res.getRefKind() == RISCVMCExpr::VK_RISCV_None && Res.getSymA() &&
2698 Res.getSymB();
2699 }
2700 return false;
2701}
2702
2703ParseStatus RISCVAsmParser::parseDirective(AsmToken DirectiveID) {
2704 StringRef IDVal = DirectiveID.getString();
2705
2706 if (IDVal == ".option")
2707 return parseDirectiveOption();
2708 if (IDVal == ".attribute")
2709 return parseDirectiveAttribute();
2710 if (IDVal == ".insn")
2711 return parseDirectiveInsn(DirectiveID.getLoc());
2712 if (IDVal == ".variant_cc")
2713 return parseDirectiveVariantCC();
2714
2715 return ParseStatus::NoMatch;
2716}
2717
2718bool RISCVAsmParser::resetToArch(StringRef Arch, SMLoc Loc, std::string &Result,
2719 bool FromOptionDirective) {
2720 for (auto &Feature : RISCVFeatureKV)
2722 clearFeatureBits(Feature.Value, Feature.Key);
2723
2724 auto ParseResult = llvm::RISCVISAInfo::parseArchString(
2725 Arch, /*EnableExperimentalExtension=*/true,
2726 /*ExperimentalExtensionVersionCheck=*/true);
2727 if (!ParseResult) {
2728 std::string Buffer;
2729 raw_string_ostream OutputErrMsg(Buffer);
2730 handleAllErrors(ParseResult.takeError(), [&](llvm::StringError &ErrMsg) {
2731 OutputErrMsg << "invalid arch name '" << Arch << "', "
2732 << ErrMsg.getMessage();
2733 });
2734
2735 return Error(Loc, OutputErrMsg.str());
2736 }
2737 auto &ISAInfo = *ParseResult;
2738
2739 for (auto &Feature : RISCVFeatureKV)
2740 if (ISAInfo->hasExtension(Feature.Key))
2741 setFeatureBits(Feature.Value, Feature.Key);
2742
2743 if (FromOptionDirective) {
2744 if (ISAInfo->getXLen() == 32 && isRV64())
2745 return Error(Loc, "bad arch string switching from rv64 to rv32");
2746 else if (ISAInfo->getXLen() == 64 && !isRV64())
2747 return Error(Loc, "bad arch string switching from rv32 to rv64");
2748 }
2749
2750 if (ISAInfo->getXLen() == 32)
2751 clearFeatureBits(RISCV::Feature64Bit, "64bit");
2752 else if (ISAInfo->getXLen() == 64)
2753 setFeatureBits(RISCV::Feature64Bit, "64bit");
2754 else
2755 return Error(Loc, "bad arch string " + Arch);
2756
2757 Result = ISAInfo->toString();
2758 return false;
2759}
2760
2761bool RISCVAsmParser::parseDirectiveOption() {
2762 MCAsmParser &Parser = getParser();
2763 // Get the option token.
2764 AsmToken Tok = Parser.getTok();
2765
2766 // At the moment only identifiers are supported.
2767 if (parseToken(AsmToken::Identifier, "expected identifier"))
2768 return true;
2769
2771
2772 if (Option == "push") {
2773 if (Parser.parseEOL())
2774 return true;
2775
2776 getTargetStreamer().emitDirectiveOptionPush();
2777 pushFeatureBits();
2778 return false;
2779 }
2780
2781 if (Option == "pop") {
2782 SMLoc StartLoc = Parser.getTok().getLoc();
2783 if (Parser.parseEOL())
2784 return true;
2785
2786 getTargetStreamer().emitDirectiveOptionPop();
2787 if (popFeatureBits())
2788 return Error(StartLoc, ".option pop with no .option push");
2789
2790 return false;
2791 }
2792
2793 if (Option == "arch") {
2795 do {
2796 if (Parser.parseComma())
2797 return true;
2798
2800 if (parseOptionalToken(AsmToken::Plus))
2801 Type = RISCVOptionArchArgType::Plus;
2802 else if (parseOptionalToken(AsmToken::Minus))
2803 Type = RISCVOptionArchArgType::Minus;
2804 else if (!Args.empty())
2805 return Error(Parser.getTok().getLoc(),
2806 "unexpected token, expected + or -");
2807 else
2808 Type = RISCVOptionArchArgType::Full;
2809
2810 if (Parser.getTok().isNot(AsmToken::Identifier))
2811 return Error(Parser.getTok().getLoc(),
2812 "unexpected token, expected identifier");
2813
2814 StringRef Arch = Parser.getTok().getString();
2815 SMLoc Loc = Parser.getTok().getLoc();
2816 Parser.Lex();
2817
2818 if (Type == RISCVOptionArchArgType::Full) {
2819 std::string Result;
2820 if (resetToArch(Arch, Loc, Result, true))
2821 return true;
2822
2823 Args.emplace_back(Type, Result);
2824 break;
2825 }
2826
2827 auto Ext = llvm::lower_bound(RISCVFeatureKV, Arch);
2828 if (Ext == std::end(RISCVFeatureKV) || StringRef(Ext->Key) != Arch ||
2830 if (isDigit(Arch.back()))
2831 return Error(
2832 Loc,
2833 "Extension version number parsing not currently implemented");
2834 return Error(Loc, "unknown extension feature");
2835 }
2836
2837 Args.emplace_back(Type, Ext->Key);
2838
2839 if (Type == RISCVOptionArchArgType::Plus) {
2840 FeatureBitset OldFeatureBits = STI->getFeatureBits();
2841
2842 setFeatureBits(Ext->Value, Ext->Key);
2843 auto ParseResult = RISCVFeatures::parseFeatureBits(isRV64(), STI->getFeatureBits());
2844 if (!ParseResult) {
2845 copySTI().setFeatureBits(OldFeatureBits);
2846 setAvailableFeatures(ComputeAvailableFeatures(OldFeatureBits));
2847
2848 std::string Buffer;
2849 raw_string_ostream OutputErrMsg(Buffer);
2850 handleAllErrors(ParseResult.takeError(), [&](llvm::StringError &ErrMsg) {
2851 OutputErrMsg << ErrMsg.getMessage();
2852 });
2853
2854 return Error(Loc, OutputErrMsg.str());
2855 }
2856 } else {
2857 assert(Type == RISCVOptionArchArgType::Minus);
2858 // It is invalid to disable an extension that there are other enabled
2859 // extensions depend on it.
2860 // TODO: Make use of RISCVISAInfo to handle this
2861 for (auto &Feature : RISCVFeatureKV) {
2862 if (getSTI().hasFeature(Feature.Value) &&
2863 Feature.Implies.test(Ext->Value))
2864 return Error(Loc,
2865 Twine("Can't disable ") + Ext->Key + " extension, " +
2866 Feature.Key + " extension requires " + Ext->Key +
2867 " extension be enabled");
2868 }
2869
2870 clearFeatureBits(Ext->Value, Ext->Key);
2871 }
2872 } while (Parser.getTok().isNot(AsmToken::EndOfStatement));
2873
2874 if (Parser.parseEOL())
2875 return true;
2876
2877 getTargetStreamer().emitDirectiveOptionArch(Args);
2878 return false;
2879 }
2880
2881 if (Option == "rvc") {
2882 if (Parser.parseEOL())
2883 return true;
2884
2885 getTargetStreamer().emitDirectiveOptionRVC();
2886 setFeatureBits(RISCV::FeatureStdExtC, "c");
2887 return false;
2888 }
2889
2890 if (Option == "norvc") {
2891 if (Parser.parseEOL())
2892 return true;
2893
2894 getTargetStreamer().emitDirectiveOptionNoRVC();
2895 clearFeatureBits(RISCV::FeatureStdExtC, "c");
2896 clearFeatureBits(RISCV::FeatureStdExtZca, "zca");
2897 return false;
2898 }
2899
2900 if (Option == "pic") {
2901 if (Parser.parseEOL())
2902 return true;
2903
2904 getTargetStreamer().emitDirectiveOptionPIC();
2905 ParserOptions.IsPicEnabled = true;
2906 return false;
2907 }
2908
2909 if (Option == "nopic") {
2910 if (Parser.parseEOL())
2911 return true;
2912
2913 getTargetStreamer().emitDirectiveOptionNoPIC();
2914 ParserOptions.IsPicEnabled = false;
2915 return false;
2916 }
2917
2918 if (Option == "relax") {
2919 if (Parser.parseEOL())
2920 return true;
2921
2922 getTargetStreamer().emitDirectiveOptionRelax();
2923 setFeatureBits(RISCV::FeatureRelax, "relax");
2924 return false;
2925 }
2926
2927 if (Option == "norelax") {
2928 if (Parser.parseEOL())
2929 return true;
2930
2931 getTargetStreamer().emitDirectiveOptionNoRelax();
2932 clearFeatureBits(RISCV::FeatureRelax, "relax");
2933 return false;
2934 }
2935
2936 // Unknown option.
2937 Warning(Parser.getTok().getLoc(), "unknown option, expected 'push', 'pop', "
2938 "'rvc', 'norvc', 'arch', 'relax' or "
2939 "'norelax'");
2940 Parser.eatToEndOfStatement();
2941 return false;
2942}
2943
2944/// parseDirectiveAttribute
2945/// ::= .attribute expression ',' ( expression | "string" )
2946/// ::= .attribute identifier ',' ( expression | "string" )
2947bool RISCVAsmParser::parseDirectiveAttribute() {
2948 MCAsmParser &Parser = getParser();
2949 int64_t Tag;
2950 SMLoc TagLoc;
2951 TagLoc = Parser.getTok().getLoc();
2952 if (Parser.getTok().is(AsmToken::Identifier)) {
2953 StringRef Name = Parser.getTok().getIdentifier();
2954 std::optional<unsigned> Ret =
2956 if (!Ret)
2957 return Error(TagLoc, "attribute name not recognised: " + Name);
2958 Tag = *Ret;
2959 Parser.Lex();
2960 } else {
2961 const MCExpr *AttrExpr;
2962
2963 TagLoc = Parser.getTok().getLoc();
2964 if (Parser.parseExpression(AttrExpr))
2965 return true;
2966
2967 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
2968 if (check(!CE, TagLoc, "expected numeric constant"))
2969 return true;
2970
2971 Tag = CE->getValue();
2972 }
2973
2974 if (Parser.parseComma())
2975 return true;
2976
2977 StringRef StringValue;
2978 int64_t IntegerValue = 0;
2979 bool IsIntegerValue = true;
2980
2981 // RISC-V attributes have a string value if the tag number is odd
2982 // and an integer value if the tag number is even.
2983 if (Tag % 2)
2984 IsIntegerValue = false;
2985
2986 SMLoc ValueExprLoc = Parser.getTok().getLoc();
2987 if (IsIntegerValue) {
2988 const MCExpr *ValueExpr;
2989 if (Parser.parseExpression(ValueExpr))
2990 return true;
2991
2992 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
2993 if (!CE)
2994 return Error(ValueExprLoc, "expected numeric constant");
2995 IntegerValue = CE->getValue();
2996 } else {
2997 if (Parser.getTok().isNot(AsmToken::String))
2998 return Error(Parser.getTok().getLoc(), "expected string constant");
2999
3000 StringValue = Parser.getTok().getStringContents();
3001 Parser.Lex();
3002 }
3003
3004 if (Parser.parseEOL())
3005 return true;
3006
3007 if (IsIntegerValue)
3008 getTargetStreamer().emitAttribute(Tag, IntegerValue);
3009 else if (Tag != RISCVAttrs::ARCH)
3010 getTargetStreamer().emitTextAttribute(Tag, StringValue);
3011 else {
3012 std::string Result;
3013 if (resetToArch(StringValue, ValueExprLoc, Result, false))
3014 return true;
3015
3016 // Then emit the arch string.
3017 getTargetStreamer().emitTextAttribute(Tag, Result);
3018 }
3019
3020 return false;
3021}
3022
3023bool isValidInsnFormat(StringRef Format, bool AllowC) {
3024 return StringSwitch<bool>(Format)
3025 .Cases("r", "r4", "i", "b", "sb", "u", "j", "uj", "s", true)
3026 .Cases("cr", "ci", "ciw", "css", "cl", "cs", "ca", "cb", "cj", AllowC)
3027 .Default(false);
3028}
3029
3030/// parseDirectiveInsn
3031/// ::= .insn [ format encoding, (operands (, operands)*) ]
3032bool RISCVAsmParser::parseDirectiveInsn(SMLoc L) {
3033 MCAsmParser &Parser = getParser();
3034
3035 // Expect instruction format as identifier.
3037 SMLoc ErrorLoc = Parser.getTok().getLoc();
3038 if (Parser.parseIdentifier(Format))
3039 return Error(ErrorLoc, "expected instruction format");
3040
3041 bool AllowC = getSTI().hasFeature(RISCV::FeatureStdExtC) ||
3042 getSTI().hasFeature(RISCV::FeatureStdExtZca);
3043 if (!isValidInsnFormat(Format, AllowC))
3044 return Error(ErrorLoc, "invalid instruction format");
3045
3046 std::string FormatName = (".insn_" + Format).str();
3047
3050
3051 if (ParseInstruction(Info, FormatName, L, Operands))
3052 return true;
3053
3054 unsigned Opcode;
3056 return MatchAndEmitInstruction(L, Opcode, Operands, Parser.getStreamer(),
3057 ErrorInfo,
3058 /*MatchingInlineAsm=*/false);
3059}
3060
3061/// parseDirectiveVariantCC
3062/// ::= .variant_cc symbol
3063bool RISCVAsmParser::parseDirectiveVariantCC() {
3065 if (getParser().parseIdentifier(Name))
3066 return TokError("expected symbol name");
3067 if (parseEOL())
3068 return true;
3069 getTargetStreamer().emitDirectiveVariantCC(
3070 *getContext().getOrCreateSymbol(Name));
3071 return false;
3072}
3073
3074void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
3075 MCInst CInst;
3076 bool Res = RISCVRVC::compress(CInst, Inst, getSTI());
3077 if (Res)
3078 ++RISCVNumInstrsCompressed;
3079 S.emitInstruction((Res ? CInst : Inst), getSTI());
3080}
3081
3082void RISCVAsmParser::emitLoadImm(MCRegister DestReg, int64_t Value,
3083 MCStreamer &Out) {
3085
3086 MCRegister SrcReg = RISCV::X0;
3087 for (const RISCVMatInt::Inst &Inst : Seq) {
3088 switch (Inst.getOpndKind()) {
3089 case RISCVMatInt::Imm:
3090 emitToStreamer(Out,
3091 MCInstBuilder(Inst.getOpcode()).addReg(DestReg).addImm(Inst.getImm()));
3092 break;
3093 case RISCVMatInt::RegX0:
3094 emitToStreamer(
3095 Out, MCInstBuilder(Inst.getOpcode()).addReg(DestReg).addReg(SrcReg).addReg(
3096 RISCV::X0));
3097 break;
3099 emitToStreamer(
3100 Out, MCInstBuilder(Inst.getOpcode()).addReg(DestReg).addReg(SrcReg).addReg(
3101 SrcReg));
3102 break;
3104 emitToStreamer(
3105 Out, MCInstBuilder(Inst.getOpcode()).addReg(DestReg).addReg(SrcReg).addImm(
3106 Inst.getImm()));
3107 break;
3108 }
3109
3110 // Only the first instruction has X0 as its source.
3111 SrcReg = DestReg;
3112 }
3113}
3114
3115void RISCVAsmParser::emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
3116 const MCExpr *Symbol,
3118 unsigned SecondOpcode, SMLoc IDLoc,
3119 MCStreamer &Out) {
3120 // A pair of instructions for PC-relative addressing; expands to
3121 // TmpLabel: AUIPC TmpReg, VKHi(symbol)
3122 // OP DestReg, TmpReg, %pcrel_lo(TmpLabel)
3123 MCContext &Ctx = getContext();
3124
3125 MCSymbol *TmpLabel = Ctx.createNamedTempSymbol("pcrel_hi");
3126 Out.emitLabel(TmpLabel);
3127
3128 const RISCVMCExpr *SymbolHi = RISCVMCExpr::create(Symbol, VKHi, Ctx);
3129 emitToStreamer(
3130 Out, MCInstBuilder(RISCV::AUIPC).addOperand(TmpReg).addExpr(SymbolHi));
3131
3132 const MCExpr *RefToLinkTmpLabel =
3135
3136 emitToStreamer(Out, MCInstBuilder(SecondOpcode)
3137 .addOperand(DestReg)
3138 .addOperand(TmpReg)
3139 .addExpr(RefToLinkTmpLabel));
3140}
3141
3142void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
3143 MCStreamer &Out) {
3144 // The load local address pseudo-instruction "lla" is used in PC-relative
3145 // addressing of local symbols:
3146 // lla rdest, symbol
3147 // expands to
3148 // TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
3149 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3150 MCOperand DestReg = Inst.getOperand(0);
3151 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3152 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
3153 RISCV::ADDI, IDLoc, Out);
3154}
3155
3156void RISCVAsmParser::emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc,
3157 MCStreamer &Out) {
3158 // The load global address pseudo-instruction "lga" is used in GOT-indirect
3159 // addressing of global symbols:
3160 // lga rdest, symbol
3161 // expands to
3162 // TmpLabel: AUIPC rdest, %got_pcrel_hi(symbol)
3163 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3164 MCOperand DestReg = Inst.getOperand(0);
3165 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3166 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3167 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_GOT_HI,
3168 SecondOpcode, IDLoc, Out);
3169}
3170
3171void RISCVAsmParser::emitLoadAddress(MCInst &Inst, SMLoc IDLoc,
3172 MCStreamer &Out) {
3173 // The load address pseudo-instruction "la" is used in PC-relative and
3174 // GOT-indirect addressing of global symbols:
3175 // la rdest, symbol
3176 // is an alias for either (for non-PIC)
3177 // lla rdest, symbol
3178 // or (for PIC)
3179 // lga rdest, symbol
3180 if (ParserOptions.IsPicEnabled)
3181 emitLoadGlobalAddress(Inst, IDLoc, Out);
3182 else
3183 emitLoadLocalAddress(Inst, IDLoc, Out);
3184}
3185
3186void RISCVAsmParser::emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc,
3187 MCStreamer &Out) {
3188 // The load TLS IE address pseudo-instruction "la.tls.ie" is used in
3189 // initial-exec TLS model addressing of global symbols:
3190 // la.tls.ie rdest, symbol
3191 // expands to
3192 // TmpLabel: AUIPC rdest, %tls_ie_pcrel_hi(symbol)
3193 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3194 MCOperand DestReg = Inst.getOperand(0);
3195 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3196 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3197 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GOT_HI,
3198 SecondOpcode, IDLoc, Out);
3199}
3200
3201void RISCVAsmParser::emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc,
3202 MCStreamer &Out) {
3203 // The load TLS GD address pseudo-instruction "la.tls.gd" is used in
3204 // global-dynamic TLS model addressing of global symbols:
3205 // la.tls.gd rdest, symbol
3206 // expands to
3207 // TmpLabel: AUIPC rdest, %tls_gd_pcrel_hi(symbol)
3208 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3209 MCOperand DestReg = Inst.getOperand(0);
3210 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3211 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GD_HI,
3212 RISCV::ADDI, IDLoc, Out);
3213}
3214
3215void RISCVAsmParser::emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode,
3216 SMLoc IDLoc, MCStreamer &Out,
3217 bool HasTmpReg) {
3218 // The load/store pseudo-instruction does a pc-relative load with
3219 // a symbol.
3220 //
3221 // The expansion looks like this
3222 //
3223 // TmpLabel: AUIPC tmp, %pcrel_hi(symbol)
3224 // [S|L]X rd, %pcrel_lo(TmpLabel)(tmp)
3225 unsigned DestRegOpIdx = HasTmpReg ? 1 : 0;
3226 MCOperand DestReg = Inst.getOperand(DestRegOpIdx);
3227 unsigned SymbolOpIdx = HasTmpReg ? 2 : 1;
3228 MCOperand TmpReg = Inst.getOperand(0);
3229 const MCExpr *Symbol = Inst.getOperand(SymbolOpIdx).getExpr();
3230 emitAuipcInstPair(DestReg, TmpReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
3231 Opcode, IDLoc, Out);
3232}
3233
3234void RISCVAsmParser::emitPseudoExtend(MCInst &Inst, bool SignExtend,
3235 int64_t Width, SMLoc IDLoc,
3236 MCStreamer &Out) {
3237 // The sign/zero extend pseudo-instruction does two shifts, with the shift
3238 // amounts dependent on the XLEN.
3239 //
3240 // The expansion looks like this
3241 //
3242 // SLLI rd, rs, XLEN - Width
3243 // SR[A|R]I rd, rd, XLEN - Width
3244 MCOperand DestReg = Inst.getOperand(0);
3245 MCOperand SourceReg = Inst.getOperand(1);
3246
3247 unsigned SecondOpcode = SignExtend ? RISCV::SRAI : RISCV::SRLI;
3248 int64_t ShAmt = (isRV64() ? 64 : 32) - Width;
3249
3250 assert(ShAmt > 0 && "Shift amount must be non-zero.");
3251
3252 emitToStreamer(Out, MCInstBuilder(RISCV::SLLI)
3253 .addOperand(DestReg)
3254 .addOperand(SourceReg)
3255 .addImm(ShAmt));
3256
3257 emitToStreamer(Out, MCInstBuilder(SecondOpcode)
3258 .addOperand(DestReg)
3259 .addOperand(DestReg)
3260 .addImm(ShAmt));
3261}
3262
3263void RISCVAsmParser::emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
3264 MCStreamer &Out) {
3265 if (Inst.getNumOperands() == 3) {
3266 // unmasked va >= x
3267 //
3268 // pseudoinstruction: vmsge{u}.vx vd, va, x
3269 // expansion: vmslt{u}.vx vd, va, x; vmnand.mm vd, vd, vd
3270 emitToStreamer(Out, MCInstBuilder(Opcode)
3271 .addOperand(Inst.getOperand(0))
3272 .addOperand(Inst.getOperand(1))
3273 .addOperand(Inst.getOperand(2))
3274 .addReg(RISCV::NoRegister)
3275 .setLoc(IDLoc));
3276 emitToStreamer(Out, MCInstBuilder(RISCV::VMNAND_MM)
3277 .addOperand(Inst.getOperand(0))
3278 .addOperand(Inst.getOperand(0))
3279 .addOperand(Inst.getOperand(0))
3280 .setLoc(IDLoc));
3281 } else if (Inst.getNumOperands() == 4) {
3282 // masked va >= x, vd != v0
3283 //
3284 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t
3285 // expansion: vmslt{u}.vx vd, va, x, v0.t; vmxor.mm vd, vd, v0
3286 assert(Inst.getOperand(0).getReg() != RISCV::V0 &&
3287 "The destination register should not be V0.");
3288 emitToStreamer(Out, MCInstBuilder(Opcode)
3289 .addOperand(Inst.getOperand(0))
3290 .addOperand(Inst.getOperand(1))
3291 .addOperand(Inst.getOperand(2))
3292 .addOperand(Inst.getOperand(3))
3293 .setLoc(IDLoc));
3294 emitToStreamer(Out, MCInstBuilder(RISCV::VMXOR_MM)
3295 .addOperand(Inst.getOperand(0))
3296 .addOperand(Inst.getOperand(0))
3297 .addReg(RISCV::V0)
3298 .setLoc(IDLoc));
3299 } else if (Inst.getNumOperands() == 5 &&
3300 Inst.getOperand(0).getReg() == RISCV::V0) {
3301 // masked va >= x, vd == v0
3302 //
3303 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3304 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vd, vd, vt
3305 assert(Inst.getOperand(0).getReg() == RISCV::V0 &&
3306 "The destination register should be V0.");
3307 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3308 "The temporary vector register should not be V0.");
3309 emitToStreamer(Out, MCInstBuilder(Opcode)
3310 .addOperand(Inst.getOperand(1))
3311 .addOperand(Inst.getOperand(2))
3312 .addOperand(Inst.getOperand(3))
3313 .addReg(RISCV::NoRegister)
3314 .setLoc(IDLoc));
3315 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3316 .addOperand(Inst.getOperand(0))
3317 .addOperand(Inst.getOperand(0))
3318 .addOperand(Inst.getOperand(1))
3319 .setLoc(IDLoc));
3320 } else if (Inst.getNumOperands() == 5) {
3321 // masked va >= x, any vd
3322 //
3323 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3324 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vt, v0, vt;
3325 // vmandn.mm vd, vd, v0; vmor.mm vd, vt, vd
3326 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3327 "The temporary vector register should not be V0.");
3328 emitToStreamer(Out, MCInstBuilder(Opcode)
3329 .addOperand(Inst.getOperand(1))
3330 .addOperand(Inst.getOperand(2))
3331 .addOperand(Inst.getOperand(3))
3332 .addReg(RISCV::NoRegister)
3333 .setLoc(IDLoc));
3334 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3335 .addOperand(Inst.getOperand(1))
3336 .addReg(RISCV::V0)
3337 .addOperand(Inst.getOperand(1))
3338 .setLoc(IDLoc));
3339 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3340 .addOperand(Inst.getOperand(0))
3341 .addOperand(Inst.getOperand(0))
3342 .addReg(RISCV::V0)
3343 .setLoc(IDLoc));
3344 emitToStreamer(Out, MCInstBuilder(RISCV::VMOR_MM)
3345 .addOperand(Inst.getOperand(0))
3346 .addOperand(Inst.getOperand(1))
3347 .addOperand(Inst.getOperand(0))
3348 .setLoc(IDLoc));
3349 }
3350}
3351
3352bool RISCVAsmParser::checkPseudoAddTPRel(MCInst &Inst,
3354 assert(Inst.getOpcode() == RISCV::PseudoAddTPRel && "Invalid instruction");
3355 assert(Inst.getOperand(2).isReg() && "Unexpected second operand kind");
3356 if (Inst.getOperand(2).getReg() != RISCV::X4) {
3357 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3358 return Error(ErrorLoc, "the second input operand must be tp/x4 when using "
3359 "%tprel_add modifier");
3360 }
3361
3362 return false;
3363}
3364
3365bool RISCVAsmParser::checkPseudoTLSDESCCall(MCInst &Inst,
3367 assert(Inst.getOpcode() == RISCV::PseudoTLSDESCCall && "Invalid instruction");
3368 assert(Inst.getOperand(0).isReg() && "Unexpected operand kind");
3369 if (Inst.getOperand(0).getReg() != RISCV::X5) {
3370 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3371 return Error(ErrorLoc, "the output operand must be t0/x5 when using "
3372 "%tlsdesc_call modifier");
3373 }
3374
3375 return false;
3376}
3377
3378std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultMaskRegOp() const {
3379 return RISCVOperand::createReg(RISCV::NoRegister, llvm::SMLoc(),
3380 llvm::SMLoc());
3381}
3382
3383std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgOp() const {
3384 return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::DYN,
3385 llvm::SMLoc());
3386}
3387
3388std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgLegacyOp() const {
3389 return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::RNE,
3390 llvm::SMLoc());
3391}
3392
3393bool RISCVAsmParser::validateInstruction(MCInst &Inst,
3395 unsigned Opcode = Inst.getOpcode();
3396
3397 if (Opcode == RISCV::PseudoVMSGEU_VX_M_T ||
3398 Opcode == RISCV::PseudoVMSGE_VX_M_T) {
3399 unsigned DestReg = Inst.getOperand(0).getReg();
3400 unsigned TempReg = Inst.getOperand(1).getReg();
3401 if (DestReg == TempReg) {
3402 SMLoc Loc = Operands.back()->getStartLoc();
3403 return Error(Loc, "The temporary vector register cannot be the same as "
3404 "the destination register.");
3405 }
3406 }
3407
3408 if (Opcode == RISCV::TH_LDD || Opcode == RISCV::TH_LWUD ||
3409 Opcode == RISCV::TH_LWD) {
3410 unsigned Rd1 = Inst.getOperand(0).getReg();
3411 unsigned Rd2 = Inst.getOperand(1).getReg();
3412 unsigned Rs1 = Inst.getOperand(2).getReg();
3413 // The encoding with rd1 == rd2 == rs1 is reserved for XTHead load pair.
3414 if (Rs1 == Rd1 && Rs1 == Rd2) {
3415 SMLoc Loc = Operands[1]->getStartLoc();
3416 return Error(Loc, "The source register and destination registers "
3417 "cannot be equal.");
3418 }
3419 }
3420
3421 if (Opcode == RISCV::CM_MVSA01) {
3422 unsigned Rd1 = Inst.getOperand(0).getReg();
3423 unsigned Rd2 = Inst.getOperand(1).getReg();
3424 if (Rd1 == Rd2) {
3425 SMLoc Loc = Operands[1]->getStartLoc();
3426 return Error(Loc, "'rs1' and 'rs2' must be different.");
3427 }
3428 }
3429
3430 bool IsTHeadMemPair32 = (Opcode == RISCV::TH_LWD ||
3431 Opcode == RISCV::TH_LWUD || Opcode == RISCV::TH_SWD);
3432 bool IsTHeadMemPair64 = (Opcode == RISCV::TH_LDD || Opcode == RISCV::TH_SDD);
3433 // The last operand of XTHeadMemPair instructions must be constant 3 or 4
3434 // depending on the data width.
3435 if (IsTHeadMemPair32 && Inst.getOperand(4).getImm() != 3) {
3436 SMLoc Loc = Operands.back()->getStartLoc();
3437 return Error(Loc, "Operand must be constant 3.");
3438 } else if (IsTHeadMemPair64 && Inst.getOperand(4).getImm() != 4) {
3439 SMLoc Loc = Operands.back()->getStartLoc();
3440 return Error(Loc, "Operand must be constant 4.");
3441 }
3442
3443 const MCInstrDesc &MCID = MII.get(Opcode);
3444 if (!(MCID.TSFlags & RISCVII::ConstraintMask))
3445 return false;
3446
3447 if (Opcode == RISCV::VC_V_XVW || Opcode == RISCV::VC_V_IVW ||
3448 Opcode == RISCV::VC_V_FVW || Opcode == RISCV::VC_V_VVW) {
3449 // Operands Opcode, Dst, uimm, Dst, Rs2, Rs1 for VC_V_XVW.
3450 unsigned VCIXDst = Inst.getOperand(0).getReg();
3451 SMLoc VCIXDstLoc = Operands[2]->getStartLoc();
3452 if (MCID.TSFlags & RISCVII::VS1Constraint) {
3453 unsigned VCIXRs1 = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
3454 if (VCIXDst == VCIXRs1)
3455 return Error(VCIXDstLoc, "The destination vector register group cannot"
3456 " overlap the source vector register group.");
3457 }
3458 if (MCID.TSFlags & RISCVII::VS2Constraint) {
3459 unsigned VCIXRs2 = Inst.getOperand(Inst.getNumOperands() - 2).getReg();
3460 if (VCIXDst == VCIXRs2)
3461 return Error(VCIXDstLoc, "The destination vector register group cannot"
3462 " overlap the source vector register group.");
3463 }
3464 return false;
3465 }
3466
3467 unsigned DestReg = Inst.getOperand(0).getReg();
3468 unsigned Offset = 0;
3469 int TiedOp = MCID.getOperandConstraint(1, MCOI::TIED_TO);
3470 if (TiedOp == 0)
3471 Offset = 1;
3472
3473 // Operands[1] will be the first operand, DestReg.
3474 SMLoc Loc = Operands[1]->getStartLoc();
3475 if (MCID.TSFlags & RISCVII::VS2Constraint) {
3476 unsigned CheckReg = Inst.getOperand(Offset + 1).getReg();
3477 if (DestReg == CheckReg)
3478 return Error(Loc, "The destination vector register group cannot overlap"
3479 " the source vector register group.");
3480 }
3481 if ((MCID.TSFlags & RISCVII::VS1Constraint) && Inst.getOperand(Offset + 2).isReg()) {
3482 unsigned CheckReg = Inst.getOperand(Offset + 2).getReg();
3483 if (DestReg == CheckReg)
3484 return Error(Loc, "The destination vector register group cannot overlap"
3485 " the source vector register group.");
3486 }
3487 if ((MCID.TSFlags & RISCVII::VMConstraint) && (DestReg == RISCV::V0)) {
3488 // vadc, vsbc are special cases. These instructions have no mask register.
3489 // The destination register could not be V0.
3490 if (Opcode == RISCV::VADC_VVM || Opcode == RISCV::VADC_VXM ||
3491 Opcode == RISCV::VADC_VIM || Opcode == RISCV::VSBC_VVM ||
3492 Opcode == RISCV::VSBC_VXM || Opcode == RISCV::VFMERGE_VFM ||
3493 Opcode == RISCV::VMERGE_VIM || Opcode == RISCV::VMERGE_VVM ||
3494 Opcode == RISCV::VMERGE_VXM)
3495 return Error(Loc, "The destination vector register group cannot be V0.");
3496
3497 // Regardless masked or unmasked version, the number of operands is the
3498 // same. For example, "viota.m v0, v2" is "viota.m v0, v2, NoRegister"
3499 // actually. We need to check the last operand to ensure whether it is
3500 // masked or not.
3501 unsigned CheckReg = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
3502 assert((CheckReg == RISCV::V0 || CheckReg == RISCV::NoRegister) &&
3503 "Unexpected register for mask operand");
3504
3505 if (DestReg == CheckReg)
3506 return Error(Loc, "The destination vector register group cannot overlap"
3507 " the mask register.");
3508 }
3509 return false;
3510}
3511
3512bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
3514 MCStreamer &Out) {
3515 Inst.setLoc(IDLoc);
3516
3517 switch (Inst.getOpcode()) {
3518 default:
3519 break;
3520 case RISCV::PseudoLLAImm:
3521 case RISCV::PseudoLAImm:
3522 case RISCV::PseudoLI: {
3523 MCRegister Reg = Inst.getOperand(0).getReg();
3524 const MCOperand &Op1 = Inst.getOperand(1);
3525 if (Op1.isExpr()) {
3526 // We must have li reg, %lo(sym) or li reg, %pcrel_lo(sym) or similar.
3527 // Just convert to an addi. This allows compatibility with gas.
3528 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
3529 .addReg(Reg)
3530 .addReg(RISCV::X0)
3531 .addExpr(Op1.getExpr()));
3532 return false;
3533 }
3534 int64_t Imm = Inst.getOperand(1).getImm();
3535 // On RV32 the immediate here can either be a signed or an unsigned
3536 // 32-bit number. Sign extension has to be performed to ensure that Imm
3537 // represents the expected signed 64-bit number.
3538 if (!isRV64())
3539 Imm = SignExtend64<32>(Imm);
3540 emitLoadImm(Reg, Imm, Out);
3541 return false;
3542 }
3543 case RISCV::PseudoLLA:
3544 emitLoadLocalAddress(Inst, IDLoc, Out);
3545 return false;
3546 case RISCV::PseudoLGA:
3547 emitLoadGlobalAddress(Inst, IDLoc, Out);
3548 return false;
3549 case RISCV::PseudoLA:
3550 emitLoadAddress(Inst, IDLoc, Out);
3551 return false;
3552 case RISCV::PseudoLA_TLS_IE:
3553 emitLoadTLSIEAddress(Inst, IDLoc, Out);
3554 return false;
3555 case RISCV::PseudoLA_TLS_GD:
3556 emitLoadTLSGDAddress(Inst, IDLoc, Out);
3557 return false;
3558 case RISCV::PseudoLB:
3559 emitLoadStoreSymbol(Inst, RISCV::LB, IDLoc, Out, /*HasTmpReg=*/false);
3560 return false;
3561 case RISCV::PseudoLBU:
3562 emitLoadStoreSymbol(Inst, RISCV::LBU, IDLoc, Out, /*HasTmpReg=*/false);
3563 return false;
3564 case RISCV::PseudoLH:
3565 emitLoadStoreSymbol(Inst, RISCV::LH, IDLoc, Out, /*HasTmpReg=*/false);
3566 return false;
3567 case RISCV::PseudoLHU:
3568 emitLoadStoreSymbol(Inst, RISCV::LHU, IDLoc, Out, /*HasTmpReg=*/false);
3569 return false;
3570 case RISCV::PseudoLW:
3571 emitLoadStoreSymbol(Inst, RISCV::LW, IDLoc, Out, /*HasTmpReg=*/false);
3572 return false;
3573 case RISCV::PseudoLWU:
3574 emitLoadStoreSymbol(Inst, RISCV::LWU, IDLoc, Out, /*HasTmpReg=*/false);
3575 return false;
3576 case RISCV::PseudoLD:
3577 emitLoadStoreSymbol(Inst, RISCV::LD, IDLoc, Out, /*HasTmpReg=*/false);
3578 return false;
3579 case RISCV::PseudoFLH:
3580 emitLoadStoreSymbol(Inst, RISCV::FLH, IDLoc, Out, /*HasTmpReg=*/true);
3581 return false;
3582 case RISCV::PseudoFLW:
3583 emitLoadStoreSymbol(Inst, RISCV::FLW, IDLoc, Out, /*HasTmpReg=*/true);
3584 return false;
3585 case RISCV::PseudoFLD:
3586 emitLoadStoreSymbol(Inst, RISCV::FLD, IDLoc, Out, /*HasTmpReg=*/true);
3587 return false;
3588 case RISCV::PseudoSB:
3589 emitLoadStoreSymbol(Inst, RISCV::SB, IDLoc, Out, /*HasTmpReg=*/true);
3590 return false;
3591 case RISCV::PseudoSH:
3592 emitLoadStoreSymbol(Inst, RISCV::SH, IDLoc, Out, /*HasTmpReg=*/true);
3593 return false;
3594 case RISCV::PseudoSW:
3595 emitLoadStoreSymbol(Inst, RISCV::SW, IDLoc, Out, /*HasTmpReg=*/true);
3596 return false;
3597 case RISCV::PseudoSD:
3598 emitLoadStoreSymbol(Inst, RISCV::SD, IDLoc, Out, /*HasTmpReg=*/true);
3599 return false;
3600 case RISCV::PseudoFSH:
3601 emitLoadStoreSymbol(Inst, RISCV::FSH, IDLoc, Out, /*HasTmpReg=*/true);
3602 return false;
3603 case RISCV::PseudoFSW:
3604 emitLoadStoreSymbol(Inst, RISCV::FSW, IDLoc, Out, /*HasTmpReg=*/true);
3605 return false;
3606 case RISCV::PseudoFSD:
3607 emitLoadStoreSymbol(Inst, RISCV::FSD, IDLoc, Out, /*HasTmpReg=*/true);
3608 return false;
3609 case RISCV::PseudoAddTPRel:
3610 if (checkPseudoAddTPRel(Inst, Operands))
3611 return true;
3612 break;
3613 case RISCV::PseudoTLSDESCCall:
3614 if (checkPseudoTLSDESCCall(Inst, Operands))
3615 return true;
3616 break;
3617 case RISCV::PseudoSEXT_B:
3618 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/8, IDLoc, Out);
3619 return false;
3620 case RISCV::PseudoSEXT_H:
3621 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/16, IDLoc, Out);
3622 return false;
3623 case RISCV::PseudoZEXT_H:
3624 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/16, IDLoc, Out);
3625 return false;
3626 case RISCV::PseudoZEXT_W:
3627 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/32, IDLoc, Out);
3628 return false;
3629 case RISCV::PseudoVMSGEU_VX:
3630 case RISCV::PseudoVMSGEU_VX_M:
3631 case RISCV::PseudoVMSGEU_VX_M_T:
3632 emitVMSGE(Inst, RISCV::VMSLTU_VX, IDLoc, Out);
3633 return false;
3634 case RISCV::PseudoVMSGE_VX:
3635 case RISCV::PseudoVMSGE_VX_M:
3636 case RISCV::PseudoVMSGE_VX_M_T:
3637 emitVMSGE(Inst, RISCV::VMSLT_VX, IDLoc, Out);
3638 return false;
3639 case RISCV::PseudoVMSGE_VI:
3640 case RISCV::PseudoVMSLT_VI: {
3641 // These instructions are signed and so is immediate so we can subtract one
3642 // and change the opcode.
3643 int64_t Imm = Inst.getOperand(2).getImm();
3644 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGE_VI ? RISCV::VMSGT_VI
3645 : RISCV::VMSLE_VI;
3646 emitToStreamer(Out, MCInstBuilder(Opc)
3647 .addOperand(Inst.getOperand(0))
3648 .addOperand(Inst.getOperand(1))
3649 .addImm(Imm - 1)
3650 .addOperand(Inst.getOperand(3))
3651 .setLoc(IDLoc));
3652 return false;
3653 }
3654 case RISCV::PseudoVMSGEU_VI:
3655 case RISCV::PseudoVMSLTU_VI: {
3656 int64_t Imm = Inst.getOperand(2).getImm();
3657 // Unsigned comparisons are tricky because the immediate is signed. If the
3658 // immediate is 0 we can't just subtract one. vmsltu.vi v0, v1, 0 is always
3659 // false, but vmsle.vi v0, v1, -1 is always true. Instead we use
3660 // vmsne v0, v1, v1 which is always false.
3661 if (Imm == 0) {
3662 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
3663 ? RISCV::VMSEQ_VV
3664 : RISCV::VMSNE_VV;
3665 emitToStreamer(Out, MCInstBuilder(Opc)
3666 .addOperand(Inst.getOperand(0))
3667 .addOperand(Inst.getOperand(1))
3668 .addOperand(Inst.getOperand(1))
3669 .addOperand(Inst.getOperand(3))
3670 .setLoc(IDLoc));
3671 } else {
3672 // Other immediate values can subtract one like signed.
3673 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
3674 ? RISCV::VMSGTU_VI
3675 : RISCV::VMSLEU_VI;
3676 emitToStreamer(Out, MCInstBuilder(Opc)
3677 .addOperand(Inst.getOperand(0))
3678 .addOperand(Inst.getOperand(1))
3679 .addImm(Imm - 1)
3680 .addOperand(Inst.getOperand(3))
3681 .setLoc(IDLoc));
3682 }
3683
3684 return false;
3685 }
3686 }
3687
3688 emitToStreamer(Out, Inst);
3689 return false;
3690}
3691
3695}
static MCRegister MatchRegisterName(StringRef Name)
static const char * getSubtargetFeatureName(uint64_t Val)
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
static bool isNot(const MachineRegisterInfo &MRI, const MachineInstr &MI)
static MCRegister MatchRegisterAltName(StringRef Name)
Maps from the set of all alternative registernames to a register number.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
static bool matchRegisterNameHelper(const MCSubtargetInfo &STI, MCRegister &Reg, StringRef Name)
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:135
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::string Name
Symbol * Sym
Definition: ELF_riscv.cpp:479
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
#define check(cond)
#define RegName(no)
static LVOptions Options
Definition: LVOptions.cpp:25
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
unsigned Reg
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
PowerPC TLS Dynamic Call Fixup
bool isValidInsnFormat(StringRef Format, bool AllowC)
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVAsmParser()
static MCRegister convertFPR64ToFPR32(MCRegister Reg)
static cl::opt< bool > AddBuildAttributes("riscv-add-build-attributes", cl::init(false))
static MCRegister convertFPR64ToFPR16(MCRegister Reg)
static MCRegister convertVRToVRMx(const MCRegisterInfo &RI, MCRegister Reg, unsigned Kind)
static bool isDigit(const char C)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isImm(const MachineOperand &MO, MachineRegisterInfo *MRI)
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file implements the SmallBitVector class.
This file defines the SmallVector class.
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:167
This file contains some functions that are useful when dealing with strings.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition: Value.cpp:469
bool parseImmediate(MCInst &MI, uint64_t &Size, ArrayRef< uint8_t > Bytes)
Class for arbitrary precision integers.
Definition: APInt.h:76
Target independent representation for an assembler token.
Definition: MCAsmMacro.h:21
SMLoc getLoc() const
Definition: MCAsmLexer.cpp:26
int64_t getIntVal() const
Definition: MCAsmMacro.h:115
bool isNot(TokenKind K) const
Definition: MCAsmMacro.h:83
StringRef getString() const
Get the string for the current token, this includes all characters (for example, the quotes on string...
Definition: MCAsmMacro.h:110
StringRef getStringContents() const
Get the contents of a string token (without quotes).
Definition: MCAsmMacro.h:90
bool is(TokenKind K) const
Definition: MCAsmMacro.h:82
SMLoc getEndLoc() const
Definition: MCAsmLexer.cpp:30
StringRef getIdentifier() const
Get the identifier string for the current token, which should be an identifier or a string.
Definition: MCAsmMacro.h:99
This class represents an Operation in the Expression.
Encoding
Size and signedness of expression operations' operands.
Base class for user error types.
Definition: Error.h:352
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Container class for subtarget features.
constexpr size_t size() const
virtual void Initialize(MCAsmParser &Parser)
Initialize the extension for parsing using the given Parser.
Generic assembler parser interface, for use by target specific assembly parsers.
Definition: MCAsmParser.h:123
virtual void eatToEndOfStatement()=0
Skip to the end of the current statement, for error recovery.
virtual MCStreamer & getStreamer()=0
Return the output streamer for the assembler.
virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc)=0
Parse an arbitrary expression.
const AsmToken & getTok() const
Get the current AsmToken from the stream.
Definition: MCAsmParser.cpp:40
virtual bool parseIdentifier(StringRef &Res)=0
Parse an identifier or string (as a quoted identifier) and set Res to the identifier contents.
virtual const AsmToken & Lex()=0
Get the next AsmToken in the stream, possibly handling file inclusion first.
virtual void addAliasForDirective(StringRef Directive, StringRef Alias)=0
virtual MCContext & getContext()=0
static const MCBinaryExpr * create(Opcode Op, const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition: MCExpr.cpp:183
@ Sub
Subtraction.
Definition: MCExpr.h:517
@ Add
Addition.
Definition: MCExpr.h:495
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:194
Context object for machine code objects.
Definition: MCContext.h:76
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:450
MCSymbol * createNamedTempSymbol()
Create a temporary symbol with a unique name whose name cannot be omitted in the symbol table.
Definition: MCContext.cpp:323
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
bool evaluateAsRelocatable(MCValue &Res, const MCAsmLayout *Layout, const MCFixup *Fixup) const
Try to evaluate the expression to a relocatable value, i.e.
Definition: MCExpr.cpp:814
ExprKind getKind() const
Definition: MCExpr.h:81
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:71
MCInstBuilder & addReg(unsigned Reg)
Add a new register operand.
Definition: MCInstBuilder.h:37
MCInstBuilder & addImm(int64_t Val)
Add a new integer immediate operand.
Definition: MCInstBuilder.h:43
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
unsigned getNumOperands() const
Definition: MCInst.h:208
void setLoc(SMLoc loc)
Definition: MCInst.h:203
unsigned getOpcode() const
Definition: MCInst.h:198
void addOperand(const MCOperand Op)
Definition: MCInst.h:210
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:206
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:198
ArrayRef< MCOperandInfo > operands() const
Definition: MCInstrDesc.h:239
unsigned short NumOperands
Definition: MCInstrDesc.h:206
int getOperandConstraint(unsigned OpNum, MCOI::OperandConstraint Constraint) const
Returns the value of the specified operand constraint if it is present.
Definition: MCInstrDesc.h:219
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:26
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition: MCInstrInfo.h:63
bool isPositionIndependent() const
Instances of this class represent operands of the MCInst class.
Definition: MCInst.h:36
static MCOperand createReg(unsigned Reg)
Definition: MCInst.h:134
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:162
int64_t getImm() const
Definition: MCInst.h:80
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:141
unsigned getReg() const
Returns the register number.
Definition: MCInst.h:69
bool isReg() const
Definition: MCInst.h:61
const MCExpr * getExpr() const
Definition: MCInst.h:114
bool isExpr() const
Definition: MCInst.h:65
MCParsedAsmOperand - This abstract class represents a source-level assembly instruction operand.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
MCRegister getMatchingSuperReg(MCRegister Reg, unsigned SubIdx, const MCRegisterClass *RC) const
Return a super-register of the specified register Reg so its sub-register of index SubIdx is Reg.
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
Streaming machine code generation interface.
Definition: MCStreamer.h:212
virtual void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:424
MCTargetStreamer * getTargetStreamer()
Definition: MCStreamer.h:304
Generic base class for all target subtargets.
bool hasFeature(unsigned Feature) const
void setFeatureBits(const FeatureBitset &FeatureBits_)
const Triple & getTargetTriple() const
const FeatureBitset & getFeatureBits() 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)
Definition: MCExpr.h:397
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:40
MCTargetAsmParser - Generic interface to target specific assembly parsers.
virtual ParseStatus parseDirective(AsmToken DirectiveID)
Parses a target-specific assembler directive.
MCSubtargetInfo & copySTI()
Create a copy of STI and return a non-const reference to it.
virtual bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc)=0
virtual ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc)=0
tryParseRegister - parse one register if possible
void setAvailableFeatures(const FeatureBitset &Value)
const MCSubtargetInfo & getSTI() const
virtual unsigned validateTargetOperandClass(MCParsedAsmOperand &Op, unsigned Kind)
Allow a target to add special case operand matching for things that tblgen doesn't/can't handle effec...
virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc, OperandVector &Operands)=0
ParseInstruction - Parse one assembly instruction.
virtual unsigned checkTargetMatchPredicate(MCInst &Inst)
checkTargetMatchPredicate - Validate the instruction match against any complex target predicates not ...
virtual bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, OperandVector &Operands, MCStreamer &Out, uint64_t &ErrorInfo, bool MatchingInlineAsm)=0
MatchAndEmitInstruction - Recognize a series of operands of a parsed instruction as an actual MCInst ...
Target specific streamer interface.
Definition: MCStreamer.h:93
This represents an "assembler immediate".
Definition: MCValue.h:36
uint32_t getRefKind() const
Definition: MCValue.h:46
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:45
const MCSymbolRefExpr * getSymA() const
Definition: MCValue.h:44
Ternary parse status returned by various parse* methods.
static constexpr StatusTy Failure
static constexpr StatusTy Success
static constexpr StatusTy NoMatch
static bool isSupportedExtensionFeature(StringRef Ext)
static bool isSupportedExtension(StringRef Ext)
static llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseArchString(StringRef Arch, bool EnableExperimentalExtension, bool ExperimentalExtensionVersionCheck=true, bool IgnoreUnknown=false)
Parse RISC-V ISA info from arch string.
static const char * getRegisterName(MCRegister Reg)
static const RISCVMCExpr * create(const MCExpr *Expr, VariantKind Kind, MCContext &Ctx)
Definition: RISCVMCExpr.cpp:31
static VariantKind getVariantKindForName(StringRef name)
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
Represents a location in source code.
Definition: SMLoc.h:23
static SMLoc getFromPointer(const char *Ptr)
Definition: SMLoc.h:36
constexpr const char * getPointer() const
Definition: SMLoc.h:34
Represents a range in source code.
Definition: SMLoc.h:48
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
This class wraps a string in an Error.
Definition: Error.h:1235
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
char back() const
back - Get the last character in the string.
Definition: StringRef.h:146
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
R Default(T Value)
Definition: StringSwitch.h:182
StringSwitch & Cases(StringLiteral S0, StringLiteral S1, T Value)
Definition: StringSwitch.h:90
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:660
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
const CustomOperand< const MCSubtargetInfo & > Msg[]
uint16_t StackAdjustment(const RuntimeFunction &RF)
StackAdjustment - calculated stack adjustment in words.
Definition: ARMWinEH.h:199
std::optional< unsigned > attrTypeFromString(StringRef tag, TagNameMap tagNameMap)
ABI computeTargetABI(const Triple &TT, const FeatureBitset &FeatureBits, StringRef ABIName)
const TagNameMap & getRISCVAttributeTags()
static RoundingMode stringToRoundingMode(StringRef Str)
llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseFeatureBits(bool IsRV64, const FeatureBitset &FeatureBits)
int getLoadFPImm(APFloat FPImm)
getLoadFPImm - Return a 5-bit binary encoding of the floating-point immediate value.
InstSeq generateInstSeq(int64_t Val, const MCSubtargetInfo &STI)
bool compress(MCInst &OutInst, const MCInst &MI, const MCSubtargetInfo &STI)
static bool isValidLMUL(unsigned LMUL, bool Fractional)
static RISCVII::VLMUL encodeLMUL(unsigned LMUL, bool Fractional)
static bool isValidSEW(unsigned SEW)
void printVType(unsigned VType, raw_ostream &OS)
unsigned encodeVTYPE(RISCVII::VLMUL VLMUL, unsigned SEW, bool TailAgnostic, bool MaskAgnostic)
unsigned encodeRlist(MCRegister EndReg, bool IsRV32E=false)
void printRlist(unsigned SlistEncode, raw_ostream &OS)
static bool getSpimm(unsigned RlistVal, unsigned &SpimmVal, int64_t StackAdjustment, bool IsRV64, bool IsEABI)
void printSpimm(int64_t Spimm, raw_ostream &OS)
@ CE
Windows NT (Windows on ARM)
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
Format
The format used for serializing/deserializing remarks.
Definition: RemarkFormat.h:25
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
Definition: Error.h:1071
@ Offset
Definition: DWP.cpp:456
@ Length
Definition: DWP.cpp:456
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:228
static bool isMem(const MachineInstr &MI, unsigned Op)
Definition: X86InstrInfo.h:152
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:970
Target & getTheRISCV32Target()
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1963
DWARFExpression::Operation Op
Target & getTheRISCV64Target()
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition: MathExtras.h:166
const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures]
#define N
RegisterMCAsmParser - Helper template for registering a target specific assembly parser,...
Used to provide key value pairs for feature and CPU bit flags.