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::FeatureStdExtE); }
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(const AsmToken &Tok, 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 parseZcmpStackAdj(OperandVector &Operands,
217 bool ExpectNegative = false);
218 ParseStatus parseZcmpNegStackAdj(OperandVector &Operands) {
219 return parseZcmpStackAdj(Operands, /*ExpectNegative*/ true);
220 }
221
222 bool parseOperand(OperandVector &Operands, StringRef Mnemonic);
223
224 bool parseDirectiveOption();
225 bool parseDirectiveAttribute();
226 bool parseDirectiveInsn(SMLoc L);
227 bool parseDirectiveVariantCC();
228
229 /// Helper to reset target features for a new arch string. It
230 /// also records the new arch string that is expanded by RISCVISAInfo
231 /// and reports error for invalid arch string.
232 bool resetToArch(StringRef Arch, SMLoc Loc, std::string &Result,
233 bool FromOptionDirective);
234
235 void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
236 if (!(getSTI().hasFeature(Feature))) {
237 MCSubtargetInfo &STI = copySTI();
239 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
240 }
241 }
242
243 void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
244 if (getSTI().hasFeature(Feature)) {
245 MCSubtargetInfo &STI = copySTI();
247 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
248 }
249 }
250
251 void pushFeatureBits() {
252 assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
253 "These two stacks must be kept synchronized");
254 FeatureBitStack.push_back(getSTI().getFeatureBits());
255 ParserOptionsStack.push_back(ParserOptions);
256 }
257
258 bool popFeatureBits() {
259 assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
260 "These two stacks must be kept synchronized");
261 if (FeatureBitStack.empty())
262 return true;
263
264 FeatureBitset FeatureBits = FeatureBitStack.pop_back_val();
265 copySTI().setFeatureBits(FeatureBits);
266 setAvailableFeatures(ComputeAvailableFeatures(FeatureBits));
267
268 ParserOptions = ParserOptionsStack.pop_back_val();
269
270 return false;
271 }
272
273 std::unique_ptr<RISCVOperand> defaultMaskRegOp() const;
274 std::unique_ptr<RISCVOperand> defaultFRMArgOp() const;
275 std::unique_ptr<RISCVOperand> defaultFRMArgLegacyOp() const;
276
277public:
278 enum RISCVMatchResultTy {
279 Match_Dummy = FIRST_TARGET_MATCH_RESULT_TY,
280 Match_RequiresEvenGPRs,
281#define GET_OPERAND_DIAGNOSTIC_TYPES
282#include "RISCVGenAsmMatcher.inc"
283#undef GET_OPERAND_DIAGNOSTIC_TYPES
284 };
285
286 static bool classifySymbolRef(const MCExpr *Expr,
288 static bool isSymbolDiff(const MCExpr *Expr);
289
290 RISCVAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
291 const MCInstrInfo &MII, const MCTargetOptions &Options)
292 : MCTargetAsmParser(Options, STI, MII) {
294
295 Parser.addAliasForDirective(".half", ".2byte");
296 Parser.addAliasForDirective(".hword", ".2byte");
297 Parser.addAliasForDirective(".word", ".4byte");
298 Parser.addAliasForDirective(".dword", ".8byte");
299 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
300
301 auto ABIName = StringRef(Options.ABIName);
302 if (ABIName.ends_with("f") && !getSTI().hasFeature(RISCV::FeatureStdExtF)) {
303 errs() << "Hard-float 'f' ABI can't be used for a target that "
304 "doesn't support the F instruction set extension (ignoring "
305 "target-abi)\n";
306 } else if (ABIName.ends_with("d") &&
307 !getSTI().hasFeature(RISCV::FeatureStdExtD)) {
308 errs() << "Hard-float 'd' ABI can't be used for a target that "
309 "doesn't support the D instruction set extension (ignoring "
310 "target-abi)\n";
311 }
312
313 // Use computeTargetABI to check if ABIName is valid. If invalid, output
314 // error message.
316 ABIName);
317
318 const MCObjectFileInfo *MOFI = Parser.getContext().getObjectFileInfo();
319 ParserOptions.IsPicEnabled = MOFI->isPositionIndependent();
320
322 getTargetStreamer().emitTargetAttributes(STI, /*EmitStackAlign*/ false);
323 }
324};
325
326/// RISCVOperand - Instances of this class represent a parsed machine
327/// instruction
328struct RISCVOperand final : public MCParsedAsmOperand {
329
330 enum class KindTy {
331 Token,
332 Register,
333 Immediate,
334 FPImmediate,
335 SystemRegister,
336 VType,
337 FRM,
338 Fence,
339 Rlist,
340 Spimm,
341 RegReg,
342 } Kind;
343
344 struct RegOp {
345 MCRegister RegNum;
346 bool IsGPRAsFPR;
347 };
348
349 struct ImmOp {
350 const MCExpr *Val;
351 bool IsRV64;
352 };
353
354 struct FPImmOp {
355 uint64_t Val;
356 };
357
358 struct SysRegOp {
359 const char *Data;
360 unsigned Length;
361 unsigned Encoding;
362 // FIXME: Add the Encoding parsed fields as needed for checks,
363 // e.g.: read/write or user/supervisor/machine privileges.
364 };
365
366 struct VTypeOp {
367 unsigned Val;
368 };
369
370 struct FRMOp {
372 };
373
374 struct FenceOp {
375 unsigned Val;
376 };
377
378 struct RlistOp {
379 unsigned Val;
380 };
381
382 struct SpimmOp {
383 unsigned Val;
384 };
385
386 struct RegRegOp {
387 MCRegister Reg1;
388 MCRegister Reg2;
389 };
390
391 SMLoc StartLoc, EndLoc;
392 union {
393 StringRef Tok;
394 RegOp Reg;
395 ImmOp Imm;
396 FPImmOp FPImm;
397 struct SysRegOp SysReg;
398 struct VTypeOp VType;
399 struct FRMOp FRM;
400 struct FenceOp Fence;
401 struct RlistOp Rlist;
402 struct SpimmOp Spimm;
403 struct RegRegOp RegReg;
404 };
405
406 RISCVOperand(KindTy K) : Kind(K) {}
407
408public:
409 RISCVOperand(const RISCVOperand &o) : MCParsedAsmOperand() {
410 Kind = o.Kind;
411 StartLoc = o.StartLoc;
412 EndLoc = o.EndLoc;
413 switch (Kind) {
414 case KindTy::Register:
415 Reg = o.Reg;
416 break;
417 case KindTy::Immediate:
418 Imm = o.Imm;
419 break;
420 case KindTy::FPImmediate:
421 FPImm = o.FPImm;
422 break;
423 case KindTy::Token:
424 Tok = o.Tok;
425 break;
426 case KindTy::SystemRegister:
427 SysReg = o.SysReg;
428 break;
429 case KindTy::VType:
430 VType = o.VType;
431 break;
432 case KindTy::FRM:
433 FRM = o.FRM;
434 break;
435 case KindTy::Fence:
436 Fence = o.Fence;
437 break;
438 case KindTy::Rlist:
439 Rlist = o.Rlist;
440 break;
441 case KindTy::Spimm:
442 Spimm = o.Spimm;
443 break;
444 case KindTy::RegReg:
445 RegReg = o.RegReg;
446 break;
447 }
448 }
449
450 bool isToken() const override { return Kind == KindTy::Token; }
451 bool isReg() const override { return Kind == KindTy::Register; }
452 bool isV0Reg() const {
453 return Kind == KindTy::Register && Reg.RegNum == RISCV::V0;
454 }
455 bool isAnyReg() const {
456 return Kind == KindTy::Register &&
457 (RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg.RegNum) ||
458 RISCVMCRegisterClasses[RISCV::FPR64RegClassID].contains(Reg.RegNum) ||
459 RISCVMCRegisterClasses[RISCV::VRRegClassID].contains(Reg.RegNum));
460 }
461 bool isAnyRegC() const {
462 return Kind == KindTy::Register &&
463 (RISCVMCRegisterClasses[RISCV::GPRCRegClassID].contains(
464 Reg.RegNum) ||
465 RISCVMCRegisterClasses[RISCV::FPR64CRegClassID].contains(
466 Reg.RegNum));
467 }
468 bool isImm() const override { return Kind == KindTy::Immediate; }
469 bool isMem() const override { return false; }
470 bool isSystemRegister() const { return Kind == KindTy::SystemRegister; }
471 bool isRegReg() const { return Kind == KindTy::RegReg; }
472 bool isRlist() const { return Kind == KindTy::Rlist; }
473 bool isSpimm() const { return Kind == KindTy::Spimm; }
474
475 bool isGPR() const {
476 return Kind == KindTy::Register &&
477 RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg.RegNum);
478 }
479
480 bool isGPRAsFPR() const { return isGPR() && Reg.IsGPRAsFPR; }
481
482 bool isGPRPair() const {
483 return Kind == KindTy::Register &&
484 RISCVMCRegisterClasses[RISCV::GPRPairRegClassID].contains(
485 Reg.RegNum);
486 }
487
488 static bool evaluateConstantImm(const MCExpr *Expr, int64_t &Imm,
490 if (auto *RE = dyn_cast<RISCVMCExpr>(Expr)) {
491 VK = RE->getKind();
492 return RE->evaluateAsConstant(Imm);
493 }
494
495 if (auto CE = dyn_cast<MCConstantExpr>(Expr)) {
497 Imm = CE->getValue();
498 return true;
499 }
500
501 return false;
502 }
503
504 // True if operand is a symbol with no modifiers, or a constant with no
505 // modifiers and isShiftedInt<N-1, 1>(Op).
506 template <int N> bool isBareSimmNLsb0() const {
507 int64_t Imm;
509 if (!isImm())
510 return false;
511 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
512 bool IsValid;
513 if (!IsConstantImm)
514 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
515 else
516 IsValid = isShiftedInt<N - 1, 1>(Imm);
517 return IsValid && VK == RISCVMCExpr::VK_RISCV_None;
518 }
519
520 // Predicate methods for AsmOperands defined in RISCVInstrInfo.td
521
522 bool isBareSymbol() const {
523 int64_t Imm;
525 // Must be of 'immediate' type but not a constant.
526 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
527 return false;
528 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
530 }
531
532 bool isCallSymbol() const {
533 int64_t Imm;
535 // Must be of 'immediate' type but not a constant.
536 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
537 return false;
538 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
541 }
542
543 bool isPseudoJumpSymbol() const {
544 int64_t Imm;
546 // Must be of 'immediate' type but not a constant.
547 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
548 return false;
549 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
551 }
552
553 bool isTPRelAddSymbol() const {
554 int64_t Imm;
556 // Must be of 'immediate' type but not a constant.
557 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
558 return false;
559 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
561 }
562
563 bool isTLSDESCCallSymbol() const {
564 int64_t Imm;
566 // Must be of 'immediate' type but not a constant.
567 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
568 return false;
569 return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
571 }
572
573 bool isCSRSystemRegister() const { return isSystemRegister(); }
574
575 bool isVTypeImm(unsigned N) const {
576 int64_t Imm;
578 if (!isImm())
579 return false;
580 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
581 return IsConstantImm && isUIntN(N, Imm) && VK == RISCVMCExpr::VK_RISCV_None;
582 }
583
584 // If the last operand of the vsetvli/vsetvli instruction is a constant
585 // expression, KindTy is Immediate.
586 bool isVTypeI10() const {
587 if (Kind == KindTy::Immediate)
588 return isVTypeImm(10);
589 return Kind == KindTy::VType;
590 }
591 bool isVTypeI11() const {
592 if (Kind == KindTy::Immediate)
593 return isVTypeImm(11);
594 return Kind == KindTy::VType;
595 }
596
597 /// Return true if the operand is a valid for the fence instruction e.g.
598 /// ('iorw').
599 bool isFenceArg() const { return Kind == KindTy::Fence; }
600
601 /// Return true if the operand is a valid floating point rounding mode.
602 bool isFRMArg() const { return Kind == KindTy::FRM; }
603 bool isFRMArgLegacy() const { return Kind == KindTy::FRM; }
604 bool isRTZArg() const { return isFRMArg() && FRM.FRM == RISCVFPRndMode::RTZ; }
605
606 /// Return true if the operand is a valid fli.s floating-point immediate.
607 bool isLoadFPImm() const {
608 if (isImm())
609 return isUImm5();
610 if (Kind != KindTy::FPImmediate)
611 return false;
613 APFloat(APFloat::IEEEdouble(), APInt(64, getFPConst())));
614 // Don't allow decimal version of the minimum value. It is a different value
615 // for each supported data type.
616 return Idx >= 0 && Idx != 1;
617 }
618
619 bool isImmXLenLI() const {
620 int64_t Imm;
622 if (!isImm())
623 return false;
624 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
625 if (VK == RISCVMCExpr::VK_RISCV_LO ||
629 return true;
630 // Given only Imm, ensuring that the actually specified constant is either
631 // a signed or unsigned 64-bit number is unfortunately impossible.
632 if (IsConstantImm) {
633 return VK == RISCVMCExpr::VK_RISCV_None &&
634 (isRV64Imm() || (isInt<32>(Imm) || isUInt<32>(Imm)));
635 }
636
637 return RISCVAsmParser::isSymbolDiff(getImm());
638 }
639
640 bool isImmXLenLI_Restricted() const {
641 int64_t Imm;
643 if (!isImm())
644 return false;
645 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
646 // 'la imm' supports constant immediates only.
647 return IsConstantImm && (VK == RISCVMCExpr::VK_RISCV_None) &&
648 (isRV64Imm() || (isInt<32>(Imm) || isUInt<32>(Imm)));
649 }
650
651 bool isUImmLog2XLen() const {
652 int64_t Imm;
654 if (!isImm())
655 return false;
656 if (!evaluateConstantImm(getImm(), Imm, VK) ||
658 return false;
659 return (isRV64Imm() && isUInt<6>(Imm)) || isUInt<5>(Imm);
660 }
661
662 bool isUImmLog2XLenNonZero() const {
663 int64_t Imm;
665 if (!isImm())
666 return false;
667 if (!evaluateConstantImm(getImm(), Imm, VK) ||
669 return false;
670 if (Imm == 0)
671 return false;
672 return (isRV64Imm() && isUInt<6>(Imm)) || isUInt<5>(Imm);
673 }
674
675 bool isUImmLog2XLenHalf() const {
676 int64_t Imm;
678 if (!isImm())
679 return false;
680 if (!evaluateConstantImm(getImm(), Imm, VK) ||
682 return false;
683 return (isRV64Imm() && isUInt<5>(Imm)) || isUInt<4>(Imm);
684 }
685
686 template <unsigned N> bool IsUImm() const {
687 int64_t Imm;
689 if (!isImm())
690 return false;
691 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
692 return IsConstantImm && isUInt<N>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
693 }
694
695 bool isUImm1() const { return IsUImm<1>(); }
696 bool isUImm2() const { return IsUImm<2>(); }
697 bool isUImm3() const { return IsUImm<3>(); }
698 bool isUImm4() const { return IsUImm<4>(); }
699 bool isUImm5() const { return IsUImm<5>(); }
700 bool isUImm6() const { return IsUImm<6>(); }
701 bool isUImm7() const { return IsUImm<7>(); }
702 bool isUImm8() const { return IsUImm<8>(); }
703 bool isUImm20() const { return IsUImm<20>(); }
704
705 bool isUImm8GE32() const {
706 int64_t Imm;
708 if (!isImm())
709 return false;
710 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
711 return IsConstantImm && isUInt<8>(Imm) && Imm >= 32 &&
713 }
714
715 bool isRnumArg() const {
716 int64_t Imm;
718 if (!isImm())
719 return false;
720 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
721 return IsConstantImm && Imm >= INT64_C(0) && Imm <= INT64_C(10) &&
723 }
724
725 bool isRnumArg_0_7() const {
726 int64_t Imm;
728 if (!isImm())
729 return false;
730 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
731 return IsConstantImm && Imm >= INT64_C(0) && Imm <= INT64_C(7) &&
733 }
734
735 bool isRnumArg_1_10() const {
736 int64_t Imm;
738 if (!isImm())
739 return false;
740 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
741 return IsConstantImm && Imm >= INT64_C(1) && Imm <= INT64_C(10) &&
743 }
744
745 bool isRnumArg_2_14() const {
746 int64_t Imm;
748 if (!isImm())
749 return false;
750 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
751 return IsConstantImm && Imm >= INT64_C(2) && Imm <= INT64_C(14) &&
753 }
754
755 bool isSImm5() const {
756 if (!isImm())
757 return false;
759 int64_t Imm;
760 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
761 return IsConstantImm && isInt<5>(fixImmediateForRV32(Imm, isRV64Imm())) &&
763 }
764
765 bool isSImm6() const {
766 if (!isImm())
767 return false;
769 int64_t Imm;
770 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
771 return IsConstantImm && isInt<6>(fixImmediateForRV32(Imm, isRV64Imm())) &&
773 }
774
775 bool isSImm6NonZero() const {
776 if (!isImm())
777 return false;
779 int64_t Imm;
780 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
781 return IsConstantImm && Imm != 0 &&
782 isInt<6>(fixImmediateForRV32(Imm, isRV64Imm())) &&
784 }
785
786 bool isCLUIImm() const {
787 if (!isImm())
788 return false;
789 int64_t Imm;
791 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
792 return IsConstantImm && (Imm != 0) &&
793 (isUInt<5>(Imm) || (Imm >= 0xfffe0 && Imm <= 0xfffff)) &&
795 }
796
797 bool isUImm2Lsb0() const {
798 if (!isImm())
799 return false;
800 int64_t Imm;
802 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
803 return IsConstantImm && isShiftedUInt<1, 1>(Imm) &&
805 }
806
807 bool isUImm7Lsb00() const {
808 if (!isImm())
809 return false;
810 int64_t Imm;
812 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
813 return IsConstantImm && isShiftedUInt<5, 2>(Imm) &&
815 }
816
817 bool isUImm8Lsb00() const {
818 if (!isImm())
819 return false;
820 int64_t Imm;
822 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
823 return IsConstantImm && isShiftedUInt<6, 2>(Imm) &&
825 }
826
827 bool isUImm8Lsb000() const {
828 if (!isImm())
829 return false;
830 int64_t Imm;
832 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
833 return IsConstantImm && isShiftedUInt<5, 3>(Imm) &&
835 }
836
837 bool isSImm9Lsb0() const { return isBareSimmNLsb0<9>(); }
838
839 bool isUImm9Lsb000() const {
840 if (!isImm())
841 return false;
842 int64_t Imm;
844 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
845 return IsConstantImm && isShiftedUInt<6, 3>(Imm) &&
847 }
848
849 bool isUImm10Lsb00NonZero() const {
850 if (!isImm())
851 return false;
852 int64_t Imm;
854 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
855 return IsConstantImm && isShiftedUInt<8, 2>(Imm) && (Imm != 0) &&
857 }
858
859 // If this a RV32 and the immediate is a uimm32, sign extend it to 32 bits.
860 // This allows writing 'addi a0, a0, 0xffffffff'.
861 static int64_t fixImmediateForRV32(int64_t Imm, bool IsRV64Imm) {
862 if (IsRV64Imm || !isUInt<32>(Imm))
863 return Imm;
864 return SignExtend64<32>(Imm);
865 }
866
867 bool isSImm12() const {
869 int64_t Imm;
870 bool IsValid;
871 if (!isImm())
872 return false;
873 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
874 if (!IsConstantImm)
875 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
876 else
877 IsValid = isInt<12>(fixImmediateForRV32(Imm, isRV64Imm()));
878 return IsValid && ((IsConstantImm && VK == RISCVMCExpr::VK_RISCV_None) ||
884 }
885
886 bool isSImm12Lsb0() const { return isBareSimmNLsb0<12>(); }
887
888 bool isSImm12Lsb00000() const {
889 if (!isImm())
890 return false;
892 int64_t Imm;
893 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
894 return IsConstantImm && isShiftedInt<7, 5>(Imm) &&
896 }
897
898 bool isSImm13Lsb0() const { return isBareSimmNLsb0<13>(); }
899
900 bool isSImm10Lsb0000NonZero() const {
901 if (!isImm())
902 return false;
903 int64_t Imm;
905 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
906 return IsConstantImm && (Imm != 0) && isShiftedInt<6, 4>(Imm) &&
908 }
909
910 bool isUImm20LUI() const {
912 int64_t Imm;
913 bool IsValid;
914 if (!isImm())
915 return false;
916 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
917 if (!IsConstantImm) {
918 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
919 return IsValid && (VK == RISCVMCExpr::VK_RISCV_HI ||
921 } else {
922 return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
925 }
926 }
927
928 bool isUImm20AUIPC() const {
930 int64_t Imm;
931 bool IsValid;
932 if (!isImm())
933 return false;
934 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
935 if (!IsConstantImm) {
936 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
937 return IsValid && (VK == RISCVMCExpr::VK_RISCV_PCREL_HI ||
942 }
943
944 return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
950 }
951
952 bool isSImm21Lsb0JAL() const { return isBareSimmNLsb0<21>(); }
953
954 bool isImmZero() const {
955 if (!isImm())
956 return false;
957 int64_t Imm;
959 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
960 return IsConstantImm && (Imm == 0) && VK == RISCVMCExpr::VK_RISCV_None;
961 }
962
963 bool isSImm5Plus1() const {
964 if (!isImm())
965 return false;
967 int64_t Imm;
968 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
969 return IsConstantImm &&
970 isInt<5>(fixImmediateForRV32(Imm, isRV64Imm()) - 1) &&
972 }
973
974 /// getStartLoc - Gets location of the first token of this operand
975 SMLoc getStartLoc() const override { return StartLoc; }
976 /// getEndLoc - Gets location of the last token of this operand
977 SMLoc getEndLoc() const override { return EndLoc; }
978 /// True if this operand is for an RV64 instruction
979 bool isRV64Imm() const {
980 assert(Kind == KindTy::Immediate && "Invalid type access!");
981 return Imm.IsRV64;
982 }
983
984 MCRegister getReg() const override {
985 assert(Kind == KindTy::Register && "Invalid type access!");
986 return Reg.RegNum;
987 }
988
989 StringRef getSysReg() const {
990 assert(Kind == KindTy::SystemRegister && "Invalid type access!");
991 return StringRef(SysReg.Data, SysReg.Length);
992 }
993
994 const MCExpr *getImm() const {
995 assert(Kind == KindTy::Immediate && "Invalid type access!");
996 return Imm.Val;
997 }
998
999 uint64_t getFPConst() const {
1000 assert(Kind == KindTy::FPImmediate && "Invalid type access!");
1001 return FPImm.Val;
1002 }
1003
1004 StringRef getToken() const {
1005 assert(Kind == KindTy::Token && "Invalid type access!");
1006 return Tok;
1007 }
1008
1009 unsigned getVType() const {
1010 assert(Kind == KindTy::VType && "Invalid type access!");
1011 return VType.Val;
1012 }
1013
1014 RISCVFPRndMode::RoundingMode getFRM() const {
1015 assert(Kind == KindTy::FRM && "Invalid type access!");
1016 return FRM.FRM;
1017 }
1018
1019 unsigned getFence() const {
1020 assert(Kind == KindTy::Fence && "Invalid type access!");
1021 return Fence.Val;
1022 }
1023
1024 void print(raw_ostream &OS) const override {
1025 auto RegName = [](MCRegister Reg) {
1026 if (Reg)
1028 else
1029 return "noreg";
1030 };
1031
1032 switch (Kind) {
1033 case KindTy::Immediate:
1034 OS << *getImm();
1035 break;
1036 case KindTy::FPImmediate:
1037 break;
1038 case KindTy::Register:
1039 OS << "<register " << RegName(getReg()) << ">";
1040 break;
1041 case KindTy::Token:
1042 OS << "'" << getToken() << "'";
1043 break;
1044 case KindTy::SystemRegister:
1045 OS << "<sysreg: " << getSysReg() << '>';
1046 break;
1047 case KindTy::VType:
1048 OS << "<vtype: ";
1049 RISCVVType::printVType(getVType(), OS);
1050 OS << '>';
1051 break;
1052 case KindTy::FRM:
1053 OS << "<frm: ";
1054 roundingModeToString(getFRM());
1055 OS << '>';
1056 break;
1057 case KindTy::Fence:
1058 OS << "<fence: ";
1059 OS << getFence();
1060 OS << '>';
1061 break;
1062 case KindTy::Rlist:
1063 OS << "<rlist: ";
1064 RISCVZC::printRlist(Rlist.Val, OS);
1065 OS << '>';
1066 break;
1067 case KindTy::Spimm:
1068 OS << "<Spimm: ";
1069 OS << Spimm.Val;
1070 OS << '>';
1071 break;
1072 case KindTy::RegReg:
1073 OS << "<RegReg: Reg1 " << RegName(RegReg.Reg1);
1074 OS << " Reg2 " << RegName(RegReg.Reg2);
1075 break;
1076 }
1077 }
1078
1079 static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S) {
1080 auto Op = std::make_unique<RISCVOperand>(KindTy::Token);
1081 Op->Tok = Str;
1082 Op->StartLoc = S;
1083 Op->EndLoc = S;
1084 return Op;
1085 }
1086
1087 static std::unique_ptr<RISCVOperand>
1088 createReg(unsigned RegNo, SMLoc S, SMLoc E, bool IsGPRAsFPR = false) {
1089 auto Op = std::make_unique<RISCVOperand>(KindTy::Register);
1090 Op->Reg.RegNum = RegNo;
1091 Op->Reg.IsGPRAsFPR = IsGPRAsFPR;
1092 Op->StartLoc = S;
1093 Op->EndLoc = E;
1094 return Op;
1095 }
1096
1097 static std::unique_ptr<RISCVOperand> createImm(const MCExpr *Val, SMLoc S,
1098 SMLoc E, bool IsRV64) {
1099 auto Op = std::make_unique<RISCVOperand>(KindTy::Immediate);
1100 Op->Imm.Val = Val;
1101 Op->Imm.IsRV64 = IsRV64;
1102 Op->StartLoc = S;
1103 Op->EndLoc = E;
1104 return Op;
1105 }
1106
1107 static std::unique_ptr<RISCVOperand> createFPImm(uint64_t Val, SMLoc S) {
1108 auto Op = std::make_unique<RISCVOperand>(KindTy::FPImmediate);
1109 Op->FPImm.Val = Val;
1110 Op->StartLoc = S;
1111 Op->EndLoc = S;
1112 return Op;
1113 }
1114
1115 static std::unique_ptr<RISCVOperand> createSysReg(StringRef Str, SMLoc S,
1116 unsigned Encoding) {
1117 auto Op = std::make_unique<RISCVOperand>(KindTy::SystemRegister);
1118 Op->SysReg.Data = Str.data();
1119 Op->SysReg.Length = Str.size();
1120 Op->SysReg.Encoding = Encoding;
1121 Op->StartLoc = S;
1122 Op->EndLoc = S;
1123 return Op;
1124 }
1125
1126 static std::unique_ptr<RISCVOperand>
1127 createFRMArg(RISCVFPRndMode::RoundingMode FRM, SMLoc S) {
1128 auto Op = std::make_unique<RISCVOperand>(KindTy::FRM);
1129 Op->FRM.FRM = FRM;
1130 Op->StartLoc = S;
1131 Op->EndLoc = S;
1132 return Op;
1133 }
1134
1135 static std::unique_ptr<RISCVOperand> createFenceArg(unsigned Val, SMLoc S) {
1136 auto Op = std::make_unique<RISCVOperand>(KindTy::Fence);
1137 Op->Fence.Val = Val;
1138 Op->StartLoc = S;
1139 Op->EndLoc = S;
1140 return Op;
1141 }
1142
1143 static std::unique_ptr<RISCVOperand> createVType(unsigned VTypeI, SMLoc S) {
1144 auto Op = std::make_unique<RISCVOperand>(KindTy::VType);
1145 Op->VType.Val = VTypeI;
1146 Op->StartLoc = S;
1147 Op->EndLoc = S;
1148 return Op;
1149 }
1150
1151 static std::unique_ptr<RISCVOperand> createRlist(unsigned RlistEncode,
1152 SMLoc S) {
1153 auto Op = std::make_unique<RISCVOperand>(KindTy::Rlist);
1154 Op->Rlist.Val = RlistEncode;
1155 Op->StartLoc = S;
1156 return Op;
1157 }
1158
1159 static std::unique_ptr<RISCVOperand> createRegReg(unsigned Reg1No,
1160 unsigned Reg2No, SMLoc S) {
1161 auto Op = std::make_unique<RISCVOperand>(KindTy::RegReg);
1162 Op->RegReg.Reg1 = Reg1No;
1163 Op->RegReg.Reg2 = Reg2No;
1164 Op->StartLoc = S;
1165 Op->EndLoc = S;
1166 return Op;
1167 }
1168
1169 static std::unique_ptr<RISCVOperand> createSpimm(unsigned Spimm, SMLoc S) {
1170 auto Op = std::make_unique<RISCVOperand>(KindTy::Spimm);
1171 Op->Spimm.Val = Spimm;
1172 Op->StartLoc = S;
1173 return Op;
1174 }
1175
1176 static void addExpr(MCInst &Inst, const MCExpr *Expr, bool IsRV64Imm) {
1177 assert(Expr && "Expr shouldn't be null!");
1178 int64_t Imm = 0;
1180 bool IsConstant = evaluateConstantImm(Expr, Imm, VK);
1181
1182 if (IsConstant)
1183 Inst.addOperand(
1184 MCOperand::createImm(fixImmediateForRV32(Imm, IsRV64Imm)));
1185 else
1187 }
1188
1189 // Used by the TableGen Code
1190 void addRegOperands(MCInst &Inst, unsigned N) const {
1191 assert(N == 1 && "Invalid number of operands!");
1193 }
1194
1195 void addImmOperands(MCInst &Inst, unsigned N) const {
1196 assert(N == 1 && "Invalid number of operands!");
1197 addExpr(Inst, getImm(), isRV64Imm());
1198 }
1199
1200 void addFPImmOperands(MCInst &Inst, unsigned N) const {
1201 assert(N == 1 && "Invalid number of operands!");
1202 if (isImm()) {
1203 addExpr(Inst, getImm(), isRV64Imm());
1204 return;
1205 }
1206
1208 APFloat(APFloat::IEEEdouble(), APInt(64, getFPConst())));
1210 }
1211
1212 void addFenceArgOperands(MCInst &Inst, unsigned N) const {
1213 assert(N == 1 && "Invalid number of operands!");
1214 Inst.addOperand(MCOperand::createImm(Fence.Val));
1215 }
1216
1217 void addCSRSystemRegisterOperands(MCInst &Inst, unsigned N) const {
1218 assert(N == 1 && "Invalid number of operands!");
1219 Inst.addOperand(MCOperand::createImm(SysReg.Encoding));
1220 }
1221
1222 // Support non-canonical syntax:
1223 // "vsetivli rd, uimm, 0xabc" or "vsetvli rd, rs1, 0xabc"
1224 // "vsetivli rd, uimm, (0xc << N)" or "vsetvli rd, rs1, (0xc << N)"
1225 void addVTypeIOperands(MCInst &Inst, unsigned N) const {
1226 assert(N == 1 && "Invalid number of operands!");
1227 int64_t Imm = 0;
1228 if (Kind == KindTy::Immediate) {
1230 [[maybe_unused]] bool IsConstantImm =
1231 evaluateConstantImm(getImm(), Imm, VK);
1232 assert(IsConstantImm && "Invalid VTypeI Operand!");
1233 } else {
1234 Imm = getVType();
1235 }
1237 }
1238
1239 void addRlistOperands(MCInst &Inst, unsigned N) const {
1240 assert(N == 1 && "Invalid number of operands!");
1241 Inst.addOperand(MCOperand::createImm(Rlist.Val));
1242 }
1243
1244 void addRegRegOperands(MCInst &Inst, unsigned N) const {
1245 assert(N == 1 && "Invalid number of operands!");
1248 }
1249
1250 void addSpimmOperands(MCInst &Inst, unsigned N) const {
1251 assert(N == 1 && "Invalid number of operands!");
1252 Inst.addOperand(MCOperand::createImm(Spimm.Val));
1253 }
1254
1255 void addFRMArgOperands(MCInst &Inst, unsigned N) const {
1256 assert(N == 1 && "Invalid number of operands!");
1257 Inst.addOperand(MCOperand::createImm(getFRM()));
1258 }
1259};
1260} // end anonymous namespace.
1261
1262#define GET_REGISTER_MATCHER
1263#define GET_SUBTARGET_FEATURE_NAME
1264#define GET_MATCHER_IMPLEMENTATION
1265#define GET_MNEMONIC_SPELL_CHECKER
1266#include "RISCVGenAsmMatcher.inc"
1267
1269 assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
1270 return Reg - RISCV::F0_D + RISCV::F0_H;
1271}
1272
1274 assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
1275 return Reg - RISCV::F0_D + RISCV::F0_F;
1276}
1277
1279 unsigned Kind) {
1280 unsigned RegClassID;
1281 if (Kind == MCK_VRM2)
1282 RegClassID = RISCV::VRM2RegClassID;
1283 else if (Kind == MCK_VRM4)
1284 RegClassID = RISCV::VRM4RegClassID;
1285 else if (Kind == MCK_VRM8)
1286 RegClassID = RISCV::VRM8RegClassID;
1287 else
1288 return 0;
1289 return RI.getMatchingSuperReg(Reg, RISCV::sub_vrm1_0,
1290 &RISCVMCRegisterClasses[RegClassID]);
1291}
1292
1293unsigned RISCVAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
1294 unsigned Kind) {
1295 RISCVOperand &Op = static_cast<RISCVOperand &>(AsmOp);
1296 if (!Op.isReg())
1297 return Match_InvalidOperand;
1298
1299 MCRegister Reg = Op.getReg();
1300 bool IsRegFPR64 =
1301 RISCVMCRegisterClasses[RISCV::FPR64RegClassID].contains(Reg);
1302 bool IsRegFPR64C =
1303 RISCVMCRegisterClasses[RISCV::FPR64CRegClassID].contains(Reg);
1304 bool IsRegVR = RISCVMCRegisterClasses[RISCV::VRRegClassID].contains(Reg);
1305
1306 // As the parser couldn't differentiate an FPR32 from an FPR64, coerce the
1307 // register from FPR64 to FPR32 or FPR64C to FPR32C if necessary.
1308 if ((IsRegFPR64 && Kind == MCK_FPR32) ||
1309 (IsRegFPR64C && Kind == MCK_FPR32C)) {
1310 Op.Reg.RegNum = convertFPR64ToFPR32(Reg);
1311 return Match_Success;
1312 }
1313 // As the parser couldn't differentiate an FPR16 from an FPR64, coerce the
1314 // register from FPR64 to FPR16 if necessary.
1315 if (IsRegFPR64 && Kind == MCK_FPR16) {
1316 Op.Reg.RegNum = convertFPR64ToFPR16(Reg);
1317 return Match_Success;
1318 }
1319 // As the parser couldn't differentiate an VRM2/VRM4/VRM8 from an VR, coerce
1320 // the register from VR to VRM2/VRM4/VRM8 if necessary.
1321 if (IsRegVR && (Kind == MCK_VRM2 || Kind == MCK_VRM4 || Kind == MCK_VRM8)) {
1322 Op.Reg.RegNum = convertVRToVRMx(*getContext().getRegisterInfo(), Reg, Kind);
1323 if (Op.Reg.RegNum == 0)
1324 return Match_InvalidOperand;
1325 return Match_Success;
1326 }
1327 return Match_InvalidOperand;
1328}
1329
1330unsigned RISCVAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
1331 const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
1332
1333 for (unsigned I = 0; I < MCID.NumOperands; ++I) {
1334 if (MCID.operands()[I].RegClass == RISCV::GPRPairRegClassID) {
1335 const auto &Op = Inst.getOperand(I);
1336 assert(Op.isReg());
1337
1338 MCRegister Reg = Op.getReg();
1339 if (RISCVMCRegisterClasses[RISCV::GPRPairRegClassID].contains(Reg))
1340 continue;
1341
1342 // FIXME: We should form a paired register during parsing/matching.
1343 if (((Reg.id() - RISCV::X0) & 1) != 0)
1344 return Match_RequiresEvenGPRs;
1345 }
1346 }
1347
1348 return Match_Success;
1349}
1350
1351bool RISCVAsmParser::generateImmOutOfRangeError(
1352 SMLoc ErrorLoc, int64_t Lower, int64_t Upper,
1353 const Twine &Msg = "immediate must be an integer in the range") {
1354 return Error(ErrorLoc, Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
1355}
1356
1357bool RISCVAsmParser::generateImmOutOfRangeError(
1358 OperandVector &Operands, uint64_t ErrorInfo, int64_t Lower, int64_t Upper,
1359 const Twine &Msg = "immediate must be an integer in the range") {
1360 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1361 return generateImmOutOfRangeError(ErrorLoc, Lower, Upper, Msg);
1362}
1363
1364bool RISCVAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1366 MCStreamer &Out,
1368 bool MatchingInlineAsm) {
1369 MCInst Inst;
1370 FeatureBitset MissingFeatures;
1371
1372 auto Result = MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,
1373 MatchingInlineAsm);
1374 switch (Result) {
1375 default:
1376 break;
1377 case Match_Success:
1378 if (validateInstruction(Inst, Operands))
1379 return true;
1380 return processInstruction(Inst, IDLoc, Operands, Out);
1381 case Match_MissingFeature: {
1382 assert(MissingFeatures.any() && "Unknown missing features!");
1383 bool FirstFeature = true;
1384 std::string Msg = "instruction requires the following:";
1385 for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i) {
1386 if (MissingFeatures[i]) {
1387 Msg += FirstFeature ? " " : ", ";
1389 FirstFeature = false;
1390 }
1391 }
1392 return Error(IDLoc, Msg);
1393 }
1394 case Match_MnemonicFail: {
1395 FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
1396 std::string Suggestion = RISCVMnemonicSpellCheck(
1397 ((RISCVOperand &)*Operands[0]).getToken(), FBS, 0);
1398 return Error(IDLoc, "unrecognized instruction mnemonic" + Suggestion);
1399 }
1400 case Match_InvalidOperand: {
1401 SMLoc ErrorLoc = IDLoc;
1402 if (ErrorInfo != ~0ULL) {
1403 if (ErrorInfo >= Operands.size())
1404 return Error(ErrorLoc, "too few operands for instruction");
1405
1406 ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1407 if (ErrorLoc == SMLoc())
1408 ErrorLoc = IDLoc;
1409 }
1410 return Error(ErrorLoc, "invalid operand for instruction");
1411 }
1412 }
1413
1414 // Handle the case when the error message is of specific type
1415 // other than the generic Match_InvalidOperand, and the
1416 // corresponding operand is missing.
1417 if (Result > FIRST_TARGET_MATCH_RESULT_TY) {
1418 SMLoc ErrorLoc = IDLoc;
1419 if (ErrorInfo != ~0ULL && ErrorInfo >= Operands.size())
1420 return Error(ErrorLoc, "too few operands for instruction");
1421 }
1422
1423 switch (Result) {
1424 default:
1425 break;
1426 case Match_RequiresEvenGPRs:
1427 return Error(IDLoc,
1428 "double precision floating point operands must use even "
1429 "numbered X register");
1430 case Match_InvalidImmXLenLI:
1431 if (isRV64()) {
1432 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1433 return Error(ErrorLoc, "operand must be a constant 64-bit integer");
1434 }
1435 return generateImmOutOfRangeError(Operands, ErrorInfo,
1436 std::numeric_limits<int32_t>::min(),
1437 std::numeric_limits<uint32_t>::max());
1438 case Match_InvalidImmXLenLI_Restricted:
1439 if (isRV64()) {
1440 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1441 return Error(ErrorLoc, "operand either must be a constant 64-bit integer "
1442 "or a bare symbol name");
1443 }
1444 return generateImmOutOfRangeError(
1445 Operands, ErrorInfo, std::numeric_limits<int32_t>::min(),
1446 std::numeric_limits<uint32_t>::max(),
1447 "operand either must be a bare symbol name or an immediate integer in "
1448 "the range");
1449 case Match_InvalidImmZero: {
1450 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1451 return Error(ErrorLoc, "immediate must be zero");
1452 }
1453 case Match_InvalidUImmLog2XLen:
1454 if (isRV64())
1455 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
1456 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1457 case Match_InvalidUImmLog2XLenNonZero:
1458 if (isRV64())
1459 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 6) - 1);
1460 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5) - 1);
1461 case Match_InvalidUImmLog2XLenHalf:
1462 if (isRV64())
1463 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1464 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 4) - 1);
1465 case Match_InvalidUImm1:
1466 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 1) - 1);
1467 case Match_InvalidUImm2:
1468 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 2) - 1);
1469 case Match_InvalidUImm2Lsb0:
1470 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, 2,
1471 "immediate must be one of");
1472 case Match_InvalidUImm3:
1473 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 3) - 1);
1474 case Match_InvalidUImm4:
1475 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 4) - 1);
1476 case Match_InvalidUImm5:
1477 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1478 case Match_InvalidUImm6:
1479 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
1480 case Match_InvalidUImm7:
1481 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 7) - 1);
1482 case Match_InvalidUImm8:
1483 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 8) - 1);
1484 case Match_InvalidUImm8GE32:
1485 return generateImmOutOfRangeError(Operands, ErrorInfo, 32, (1 << 8) - 1);
1486 case Match_InvalidSImm5:
1487 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 4),
1488 (1 << 4) - 1);
1489 case Match_InvalidSImm6:
1490 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
1491 (1 << 5) - 1);
1492 case Match_InvalidSImm6NonZero:
1493 return generateImmOutOfRangeError(
1494 Operands, ErrorInfo, -(1 << 5), (1 << 5) - 1,
1495 "immediate must be non-zero in the range");
1496 case Match_InvalidCLUIImm:
1497 return generateImmOutOfRangeError(
1498 Operands, ErrorInfo, 1, (1 << 5) - 1,
1499 "immediate must be in [0xfffe0, 0xfffff] or");
1500 case Match_InvalidUImm7Lsb00:
1501 return generateImmOutOfRangeError(
1502 Operands, ErrorInfo, 0, (1 << 7) - 4,
1503 "immediate must be a multiple of 4 bytes in the range");
1504 case Match_InvalidUImm8Lsb00:
1505 return generateImmOutOfRangeError(
1506 Operands, ErrorInfo, 0, (1 << 8) - 4,
1507 "immediate must be a multiple of 4 bytes in the range");
1508 case Match_InvalidUImm8Lsb000:
1509 return generateImmOutOfRangeError(
1510 Operands, ErrorInfo, 0, (1 << 8) - 8,
1511 "immediate must be a multiple of 8 bytes in the range");
1512 case Match_InvalidSImm9Lsb0:
1513 return generateImmOutOfRangeError(
1514 Operands, ErrorInfo, -(1 << 8), (1 << 8) - 2,
1515 "immediate must be a multiple of 2 bytes in the range");
1516 case Match_InvalidUImm9Lsb000:
1517 return generateImmOutOfRangeError(
1518 Operands, ErrorInfo, 0, (1 << 9) - 8,
1519 "immediate must be a multiple of 8 bytes in the range");
1520 case Match_InvalidUImm10Lsb00NonZero:
1521 return generateImmOutOfRangeError(
1522 Operands, ErrorInfo, 4, (1 << 10) - 4,
1523 "immediate must be a multiple of 4 bytes in the range");
1524 case Match_InvalidSImm10Lsb0000NonZero:
1525 return generateImmOutOfRangeError(
1526 Operands, ErrorInfo, -(1 << 9), (1 << 9) - 16,
1527 "immediate must be a multiple of 16 bytes and non-zero in the range");
1528 case Match_InvalidSImm12:
1529 return generateImmOutOfRangeError(
1530 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 1,
1531 "operand must be a symbol with %lo/%pcrel_lo/%tprel_lo modifier or an "
1532 "integer in the range");
1533 case Match_InvalidSImm12Lsb0:
1534 return generateImmOutOfRangeError(
1535 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 2,
1536 "immediate must be a multiple of 2 bytes in the range");
1537 case Match_InvalidSImm12Lsb00000:
1538 return generateImmOutOfRangeError(
1539 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 32,
1540 "immediate must be a multiple of 32 bytes in the range");
1541 case Match_InvalidSImm13Lsb0:
1542 return generateImmOutOfRangeError(
1543 Operands, ErrorInfo, -(1 << 12), (1 << 12) - 2,
1544 "immediate must be a multiple of 2 bytes in the range");
1545 case Match_InvalidUImm20LUI:
1546 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1,
1547 "operand must be a symbol with "
1548 "%hi/%tprel_hi modifier or an integer in "
1549 "the range");
1550 case Match_InvalidUImm20:
1551 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1);
1552 case Match_InvalidUImm20AUIPC:
1553 return generateImmOutOfRangeError(
1554 Operands, ErrorInfo, 0, (1 << 20) - 1,
1555 "operand must be a symbol with a "
1556 "%pcrel_hi/%got_pcrel_hi/%tls_ie_pcrel_hi/%tls_gd_pcrel_hi modifier or "
1557 "an integer in the range");
1558 case Match_InvalidSImm21Lsb0JAL:
1559 return generateImmOutOfRangeError(
1560 Operands, ErrorInfo, -(1 << 20), (1 << 20) - 2,
1561 "immediate must be a multiple of 2 bytes in the range");
1562 case Match_InvalidCSRSystemRegister: {
1563 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 12) - 1,
1564 "operand must be a valid system register "
1565 "name or an integer in the range");
1566 }
1567 case Match_InvalidLoadFPImm: {
1568 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1569 return Error(ErrorLoc, "operand must be a valid floating-point constant");
1570 }
1571 case Match_InvalidBareSymbol: {
1572 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1573 return Error(ErrorLoc, "operand must be a bare symbol name");
1574 }
1575 case Match_InvalidPseudoJumpSymbol: {
1576 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1577 return Error(ErrorLoc, "operand must be a valid jump target");
1578 }
1579 case Match_InvalidCallSymbol: {
1580 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1581 return Error(ErrorLoc, "operand must be a bare symbol name");
1582 }
1583 case Match_InvalidTPRelAddSymbol: {
1584 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1585 return Error(ErrorLoc, "operand must be a symbol with %tprel_add modifier");
1586 }
1587 case Match_InvalidTLSDESCCallSymbol: {
1588 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1589 return Error(ErrorLoc,
1590 "operand must be a symbol with %tlsdesc_call modifier");
1591 }
1592 case Match_InvalidRTZArg: {
1593 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1594 return Error(ErrorLoc, "operand must be 'rtz' floating-point rounding mode");
1595 }
1596 case Match_InvalidVTypeI: {
1597 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1598 return generateVTypeError(ErrorLoc);
1599 }
1600 case Match_InvalidVMaskRegister: {
1601 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1602 return Error(ErrorLoc, "operand must be v0.t");
1603 }
1604 case Match_InvalidSImm5Plus1: {
1605 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 4) + 1,
1606 (1 << 4),
1607 "immediate must be in the range");
1608 }
1609 case Match_InvalidRlist: {
1610 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1611 return Error(
1612 ErrorLoc,
1613 "operand must be {ra [, s0[-sN]]} or {x1 [, x8[-x9][, x18[-xN]]]}");
1614 }
1615 case Match_InvalidStackAdj: {
1616 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1617 return Error(
1618 ErrorLoc,
1619 "stack adjustment is invalid for this instruction and register list; "
1620 "refer to Zc spec for a detailed range of stack adjustment");
1621 }
1622 case Match_InvalidRnumArg: {
1623 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, 10);
1624 }
1625 case Match_InvalidRegReg: {
1626 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1627 return Error(ErrorLoc, "operands must be register and register");
1628 }
1629 }
1630
1631 llvm_unreachable("Unknown match type detected!");
1632}
1633
1634// Attempts to match Name as a register (either using the default name or
1635// alternative ABI names), setting RegNo to the matching register. Upon
1636// failure, returns a non-valid MCRegister. If IsRVE, then registers x16-x31
1637// will be rejected.
1638MCRegister RISCVAsmParser::matchRegisterNameHelper(StringRef Name) const {
1640 // The 16-/32- and 64-bit FPRs have the same asm name. Check that the initial
1641 // match always matches the 64-bit variant, and not the 16/32-bit one.
1642 assert(!(Reg >= RISCV::F0_H && Reg <= RISCV::F31_H));
1643 assert(!(Reg >= RISCV::F0_F && Reg <= RISCV::F31_F));
1644 // The default FPR register class is based on the tablegen enum ordering.
1645 static_assert(RISCV::F0_D < RISCV::F0_H, "FPR matching must be updated");
1646 static_assert(RISCV::F0_D < RISCV::F0_F, "FPR matching must be updated");
1647 if (!Reg)
1649 if (isRVE() && Reg >= RISCV::X16 && Reg <= RISCV::X31)
1650 Reg = RISCV::NoRegister;
1651 return Reg;
1652}
1653
1654bool RISCVAsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
1655 SMLoc &EndLoc) {
1656 if (!tryParseRegister(Reg, StartLoc, EndLoc).isSuccess())
1657 return Error(StartLoc, "invalid register name");
1658 return false;
1659}
1660
1661ParseStatus RISCVAsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
1662 SMLoc &EndLoc) {
1663 const AsmToken &Tok = getParser().getTok();
1664 StartLoc = Tok.getLoc();
1665 EndLoc = Tok.getEndLoc();
1666 StringRef Name = getLexer().getTok().getIdentifier();
1667
1669 if (!Reg)
1670 return ParseStatus::NoMatch;
1671
1672 getParser().Lex(); // Eat identifier token.
1673 return ParseStatus::Success;
1674}
1675
1676ParseStatus RISCVAsmParser::parseRegister(OperandVector &Operands,
1677 bool AllowParens) {
1678 SMLoc FirstS = getLoc();
1679 bool HadParens = false;
1680 AsmToken LParen;
1681
1682 // If this is an LParen and a parenthesised register name is allowed, parse it
1683 // atomically.
1684 if (AllowParens && getLexer().is(AsmToken::LParen)) {
1685 AsmToken Buf[2];
1686 size_t ReadCount = getLexer().peekTokens(Buf);
1687 if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
1688 HadParens = true;
1689 LParen = getParser().getTok();
1690 getParser().Lex(); // Eat '('
1691 }
1692 }
1693
1694 switch (getLexer().getKind()) {
1695 default:
1696 if (HadParens)
1697 getLexer().UnLex(LParen);
1698 return ParseStatus::NoMatch;
1700 StringRef Name = getLexer().getTok().getIdentifier();
1702
1703 if (!RegNo) {
1704 if (HadParens)
1705 getLexer().UnLex(LParen);
1706 return ParseStatus::NoMatch;
1707 }
1708 if (HadParens)
1709 Operands.push_back(RISCVOperand::createToken("(", FirstS));
1710 SMLoc S = getLoc();
1712 getLexer().Lex();
1713 Operands.push_back(RISCVOperand::createReg(RegNo, S, E));
1714 }
1715
1716 if (HadParens) {
1717 getParser().Lex(); // Eat ')'
1718 Operands.push_back(RISCVOperand::createToken(")", getLoc()));
1719 }
1720
1721 return ParseStatus::Success;
1722}
1723
1724ParseStatus RISCVAsmParser::parseInsnDirectiveOpcode(OperandVector &Operands) {
1725 SMLoc S = getLoc();
1726 SMLoc E;
1727 const MCExpr *Res;
1728
1729 switch (getLexer().getKind()) {
1730 default:
1731 return ParseStatus::NoMatch;
1732 case AsmToken::LParen:
1733 case AsmToken::Minus:
1734 case AsmToken::Plus:
1735 case AsmToken::Exclaim:
1736 case AsmToken::Tilde:
1737 case AsmToken::Integer:
1738 case AsmToken::String: {
1739 if (getParser().parseExpression(Res, E))
1740 return ParseStatus::Failure;
1741
1742 auto *CE = dyn_cast<MCConstantExpr>(Res);
1743 if (CE) {
1744 int64_t Imm = CE->getValue();
1745 if (isUInt<7>(Imm)) {
1746 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1747 return ParseStatus::Success;
1748 }
1749 }
1750
1751 break;
1752 }
1753 case AsmToken::Identifier: {
1755 if (getParser().parseIdentifier(Identifier))
1756 return ParseStatus::Failure;
1757
1758 auto Opcode = RISCVInsnOpcode::lookupRISCVOpcodeByName(Identifier);
1759 if (Opcode) {
1760 assert(isUInt<7>(Opcode->Value) && (Opcode->Value & 0x3) == 3 &&
1761 "Unexpected opcode");
1762 Res = MCConstantExpr::create(Opcode->Value, getContext());
1764 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1765 return ParseStatus::Success;
1766 }
1767
1768 break;
1769 }
1770 case AsmToken::Percent:
1771 break;
1772 }
1773
1774 return generateImmOutOfRangeError(
1775 S, 0, 127,
1776 "opcode must be a valid opcode name or an immediate in the range");
1777}
1778
1779ParseStatus RISCVAsmParser::parseInsnCDirectiveOpcode(OperandVector &Operands) {
1780 SMLoc S = getLoc();
1781 SMLoc E;
1782 const MCExpr *Res;
1783
1784 switch (getLexer().getKind()) {
1785 default:
1786 return ParseStatus::NoMatch;
1787 case AsmToken::LParen:
1788 case AsmToken::Minus:
1789 case AsmToken::Plus:
1790 case AsmToken::Exclaim:
1791 case AsmToken::Tilde:
1792 case AsmToken::Integer:
1793 case AsmToken::String: {
1794 if (getParser().parseExpression(Res, E))
1795 return ParseStatus::Failure;
1796
1797 auto *CE = dyn_cast<MCConstantExpr>(Res);
1798 if (CE) {
1799 int64_t Imm = CE->getValue();
1800 if (Imm >= 0 && Imm <= 2) {
1801 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1802 return ParseStatus::Success;
1803 }
1804 }
1805
1806 break;
1807 }
1808 case AsmToken::Identifier: {
1810 if (getParser().parseIdentifier(Identifier))
1811 return ParseStatus::Failure;
1812
1813 unsigned Opcode;
1814 if (Identifier == "C0")
1815 Opcode = 0;
1816 else if (Identifier == "C1")
1817 Opcode = 1;
1818 else if (Identifier == "C2")
1819 Opcode = 2;
1820 else
1821 break;
1822
1823 Res = MCConstantExpr::create(Opcode, getContext());
1825 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1826 return ParseStatus::Success;
1827 }
1828 case AsmToken::Percent: {
1829 // Discard operand with modifier.
1830 break;
1831 }
1832 }
1833
1834 return generateImmOutOfRangeError(
1835 S, 0, 2,
1836 "opcode must be a valid opcode name or an immediate in the range");
1837}
1838
1839ParseStatus RISCVAsmParser::parseCSRSystemRegister(OperandVector &Operands) {
1840 SMLoc S = getLoc();
1841 const MCExpr *Res;
1842
1843 switch (getLexer().getKind()) {
1844 default:
1845 return ParseStatus::NoMatch;
1846 case AsmToken::LParen:
1847 case AsmToken::Minus:
1848 case AsmToken::Plus:
1849 case AsmToken::Exclaim:
1850 case AsmToken::Tilde:
1851 case AsmToken::Integer:
1852 case AsmToken::String: {
1853 if (getParser().parseExpression(Res))
1854 return ParseStatus::Failure;
1855
1856 auto *CE = dyn_cast<MCConstantExpr>(Res);
1857 if (CE) {
1858 int64_t Imm = CE->getValue();
1859 if (isUInt<12>(Imm)) {
1860 auto SysReg = RISCVSysReg::lookupSysRegByEncoding(Imm);
1861 // Accept an immediate representing a named or un-named Sys Reg
1862 // if the range is valid, regardless of the required features.
1863 Operands.push_back(
1864 RISCVOperand::createSysReg(SysReg ? SysReg->Name : "", S, Imm));
1865 return ParseStatus::Success;
1866 }
1867 }
1868
1869 return generateImmOutOfRangeError(S, 0, (1 << 12) - 1);
1870 }
1871 case AsmToken::Identifier: {
1873 if (getParser().parseIdentifier(Identifier))
1874 return ParseStatus::Failure;
1875
1876 auto SysReg = RISCVSysReg::lookupSysRegByName(Identifier);
1877 if (!SysReg)
1878 SysReg = RISCVSysReg::lookupSysRegByAltName(Identifier);
1879 if (!SysReg)
1880 if ((SysReg = RISCVSysReg::lookupSysRegByDeprecatedName(Identifier)))
1881 Warning(S, "'" + Identifier + "' is a deprecated alias for '" +
1882 SysReg->Name + "'");
1883
1884 // Accept a named Sys Reg if the required features are present.
1885 if (SysReg) {
1886 if (!SysReg->haveRequiredFeatures(getSTI().getFeatureBits()))
1887 return Error(S, "system register use requires an option to be enabled");
1888 Operands.push_back(
1889 RISCVOperand::createSysReg(Identifier, S, SysReg->Encoding));
1890 return ParseStatus::Success;
1891 }
1892
1893 return generateImmOutOfRangeError(S, 0, (1 << 12) - 1,
1894 "operand must be a valid system register "
1895 "name or an integer in the range");
1896 }
1897 case AsmToken::Percent: {
1898 // Discard operand with modifier.
1899 return generateImmOutOfRangeError(S, 0, (1 << 12) - 1);
1900 }
1901 }
1902
1903 return ParseStatus::NoMatch;
1904}
1905
1906ParseStatus RISCVAsmParser::parseFPImm(OperandVector &Operands) {
1907 SMLoc S = getLoc();
1908
1909 // Parse special floats (inf/nan/min) representation.
1910 if (getTok().is(AsmToken::Identifier)) {
1911 StringRef Identifier = getTok().getIdentifier();
1912 if (Identifier.compare_insensitive("inf") == 0) {
1913 Operands.push_back(
1914 RISCVOperand::createImm(MCConstantExpr::create(30, getContext()), S,
1915 getTok().getEndLoc(), isRV64()));
1916 } else if (Identifier.compare_insensitive("nan") == 0) {
1917 Operands.push_back(
1918 RISCVOperand::createImm(MCConstantExpr::create(31, getContext()), S,
1919 getTok().getEndLoc(), isRV64()));
1920 } else if (Identifier.compare_insensitive("min") == 0) {
1921 Operands.push_back(
1922 RISCVOperand::createImm(MCConstantExpr::create(1, getContext()), S,
1923 getTok().getEndLoc(), isRV64()));
1924 } else {
1925 return TokError("invalid floating point literal");
1926 }
1927
1928 Lex(); // Eat the token.
1929
1930 return ParseStatus::Success;
1931 }
1932
1933 // Handle negation, as that still comes through as a separate token.
1934 bool IsNegative = parseOptionalToken(AsmToken::Minus);
1935
1936 const AsmToken &Tok = getTok();
1937 if (!Tok.is(AsmToken::Real))
1938 return TokError("invalid floating point immediate");
1939
1940 // Parse FP representation.
1941 APFloat RealVal(APFloat::IEEEdouble());
1942 auto StatusOrErr =
1943 RealVal.convertFromString(Tok.getString(), APFloat::rmTowardZero);
1944 if (errorToBool(StatusOrErr.takeError()))
1945 return TokError("invalid floating point representation");
1946
1947 if (IsNegative)
1948 RealVal.changeSign();
1949
1950 Operands.push_back(RISCVOperand::createFPImm(
1951 RealVal.bitcastToAPInt().getZExtValue(), S));
1952
1953 Lex(); // Eat the token.
1954
1955 return ParseStatus::Success;
1956}
1957
1958ParseStatus RISCVAsmParser::parseImmediate(OperandVector &Operands) {
1959 SMLoc S = getLoc();
1960 SMLoc E;
1961 const MCExpr *Res;
1962
1963 switch (getLexer().getKind()) {
1964 default:
1965 return ParseStatus::NoMatch;
1966 case AsmToken::LParen:
1967 case AsmToken::Dot:
1968 case AsmToken::Minus:
1969 case AsmToken::Plus:
1970 case AsmToken::Exclaim:
1971 case AsmToken::Tilde:
1972 case AsmToken::Integer:
1973 case AsmToken::String:
1975 if (getParser().parseExpression(Res, E))
1976 return ParseStatus::Failure;
1977 break;
1978 case AsmToken::Percent:
1979 return parseOperandWithModifier(Operands);
1980 }
1981
1982 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1983 return ParseStatus::Success;
1984}
1985
1986ParseStatus RISCVAsmParser::parseOperandWithModifier(OperandVector &Operands) {
1987 SMLoc S = getLoc();
1988 SMLoc E;
1989
1990 if (parseToken(AsmToken::Percent, "expected '%' for operand modifier"))
1991 return ParseStatus::Failure;
1992
1993 if (getLexer().getKind() != AsmToken::Identifier)
1994 return Error(getLoc(), "expected valid identifier for operand modifier");
1995 StringRef Identifier = getParser().getTok().getIdentifier();
1998 return Error(getLoc(), "unrecognized operand modifier");
1999
2000 getParser().Lex(); // Eat the identifier
2001 if (parseToken(AsmToken::LParen, "expected '('"))
2002 return ParseStatus::Failure;
2003
2004 const MCExpr *SubExpr;
2005 if (getParser().parseParenExpression(SubExpr, E))
2006 return ParseStatus::Failure;
2007
2008 const MCExpr *ModExpr = RISCVMCExpr::create(SubExpr, VK, getContext());
2009 Operands.push_back(RISCVOperand::createImm(ModExpr, S, E, isRV64()));
2010 return ParseStatus::Success;
2011}
2012
2013ParseStatus RISCVAsmParser::parseBareSymbol(OperandVector &Operands) {
2014 SMLoc S = getLoc();
2015 const MCExpr *Res;
2016
2017 if (getLexer().getKind() != AsmToken::Identifier)
2018 return ParseStatus::NoMatch;
2019
2021 AsmToken Tok = getLexer().getTok();
2022
2023 if (getParser().parseIdentifier(Identifier))
2024 return ParseStatus::Failure;
2025
2027
2028 if (Identifier.consume_back("@plt"))
2029 return Error(getLoc(), "'@plt' operand not valid for instruction");
2030
2031 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
2032
2033 if (Sym->isVariable()) {
2034 const MCExpr *V = Sym->getVariableValue(/*SetUsed=*/false);
2035 if (!isa<MCSymbolRefExpr>(V)) {
2036 getLexer().UnLex(Tok); // Put back if it's not a bare symbol.
2037 return ParseStatus::NoMatch;
2038 }
2039 Res = V;
2040 } else
2042
2043 MCBinaryExpr::Opcode Opcode;
2044 switch (getLexer().getKind()) {
2045 default:
2046 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
2047 return ParseStatus::Success;
2048 case AsmToken::Plus:
2049 Opcode = MCBinaryExpr::Add;
2050 getLexer().Lex();
2051 break;
2052 case AsmToken::Minus:
2053 Opcode = MCBinaryExpr::Sub;
2054 getLexer().Lex();
2055 break;
2056 }
2057
2058 const MCExpr *Expr;
2059 if (getParser().parseExpression(Expr, E))
2060 return ParseStatus::Failure;
2061 Res = MCBinaryExpr::create(Opcode, Res, Expr, getContext());
2062 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
2063 return ParseStatus::Success;
2064}
2065
2066ParseStatus RISCVAsmParser::parseCallSymbol(OperandVector &Operands) {
2067 SMLoc S = getLoc();
2068 const MCExpr *Res;
2069
2070 if (getLexer().getKind() != AsmToken::Identifier)
2071 return ParseStatus::NoMatch;
2072
2073 // Avoid parsing the register in `call rd, foo` as a call symbol.
2074 if (getLexer().peekTok().getKind() != AsmToken::EndOfStatement)
2075 return ParseStatus::NoMatch;
2076
2078 if (getParser().parseIdentifier(Identifier))
2079 return ParseStatus::Failure;
2080
2082
2084 (void)Identifier.consume_back("@plt");
2085
2086 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
2088 Res = RISCVMCExpr::create(Res, Kind, getContext());
2089 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
2090 return ParseStatus::Success;
2091}
2092
2093ParseStatus RISCVAsmParser::parsePseudoJumpSymbol(OperandVector &Operands) {
2094 SMLoc S = getLoc();
2095 SMLoc E;
2096 const MCExpr *Res;
2097
2098 if (getParser().parseExpression(Res, E))
2099 return ParseStatus::Failure;
2100
2101 if (Res->getKind() != MCExpr::ExprKind::SymbolRef ||
2102 cast<MCSymbolRefExpr>(Res)->getKind() ==
2103 MCSymbolRefExpr::VariantKind::VK_PLT)
2104 return Error(S, "operand must be a valid jump target");
2105
2106 Res = RISCVMCExpr::create(Res, RISCVMCExpr::VK_RISCV_CALL, getContext());
2107 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
2108 return ParseStatus::Success;
2109}
2110
2111ParseStatus RISCVAsmParser::parseJALOffset(OperandVector &Operands) {
2112 // Parsing jal operands is fiddly due to the `jal foo` and `jal ra, foo`
2113 // both being acceptable forms. When parsing `jal ra, foo` this function
2114 // will be called for the `ra` register operand in an attempt to match the
2115 // single-operand alias. parseJALOffset must fail for this case. It would
2116 // seem logical to try parse the operand using parseImmediate and return
2117 // NoMatch if the next token is a comma (meaning we must be parsing a jal in
2118 // the second form rather than the first). We can't do this as there's no
2119 // way of rewinding the lexer state. Instead, return NoMatch if this operand
2120 // is an identifier and is followed by a comma.
2121 if (getLexer().is(AsmToken::Identifier) &&
2122 getLexer().peekTok().is(AsmToken::Comma))
2123 return ParseStatus::NoMatch;
2124
2125 return parseImmediate(Operands);
2126}
2127
2128bool RISCVAsmParser::parseVTypeToken(const AsmToken &Tok, VTypeState &State,
2129 unsigned &Sew, unsigned &Lmul,
2130 bool &Fractional, bool &TailAgnostic,
2131 bool &MaskAgnostic) {
2132 if (Tok.isNot(AsmToken::Identifier))
2133 return true;
2134
2136
2137 switch (State) {
2138 case VTypeState_SEW:
2139 if (!Identifier.consume_front("e"))
2140 break;
2141 if (Identifier.getAsInteger(10, Sew))
2142 break;
2143 if (!RISCVVType::isValidSEW(Sew))
2144 break;
2145 State = VTypeState_LMUL;
2146 return false;
2147 case VTypeState_LMUL: {
2148 if (!Identifier.consume_front("m"))
2149 break;
2150 Fractional = Identifier.consume_front("f");
2151 if (Identifier.getAsInteger(10, Lmul))
2152 break;
2153 if (!RISCVVType::isValidLMUL(Lmul, Fractional))
2154 break;
2155 State = VTypeState_TailPolicy;
2156 return false;
2157 }
2158 case VTypeState_TailPolicy:
2159 if (Identifier == "ta")
2160 TailAgnostic = true;
2161 else if (Identifier == "tu")
2162 TailAgnostic = false;
2163 else
2164 break;
2165 State = VTypeState_MaskPolicy;
2166 return false;
2167 case VTypeState_MaskPolicy:
2168 if (Identifier == "ma")
2169 MaskAgnostic = true;
2170 else if (Identifier == "mu")
2171 MaskAgnostic = false;
2172 else
2173 break;
2174 State = VTypeState_Done;
2175 return false;
2176 case VTypeState_Done:
2177 // Extra token?
2178 break;
2179 }
2180
2181 return true;
2182}
2183
2184ParseStatus RISCVAsmParser::parseVTypeI(OperandVector &Operands) {
2185 SMLoc S = getLoc();
2186
2187 unsigned Sew = 0;
2188 unsigned Lmul = 0;
2189 bool Fractional = false;
2190 bool TailAgnostic = false;
2191 bool MaskAgnostic = false;
2192
2193 VTypeState State = VTypeState_SEW;
2194
2195 if (parseVTypeToken(getTok(), State, Sew, Lmul, Fractional, TailAgnostic,
2196 MaskAgnostic))
2197 return ParseStatus::NoMatch;
2198
2199 getLexer().Lex();
2200
2201 while (parseOptionalToken(AsmToken::Comma)) {
2202 if (parseVTypeToken(getTok(), State, Sew, Lmul, Fractional, TailAgnostic,
2203 MaskAgnostic))
2204 break;
2205
2206 getLexer().Lex();
2207 }
2208
2209 if (getLexer().is(AsmToken::EndOfStatement) && State == VTypeState_Done) {
2210 RISCVII::VLMUL VLMUL = RISCVVType::encodeLMUL(Lmul, Fractional);
2211
2212 unsigned VTypeI =
2213 RISCVVType::encodeVTYPE(VLMUL, Sew, TailAgnostic, MaskAgnostic);
2214 Operands.push_back(RISCVOperand::createVType(VTypeI, S));
2215 return ParseStatus::Success;
2216 }
2217
2218 return generateVTypeError(S);
2219}
2220
2221bool RISCVAsmParser::generateVTypeError(SMLoc ErrorLoc) {
2222 return Error(
2223 ErrorLoc,
2224 "operand must be "
2225 "e[8|16|32|64|128|256|512|1024],m[1|2|4|8|f2|f4|f8],[ta|tu],[ma|mu]");
2226}
2227
2228ParseStatus RISCVAsmParser::parseMaskReg(OperandVector &Operands) {
2229 if (getLexer().isNot(AsmToken::Identifier))
2230 return ParseStatus::NoMatch;
2231
2232 StringRef Name = getLexer().getTok().getIdentifier();
2233 if (!Name.consume_back(".t"))
2234 return Error(getLoc(), "expected '.t' suffix");
2236
2237 if (!RegNo)
2238 return ParseStatus::NoMatch;
2239 if (RegNo != RISCV::V0)
2240 return ParseStatus::NoMatch;
2241 SMLoc S = getLoc();
2243 getLexer().Lex();
2244 Operands.push_back(RISCVOperand::createReg(RegNo, S, E));
2245 return ParseStatus::Success;
2246}
2247
2248ParseStatus RISCVAsmParser::parseGPRAsFPR(OperandVector &Operands) {
2249 if (getLexer().isNot(AsmToken::Identifier))
2250 return ParseStatus::NoMatch;
2251
2252 StringRef Name = getLexer().getTok().getIdentifier();
2254
2255 if (!RegNo)
2256 return ParseStatus::NoMatch;
2257 SMLoc S = getLoc();
2259 getLexer().Lex();
2260 Operands.push_back(RISCVOperand::createReg(
2261 RegNo, S, E, !getSTI().hasFeature(RISCV::FeatureStdExtF)));
2262 return ParseStatus::Success;
2263}
2264
2265template <bool IsRV64>
2266ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands) {
2267 return parseGPRPair(Operands, IsRV64);
2268}
2269
2270ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands,
2271 bool IsRV64Inst) {
2272 // If this is not an RV64 GPRPair instruction, don't parse as a GPRPair on
2273 // RV64 as it will prevent matching the RV64 version of the same instruction
2274 // that doesn't use a GPRPair.
2275 // If this is an RV64 GPRPair instruction, there is no RV32 version so we can
2276 // still parse as a pair.
2277 if (!IsRV64Inst && isRV64())
2278 return ParseStatus::NoMatch;
2279
2280 if (getLexer().isNot(AsmToken::Identifier))
2281 return ParseStatus::NoMatch;
2282
2283 StringRef Name = getLexer().getTok().getIdentifier();
2285
2286 if (!RegNo)
2287 return ParseStatus::NoMatch;
2288
2289 if (!RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(RegNo))
2290 return ParseStatus::NoMatch;
2291
2292 if ((RegNo - RISCV::X0) & 1)
2293 return TokError("register must be even");
2294
2295 SMLoc S = getLoc();
2297 getLexer().Lex();
2298
2299 const MCRegisterInfo *RI = getContext().getRegisterInfo();
2300 unsigned Pair = RI->getMatchingSuperReg(
2301 RegNo, RISCV::sub_gpr_even,
2302 &RISCVMCRegisterClasses[RISCV::GPRPairRegClassID]);
2303 Operands.push_back(RISCVOperand::createReg(Pair, S, E));
2304 return ParseStatus::Success;
2305}
2306
2307ParseStatus RISCVAsmParser::parseFRMArg(OperandVector &Operands) {
2308 if (getLexer().isNot(AsmToken::Identifier))
2309 return TokError(
2310 "operand must be a valid floating point rounding mode mnemonic");
2311
2312 StringRef Str = getLexer().getTok().getIdentifier();
2314
2315 if (FRM == RISCVFPRndMode::Invalid)
2316 return TokError(
2317 "operand must be a valid floating point rounding mode mnemonic");
2318
2319 Operands.push_back(RISCVOperand::createFRMArg(FRM, getLoc()));
2320 Lex(); // Eat identifier token.
2321 return ParseStatus::Success;
2322}
2323
2324ParseStatus RISCVAsmParser::parseFenceArg(OperandVector &Operands) {
2325 const AsmToken &Tok = getLexer().getTok();
2326
2327 if (Tok.is(AsmToken::Integer)) {
2328 if (Tok.getIntVal() != 0)
2329 goto ParseFail;
2330
2331 Operands.push_back(RISCVOperand::createFenceArg(0, getLoc()));
2332 Lex();
2333 return ParseStatus::Success;
2334 }
2335
2336 if (Tok.is(AsmToken::Identifier)) {
2337 StringRef Str = Tok.getIdentifier();
2338
2339 // Letters must be unique, taken from 'iorw', and in ascending order. This
2340 // holds as long as each individual character is one of 'iorw' and is
2341 // greater than the previous character.
2342 unsigned Imm = 0;
2343 bool Valid = true;
2344 char Prev = '\0';
2345 for (char c : Str) {
2346 switch (c) {
2347 default:
2348 Valid = false;
2349 break;
2350 case 'i':
2352 break;
2353 case 'o':
2355 break;
2356 case 'r':
2358 break;
2359 case 'w':
2361 break;
2362 }
2363
2364 if (c <= Prev) {
2365 Valid = false;
2366 break;
2367 }
2368 Prev = c;
2369 }
2370
2371 if (!Valid)
2372 goto ParseFail;
2373
2374 Operands.push_back(RISCVOperand::createFenceArg(Imm, getLoc()));
2375 Lex();
2376 return ParseStatus::Success;
2377 }
2378
2379ParseFail:
2380 return TokError("operand must be formed of letters selected in-order from "
2381 "'iorw' or be 0");
2382}
2383
2384ParseStatus RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
2385 if (parseToken(AsmToken::LParen, "expected '('"))
2386 return ParseStatus::Failure;
2387 Operands.push_back(RISCVOperand::createToken("(", getLoc()));
2388
2389 if (!parseRegister(Operands).isSuccess())
2390 return Error(getLoc(), "expected register");
2391
2392 if (parseToken(AsmToken::RParen, "expected ')'"))
2393 return ParseStatus::Failure;
2394 Operands.push_back(RISCVOperand::createToken(")", getLoc()));
2395
2396 return ParseStatus::Success;
2397}
2398
2399ParseStatus RISCVAsmParser::parseZeroOffsetMemOp(OperandVector &Operands) {
2400 // Atomic operations such as lr.w, sc.w, and amo*.w accept a "memory operand"
2401 // as one of their register operands, such as `(a0)`. This just denotes that
2402 // the register (in this case `a0`) contains a memory address.
2403 //
2404 // Normally, we would be able to parse these by putting the parens into the
2405 // instruction string. However, GNU as also accepts a zero-offset memory
2406 // operand (such as `0(a0)`), and ignores the 0. Normally this would be parsed
2407 // with parseImmediate followed by parseMemOpBaseReg, but these instructions
2408 // do not accept an immediate operand, and we do not want to add a "dummy"
2409 // operand that is silently dropped.
2410 //
2411 // Instead, we use this custom parser. This will: allow (and discard) an
2412 // offset if it is zero; require (and discard) parentheses; and add only the
2413 // parsed register operand to `Operands`.
2414 //
2415 // These operands are printed with RISCVInstPrinter::printZeroOffsetMemOp,
2416 // which will only print the register surrounded by parentheses (which GNU as
2417 // also uses as its canonical representation for these operands).
2418 std::unique_ptr<RISCVOperand> OptionalImmOp;
2419
2420 if (getLexer().isNot(AsmToken::LParen)) {
2421 // Parse an Integer token. We do not accept arbritrary constant expressions
2422 // in the offset field (because they may include parens, which complicates
2423 // parsing a lot).
2424 int64_t ImmVal;
2425 SMLoc ImmStart = getLoc();
2426 if (getParser().parseIntToken(ImmVal,
2427 "expected '(' or optional integer offset"))
2428 return ParseStatus::Failure;
2429
2430 // Create a RISCVOperand for checking later (so the error messages are
2431 // nicer), but we don't add it to Operands.
2432 SMLoc ImmEnd = getLoc();
2433 OptionalImmOp =
2434 RISCVOperand::createImm(MCConstantExpr::create(ImmVal, getContext()),
2435 ImmStart, ImmEnd, isRV64());
2436 }
2437
2438 if (parseToken(AsmToken::LParen,
2439 OptionalImmOp ? "expected '(' after optional integer offset"
2440 : "expected '(' or optional integer offset"))
2441 return ParseStatus::Failure;
2442
2443 if (!parseRegister(Operands).isSuccess())
2444 return Error(getLoc(), "expected register");
2445
2446 if (parseToken(AsmToken::RParen, "expected ')'"))
2447 return ParseStatus::Failure;
2448
2449 // Deferred Handling of non-zero offsets. This makes the error messages nicer.
2450 if (OptionalImmOp && !OptionalImmOp->isImmZero())
2451 return Error(
2452 OptionalImmOp->getStartLoc(), "optional integer offset must be 0",
2453 SMRange(OptionalImmOp->getStartLoc(), OptionalImmOp->getEndLoc()));
2454
2455 return ParseStatus::Success;
2456}
2457
2458ParseStatus RISCVAsmParser::parseRegReg(OperandVector &Operands) {
2459 // RR : a2(a1)
2460 if (getLexer().getKind() != AsmToken::Identifier)
2461 return ParseStatus::NoMatch;
2462
2463 StringRef RegName = getLexer().getTok().getIdentifier();
2465 if (!Reg)
2466 return Error(getLoc(), "invalid register");
2467 getLexer().Lex();
2468
2469 if (parseToken(AsmToken::LParen, "expected '(' or invalid operand"))
2470 return ParseStatus::Failure;
2471
2472 if (getLexer().getKind() != AsmToken::Identifier)
2473 return Error(getLoc(), "expected register");
2474
2475 StringRef Reg2Name = getLexer().getTok().getIdentifier();
2476 MCRegister Reg2 = matchRegisterNameHelper(Reg2Name);
2477 if (!Reg2)
2478 return Error(getLoc(), "invalid register");
2479 getLexer().Lex();
2480
2481 if (parseToken(AsmToken::RParen, "expected ')'"))
2482 return ParseStatus::Failure;
2483
2484 Operands.push_back(RISCVOperand::createRegReg(Reg, Reg2, getLoc()));
2485
2486 return ParseStatus::Success;
2487}
2488
2489ParseStatus RISCVAsmParser::parseReglist(OperandVector &Operands) {
2490 // Rlist: {ra [, s0[-sN]]}
2491 // XRlist: {x1 [, x8[-x9][, x18[-xN]]]}
2492 SMLoc S = getLoc();
2493
2494 if (parseToken(AsmToken::LCurly, "register list must start with '{'"))
2495 return ParseStatus::Failure;
2496
2497 bool IsEABI = isRVE();
2498
2499 if (getLexer().isNot(AsmToken::Identifier))
2500 return Error(getLoc(), "register list must start from 'ra' or 'x1'");
2501
2502 StringRef RegName = getLexer().getTok().getIdentifier();
2504 MCRegister RegEnd;
2505 if (RegStart != RISCV::X1)
2506 return Error(getLoc(), "register list must start from 'ra' or 'x1'");
2507 getLexer().Lex();
2508
2509 // parse case like ,s0
2510 if (parseOptionalToken(AsmToken::Comma)) {
2511 if (getLexer().isNot(AsmToken::Identifier))
2512 return Error(getLoc(), "invalid register");
2513 StringRef RegName = getLexer().getTok().getIdentifier();
2514 RegStart = matchRegisterNameHelper(RegName);
2515 if (!RegStart)
2516 return Error(getLoc(), "invalid register");
2517 if (RegStart != RISCV::X8)
2518 return Error(getLoc(),
2519 "continuous register list must start from 's0' or 'x8'");
2520 getLexer().Lex(); // eat reg
2521 }
2522
2523 // parse case like -s1
2524 if (parseOptionalToken(AsmToken::Minus)) {
2525 StringRef EndName = getLexer().getTok().getIdentifier();
2526 // FIXME: the register mapping and checks of EABI is wrong
2527 RegEnd = matchRegisterNameHelper(EndName);
2528 if (!RegEnd)
2529 return Error(getLoc(), "invalid register");
2530 if (IsEABI && RegEnd != RISCV::X9)
2531 return Error(getLoc(), "contiguous register list of EABI can only be "
2532 "'s0-s1' or 'x8-x9' pair");
2533 getLexer().Lex();
2534 }
2535
2536 if (!IsEABI) {
2537 // parse extra part like ', x18[-x20]' for XRegList
2538 if (parseOptionalToken(AsmToken::Comma)) {
2539 if (RegEnd != RISCV::X9)
2540 return Error(
2541 getLoc(),
2542 "first contiguous registers pair of register list must be 'x8-x9'");
2543
2544 // parse ', x18' for extra part
2545 if (getLexer().isNot(AsmToken::Identifier))
2546 return Error(getLoc(), "invalid register");
2547 StringRef EndName = getLexer().getTok().getIdentifier();
2548 if (MatchRegisterName(EndName) != RISCV::X18)
2549 return Error(getLoc(),
2550 "second contiguous registers pair of register list "
2551 "must start from 'x18'");
2552 getLexer().Lex();
2553
2554 // parse '-x20' for extra part
2555 if (parseOptionalToken(AsmToken::Minus)) {
2556 if (getLexer().isNot(AsmToken::Identifier))
2557 return Error(getLoc(), "invalid register");
2558 EndName = getLexer().getTok().getIdentifier();
2559 if (MatchRegisterName(EndName) == RISCV::NoRegister)
2560 return Error(getLoc(), "invalid register");
2561 getLexer().Lex();
2562 }
2563 RegEnd = MatchRegisterName(EndName);
2564 }
2565 }
2566
2567 if (RegEnd == RISCV::X26)
2568 return Error(getLoc(), "invalid register list, {ra, s0-s10} or {x1, x8-x9, "
2569 "x18-x26} is not supported");
2570
2571 if (parseToken(AsmToken::RCurly, "register list must end with '}'"))
2572 return ParseStatus::Failure;
2573
2574 if (RegEnd == RISCV::NoRegister)
2575 RegEnd = RegStart;
2576
2577 auto Encode = RISCVZC::encodeRlist(RegEnd, IsEABI);
2578 if (Encode == RISCVZC::INVALID_RLIST)
2579 return Error(S, "invalid register list");
2580 Operands.push_back(RISCVOperand::createRlist(Encode, S));
2581
2582 return ParseStatus::Success;
2583}
2584
2585ParseStatus RISCVAsmParser::parseZcmpStackAdj(OperandVector &Operands,
2586 bool ExpectNegative) {
2587 bool Negative = 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 if (Negative != ExpectNegative ||
2595 !RISCVZC::getSpimm(RlistVal, Spimm, StackAdjustment, isRV64()))
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 RISCVMatInt::generateMCInstSeq(Value, getSTI(), DestReg, Seq);
3086
3087 for (MCInst &Inst : Seq) {
3088 emitToStreamer(Out, Inst);
3089 }
3090}
3091
3092void RISCVAsmParser::emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
3093 const MCExpr *Symbol,
3095 unsigned SecondOpcode, SMLoc IDLoc,
3096 MCStreamer &Out) {
3097 // A pair of instructions for PC-relative addressing; expands to
3098 // TmpLabel: AUIPC TmpReg, VKHi(symbol)
3099 // OP DestReg, TmpReg, %pcrel_lo(TmpLabel)
3100 MCContext &Ctx = getContext();
3101
3102 MCSymbol *TmpLabel = Ctx.createNamedTempSymbol("pcrel_hi");
3103 Out.emitLabel(TmpLabel);
3104
3105 const RISCVMCExpr *SymbolHi = RISCVMCExpr::create(Symbol, VKHi, Ctx);
3106 emitToStreamer(
3107 Out, MCInstBuilder(RISCV::AUIPC).addOperand(TmpReg).addExpr(SymbolHi));
3108
3109 const MCExpr *RefToLinkTmpLabel =
3112
3113 emitToStreamer(Out, MCInstBuilder(SecondOpcode)
3114 .addOperand(DestReg)
3115 .addOperand(TmpReg)
3116 .addExpr(RefToLinkTmpLabel));
3117}
3118
3119void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
3120 MCStreamer &Out) {
3121 // The load local address pseudo-instruction "lla" is used in PC-relative
3122 // addressing of local symbols:
3123 // lla rdest, symbol
3124 // expands to
3125 // TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
3126 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3127 MCOperand DestReg = Inst.getOperand(0);
3128 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3129 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
3130 RISCV::ADDI, IDLoc, Out);
3131}
3132
3133void RISCVAsmParser::emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc,
3134 MCStreamer &Out) {
3135 // The load global address pseudo-instruction "lga" is used in GOT-indirect
3136 // addressing of global symbols:
3137 // lga rdest, symbol
3138 // expands to
3139 // TmpLabel: AUIPC rdest, %got_pcrel_hi(symbol)
3140 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3141 MCOperand DestReg = Inst.getOperand(0);
3142 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3143 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3144 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_GOT_HI,
3145 SecondOpcode, IDLoc, Out);
3146}
3147
3148void RISCVAsmParser::emitLoadAddress(MCInst &Inst, SMLoc IDLoc,
3149 MCStreamer &Out) {
3150 // The load address pseudo-instruction "la" is used in PC-relative and
3151 // GOT-indirect addressing of global symbols:
3152 // la rdest, symbol
3153 // is an alias for either (for non-PIC)
3154 // lla rdest, symbol
3155 // or (for PIC)
3156 // lga rdest, symbol
3157 if (ParserOptions.IsPicEnabled)
3158 emitLoadGlobalAddress(Inst, IDLoc, Out);
3159 else
3160 emitLoadLocalAddress(Inst, IDLoc, Out);
3161}
3162
3163void RISCVAsmParser::emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc,
3164 MCStreamer &Out) {
3165 // The load TLS IE address pseudo-instruction "la.tls.ie" is used in
3166 // initial-exec TLS model addressing of global symbols:
3167 // la.tls.ie rdest, symbol
3168 // expands to
3169 // TmpLabel: AUIPC rdest, %tls_ie_pcrel_hi(symbol)
3170 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3171 MCOperand DestReg = Inst.getOperand(0);
3172 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3173 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3174 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GOT_HI,
3175 SecondOpcode, IDLoc, Out);
3176}
3177
3178void RISCVAsmParser::emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc,
3179 MCStreamer &Out) {
3180 // The load TLS GD address pseudo-instruction "la.tls.gd" is used in
3181 // global-dynamic TLS model addressing of global symbols:
3182 // la.tls.gd rdest, symbol
3183 // expands to
3184 // TmpLabel: AUIPC rdest, %tls_gd_pcrel_hi(symbol)
3185 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3186 MCOperand DestReg = Inst.getOperand(0);
3187 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3188 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GD_HI,
3189 RISCV::ADDI, IDLoc, Out);
3190}
3191
3192void RISCVAsmParser::emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode,
3193 SMLoc IDLoc, MCStreamer &Out,
3194 bool HasTmpReg) {
3195 // The load/store pseudo-instruction does a pc-relative load with
3196 // a symbol.
3197 //
3198 // The expansion looks like this
3199 //
3200 // TmpLabel: AUIPC tmp, %pcrel_hi(symbol)
3201 // [S|L]X rd, %pcrel_lo(TmpLabel)(tmp)
3202 unsigned DestRegOpIdx = HasTmpReg ? 1 : 0;
3203 MCOperand DestReg = Inst.getOperand(DestRegOpIdx);
3204 unsigned SymbolOpIdx = HasTmpReg ? 2 : 1;
3205 MCOperand TmpReg = Inst.getOperand(0);
3206 const MCExpr *Symbol = Inst.getOperand(SymbolOpIdx).getExpr();
3207 emitAuipcInstPair(DestReg, TmpReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
3208 Opcode, IDLoc, Out);
3209}
3210
3211void RISCVAsmParser::emitPseudoExtend(MCInst &Inst, bool SignExtend,
3212 int64_t Width, SMLoc IDLoc,
3213 MCStreamer &Out) {
3214 // The sign/zero extend pseudo-instruction does two shifts, with the shift
3215 // amounts dependent on the XLEN.
3216 //
3217 // The expansion looks like this
3218 //
3219 // SLLI rd, rs, XLEN - Width
3220 // SR[A|R]I rd, rd, XLEN - Width
3221 MCOperand DestReg = Inst.getOperand(0);
3222 MCOperand SourceReg = Inst.getOperand(1);
3223
3224 unsigned SecondOpcode = SignExtend ? RISCV::SRAI : RISCV::SRLI;
3225 int64_t ShAmt = (isRV64() ? 64 : 32) - Width;
3226
3227 assert(ShAmt > 0 && "Shift amount must be non-zero.");
3228
3229 emitToStreamer(Out, MCInstBuilder(RISCV::SLLI)
3230 .addOperand(DestReg)
3231 .addOperand(SourceReg)
3232 .addImm(ShAmt));
3233
3234 emitToStreamer(Out, MCInstBuilder(SecondOpcode)
3235 .addOperand(DestReg)
3236 .addOperand(DestReg)
3237 .addImm(ShAmt));
3238}
3239
3240void RISCVAsmParser::emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
3241 MCStreamer &Out) {
3242 if (Inst.getNumOperands() == 3) {
3243 // unmasked va >= x
3244 //
3245 // pseudoinstruction: vmsge{u}.vx vd, va, x
3246 // expansion: vmslt{u}.vx vd, va, x; vmnand.mm vd, vd, vd
3247 emitToStreamer(Out, MCInstBuilder(Opcode)
3248 .addOperand(Inst.getOperand(0))
3249 .addOperand(Inst.getOperand(1))
3250 .addOperand(Inst.getOperand(2))
3251 .addReg(RISCV::NoRegister)
3252 .setLoc(IDLoc));
3253 emitToStreamer(Out, MCInstBuilder(RISCV::VMNAND_MM)
3254 .addOperand(Inst.getOperand(0))
3255 .addOperand(Inst.getOperand(0))
3256 .addOperand(Inst.getOperand(0))
3257 .setLoc(IDLoc));
3258 } else if (Inst.getNumOperands() == 4) {
3259 // masked va >= x, vd != v0
3260 //
3261 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t
3262 // expansion: vmslt{u}.vx vd, va, x, v0.t; vmxor.mm vd, vd, v0
3263 assert(Inst.getOperand(0).getReg() != RISCV::V0 &&
3264 "The destination register should not be V0.");
3265 emitToStreamer(Out, MCInstBuilder(Opcode)
3266 .addOperand(Inst.getOperand(0))
3267 .addOperand(Inst.getOperand(1))
3268 .addOperand(Inst.getOperand(2))
3269 .addOperand(Inst.getOperand(3))
3270 .setLoc(IDLoc));
3271 emitToStreamer(Out, MCInstBuilder(RISCV::VMXOR_MM)
3272 .addOperand(Inst.getOperand(0))
3273 .addOperand(Inst.getOperand(0))
3274 .addReg(RISCV::V0)
3275 .setLoc(IDLoc));
3276 } else if (Inst.getNumOperands() == 5 &&
3277 Inst.getOperand(0).getReg() == RISCV::V0) {
3278 // masked va >= x, vd == v0
3279 //
3280 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3281 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vd, vd, vt
3282 assert(Inst.getOperand(0).getReg() == RISCV::V0 &&
3283 "The destination register should be V0.");
3284 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3285 "The temporary vector register should not be V0.");
3286 emitToStreamer(Out, MCInstBuilder(Opcode)
3287 .addOperand(Inst.getOperand(1))
3288 .addOperand(Inst.getOperand(2))
3289 .addOperand(Inst.getOperand(3))
3290 .addReg(RISCV::NoRegister)
3291 .setLoc(IDLoc));
3292 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3293 .addOperand(Inst.getOperand(0))
3294 .addOperand(Inst.getOperand(0))
3295 .addOperand(Inst.getOperand(1))
3296 .setLoc(IDLoc));
3297 } else if (Inst.getNumOperands() == 5) {
3298 // masked va >= x, any vd
3299 //
3300 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3301 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vt, v0, vt;
3302 // vmandn.mm vd, vd, v0; vmor.mm vd, vt, vd
3303 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3304 "The temporary vector register should not be V0.");
3305 emitToStreamer(Out, MCInstBuilder(Opcode)
3306 .addOperand(Inst.getOperand(1))
3307 .addOperand(Inst.getOperand(2))
3308 .addOperand(Inst.getOperand(3))
3309 .addReg(RISCV::NoRegister)
3310 .setLoc(IDLoc));
3311 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3312 .addOperand(Inst.getOperand(1))
3313 .addReg(RISCV::V0)
3314 .addOperand(Inst.getOperand(1))
3315 .setLoc(IDLoc));
3316 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3317 .addOperand(Inst.getOperand(0))
3318 .addOperand(Inst.getOperand(0))
3319 .addReg(RISCV::V0)
3320 .setLoc(IDLoc));
3321 emitToStreamer(Out, MCInstBuilder(RISCV::VMOR_MM)
3322 .addOperand(Inst.getOperand(0))
3323 .addOperand(Inst.getOperand(1))
3324 .addOperand(Inst.getOperand(0))
3325 .setLoc(IDLoc));
3326 }
3327}
3328
3329bool RISCVAsmParser::checkPseudoAddTPRel(MCInst &Inst,
3331 assert(Inst.getOpcode() == RISCV::PseudoAddTPRel && "Invalid instruction");
3332 assert(Inst.getOperand(2).isReg() && "Unexpected second operand kind");
3333 if (Inst.getOperand(2).getReg() != RISCV::X4) {
3334 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3335 return Error(ErrorLoc, "the second input operand must be tp/x4 when using "
3336 "%tprel_add modifier");
3337 }
3338
3339 return false;
3340}
3341
3342bool RISCVAsmParser::checkPseudoTLSDESCCall(MCInst &Inst,
3344 assert(Inst.getOpcode() == RISCV::PseudoTLSDESCCall && "Invalid instruction");
3345 assert(Inst.getOperand(0).isReg() && "Unexpected operand kind");
3346 if (Inst.getOperand(0).getReg() != RISCV::X5) {
3347 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3348 return Error(ErrorLoc, "the output operand must be t0/x5 when using "
3349 "%tlsdesc_call modifier");
3350 }
3351
3352 return false;
3353}
3354
3355std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultMaskRegOp() const {
3356 return RISCVOperand::createReg(RISCV::NoRegister, llvm::SMLoc(),
3357 llvm::SMLoc());
3358}
3359
3360std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgOp() const {
3361 return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::DYN,
3362 llvm::SMLoc());
3363}
3364
3365std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgLegacyOp() const {
3366 return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::RNE,
3367 llvm::SMLoc());
3368}
3369
3370bool RISCVAsmParser::validateInstruction(MCInst &Inst,
3372 unsigned Opcode = Inst.getOpcode();
3373
3374 if (Opcode == RISCV::PseudoVMSGEU_VX_M_T ||
3375 Opcode == RISCV::PseudoVMSGE_VX_M_T) {
3376 unsigned DestReg = Inst.getOperand(0).getReg();
3377 unsigned TempReg = Inst.getOperand(1).getReg();
3378 if (DestReg == TempReg) {
3379 SMLoc Loc = Operands.back()->getStartLoc();
3380 return Error(Loc, "The temporary vector register cannot be the same as "
3381 "the destination register.");
3382 }
3383 }
3384
3385 if (Opcode == RISCV::TH_LDD || Opcode == RISCV::TH_LWUD ||
3386 Opcode == RISCV::TH_LWD) {
3387 unsigned Rd1 = Inst.getOperand(0).getReg();
3388 unsigned Rd2 = Inst.getOperand(1).getReg();
3389 unsigned Rs1 = Inst.getOperand(2).getReg();
3390 // The encoding with rd1 == rd2 == rs1 is reserved for XTHead load pair.
3391 if (Rs1 == Rd1 && Rs1 == Rd2) {
3392 SMLoc Loc = Operands[1]->getStartLoc();
3393 return Error(Loc, "The source register and destination registers "
3394 "cannot be equal.");
3395 }
3396 }
3397
3398 if (Opcode == RISCV::CM_MVSA01) {
3399 unsigned Rd1 = Inst.getOperand(0).getReg();
3400 unsigned Rd2 = Inst.getOperand(1).getReg();
3401 if (Rd1 == Rd2) {
3402 SMLoc Loc = Operands[1]->getStartLoc();
3403 return Error(Loc, "'rs1' and 'rs2' must be different.");
3404 }
3405 }
3406
3407 bool IsTHeadMemPair32 = (Opcode == RISCV::TH_LWD ||
3408 Opcode == RISCV::TH_LWUD || Opcode == RISCV::TH_SWD);
3409 bool IsTHeadMemPair64 = (Opcode == RISCV::TH_LDD || Opcode == RISCV::TH_SDD);
3410 // The last operand of XTHeadMemPair instructions must be constant 3 or 4
3411 // depending on the data width.
3412 if (IsTHeadMemPair32 && Inst.getOperand(4).getImm() != 3) {
3413 SMLoc Loc = Operands.back()->getStartLoc();
3414 return Error(Loc, "Operand must be constant 3.");
3415 } else if (IsTHeadMemPair64 && Inst.getOperand(4).getImm() != 4) {
3416 SMLoc Loc = Operands.back()->getStartLoc();
3417 return Error(Loc, "Operand must be constant 4.");
3418 }
3419
3420 const MCInstrDesc &MCID = MII.get(Opcode);
3421 if (!(MCID.TSFlags & RISCVII::ConstraintMask))
3422 return false;
3423
3424 if (Opcode == RISCV::VC_V_XVW || Opcode == RISCV::VC_V_IVW ||
3425 Opcode == RISCV::VC_V_FVW || Opcode == RISCV::VC_V_VVW) {
3426 // Operands Opcode, Dst, uimm, Dst, Rs2, Rs1 for VC_V_XVW.
3427 unsigned VCIXDst = Inst.getOperand(0).getReg();
3428 SMLoc VCIXDstLoc = Operands[2]->getStartLoc();
3429 if (MCID.TSFlags & RISCVII::VS1Constraint) {
3430 unsigned VCIXRs1 = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
3431 if (VCIXDst == VCIXRs1)
3432 return Error(VCIXDstLoc, "The destination vector register group cannot"
3433 " overlap the source vector register group.");
3434 }
3435 if (MCID.TSFlags & RISCVII::VS2Constraint) {
3436 unsigned VCIXRs2 = Inst.getOperand(Inst.getNumOperands() - 2).getReg();
3437 if (VCIXDst == VCIXRs2)
3438 return Error(VCIXDstLoc, "The destination vector register group cannot"
3439 " overlap the source vector register group.");
3440 }
3441 return false;
3442 }
3443
3444 unsigned DestReg = Inst.getOperand(0).getReg();
3445 unsigned Offset = 0;
3446 int TiedOp = MCID.getOperandConstraint(1, MCOI::TIED_TO);
3447 if (TiedOp == 0)
3448 Offset = 1;
3449
3450 // Operands[1] will be the first operand, DestReg.
3451 SMLoc Loc = Operands[1]->getStartLoc();
3452 if (MCID.TSFlags & RISCVII::VS2Constraint) {
3453 unsigned CheckReg = Inst.getOperand(Offset + 1).getReg();
3454 if (DestReg == CheckReg)
3455 return Error(Loc, "The destination vector register group cannot overlap"
3456 " the source vector register group.");
3457 }
3458 if ((MCID.TSFlags & RISCVII::VS1Constraint) && Inst.getOperand(Offset + 2).isReg()) {
3459 unsigned CheckReg = Inst.getOperand(Offset + 2).getReg();
3460 if (DestReg == CheckReg)
3461 return Error(Loc, "The destination vector register group cannot overlap"
3462 " the source vector register group.");
3463 }
3464 if ((MCID.TSFlags & RISCVII::VMConstraint) && (DestReg == RISCV::V0)) {
3465 // vadc, vsbc are special cases. These instructions have no mask register.
3466 // The destination register could not be V0.
3467 if (Opcode == RISCV::VADC_VVM || Opcode == RISCV::VADC_VXM ||
3468 Opcode == RISCV::VADC_VIM || Opcode == RISCV::VSBC_VVM ||
3469 Opcode == RISCV::VSBC_VXM || Opcode == RISCV::VFMERGE_VFM ||
3470 Opcode == RISCV::VMERGE_VIM || Opcode == RISCV::VMERGE_VVM ||
3471 Opcode == RISCV::VMERGE_VXM)
3472 return Error(Loc, "The destination vector register group cannot be V0.");
3473
3474 // Regardless masked or unmasked version, the number of operands is the
3475 // same. For example, "viota.m v0, v2" is "viota.m v0, v2, NoRegister"
3476 // actually. We need to check the last operand to ensure whether it is
3477 // masked or not.
3478 unsigned CheckReg = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
3479 assert((CheckReg == RISCV::V0 || CheckReg == RISCV::NoRegister) &&
3480 "Unexpected register for mask operand");
3481
3482 if (DestReg == CheckReg)
3483 return Error(Loc, "The destination vector register group cannot overlap"
3484 " the mask register.");
3485 }
3486 return false;
3487}
3488
3489bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
3491 MCStreamer &Out) {
3492 Inst.setLoc(IDLoc);
3493
3494 switch (Inst.getOpcode()) {
3495 default:
3496 break;
3497 case RISCV::PseudoLLAImm:
3498 case RISCV::PseudoLAImm:
3499 case RISCV::PseudoLI: {
3500 MCRegister Reg = Inst.getOperand(0).getReg();
3501 const MCOperand &Op1 = Inst.getOperand(1);
3502 if (Op1.isExpr()) {
3503 // We must have li reg, %lo(sym) or li reg, %pcrel_lo(sym) or similar.
3504 // Just convert to an addi. This allows compatibility with gas.
3505 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
3506 .addReg(Reg)
3507 .addReg(RISCV::X0)
3508 .addExpr(Op1.getExpr()));
3509 return false;
3510 }
3511 int64_t Imm = Inst.getOperand(1).getImm();
3512 // On RV32 the immediate here can either be a signed or an unsigned
3513 // 32-bit number. Sign extension has to be performed to ensure that Imm
3514 // represents the expected signed 64-bit number.
3515 if (!isRV64())
3516 Imm = SignExtend64<32>(Imm);
3517 emitLoadImm(Reg, Imm, Out);
3518 return false;
3519 }
3520 case RISCV::PseudoLLA:
3521 emitLoadLocalAddress(Inst, IDLoc, Out);
3522 return false;
3523 case RISCV::PseudoLGA:
3524 emitLoadGlobalAddress(Inst, IDLoc, Out);
3525 return false;
3526 case RISCV::PseudoLA:
3527 emitLoadAddress(Inst, IDLoc, Out);
3528 return false;
3529 case RISCV::PseudoLA_TLS_IE:
3530 emitLoadTLSIEAddress(Inst, IDLoc, Out);
3531 return false;
3532 case RISCV::PseudoLA_TLS_GD:
3533 emitLoadTLSGDAddress(Inst, IDLoc, Out);
3534 return false;
3535 case RISCV::PseudoLB:
3536 emitLoadStoreSymbol(Inst, RISCV::LB, IDLoc, Out, /*HasTmpReg=*/false);
3537 return false;
3538 case RISCV::PseudoLBU:
3539 emitLoadStoreSymbol(Inst, RISCV::LBU, IDLoc, Out, /*HasTmpReg=*/false);
3540 return false;
3541 case RISCV::PseudoLH:
3542 emitLoadStoreSymbol(Inst, RISCV::LH, IDLoc, Out, /*HasTmpReg=*/false);
3543 return false;
3544 case RISCV::PseudoLHU:
3545 emitLoadStoreSymbol(Inst, RISCV::LHU, IDLoc, Out, /*HasTmpReg=*/false);
3546 return false;
3547 case RISCV::PseudoLW:
3548 emitLoadStoreSymbol(Inst, RISCV::LW, IDLoc, Out, /*HasTmpReg=*/false);
3549 return false;
3550 case RISCV::PseudoLWU:
3551 emitLoadStoreSymbol(Inst, RISCV::LWU, IDLoc, Out, /*HasTmpReg=*/false);
3552 return false;
3553 case RISCV::PseudoLD:
3554 emitLoadStoreSymbol(Inst, RISCV::LD, IDLoc, Out, /*HasTmpReg=*/false);
3555 return false;
3556 case RISCV::PseudoFLH:
3557 emitLoadStoreSymbol(Inst, RISCV::FLH, IDLoc, Out, /*HasTmpReg=*/true);
3558 return false;
3559 case RISCV::PseudoFLW:
3560 emitLoadStoreSymbol(Inst, RISCV::FLW, IDLoc, Out, /*HasTmpReg=*/true);
3561 return false;
3562 case RISCV::PseudoFLD:
3563 emitLoadStoreSymbol(Inst, RISCV::FLD, IDLoc, Out, /*HasTmpReg=*/true);
3564 return false;
3565 case RISCV::PseudoSB:
3566 emitLoadStoreSymbol(Inst, RISCV::SB, IDLoc, Out, /*HasTmpReg=*/true);
3567 return false;
3568 case RISCV::PseudoSH:
3569 emitLoadStoreSymbol(Inst, RISCV::SH, IDLoc, Out, /*HasTmpReg=*/true);
3570 return false;
3571 case RISCV::PseudoSW:
3572 emitLoadStoreSymbol(Inst, RISCV::SW, IDLoc, Out, /*HasTmpReg=*/true);
3573 return false;
3574 case RISCV::PseudoSD:
3575 emitLoadStoreSymbol(Inst, RISCV::SD, IDLoc, Out, /*HasTmpReg=*/true);
3576 return false;
3577 case RISCV::PseudoFSH:
3578 emitLoadStoreSymbol(Inst, RISCV::FSH, IDLoc, Out, /*HasTmpReg=*/true);
3579 return false;
3580 case RISCV::PseudoFSW:
3581 emitLoadStoreSymbol(Inst, RISCV::FSW, IDLoc, Out, /*HasTmpReg=*/true);
3582 return false;
3583 case RISCV::PseudoFSD:
3584 emitLoadStoreSymbol(Inst, RISCV::FSD, IDLoc, Out, /*HasTmpReg=*/true);
3585 return false;
3586 case RISCV::PseudoAddTPRel:
3587 if (checkPseudoAddTPRel(Inst, Operands))
3588 return true;
3589 break;
3590 case RISCV::PseudoTLSDESCCall:
3591 if (checkPseudoTLSDESCCall(Inst, Operands))
3592 return true;
3593 break;
3594 case RISCV::PseudoSEXT_B:
3595 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/8, IDLoc, Out);
3596 return false;
3597 case RISCV::PseudoSEXT_H:
3598 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/16, IDLoc, Out);
3599 return false;
3600 case RISCV::PseudoZEXT_H:
3601 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/16, IDLoc, Out);
3602 return false;
3603 case RISCV::PseudoZEXT_W:
3604 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/32, IDLoc, Out);
3605 return false;
3606 case RISCV::PseudoVMSGEU_VX:
3607 case RISCV::PseudoVMSGEU_VX_M:
3608 case RISCV::PseudoVMSGEU_VX_M_T:
3609 emitVMSGE(Inst, RISCV::VMSLTU_VX, IDLoc, Out);
3610 return false;
3611 case RISCV::PseudoVMSGE_VX:
3612 case RISCV::PseudoVMSGE_VX_M:
3613 case RISCV::PseudoVMSGE_VX_M_T:
3614 emitVMSGE(Inst, RISCV::VMSLT_VX, IDLoc, Out);
3615 return false;
3616 case RISCV::PseudoVMSGE_VI:
3617 case RISCV::PseudoVMSLT_VI: {
3618 // These instructions are signed and so is immediate so we can subtract one
3619 // and change the opcode.
3620 int64_t Imm = Inst.getOperand(2).getImm();
3621 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGE_VI ? RISCV::VMSGT_VI
3622 : RISCV::VMSLE_VI;
3623 emitToStreamer(Out, MCInstBuilder(Opc)
3624 .addOperand(Inst.getOperand(0))
3625 .addOperand(Inst.getOperand(1))
3626 .addImm(Imm - 1)
3627 .addOperand(Inst.getOperand(3))
3628 .setLoc(IDLoc));
3629 return false;
3630 }
3631 case RISCV::PseudoVMSGEU_VI:
3632 case RISCV::PseudoVMSLTU_VI: {
3633 int64_t Imm = Inst.getOperand(2).getImm();
3634 // Unsigned comparisons are tricky because the immediate is signed. If the
3635 // immediate is 0 we can't just subtract one. vmsltu.vi v0, v1, 0 is always
3636 // false, but vmsle.vi v0, v1, -1 is always true. Instead we use
3637 // vmsne v0, v1, v1 which is always false.
3638 if (Imm == 0) {
3639 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
3640 ? RISCV::VMSEQ_VV
3641 : RISCV::VMSNE_VV;
3642 emitToStreamer(Out, MCInstBuilder(Opc)
3643 .addOperand(Inst.getOperand(0))
3644 .addOperand(Inst.getOperand(1))
3645 .addOperand(Inst.getOperand(1))
3646 .addOperand(Inst.getOperand(3))
3647 .setLoc(IDLoc));
3648 } else {
3649 // Other immediate values can subtract one like signed.
3650 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
3651 ? RISCV::VMSGTU_VI
3652 : RISCV::VMSLEU_VI;
3653 emitToStreamer(Out, MCInstBuilder(Opc)
3654 .addOperand(Inst.getOperand(0))
3655 .addOperand(Inst.getOperand(1))
3656 .addImm(Imm - 1)
3657 .addOperand(Inst.getOperand(3))
3658 .setLoc(IDLoc));
3659 }
3660
3661 return false;
3662 }
3663 }
3664
3665 emitToStreamer(Out, Inst);
3666 return false;
3667}
3668
3672}
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
if(VerifyEach)
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:81
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:457
MCSymbol * createNamedTempSymbol()
Create a temporary symbol with a unique name whose name cannot be omitted in the symbol table.
Definition: MCContext.cpp:324
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
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.
void generateMCInstSeq(int64_t Val, const MCSubtargetInfo &STI, MCRegister DestReg, SmallVectorImpl< MCInst > &Insts)
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)
@ 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:239
static bool isMem(const MachineInstr &MI, unsigned Op)
Definition: X86InstrInfo.h:158
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:1954
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:170
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.