LLVM 19.0.0git
RISCVAsmParser.cpp
Go to the documentation of this file.
1//===-- RISCVAsmParser.cpp - Parse RISC-V assembly to MCInst instructions -===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
17#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/Statistic.h"
22#include "llvm/MC/MCAssembler.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCExpr.h"
25#include "llvm/MC/MCInst.h"
27#include "llvm/MC/MCInstrInfo.h"
33#include "llvm/MC/MCStreamer.h"
35#include "llvm/MC/MCValue.h"
42
43#include <limits>
44
45using namespace llvm;
46
47#define DEBUG_TYPE "riscv-asm-parser"
48
49STATISTIC(RISCVNumInstrsCompressed,
50 "Number of RISC-V Compressed instructions emitted");
51
52static cl::opt<bool> AddBuildAttributes("riscv-add-build-attributes",
53 cl::init(false));
54
55namespace llvm {
56extern const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures];
57} // namespace llvm
58
59namespace {
60struct RISCVOperand;
61
62struct ParserOptionsSet {
63 bool IsPicEnabled;
64};
65
66class RISCVAsmParser : public MCTargetAsmParser {
67 // This tracks the parsing of the 4 operands that make up the vtype portion
68 // of vset(i)vli instructions which are separated by commas. The state names
69 // represent the next expected operand with Done meaning no other operands are
70 // expected.
71 enum VTypeState {
72 VTypeState_SEW,
73 VTypeState_LMUL,
74 VTypeState_TailPolicy,
75 VTypeState_MaskPolicy,
76 VTypeState_Done,
77 };
78
79 SmallVector<FeatureBitset, 4> FeatureBitStack;
80
81 SmallVector<ParserOptionsSet, 4> ParserOptionsStack;
82 ParserOptionsSet ParserOptions;
83
84 SMLoc getLoc() const { return getParser().getTok().getLoc(); }
85 bool isRV64() const { return getSTI().hasFeature(RISCV::Feature64Bit); }
86 bool isRVE() const { return getSTI().hasFeature(RISCV::FeatureRVE); }
87
88 RISCVTargetStreamer &getTargetStreamer() {
89 assert(getParser().getStreamer().getTargetStreamer() &&
90 "do not have a target streamer");
92 return static_cast<RISCVTargetStreamer &>(TS);
93 }
94
96 unsigned Kind) override;
97 unsigned checkTargetMatchPredicate(MCInst &Inst) override;
98
99 bool generateImmOutOfRangeError(OperandVector &Operands, uint64_t ErrorInfo,
100 int64_t Lower, int64_t Upper,
101 const Twine &Msg);
102 bool generateImmOutOfRangeError(SMLoc ErrorLoc, int64_t Lower, int64_t Upper,
103 const Twine &Msg);
104
105 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
108 bool MatchingInlineAsm) override;
109
111 bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
113 SMLoc &EndLoc) override;
114
116 SMLoc NameLoc, OperandVector &Operands) override;
117
118 ParseStatus parseDirective(AsmToken DirectiveID) override;
119
120 bool parseVTypeToken(StringRef Identifier, VTypeState &State, unsigned &Sew,
121 unsigned &Lmul, bool &Fractional, bool &TailAgnostic,
122 bool &MaskAgnostic);
123 bool generateVTypeError(SMLoc ErrorLoc);
124
125 // Helper to actually emit an instruction to the MCStreamer. Also, when
126 // possible, compression of the instruction is performed.
127 void emitToStreamer(MCStreamer &S, const MCInst &Inst);
128
129 // Helper to emit a combination of LUI, ADDI(W), and SLLI instructions that
130 // synthesize the desired immedate value into the destination register.
131 void emitLoadImm(MCRegister DestReg, int64_t Value, MCStreamer &Out);
132
133 // Helper to emit a combination of AUIPC and SecondOpcode. Used to implement
134 // helpers such as emitLoadLocalAddress and emitLoadAddress.
135 void emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
136 const MCExpr *Symbol, RISCVMCExpr::VariantKind VKHi,
137 unsigned SecondOpcode, SMLoc IDLoc, MCStreamer &Out);
138
139 // Helper to emit pseudo instruction "lla" used in PC-rel addressing.
140 void emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
141
142 // Helper to emit pseudo instruction "lga" used in GOT-rel addressing.
143 void emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
144
145 // Helper to emit pseudo instruction "la" used in GOT/PC-rel addressing.
146 void emitLoadAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
147
148 // Helper to emit pseudo instruction "la.tls.ie" used in initial-exec TLS
149 // addressing.
150 void emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
151
152 // Helper to emit pseudo instruction "la.tls.gd" used in global-dynamic TLS
153 // addressing.
154 void emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
155
156 // Helper to emit pseudo load/store instruction with a symbol.
157 void emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
158 MCStreamer &Out, bool HasTmpReg);
159
160 // Helper to emit pseudo sign/zero extend instruction.
161 void emitPseudoExtend(MCInst &Inst, bool SignExtend, int64_t Width,
162 SMLoc IDLoc, MCStreamer &Out);
163
164 // Helper to emit pseudo vmsge{u}.vx instruction.
165 void emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc, MCStreamer &Out);
166
167 // Checks that a PseudoAddTPRel is using x4/tp in its second input operand.
168 // Enforcing this using a restricted register class for the second input
169 // operand of PseudoAddTPRel results in a poor diagnostic due to the fact
170 // 'add' is an overloaded mnemonic.
171 bool checkPseudoAddTPRel(MCInst &Inst, OperandVector &Operands);
172
173 // Checks that a PseudoTLSDESCCall is using x5/t0 in its output operand.
174 // Enforcing this using a restricted register class for the output
175 // operand of PseudoTLSDESCCall results in a poor diagnostic due to the fact
176 // 'jalr' is an overloaded mnemonic.
177 bool checkPseudoTLSDESCCall(MCInst &Inst, OperandVector &Operands);
178
179 // Check instruction constraints.
180 bool validateInstruction(MCInst &Inst, OperandVector &Operands);
181
182 /// Helper for processing MC instructions that have been successfully matched
183 /// by MatchAndEmitInstruction. Modifications to the emitted instructions,
184 /// like the expansion of pseudo instructions (e.g., "li"), can be performed
185 /// in this method.
186 bool processInstruction(MCInst &Inst, SMLoc IDLoc, OperandVector &Operands,
187 MCStreamer &Out);
188
189// Auto-generated instruction matching functions
190#define GET_ASSEMBLER_HEADER
191#include "RISCVGenAsmMatcher.inc"
192
193 ParseStatus parseCSRSystemRegister(OperandVector &Operands);
196 ParseStatus parseRegister(OperandVector &Operands, bool AllowParens = false);
197 ParseStatus parseMemOpBaseReg(OperandVector &Operands);
198 ParseStatus parseZeroOffsetMemOp(OperandVector &Operands);
199 ParseStatus parseOperandWithModifier(OperandVector &Operands);
200 ParseStatus parseBareSymbol(OperandVector &Operands);
201 ParseStatus parseCallSymbol(OperandVector &Operands);
202 ParseStatus parsePseudoJumpSymbol(OperandVector &Operands);
203 ParseStatus parseJALOffset(OperandVector &Operands);
204 ParseStatus parseVTypeI(OperandVector &Operands);
205 ParseStatus parseMaskReg(OperandVector &Operands);
206 ParseStatus parseInsnDirectiveOpcode(OperandVector &Operands);
207 ParseStatus parseInsnCDirectiveOpcode(OperandVector &Operands);
208 ParseStatus parseGPRAsFPR(OperandVector &Operands);
209 template <bool IsRV64Inst> ParseStatus parseGPRPair(OperandVector &Operands);
210 ParseStatus parseGPRPair(OperandVector &Operands, bool IsRV64Inst);
211 ParseStatus parseFRMArg(OperandVector &Operands);
212 ParseStatus parseFenceArg(OperandVector &Operands);
213 ParseStatus parseReglist(OperandVector &Operands);
214 ParseStatus parseRegReg(OperandVector &Operands);
215 ParseStatus parseRetval(OperandVector &Operands);
216 ParseStatus 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(StringRef Identifier, VTypeState &State,
2129 unsigned &Sew, unsigned &Lmul,
2130 bool &Fractional, bool &TailAgnostic,
2131 bool &MaskAgnostic) {
2132 switch (State) {
2133 case VTypeState_SEW:
2134 if (!Identifier.consume_front("e"))
2135 break;
2136 if (Identifier.getAsInteger(10, Sew))
2137 break;
2138 if (!RISCVVType::isValidSEW(Sew))
2139 break;
2140 State = VTypeState_LMUL;
2141 return false;
2142 case VTypeState_LMUL: {
2143 if (!Identifier.consume_front("m"))
2144 break;
2145 Fractional = Identifier.consume_front("f");
2146 if (Identifier.getAsInteger(10, Lmul))
2147 break;
2148 if (!RISCVVType::isValidLMUL(Lmul, Fractional))
2149 break;
2150 State = VTypeState_TailPolicy;
2151 return false;
2152 }
2153 case VTypeState_TailPolicy:
2154 if (Identifier == "ta")
2155 TailAgnostic = true;
2156 else if (Identifier == "tu")
2157 TailAgnostic = false;
2158 else
2159 break;
2160 State = VTypeState_MaskPolicy;
2161 return false;
2162 case VTypeState_MaskPolicy:
2163 if (Identifier == "ma")
2164 MaskAgnostic = true;
2165 else if (Identifier == "mu")
2166 MaskAgnostic = false;
2167 else
2168 break;
2169 State = VTypeState_Done;
2170 return false;
2171 case VTypeState_Done:
2172 // Extra token?
2173 break;
2174 }
2175
2176 return true;
2177}
2178
2179ParseStatus RISCVAsmParser::parseVTypeI(OperandVector &Operands) {
2180 SMLoc S = getLoc();
2181
2182 unsigned Sew = 0;
2183 unsigned Lmul = 0;
2184 bool Fractional = false;
2185 bool TailAgnostic = false;
2186 bool MaskAgnostic = false;
2187
2188 VTypeState State = VTypeState_SEW;
2189
2190 if (getLexer().isNot(AsmToken::Identifier))
2191 return ParseStatus::NoMatch;
2192
2193 StringRef Identifier = getTok().getIdentifier();
2194
2195 if (parseVTypeToken(Identifier, State, Sew, Lmul, Fractional, TailAgnostic,
2196 MaskAgnostic))
2197 return ParseStatus::NoMatch;
2198
2199 getLexer().Lex();
2200
2201 while (parseOptionalToken(AsmToken::Comma)) {
2202 if (getLexer().isNot(AsmToken::Identifier))
2203 break;
2204
2205 Identifier = getTok().getIdentifier();
2206
2207 if (parseVTypeToken(Identifier, State, Sew, Lmul, Fractional, TailAgnostic,
2208 MaskAgnostic))
2209 break;
2210
2211 getLexer().Lex();
2212 }
2213
2214 if (getLexer().is(AsmToken::EndOfStatement) && State == VTypeState_Done) {
2215 RISCVII::VLMUL VLMUL = RISCVVType::encodeLMUL(Lmul, Fractional);
2216
2217 unsigned VTypeI =
2218 RISCVVType::encodeVTYPE(VLMUL, Sew, TailAgnostic, MaskAgnostic);
2219 Operands.push_back(RISCVOperand::createVType(VTypeI, S));
2220 return ParseStatus::Success;
2221 }
2222
2223 return generateVTypeError(S);
2224}
2225
2226bool RISCVAsmParser::generateVTypeError(SMLoc ErrorLoc) {
2227 return Error(
2228 ErrorLoc,
2229 "operand must be "
2230 "e[8|16|32|64|128|256|512|1024],m[1|2|4|8|f2|f4|f8],[ta|tu],[ma|mu]");
2231}
2232
2233ParseStatus RISCVAsmParser::parseMaskReg(OperandVector &Operands) {
2234 if (getLexer().isNot(AsmToken::Identifier))
2235 return ParseStatus::NoMatch;
2236
2237 StringRef Name = getLexer().getTok().getIdentifier();
2238 if (!Name.consume_back(".t"))
2239 return Error(getLoc(), "expected '.t' suffix");
2241
2242 if (!RegNo)
2243 return ParseStatus::NoMatch;
2244 if (RegNo != RISCV::V0)
2245 return ParseStatus::NoMatch;
2246 SMLoc S = getLoc();
2248 getLexer().Lex();
2249 Operands.push_back(RISCVOperand::createReg(RegNo, S, E));
2250 return ParseStatus::Success;
2251}
2252
2253ParseStatus RISCVAsmParser::parseGPRAsFPR(OperandVector &Operands) {
2254 if (getLexer().isNot(AsmToken::Identifier))
2255 return ParseStatus::NoMatch;
2256
2257 StringRef Name = getLexer().getTok().getIdentifier();
2259
2260 if (!RegNo)
2261 return ParseStatus::NoMatch;
2262 SMLoc S = getLoc();
2264 getLexer().Lex();
2265 Operands.push_back(RISCVOperand::createReg(
2266 RegNo, S, E, !getSTI().hasFeature(RISCV::FeatureStdExtF)));
2267 return ParseStatus::Success;
2268}
2269
2270template <bool IsRV64>
2271ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands) {
2272 return parseGPRPair(Operands, IsRV64);
2273}
2274
2275ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands,
2276 bool IsRV64Inst) {
2277 // If this is not an RV64 GPRPair instruction, don't parse as a GPRPair on
2278 // RV64 as it will prevent matching the RV64 version of the same instruction
2279 // that doesn't use a GPRPair.
2280 // If this is an RV64 GPRPair instruction, there is no RV32 version so we can
2281 // still parse as a pair.
2282 if (!IsRV64Inst && isRV64())
2283 return ParseStatus::NoMatch;
2284
2285 if (getLexer().isNot(AsmToken::Identifier))
2286 return ParseStatus::NoMatch;
2287
2288 StringRef Name = getLexer().getTok().getIdentifier();
2290
2291 if (!RegNo)
2292 return ParseStatus::NoMatch;
2293
2294 if (!RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(RegNo))
2295 return ParseStatus::NoMatch;
2296
2297 if ((RegNo - RISCV::X0) & 1)
2298 return TokError("register must be even");
2299
2300 SMLoc S = getLoc();
2302 getLexer().Lex();
2303
2304 const MCRegisterInfo *RI = getContext().getRegisterInfo();
2305 unsigned Pair = RI->getMatchingSuperReg(
2306 RegNo, RISCV::sub_gpr_even,
2307 &RISCVMCRegisterClasses[RISCV::GPRPairRegClassID]);
2308 Operands.push_back(RISCVOperand::createReg(Pair, S, E));
2309 return ParseStatus::Success;
2310}
2311
2312ParseStatus RISCVAsmParser::parseFRMArg(OperandVector &Operands) {
2313 if (getLexer().isNot(AsmToken::Identifier))
2314 return TokError(
2315 "operand must be a valid floating point rounding mode mnemonic");
2316
2317 StringRef Str = getLexer().getTok().getIdentifier();
2319
2320 if (FRM == RISCVFPRndMode::Invalid)
2321 return TokError(
2322 "operand must be a valid floating point rounding mode mnemonic");
2323
2324 Operands.push_back(RISCVOperand::createFRMArg(FRM, getLoc()));
2325 Lex(); // Eat identifier token.
2326 return ParseStatus::Success;
2327}
2328
2329ParseStatus RISCVAsmParser::parseFenceArg(OperandVector &Operands) {
2330 const AsmToken &Tok = getLexer().getTok();
2331
2332 if (Tok.is(AsmToken::Integer)) {
2333 if (Tok.getIntVal() != 0)
2334 goto ParseFail;
2335
2336 Operands.push_back(RISCVOperand::createFenceArg(0, getLoc()));
2337 Lex();
2338 return ParseStatus::Success;
2339 }
2340
2341 if (Tok.is(AsmToken::Identifier)) {
2342 StringRef Str = Tok.getIdentifier();
2343
2344 // Letters must be unique, taken from 'iorw', and in ascending order. This
2345 // holds as long as each individual character is one of 'iorw' and is
2346 // greater than the previous character.
2347 unsigned Imm = 0;
2348 bool Valid = true;
2349 char Prev = '\0';
2350 for (char c : Str) {
2351 switch (c) {
2352 default:
2353 Valid = false;
2354 break;
2355 case 'i':
2357 break;
2358 case 'o':
2360 break;
2361 case 'r':
2363 break;
2364 case 'w':
2366 break;
2367 }
2368
2369 if (c <= Prev) {
2370 Valid = false;
2371 break;
2372 }
2373 Prev = c;
2374 }
2375
2376 if (!Valid)
2377 goto ParseFail;
2378
2379 Operands.push_back(RISCVOperand::createFenceArg(Imm, getLoc()));
2380 Lex();
2381 return ParseStatus::Success;
2382 }
2383
2384ParseFail:
2385 return TokError("operand must be formed of letters selected in-order from "
2386 "'iorw' or be 0");
2387}
2388
2389ParseStatus RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
2390 if (parseToken(AsmToken::LParen, "expected '('"))
2391 return ParseStatus::Failure;
2392 Operands.push_back(RISCVOperand::createToken("(", getLoc()));
2393
2394 if (!parseRegister(Operands).isSuccess())
2395 return Error(getLoc(), "expected register");
2396
2397 if (parseToken(AsmToken::RParen, "expected ')'"))
2398 return ParseStatus::Failure;
2399 Operands.push_back(RISCVOperand::createToken(")", getLoc()));
2400
2401 return ParseStatus::Success;
2402}
2403
2404ParseStatus RISCVAsmParser::parseZeroOffsetMemOp(OperandVector &Operands) {
2405 // Atomic operations such as lr.w, sc.w, and amo*.w accept a "memory operand"
2406 // as one of their register operands, such as `(a0)`. This just denotes that
2407 // the register (in this case `a0`) contains a memory address.
2408 //
2409 // Normally, we would be able to parse these by putting the parens into the
2410 // instruction string. However, GNU as also accepts a zero-offset memory
2411 // operand (such as `0(a0)`), and ignores the 0. Normally this would be parsed
2412 // with parseImmediate followed by parseMemOpBaseReg, but these instructions
2413 // do not accept an immediate operand, and we do not want to add a "dummy"
2414 // operand that is silently dropped.
2415 //
2416 // Instead, we use this custom parser. This will: allow (and discard) an
2417 // offset if it is zero; require (and discard) parentheses; and add only the
2418 // parsed register operand to `Operands`.
2419 //
2420 // These operands are printed with RISCVInstPrinter::printZeroOffsetMemOp,
2421 // which will only print the register surrounded by parentheses (which GNU as
2422 // also uses as its canonical representation for these operands).
2423 std::unique_ptr<RISCVOperand> OptionalImmOp;
2424
2425 if (getLexer().isNot(AsmToken::LParen)) {
2426 // Parse an Integer token. We do not accept arbritrary constant expressions
2427 // in the offset field (because they may include parens, which complicates
2428 // parsing a lot).
2429 int64_t ImmVal;
2430 SMLoc ImmStart = getLoc();
2431 if (getParser().parseIntToken(ImmVal,
2432 "expected '(' or optional integer offset"))
2433 return ParseStatus::Failure;
2434
2435 // Create a RISCVOperand for checking later (so the error messages are
2436 // nicer), but we don't add it to Operands.
2437 SMLoc ImmEnd = getLoc();
2438 OptionalImmOp =
2439 RISCVOperand::createImm(MCConstantExpr::create(ImmVal, getContext()),
2440 ImmStart, ImmEnd, isRV64());
2441 }
2442
2443 if (parseToken(AsmToken::LParen,
2444 OptionalImmOp ? "expected '(' after optional integer offset"
2445 : "expected '(' or optional integer offset"))
2446 return ParseStatus::Failure;
2447
2448 if (!parseRegister(Operands).isSuccess())
2449 return Error(getLoc(), "expected register");
2450
2451 if (parseToken(AsmToken::RParen, "expected ')'"))
2452 return ParseStatus::Failure;
2453
2454 // Deferred Handling of non-zero offsets. This makes the error messages nicer.
2455 if (OptionalImmOp && !OptionalImmOp->isImmZero())
2456 return Error(
2457 OptionalImmOp->getStartLoc(), "optional integer offset must be 0",
2458 SMRange(OptionalImmOp->getStartLoc(), OptionalImmOp->getEndLoc()));
2459
2460 return ParseStatus::Success;
2461}
2462
2463ParseStatus RISCVAsmParser::parseRegReg(OperandVector &Operands) {
2464 // RR : a2(a1)
2465 if (getLexer().getKind() != AsmToken::Identifier)
2466 return ParseStatus::NoMatch;
2467
2468 StringRef RegName = getLexer().getTok().getIdentifier();
2470 if (!Reg)
2471 return Error(getLoc(), "invalid register");
2472 getLexer().Lex();
2473
2474 if (parseToken(AsmToken::LParen, "expected '(' or invalid operand"))
2475 return ParseStatus::Failure;
2476
2477 if (getLexer().getKind() != AsmToken::Identifier)
2478 return Error(getLoc(), "expected register");
2479
2480 StringRef Reg2Name = getLexer().getTok().getIdentifier();
2481 MCRegister Reg2 = matchRegisterNameHelper(Reg2Name);
2482 if (!Reg2)
2483 return Error(getLoc(), "invalid register");
2484 getLexer().Lex();
2485
2486 if (parseToken(AsmToken::RParen, "expected ')'"))
2487 return ParseStatus::Failure;
2488
2489 Operands.push_back(RISCVOperand::createRegReg(Reg, Reg2, getLoc()));
2490
2491 return ParseStatus::Success;
2492}
2493
2494ParseStatus RISCVAsmParser::parseReglist(OperandVector &Operands) {
2495 // Rlist: {ra [, s0[-sN]]}
2496 // XRlist: {x1 [, x8[-x9][, x18[-xN]]]}
2497 SMLoc S = getLoc();
2498
2499 if (parseToken(AsmToken::LCurly, "register list must start with '{'"))
2500 return ParseStatus::Failure;
2501
2502 bool IsEABI = isRVE();
2503
2504 if (getLexer().isNot(AsmToken::Identifier))
2505 return Error(getLoc(), "register list must start from 'ra' or 'x1'");
2506
2507 StringRef RegName = getLexer().getTok().getIdentifier();
2509 MCRegister RegEnd;
2510 if (RegStart != RISCV::X1)
2511 return Error(getLoc(), "register list must start from 'ra' or 'x1'");
2512 getLexer().Lex();
2513
2514 // parse case like ,s0
2515 if (parseOptionalToken(AsmToken::Comma)) {
2516 if (getLexer().isNot(AsmToken::Identifier))
2517 return Error(getLoc(), "invalid register");
2518 StringRef RegName = getLexer().getTok().getIdentifier();
2519 RegStart = matchRegisterNameHelper(RegName);
2520 if (!RegStart)
2521 return Error(getLoc(), "invalid register");
2522 if (RegStart != RISCV::X8)
2523 return Error(getLoc(),
2524 "continuous register list must start from 's0' or 'x8'");
2525 getLexer().Lex(); // eat reg
2526 }
2527
2528 // parse case like -s1
2529 if (parseOptionalToken(AsmToken::Minus)) {
2530 StringRef EndName = getLexer().getTok().getIdentifier();
2531 // FIXME: the register mapping and checks of EABI is wrong
2532 RegEnd = matchRegisterNameHelper(EndName);
2533 if (!RegEnd)
2534 return Error(getLoc(), "invalid register");
2535 if (IsEABI && RegEnd != RISCV::X9)
2536 return Error(getLoc(), "contiguous register list of EABI can only be "
2537 "'s0-s1' or 'x8-x9' pair");
2538 getLexer().Lex();
2539 }
2540
2541 if (!IsEABI) {
2542 // parse extra part like ', x18[-x20]' for XRegList
2543 if (parseOptionalToken(AsmToken::Comma)) {
2544 if (RegEnd != RISCV::X9)
2545 return Error(
2546 getLoc(),
2547 "first contiguous registers pair of register list must be 'x8-x9'");
2548
2549 // parse ', x18' for extra part
2550 if (getLexer().isNot(AsmToken::Identifier))
2551 return Error(getLoc(), "invalid register");
2552 StringRef EndName = getLexer().getTok().getIdentifier();
2553 if (MatchRegisterName(EndName) != RISCV::X18)
2554 return Error(getLoc(),
2555 "second contiguous registers pair of register list "
2556 "must start from 'x18'");
2557 getLexer().Lex();
2558
2559 // parse '-x20' for extra part
2560 if (parseOptionalToken(AsmToken::Minus)) {
2561 if (getLexer().isNot(AsmToken::Identifier))
2562 return Error(getLoc(), "invalid register");
2563 EndName = getLexer().getTok().getIdentifier();
2564 if (MatchRegisterName(EndName) == RISCV::NoRegister)
2565 return Error(getLoc(), "invalid register");
2566 getLexer().Lex();
2567 }
2568 RegEnd = MatchRegisterName(EndName);
2569 }
2570 }
2571
2572 if (RegEnd == RISCV::X26)
2573 return Error(getLoc(), "invalid register list, {ra, s0-s10} or {x1, x8-x9, "
2574 "x18-x26} is not supported");
2575
2576 if (parseToken(AsmToken::RCurly, "register list must end with '}'"))
2577 return ParseStatus::Failure;
2578
2579 if (RegEnd == RISCV::NoRegister)
2580 RegEnd = RegStart;
2581
2582 auto Encode = RISCVZC::encodeRlist(RegEnd, IsEABI);
2583 if (Encode == RISCVZC::INVALID_RLIST)
2584 return Error(S, "invalid register list");
2585 Operands.push_back(RISCVOperand::createRlist(Encode, S));
2586
2587 return ParseStatus::Success;
2588}
2589
2590ParseStatus RISCVAsmParser::parseZcmpStackAdj(OperandVector &Operands,
2591 bool ExpectNegative) {
2592 bool Negative = parseOptionalToken(AsmToken::Minus);
2593
2594 SMLoc S = getLoc();
2595 int64_t StackAdjustment = getLexer().getTok().getIntVal();
2596 unsigned Spimm = 0;
2597 unsigned RlistVal = static_cast<RISCVOperand *>(Operands[1].get())->Rlist.Val;
2598
2599 bool IsEABI = isRVE();
2600 if (Negative != ExpectNegative ||
2601 !RISCVZC::getSpimm(RlistVal, Spimm, StackAdjustment, isRV64(), IsEABI))
2602 return ParseStatus::NoMatch;
2603 Operands.push_back(RISCVOperand::createSpimm(Spimm << 4, S));
2604 getLexer().Lex();
2605 return ParseStatus::Success;
2606}
2607
2608/// Looks at a token type and creates the relevant operand from this
2609/// information, adding to Operands. If operand was parsed, returns false, else
2610/// true.
2611bool RISCVAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
2612 // Check if the current operand has a custom associated parser, if so, try to
2613 // custom parse the operand, or fallback to the general approach.
2615 MatchOperandParserImpl(Operands, Mnemonic, /*ParseForAllFeatures=*/true);
2616 if (Result.isSuccess())
2617 return false;
2618 if (Result.isFailure())
2619 return true;
2620
2621 // Attempt to parse token as a register.
2622 if (parseRegister(Operands, true).isSuccess())
2623 return false;
2624
2625 // Attempt to parse token as an immediate
2626 if (parseImmediate(Operands).isSuccess()) {
2627 // Parse memory base register if present
2628 if (getLexer().is(AsmToken::LParen))
2629 return !parseMemOpBaseReg(Operands).isSuccess();
2630 return false;
2631 }
2632
2633 // Finally we have exhausted all options and must declare defeat.
2634 Error(getLoc(), "unknown operand");
2635 return true;
2636}
2637
2638bool RISCVAsmParser::ParseInstruction(ParseInstructionInfo &Info,
2639 StringRef Name, SMLoc NameLoc,
2641 // Ensure that if the instruction occurs when relaxation is enabled,
2642 // relocations are forced for the file. Ideally this would be done when there
2643 // is enough information to reliably determine if the instruction itself may
2644 // cause relaxations. Unfortunately instruction processing stage occurs in the
2645 // same pass as relocation emission, so it's too late to set a 'sticky bit'
2646 // for the entire file.
2647 if (getSTI().hasFeature(RISCV::FeatureRelax)) {
2648 auto *Assembler = getTargetStreamer().getStreamer().getAssemblerPtr();
2649 if (Assembler != nullptr) {
2650 RISCVAsmBackend &MAB =
2651 static_cast<RISCVAsmBackend &>(Assembler->getBackend());
2652 MAB.setForceRelocs();
2653 }
2654 }
2655
2656 // First operand is token for instruction
2657 Operands.push_back(RISCVOperand::createToken(Name, NameLoc));
2658
2659 // If there are no more operands, then finish
2660 if (getLexer().is(AsmToken::EndOfStatement)) {
2661 getParser().Lex(); // Consume the EndOfStatement.
2662 return false;
2663 }
2664
2665 // Parse first operand
2666 if (parseOperand(Operands, Name))
2667 return true;
2668
2669 // Parse until end of statement, consuming commas between operands
2670 while (parseOptionalToken(AsmToken::Comma)) {
2671 // Parse next operand
2672 if (parseOperand(Operands, Name))
2673 return true;
2674 }
2675
2676 if (getParser().parseEOL("unexpected token")) {
2677 getParser().eatToEndOfStatement();
2678 return true;
2679 }
2680 return false;
2681}
2682
2683bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
2686
2687 if (const RISCVMCExpr *RE = dyn_cast<RISCVMCExpr>(Expr)) {
2688 Kind = RE->getKind();
2689 Expr = RE->getSubExpr();
2690 }
2691
2692 MCValue Res;
2693 MCFixup Fixup;
2694 if (Expr->evaluateAsRelocatable(Res, nullptr, &Fixup))
2695 return Res.getRefKind() == RISCVMCExpr::VK_RISCV_None;
2696 return false;
2697}
2698
2699bool RISCVAsmParser::isSymbolDiff(const MCExpr *Expr) {
2700 MCValue Res;
2701 MCFixup Fixup;
2702 if (Expr->evaluateAsRelocatable(Res, nullptr, &Fixup)) {
2703 return Res.getRefKind() == RISCVMCExpr::VK_RISCV_None && Res.getSymA() &&
2704 Res.getSymB();
2705 }
2706 return false;
2707}
2708
2709ParseStatus RISCVAsmParser::parseDirective(AsmToken DirectiveID) {
2710 StringRef IDVal = DirectiveID.getString();
2711
2712 if (IDVal == ".option")
2713 return parseDirectiveOption();
2714 if (IDVal == ".attribute")
2715 return parseDirectiveAttribute();
2716 if (IDVal == ".insn")
2717 return parseDirectiveInsn(DirectiveID.getLoc());
2718 if (IDVal == ".variant_cc")
2719 return parseDirectiveVariantCC();
2720
2721 return ParseStatus::NoMatch;
2722}
2723
2724bool RISCVAsmParser::resetToArch(StringRef Arch, SMLoc Loc, std::string &Result,
2725 bool FromOptionDirective) {
2726 for (auto &Feature : RISCVFeatureKV)
2728 clearFeatureBits(Feature.Value, Feature.Key);
2729
2730 auto ParseResult = llvm::RISCVISAInfo::parseArchString(
2731 Arch, /*EnableExperimentalExtension=*/true,
2732 /*ExperimentalExtensionVersionCheck=*/true);
2733 if (!ParseResult) {
2734 std::string Buffer;
2735 raw_string_ostream OutputErrMsg(Buffer);
2736 handleAllErrors(ParseResult.takeError(), [&](llvm::StringError &ErrMsg) {
2737 OutputErrMsg << "invalid arch name '" << Arch << "', "
2738 << ErrMsg.getMessage();
2739 });
2740
2741 return Error(Loc, OutputErrMsg.str());
2742 }
2743 auto &ISAInfo = *ParseResult;
2744
2745 for (auto &Feature : RISCVFeatureKV)
2746 if (ISAInfo->hasExtension(Feature.Key))
2747 setFeatureBits(Feature.Value, Feature.Key);
2748
2749 if (FromOptionDirective) {
2750 if (ISAInfo->getXLen() == 32 && isRV64())
2751 return Error(Loc, "bad arch string switching from rv64 to rv32");
2752 else if (ISAInfo->getXLen() == 64 && !isRV64())
2753 return Error(Loc, "bad arch string switching from rv32 to rv64");
2754 }
2755
2756 if (ISAInfo->getXLen() == 32)
2757 clearFeatureBits(RISCV::Feature64Bit, "64bit");
2758 else if (ISAInfo->getXLen() == 64)
2759 setFeatureBits(RISCV::Feature64Bit, "64bit");
2760 else
2761 return Error(Loc, "bad arch string " + Arch);
2762
2763 Result = ISAInfo->toString();
2764 return false;
2765}
2766
2767bool RISCVAsmParser::parseDirectiveOption() {
2768 MCAsmParser &Parser = getParser();
2769 // Get the option token.
2770 AsmToken Tok = Parser.getTok();
2771
2772 // At the moment only identifiers are supported.
2773 if (parseToken(AsmToken::Identifier, "expected identifier"))
2774 return true;
2775
2777
2778 if (Option == "push") {
2779 if (Parser.parseEOL())
2780 return true;
2781
2782 getTargetStreamer().emitDirectiveOptionPush();
2783 pushFeatureBits();
2784 return false;
2785 }
2786
2787 if (Option == "pop") {
2788 SMLoc StartLoc = Parser.getTok().getLoc();
2789 if (Parser.parseEOL())
2790 return true;
2791
2792 getTargetStreamer().emitDirectiveOptionPop();
2793 if (popFeatureBits())
2794 return Error(StartLoc, ".option pop with no .option push");
2795
2796 return false;
2797 }
2798
2799 if (Option == "arch") {
2801 do {
2802 if (Parser.parseComma())
2803 return true;
2804
2806 if (parseOptionalToken(AsmToken::Plus))
2807 Type = RISCVOptionArchArgType::Plus;
2808 else if (parseOptionalToken(AsmToken::Minus))
2809 Type = RISCVOptionArchArgType::Minus;
2810 else if (!Args.empty())
2811 return Error(Parser.getTok().getLoc(),
2812 "unexpected token, expected + or -");
2813 else
2814 Type = RISCVOptionArchArgType::Full;
2815
2816 if (Parser.getTok().isNot(AsmToken::Identifier))
2817 return Error(Parser.getTok().getLoc(),
2818 "unexpected token, expected identifier");
2819
2820 StringRef Arch = Parser.getTok().getString();
2821 SMLoc Loc = Parser.getTok().getLoc();
2822 Parser.Lex();
2823
2824 if (Type == RISCVOptionArchArgType::Full) {
2825 std::string Result;
2826 if (resetToArch(Arch, Loc, Result, true))
2827 return true;
2828
2829 Args.emplace_back(Type, Result);
2830 break;
2831 }
2832
2833 auto Ext = llvm::lower_bound(RISCVFeatureKV, Arch);
2834 if (Ext == std::end(RISCVFeatureKV) || StringRef(Ext->Key) != Arch ||
2836 if (isDigit(Arch.back()))
2837 return Error(
2838 Loc,
2839 "Extension version number parsing not currently implemented");
2840 return Error(Loc, "unknown extension feature");
2841 }
2842
2843 Args.emplace_back(Type, Ext->Key);
2844
2845 if (Type == RISCVOptionArchArgType::Plus) {
2846 FeatureBitset OldFeatureBits = STI->getFeatureBits();
2847
2848 setFeatureBits(Ext->Value, Ext->Key);
2849 auto ParseResult = RISCVFeatures::parseFeatureBits(isRV64(), STI->getFeatureBits());
2850 if (!ParseResult) {
2851 copySTI().setFeatureBits(OldFeatureBits);
2852 setAvailableFeatures(ComputeAvailableFeatures(OldFeatureBits));
2853
2854 std::string Buffer;
2855 raw_string_ostream OutputErrMsg(Buffer);
2856 handleAllErrors(ParseResult.takeError(), [&](llvm::StringError &ErrMsg) {
2857 OutputErrMsg << ErrMsg.getMessage();
2858 });
2859
2860 return Error(Loc, OutputErrMsg.str());
2861 }
2862 } else {
2863 assert(Type == RISCVOptionArchArgType::Minus);
2864 // It is invalid to disable an extension that there are other enabled
2865 // extensions depend on it.
2866 // TODO: Make use of RISCVISAInfo to handle this
2867 for (auto &Feature : RISCVFeatureKV) {
2868 if (getSTI().hasFeature(Feature.Value) &&
2869 Feature.Implies.test(Ext->Value))
2870 return Error(Loc,
2871 Twine("Can't disable ") + Ext->Key + " extension, " +
2872 Feature.Key + " extension requires " + Ext->Key +
2873 " extension be enabled");
2874 }
2875
2876 clearFeatureBits(Ext->Value, Ext->Key);
2877 }
2878 } while (Parser.getTok().isNot(AsmToken::EndOfStatement));
2879
2880 if (Parser.parseEOL())
2881 return true;
2882
2883 getTargetStreamer().emitDirectiveOptionArch(Args);
2884 return false;
2885 }
2886
2887 if (Option == "rvc") {
2888 if (Parser.parseEOL())
2889 return true;
2890
2891 getTargetStreamer().emitDirectiveOptionRVC();
2892 setFeatureBits(RISCV::FeatureStdExtC, "c");
2893 return false;
2894 }
2895
2896 if (Option == "norvc") {
2897 if (Parser.parseEOL())
2898 return true;
2899
2900 getTargetStreamer().emitDirectiveOptionNoRVC();
2901 clearFeatureBits(RISCV::FeatureStdExtC, "c");
2902 clearFeatureBits(RISCV::FeatureStdExtZca, "zca");
2903 return false;
2904 }
2905
2906 if (Option == "pic") {
2907 if (Parser.parseEOL())
2908 return true;
2909
2910 getTargetStreamer().emitDirectiveOptionPIC();
2911 ParserOptions.IsPicEnabled = true;
2912 return false;
2913 }
2914
2915 if (Option == "nopic") {
2916 if (Parser.parseEOL())
2917 return true;
2918
2919 getTargetStreamer().emitDirectiveOptionNoPIC();
2920 ParserOptions.IsPicEnabled = false;
2921 return false;
2922 }
2923
2924 if (Option == "relax") {
2925 if (Parser.parseEOL())
2926 return true;
2927
2928 getTargetStreamer().emitDirectiveOptionRelax();
2929 setFeatureBits(RISCV::FeatureRelax, "relax");
2930 return false;
2931 }
2932
2933 if (Option == "norelax") {
2934 if (Parser.parseEOL())
2935 return true;
2936
2937 getTargetStreamer().emitDirectiveOptionNoRelax();
2938 clearFeatureBits(RISCV::FeatureRelax, "relax");
2939 return false;
2940 }
2941
2942 // Unknown option.
2943 Warning(Parser.getTok().getLoc(), "unknown option, expected 'push', 'pop', "
2944 "'rvc', 'norvc', 'arch', 'relax' or "
2945 "'norelax'");
2946 Parser.eatToEndOfStatement();
2947 return false;
2948}
2949
2950/// parseDirectiveAttribute
2951/// ::= .attribute expression ',' ( expression | "string" )
2952/// ::= .attribute identifier ',' ( expression | "string" )
2953bool RISCVAsmParser::parseDirectiveAttribute() {
2954 MCAsmParser &Parser = getParser();
2955 int64_t Tag;
2956 SMLoc TagLoc;
2957 TagLoc = Parser.getTok().getLoc();
2958 if (Parser.getTok().is(AsmToken::Identifier)) {
2959 StringRef Name = Parser.getTok().getIdentifier();
2960 std::optional<unsigned> Ret =
2962 if (!Ret)
2963 return Error(TagLoc, "attribute name not recognised: " + Name);
2964 Tag = *Ret;
2965 Parser.Lex();
2966 } else {
2967 const MCExpr *AttrExpr;
2968
2969 TagLoc = Parser.getTok().getLoc();
2970 if (Parser.parseExpression(AttrExpr))
2971 return true;
2972
2973 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
2974 if (check(!CE, TagLoc, "expected numeric constant"))
2975 return true;
2976
2977 Tag = CE->getValue();
2978 }
2979
2980 if (Parser.parseComma())
2981 return true;
2982
2983 StringRef StringValue;
2984 int64_t IntegerValue = 0;
2985 bool IsIntegerValue = true;
2986
2987 // RISC-V attributes have a string value if the tag number is odd
2988 // and an integer value if the tag number is even.
2989 if (Tag % 2)
2990 IsIntegerValue = false;
2991
2992 SMLoc ValueExprLoc = Parser.getTok().getLoc();
2993 if (IsIntegerValue) {
2994 const MCExpr *ValueExpr;
2995 if (Parser.parseExpression(ValueExpr))
2996 return true;
2997
2998 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
2999 if (!CE)
3000 return Error(ValueExprLoc, "expected numeric constant");
3001 IntegerValue = CE->getValue();
3002 } else {
3003 if (Parser.getTok().isNot(AsmToken::String))
3004 return Error(Parser.getTok().getLoc(), "expected string constant");
3005
3006 StringValue = Parser.getTok().getStringContents();
3007 Parser.Lex();
3008 }
3009
3010 if (Parser.parseEOL())
3011 return true;
3012
3013 if (IsIntegerValue)
3014 getTargetStreamer().emitAttribute(Tag, IntegerValue);
3015 else if (Tag != RISCVAttrs::ARCH)
3016 getTargetStreamer().emitTextAttribute(Tag, StringValue);
3017 else {
3018 std::string Result;
3019 if (resetToArch(StringValue, ValueExprLoc, Result, false))
3020 return true;
3021
3022 // Then emit the arch string.
3023 getTargetStreamer().emitTextAttribute(Tag, Result);
3024 }
3025
3026 return false;
3027}
3028
3029bool isValidInsnFormat(StringRef Format, bool AllowC) {
3030 return StringSwitch<bool>(Format)
3031 .Cases("r", "r4", "i", "b", "sb", "u", "j", "uj", "s", true)
3032 .Cases("cr", "ci", "ciw", "css", "cl", "cs", "ca", "cb", "cj", AllowC)
3033 .Default(false);
3034}
3035
3036/// parseDirectiveInsn
3037/// ::= .insn [ format encoding, (operands (, operands)*) ]
3038bool RISCVAsmParser::parseDirectiveInsn(SMLoc L) {
3039 MCAsmParser &Parser = getParser();
3040
3041 // Expect instruction format as identifier.
3043 SMLoc ErrorLoc = Parser.getTok().getLoc();
3044 if (Parser.parseIdentifier(Format))
3045 return Error(ErrorLoc, "expected instruction format");
3046
3047 bool AllowC = getSTI().hasFeature(RISCV::FeatureStdExtC) ||
3048 getSTI().hasFeature(RISCV::FeatureStdExtZca);
3049 if (!isValidInsnFormat(Format, AllowC))
3050 return Error(ErrorLoc, "invalid instruction format");
3051
3052 std::string FormatName = (".insn_" + Format).str();
3053
3056
3057 if (ParseInstruction(Info, FormatName, L, Operands))
3058 return true;
3059
3060 unsigned Opcode;
3062 return MatchAndEmitInstruction(L, Opcode, Operands, Parser.getStreamer(),
3063 ErrorInfo,
3064 /*MatchingInlineAsm=*/false);
3065}
3066
3067/// parseDirectiveVariantCC
3068/// ::= .variant_cc symbol
3069bool RISCVAsmParser::parseDirectiveVariantCC() {
3071 if (getParser().parseIdentifier(Name))
3072 return TokError("expected symbol name");
3073 if (parseEOL())
3074 return true;
3075 getTargetStreamer().emitDirectiveVariantCC(
3076 *getContext().getOrCreateSymbol(Name));
3077 return false;
3078}
3079
3080void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
3081 MCInst CInst;
3082 bool Res = RISCVRVC::compress(CInst, Inst, getSTI());
3083 if (Res)
3084 ++RISCVNumInstrsCompressed;
3085 S.emitInstruction((Res ? CInst : Inst), getSTI());
3086}
3087
3088void RISCVAsmParser::emitLoadImm(MCRegister DestReg, int64_t Value,
3089 MCStreamer &Out) {
3091 RISCVMatInt::generateMCInstSeq(Value, getSTI(), DestReg, Seq);
3092
3093 for (MCInst &Inst : Seq) {
3094 emitToStreamer(Out, Inst);
3095 }
3096}
3097
3098void RISCVAsmParser::emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
3099 const MCExpr *Symbol,
3101 unsigned SecondOpcode, SMLoc IDLoc,
3102 MCStreamer &Out) {
3103 // A pair of instructions for PC-relative addressing; expands to
3104 // TmpLabel: AUIPC TmpReg, VKHi(symbol)
3105 // OP DestReg, TmpReg, %pcrel_lo(TmpLabel)
3106 MCContext &Ctx = getContext();
3107
3108 MCSymbol *TmpLabel = Ctx.createNamedTempSymbol("pcrel_hi");
3109 Out.emitLabel(TmpLabel);
3110
3111 const RISCVMCExpr *SymbolHi = RISCVMCExpr::create(Symbol, VKHi, Ctx);
3112 emitToStreamer(
3113 Out, MCInstBuilder(RISCV::AUIPC).addOperand(TmpReg).addExpr(SymbolHi));
3114
3115 const MCExpr *RefToLinkTmpLabel =
3118
3119 emitToStreamer(Out, MCInstBuilder(SecondOpcode)
3120 .addOperand(DestReg)
3121 .addOperand(TmpReg)
3122 .addExpr(RefToLinkTmpLabel));
3123}
3124
3125void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
3126 MCStreamer &Out) {
3127 // The load local address pseudo-instruction "lla" is used in PC-relative
3128 // addressing of local symbols:
3129 // lla rdest, symbol
3130 // expands to
3131 // TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
3132 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3133 MCOperand DestReg = Inst.getOperand(0);
3134 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3135 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
3136 RISCV::ADDI, IDLoc, Out);
3137}
3138
3139void RISCVAsmParser::emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc,
3140 MCStreamer &Out) {
3141 // The load global address pseudo-instruction "lga" is used in GOT-indirect
3142 // addressing of global symbols:
3143 // lga rdest, symbol
3144 // expands to
3145 // TmpLabel: AUIPC rdest, %got_pcrel_hi(symbol)
3146 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3147 MCOperand DestReg = Inst.getOperand(0);
3148 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3149 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3150 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_GOT_HI,
3151 SecondOpcode, IDLoc, Out);
3152}
3153
3154void RISCVAsmParser::emitLoadAddress(MCInst &Inst, SMLoc IDLoc,
3155 MCStreamer &Out) {
3156 // The load address pseudo-instruction "la" is used in PC-relative and
3157 // GOT-indirect addressing of global symbols:
3158 // la rdest, symbol
3159 // is an alias for either (for non-PIC)
3160 // lla rdest, symbol
3161 // or (for PIC)
3162 // lga rdest, symbol
3163 if (ParserOptions.IsPicEnabled)
3164 emitLoadGlobalAddress(Inst, IDLoc, Out);
3165 else
3166 emitLoadLocalAddress(Inst, IDLoc, Out);
3167}
3168
3169void RISCVAsmParser::emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc,
3170 MCStreamer &Out) {
3171 // The load TLS IE address pseudo-instruction "la.tls.ie" is used in
3172 // initial-exec TLS model addressing of global symbols:
3173 // la.tls.ie rdest, symbol
3174 // expands to
3175 // TmpLabel: AUIPC rdest, %tls_ie_pcrel_hi(symbol)
3176 // Lx rdest, %pcrel_lo(TmpLabel)(rdest)
3177 MCOperand DestReg = Inst.getOperand(0);
3178 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3179 unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
3180 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GOT_HI,
3181 SecondOpcode, IDLoc, Out);
3182}
3183
3184void RISCVAsmParser::emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc,
3185 MCStreamer &Out) {
3186 // The load TLS GD address pseudo-instruction "la.tls.gd" is used in
3187 // global-dynamic TLS model addressing of global symbols:
3188 // la.tls.gd rdest, symbol
3189 // expands to
3190 // TmpLabel: AUIPC rdest, %tls_gd_pcrel_hi(symbol)
3191 // ADDI rdest, rdest, %pcrel_lo(TmpLabel)
3192 MCOperand DestReg = Inst.getOperand(0);
3193 const MCExpr *Symbol = Inst.getOperand(1).getExpr();
3194 emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GD_HI,
3195 RISCV::ADDI, IDLoc, Out);
3196}
3197
3198void RISCVAsmParser::emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode,
3199 SMLoc IDLoc, MCStreamer &Out,
3200 bool HasTmpReg) {
3201 // The load/store pseudo-instruction does a pc-relative load with
3202 // a symbol.
3203 //
3204 // The expansion looks like this
3205 //
3206 // TmpLabel: AUIPC tmp, %pcrel_hi(symbol)
3207 // [S|L]X rd, %pcrel_lo(TmpLabel)(tmp)
3208 unsigned DestRegOpIdx = HasTmpReg ? 1 : 0;
3209 MCOperand DestReg = Inst.getOperand(DestRegOpIdx);
3210 unsigned SymbolOpIdx = HasTmpReg ? 2 : 1;
3211 MCOperand TmpReg = Inst.getOperand(0);
3212 const MCExpr *Symbol = Inst.getOperand(SymbolOpIdx).getExpr();
3213 emitAuipcInstPair(DestReg, TmpReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
3214 Opcode, IDLoc, Out);
3215}
3216
3217void RISCVAsmParser::emitPseudoExtend(MCInst &Inst, bool SignExtend,
3218 int64_t Width, SMLoc IDLoc,
3219 MCStreamer &Out) {
3220 // The sign/zero extend pseudo-instruction does two shifts, with the shift
3221 // amounts dependent on the XLEN.
3222 //
3223 // The expansion looks like this
3224 //
3225 // SLLI rd, rs, XLEN - Width
3226 // SR[A|R]I rd, rd, XLEN - Width
3227 MCOperand DestReg = Inst.getOperand(0);
3228 MCOperand SourceReg = Inst.getOperand(1);
3229
3230 unsigned SecondOpcode = SignExtend ? RISCV::SRAI : RISCV::SRLI;
3231 int64_t ShAmt = (isRV64() ? 64 : 32) - Width;
3232
3233 assert(ShAmt > 0 && "Shift amount must be non-zero.");
3234
3235 emitToStreamer(Out, MCInstBuilder(RISCV::SLLI)
3236 .addOperand(DestReg)
3237 .addOperand(SourceReg)
3238 .addImm(ShAmt));
3239
3240 emitToStreamer(Out, MCInstBuilder(SecondOpcode)
3241 .addOperand(DestReg)
3242 .addOperand(DestReg)
3243 .addImm(ShAmt));
3244}
3245
3246void RISCVAsmParser::emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
3247 MCStreamer &Out) {
3248 if (Inst.getNumOperands() == 3) {
3249 // unmasked va >= x
3250 //
3251 // pseudoinstruction: vmsge{u}.vx vd, va, x
3252 // expansion: vmslt{u}.vx vd, va, x; vmnand.mm vd, vd, vd
3253 emitToStreamer(Out, MCInstBuilder(Opcode)
3254 .addOperand(Inst.getOperand(0))
3255 .addOperand(Inst.getOperand(1))
3256 .addOperand(Inst.getOperand(2))
3257 .addReg(RISCV::NoRegister)
3258 .setLoc(IDLoc));
3259 emitToStreamer(Out, MCInstBuilder(RISCV::VMNAND_MM)
3260 .addOperand(Inst.getOperand(0))
3261 .addOperand(Inst.getOperand(0))
3262 .addOperand(Inst.getOperand(0))
3263 .setLoc(IDLoc));
3264 } else if (Inst.getNumOperands() == 4) {
3265 // masked va >= x, vd != v0
3266 //
3267 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t
3268 // expansion: vmslt{u}.vx vd, va, x, v0.t; vmxor.mm vd, vd, v0
3269 assert(Inst.getOperand(0).getReg() != RISCV::V0 &&
3270 "The destination register should not be V0.");
3271 emitToStreamer(Out, MCInstBuilder(Opcode)
3272 .addOperand(Inst.getOperand(0))
3273 .addOperand(Inst.getOperand(1))
3274 .addOperand(Inst.getOperand(2))
3275 .addOperand(Inst.getOperand(3))
3276 .setLoc(IDLoc));
3277 emitToStreamer(Out, MCInstBuilder(RISCV::VMXOR_MM)
3278 .addOperand(Inst.getOperand(0))
3279 .addOperand(Inst.getOperand(0))
3280 .addReg(RISCV::V0)
3281 .setLoc(IDLoc));
3282 } else if (Inst.getNumOperands() == 5 &&
3283 Inst.getOperand(0).getReg() == RISCV::V0) {
3284 // masked va >= x, vd == v0
3285 //
3286 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3287 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vd, vd, vt
3288 assert(Inst.getOperand(0).getReg() == RISCV::V0 &&
3289 "The destination register should be V0.");
3290 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3291 "The temporary vector register should not be V0.");
3292 emitToStreamer(Out, MCInstBuilder(Opcode)
3293 .addOperand(Inst.getOperand(1))
3294 .addOperand(Inst.getOperand(2))
3295 .addOperand(Inst.getOperand(3))
3296 .addReg(RISCV::NoRegister)
3297 .setLoc(IDLoc));
3298 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3299 .addOperand(Inst.getOperand(0))
3300 .addOperand(Inst.getOperand(0))
3301 .addOperand(Inst.getOperand(1))
3302 .setLoc(IDLoc));
3303 } else if (Inst.getNumOperands() == 5) {
3304 // masked va >= x, any vd
3305 //
3306 // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
3307 // expansion: vmslt{u}.vx vt, va, x; vmandn.mm vt, v0, vt;
3308 // vmandn.mm vd, vd, v0; vmor.mm vd, vt, vd
3309 assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
3310 "The temporary vector register should not be V0.");
3311 emitToStreamer(Out, MCInstBuilder(Opcode)
3312 .addOperand(Inst.getOperand(1))
3313 .addOperand(Inst.getOperand(2))
3314 .addOperand(Inst.getOperand(3))
3315 .addReg(RISCV::NoRegister)
3316 .setLoc(IDLoc));
3317 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3318 .addOperand(Inst.getOperand(1))
3319 .addReg(RISCV::V0)
3320 .addOperand(Inst.getOperand(1))
3321 .setLoc(IDLoc));
3322 emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
3323 .addOperand(Inst.getOperand(0))
3324 .addOperand(Inst.getOperand(0))
3325 .addReg(RISCV::V0)
3326 .setLoc(IDLoc));
3327 emitToStreamer(Out, MCInstBuilder(RISCV::VMOR_MM)
3328 .addOperand(Inst.getOperand(0))
3329 .addOperand(Inst.getOperand(1))
3330 .addOperand(Inst.getOperand(0))
3331 .setLoc(IDLoc));
3332 }
3333}
3334
3335bool RISCVAsmParser::checkPseudoAddTPRel(MCInst &Inst,
3337 assert(Inst.getOpcode() == RISCV::PseudoAddTPRel && "Invalid instruction");
3338 assert(Inst.getOperand(2).isReg() && "Unexpected second operand kind");
3339 if (Inst.getOperand(2).getReg() != RISCV::X4) {
3340 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3341 return Error(ErrorLoc, "the second input operand must be tp/x4 when using "
3342 "%tprel_add modifier");
3343 }
3344
3345 return false;
3346}
3347
3348bool RISCVAsmParser::checkPseudoTLSDESCCall(MCInst &Inst,
3350 assert(Inst.getOpcode() == RISCV::PseudoTLSDESCCall && "Invalid instruction");
3351 assert(Inst.getOperand(0).isReg() && "Unexpected operand kind");
3352 if (Inst.getOperand(0).getReg() != RISCV::X5) {
3353 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
3354 return Error(ErrorLoc, "the output operand must be t0/x5 when using "
3355 "%tlsdesc_call modifier");
3356 }
3357
3358 return false;
3359}
3360
3361std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultMaskRegOp() const {
3362 return RISCVOperand::createReg(RISCV::NoRegister, llvm::SMLoc(),
3363 llvm::SMLoc());
3364}
3365
3366std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgOp() const {
3367 return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::DYN,
3368 llvm::SMLoc());
3369}
3370
3371std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgLegacyOp() const {
3372 return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::RNE,
3373 llvm::SMLoc());
3374}
3375
3376bool RISCVAsmParser::validateInstruction(MCInst &Inst,
3378 unsigned Opcode = Inst.getOpcode();
3379
3380 if (Opcode == RISCV::PseudoVMSGEU_VX_M_T ||
3381 Opcode == RISCV::PseudoVMSGE_VX_M_T) {
3382 unsigned DestReg = Inst.getOperand(0).getReg();
3383 unsigned TempReg = Inst.getOperand(1).getReg();
3384 if (DestReg == TempReg) {
3385 SMLoc Loc = Operands.back()->getStartLoc();
3386 return Error(Loc, "The temporary vector register cannot be the same as "
3387 "the destination register.");
3388 }
3389 }
3390
3391 if (Opcode == RISCV::TH_LDD || Opcode == RISCV::TH_LWUD ||
3392 Opcode == RISCV::TH_LWD) {
3393 unsigned Rd1 = Inst.getOperand(0).getReg();
3394 unsigned Rd2 = Inst.getOperand(1).getReg();
3395 unsigned Rs1 = Inst.getOperand(2).getReg();
3396 // The encoding with rd1 == rd2 == rs1 is reserved for XTHead load pair.
3397 if (Rs1 == Rd1 && Rs1 == Rd2) {
3398 SMLoc Loc = Operands[1]->getStartLoc();
3399 return Error(Loc, "The source register and destination registers "
3400 "cannot be equal.");
3401 }
3402 }
3403
3404 if (Opcode == RISCV::CM_MVSA01) {
3405 unsigned Rd1 = Inst.getOperand(0).getReg();
3406 unsigned Rd2 = Inst.getOperand(1).getReg();
3407 if (Rd1 == Rd2) {
3408 SMLoc Loc = Operands[1]->getStartLoc();
3409 return Error(Loc, "'rs1' and 'rs2' must be different.");
3410 }
3411 }
3412
3413 bool IsTHeadMemPair32 = (Opcode == RISCV::TH_LWD ||
3414 Opcode == RISCV::TH_LWUD || Opcode == RISCV::TH_SWD);
3415 bool IsTHeadMemPair64 = (Opcode == RISCV::TH_LDD || Opcode == RISCV::TH_SDD);
3416 // The last operand of XTHeadMemPair instructions must be constant 3 or 4
3417 // depending on the data width.
3418 if (IsTHeadMemPair32 && Inst.getOperand(4).getImm() != 3) {
3419 SMLoc Loc = Operands.back()->getStartLoc();
3420 return Error(Loc, "Operand must be constant 3.");
3421 } else if (IsTHeadMemPair64 && Inst.getOperand(4).getImm() != 4) {
3422 SMLoc Loc = Operands.back()->getStartLoc();
3423 return Error(Loc, "Operand must be constant 4.");
3424 }
3425
3426 const MCInstrDesc &MCID = MII.get(Opcode);
3427 if (!(MCID.TSFlags & RISCVII::ConstraintMask))
3428 return false;
3429
3430 if (Opcode == RISCV::VC_V_XVW || Opcode == RISCV::VC_V_IVW ||
3431 Opcode == RISCV::VC_V_FVW || Opcode == RISCV::VC_V_VVW) {
3432 // Operands Opcode, Dst, uimm, Dst, Rs2, Rs1 for VC_V_XVW.
3433 unsigned VCIXDst = Inst.getOperand(0).getReg();
3434 SMLoc VCIXDstLoc = Operands[2]->getStartLoc();
3435 if (MCID.TSFlags & RISCVII::VS1Constraint) {
3436 unsigned VCIXRs1 = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
3437 if (VCIXDst == VCIXRs1)
3438 return Error(VCIXDstLoc, "The destination vector register group cannot"
3439 " overlap the source vector register group.");
3440 }
3441 if (MCID.TSFlags & RISCVII::VS2Constraint) {
3442 unsigned VCIXRs2 = Inst.getOperand(Inst.getNumOperands() - 2).getReg();
3443 if (VCIXDst == VCIXRs2)
3444 return Error(VCIXDstLoc, "The destination vector register group cannot"
3445 " overlap the source vector register group.");
3446 }
3447 return false;
3448 }
3449
3450 unsigned DestReg = Inst.getOperand(0).getReg();
3451 unsigned Offset = 0;
3452 int TiedOp = MCID.getOperandConstraint(1, MCOI::TIED_TO);
3453 if (TiedOp == 0)
3454 Offset = 1;
3455
3456 // Operands[1] will be the first operand, DestReg.
3457 SMLoc Loc = Operands[1]->getStartLoc();
3458 if (MCID.TSFlags & RISCVII::VS2Constraint) {
3459 unsigned CheckReg = Inst.getOperand(Offset + 1).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::VS1Constraint) && Inst.getOperand(Offset + 2).isReg()) {
3465 unsigned CheckReg = Inst.getOperand(Offset + 2).getReg();
3466 if (DestReg == CheckReg)
3467 return Error(Loc, "The destination vector register group cannot overlap"
3468 " the source vector register group.");
3469 }
3470 if ((MCID.TSFlags & RISCVII::VMConstraint) && (DestReg == RISCV::V0)) {
3471 // vadc, vsbc are special cases. These instructions have no mask register.
3472 // The destination register could not be V0.
3473 if (Opcode == RISCV::VADC_VVM || Opcode == RISCV::VADC_VXM ||
3474 Opcode == RISCV::VADC_VIM || Opcode == RISCV::VSBC_VVM ||
3475 Opcode == RISCV::VSBC_VXM || Opcode == RISCV::VFMERGE_VFM ||
3476 Opcode == RISCV::VMERGE_VIM || Opcode == RISCV::VMERGE_VVM ||
3477 Opcode == RISCV::VMERGE_VXM)
3478 return Error(Loc, "The destination vector register group cannot be V0.");
3479
3480 // Regardless masked or unmasked version, the number of operands is the
3481 // same. For example, "viota.m v0, v2" is "viota.m v0, v2, NoRegister"
3482 // actually. We need to check the last operand to ensure whether it is
3483 // masked or not.
3484 unsigned CheckReg = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
3485 assert((CheckReg == RISCV::V0 || CheckReg == RISCV::NoRegister) &&
3486 "Unexpected register for mask operand");
3487
3488 if (DestReg == CheckReg)
3489 return Error(Loc, "The destination vector register group cannot overlap"
3490 " the mask register.");
3491 }
3492 return false;
3493}
3494
3495bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
3497 MCStreamer &Out) {
3498 Inst.setLoc(IDLoc);
3499
3500 switch (Inst.getOpcode()) {
3501 default:
3502 break;
3503 case RISCV::PseudoLLAImm:
3504 case RISCV::PseudoLAImm:
3505 case RISCV::PseudoLI: {
3506 MCRegister Reg = Inst.getOperand(0).getReg();
3507 const MCOperand &Op1 = Inst.getOperand(1);
3508 if (Op1.isExpr()) {
3509 // We must have li reg, %lo(sym) or li reg, %pcrel_lo(sym) or similar.
3510 // Just convert to an addi. This allows compatibility with gas.
3511 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
3512 .addReg(Reg)
3513 .addReg(RISCV::X0)
3514 .addExpr(Op1.getExpr()));
3515 return false;
3516 }
3517 int64_t Imm = Inst.getOperand(1).getImm();
3518 // On RV32 the immediate here can either be a signed or an unsigned
3519 // 32-bit number. Sign extension has to be performed to ensure that Imm
3520 // represents the expected signed 64-bit number.
3521 if (!isRV64())
3522 Imm = SignExtend64<32>(Imm);
3523 emitLoadImm(Reg, Imm, Out);
3524 return false;
3525 }
3526 case RISCV::PseudoLLA:
3527 emitLoadLocalAddress(Inst, IDLoc, Out);
3528 return false;
3529 case RISCV::PseudoLGA:
3530 emitLoadGlobalAddress(Inst, IDLoc, Out);
3531 return false;
3532 case RISCV::PseudoLA:
3533 emitLoadAddress(Inst, IDLoc, Out);
3534 return false;
3535 case RISCV::PseudoLA_TLS_IE:
3536 emitLoadTLSIEAddress(Inst, IDLoc, Out);
3537 return false;
3538 case RISCV::PseudoLA_TLS_GD:
3539 emitLoadTLSGDAddress(Inst, IDLoc, Out);
3540 return false;
3541 case RISCV::PseudoLB:
3542 emitLoadStoreSymbol(Inst, RISCV::LB, IDLoc, Out, /*HasTmpReg=*/false);
3543 return false;
3544 case RISCV::PseudoLBU:
3545 emitLoadStoreSymbol(Inst, RISCV::LBU, IDLoc, Out, /*HasTmpReg=*/false);
3546 return false;
3547 case RISCV::PseudoLH:
3548 emitLoadStoreSymbol(Inst, RISCV::LH, IDLoc, Out, /*HasTmpReg=*/false);
3549 return false;
3550 case RISCV::PseudoLHU:
3551 emitLoadStoreSymbol(Inst, RISCV::LHU, IDLoc, Out, /*HasTmpReg=*/false);
3552 return false;
3553 case RISCV::PseudoLW:
3554 emitLoadStoreSymbol(Inst, RISCV::LW, IDLoc, Out, /*HasTmpReg=*/false);
3555 return false;
3556 case RISCV::PseudoLWU:
3557 emitLoadStoreSymbol(Inst, RISCV::LWU, IDLoc, Out, /*HasTmpReg=*/false);
3558 return false;
3559 case RISCV::PseudoLD:
3560 emitLoadStoreSymbol(Inst, RISCV::LD, IDLoc, Out, /*HasTmpReg=*/false);
3561 return false;
3562 case RISCV::PseudoFLH:
3563 emitLoadStoreSymbol(Inst, RISCV::FLH, IDLoc, Out, /*HasTmpReg=*/true);
3564 return false;
3565 case RISCV::PseudoFLW:
3566 emitLoadStoreSymbol(Inst, RISCV::FLW, IDLoc, Out, /*HasTmpReg=*/true);
3567 return false;
3568 case RISCV::PseudoFLD:
3569 emitLoadStoreSymbol(Inst, RISCV::FLD, IDLoc, Out, /*HasTmpReg=*/true);
3570 return false;
3571 case RISCV::PseudoSB:
3572 emitLoadStoreSymbol(Inst, RISCV::SB, IDLoc, Out, /*HasTmpReg=*/true);
3573 return false;
3574 case RISCV::PseudoSH:
3575 emitLoadStoreSymbol(Inst, RISCV::SH, IDLoc, Out, /*HasTmpReg=*/true);
3576 return false;
3577 case RISCV::PseudoSW:
3578 emitLoadStoreSymbol(Inst, RISCV::SW, IDLoc, Out, /*HasTmpReg=*/true);
3579 return false;
3580 case RISCV::PseudoSD:
3581 emitLoadStoreSymbol(Inst, RISCV::SD, IDLoc, Out, /*HasTmpReg=*/true);
3582 return false;
3583 case RISCV::PseudoFSH:
3584 emitLoadStoreSymbol(Inst, RISCV::FSH, IDLoc, Out, /*HasTmpReg=*/true);
3585 return false;
3586 case RISCV::PseudoFSW:
3587 emitLoadStoreSymbol(Inst, RISCV::FSW, IDLoc, Out, /*HasTmpReg=*/true);
3588 return false;
3589 case RISCV::PseudoFSD:
3590 emitLoadStoreSymbol(Inst, RISCV::FSD, IDLoc, Out, /*HasTmpReg=*/true);
3591 return false;
3592 case RISCV::PseudoAddTPRel:
3593 if (checkPseudoAddTPRel(Inst, Operands))
3594 return true;
3595 break;
3596 case RISCV::PseudoTLSDESCCall:
3597 if (checkPseudoTLSDESCCall(Inst, Operands))
3598 return true;
3599 break;
3600 case RISCV::PseudoSEXT_B:
3601 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/8, IDLoc, Out);
3602 return false;
3603 case RISCV::PseudoSEXT_H:
3604 emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/16, IDLoc, Out);
3605 return false;
3606 case RISCV::PseudoZEXT_H:
3607 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/16, IDLoc, Out);
3608 return false;
3609 case RISCV::PseudoZEXT_W:
3610 emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/32, IDLoc, Out);
3611 return false;
3612 case RISCV::PseudoVMSGEU_VX:
3613 case RISCV::PseudoVMSGEU_VX_M:
3614 case RISCV::PseudoVMSGEU_VX_M_T:
3615 emitVMSGE(Inst, RISCV::VMSLTU_VX, IDLoc, Out);
3616 return false;
3617 case RISCV::PseudoVMSGE_VX:
3618 case RISCV::PseudoVMSGE_VX_M:
3619 case RISCV::PseudoVMSGE_VX_M_T:
3620 emitVMSGE(Inst, RISCV::VMSLT_VX, IDLoc, Out);
3621 return false;
3622 case RISCV::PseudoVMSGE_VI:
3623 case RISCV::PseudoVMSLT_VI: {
3624 // These instructions are signed and so is immediate so we can subtract one
3625 // and change the opcode.
3626 int64_t Imm = Inst.getOperand(2).getImm();
3627 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGE_VI ? RISCV::VMSGT_VI
3628 : RISCV::VMSLE_VI;
3629 emitToStreamer(Out, MCInstBuilder(Opc)
3630 .addOperand(Inst.getOperand(0))
3631 .addOperand(Inst.getOperand(1))
3632 .addImm(Imm - 1)
3633 .addOperand(Inst.getOperand(3))
3634 .setLoc(IDLoc));
3635 return false;
3636 }
3637 case RISCV::PseudoVMSGEU_VI:
3638 case RISCV::PseudoVMSLTU_VI: {
3639 int64_t Imm = Inst.getOperand(2).getImm();
3640 // Unsigned comparisons are tricky because the immediate is signed. If the
3641 // immediate is 0 we can't just subtract one. vmsltu.vi v0, v1, 0 is always
3642 // false, but vmsle.vi v0, v1, -1 is always true. Instead we use
3643 // vmsne v0, v1, v1 which is always false.
3644 if (Imm == 0) {
3645 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
3646 ? RISCV::VMSEQ_VV
3647 : RISCV::VMSNE_VV;
3648 emitToStreamer(Out, MCInstBuilder(Opc)
3649 .addOperand(Inst.getOperand(0))
3650 .addOperand(Inst.getOperand(1))
3651 .addOperand(Inst.getOperand(1))
3652 .addOperand(Inst.getOperand(3))
3653 .setLoc(IDLoc));
3654 } else {
3655 // Other immediate values can subtract one like signed.
3656 unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
3657 ? RISCV::VMSGTU_VI
3658 : RISCV::VMSLEU_VI;
3659 emitToStreamer(Out, MCInstBuilder(Opc)
3660 .addOperand(Inst.getOperand(0))
3661 .addOperand(Inst.getOperand(1))
3662 .addImm(Imm - 1)
3663 .addOperand(Inst.getOperand(3))
3664 .setLoc(IDLoc));
3665 }
3666
3667 return false;
3668 }
3669 }
3670
3671 emitToStreamer(Out, Inst);
3672 return false;
3673}
3674
3678}
static MCRegister MatchRegisterName(StringRef Name)
static const char * getSubtargetFeatureName(uint64_t Val)
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
static bool isNot(const MachineRegisterInfo &MRI, const MachineInstr &MI)
static MCRegister MatchRegisterAltName(StringRef Name)
Maps from the set of all alternative registernames to a register number.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
static bool matchRegisterNameHelper(const MCSubtargetInfo &STI, MCRegister &Reg, StringRef Name)
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:135
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::string Name
Symbol * Sym
Definition: ELF_riscv.cpp:479
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
#define check(cond)
#define RegName(no)
static LVOptions Options
Definition: LVOptions.cpp:25
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
unsigned Reg
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
PowerPC TLS Dynamic Call Fixup
bool isValidInsnFormat(StringRef Format, bool AllowC)
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVAsmParser()
static MCRegister convertFPR64ToFPR32(MCRegister Reg)
static cl::opt< bool > AddBuildAttributes("riscv-add-build-attributes", cl::init(false))
static MCRegister convertFPR64ToFPR16(MCRegister Reg)
static MCRegister convertVRToVRMx(const MCRegisterInfo &RI, MCRegister Reg, unsigned Kind)
static bool isDigit(const char C)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isImm(const MachineOperand &MO, MachineRegisterInfo *MRI)
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file implements the SmallBitVector class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This file contains some functions that are useful when dealing with strings.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition: Value.cpp:469
bool parseImmediate(MCInst &MI, uint64_t &Size, ArrayRef< uint8_t > Bytes)
Class for arbitrary precision integers.
Definition: APInt.h:76
Target independent representation for an assembler token.
Definition: MCAsmMacro.h:21
SMLoc getLoc() const
Definition: MCAsmLexer.cpp:26
int64_t getIntVal() const
Definition: MCAsmMacro.h:115
bool isNot(TokenKind K) const
Definition: MCAsmMacro.h:83
StringRef getString() const
Get the string for the current token, this includes all characters (for example, the quotes on string...
Definition: MCAsmMacro.h:110
StringRef getStringContents() const
Get the contents of a string token (without quotes).
Definition: MCAsmMacro.h:90
bool is(TokenKind K) const
Definition: MCAsmMacro.h:82
SMLoc getEndLoc() const
Definition: MCAsmLexer.cpp:30
StringRef getIdentifier() const
Get the identifier string for the current token, which should be an identifier or a string.
Definition: MCAsmMacro.h:99
This class represents an Operation in the Expression.
Encoding
Size and signedness of expression operations' operands.
Base class for user error types.
Definition: Error.h:352
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Container class for subtarget features.
constexpr size_t size() const
virtual void Initialize(MCAsmParser &Parser)
Initialize the extension for parsing using the given Parser.
Generic assembler parser interface, for use by target specific assembly parsers.
Definition: MCAsmParser.h:123
virtual void eatToEndOfStatement()=0
Skip to the end of the current statement, for error recovery.
virtual MCStreamer & getStreamer()=0
Return the output streamer for the assembler.
virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc)=0
Parse an arbitrary expression.
const AsmToken & getTok() const
Get the current AsmToken from the stream.
Definition: MCAsmParser.cpp:40
virtual bool parseIdentifier(StringRef &Res)=0
Parse an identifier or string (as a quoted identifier) and set Res to the identifier contents.
virtual const AsmToken & Lex()=0
Get the next AsmToken in the stream, possibly handling file inclusion first.
virtual void addAliasForDirective(StringRef Directive, StringRef Alias)=0
virtual MCContext & getContext()=0
static const MCBinaryExpr * create(Opcode Op, const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition: MCExpr.cpp:183
@ Sub
Subtraction.
Definition: MCExpr.h:517
@ Add
Addition.
Definition: MCExpr.h:495
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:194
Context object for machine code objects.
Definition: MCContext.h:76
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:450
MCSymbol * createNamedTempSymbol()
Create a temporary symbol with a unique name whose name cannot be omitted in the symbol table.
Definition: MCContext.cpp:323
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
bool evaluateAsRelocatable(MCValue &Res, const MCAsmLayout *Layout, const MCFixup *Fixup) const
Try to evaluate the expression to a relocatable value, i.e.
Definition: MCExpr.cpp:814
ExprKind getKind() const
Definition: MCExpr.h:81
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:71
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, bool IsEABI)
@ CE
Windows NT (Windows on ARM)
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
Format
The format used for serializing/deserializing remarks.
Definition: RemarkFormat.h:25
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
Definition: Error.h:1071
@ Offset
Definition: DWP.cpp:456
@ Length
Definition: DWP.cpp:456
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:228
static bool isMem(const MachineInstr &MI, unsigned Op)
Definition: X86InstrInfo.h:152
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:970
Target & getTheRISCV32Target()
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1963
DWARFExpression::Operation Op
Target & getTheRISCV64Target()
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition: MathExtras.h:166
const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures]
#define N
RegisterMCAsmParser - Helper template for registering a target specific assembly parser,...
Used to provide key value pairs for feature and CPU bit flags.