1 //===-- RISCVAsmParser.cpp - Parse RISCV 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 
9 #include "MCTargetDesc/RISCVAsmBackend.h"
10 #include "MCTargetDesc/RISCVBaseInfo.h"
11 #include "MCTargetDesc/RISCVInstPrinter.h"
12 #include "MCTargetDesc/RISCVMCExpr.h"
13 #include "MCTargetDesc/RISCVMCTargetDesc.h"
14 #include "MCTargetDesc/RISCVMatInt.h"
15 #include "MCTargetDesc/RISCVTargetStreamer.h"
16 #include "TargetInfo/RISCVTargetInfo.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallBitVector.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #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"
26 #include "llvm/MC/MCInstBuilder.h"
27 #include "llvm/MC/MCObjectFileInfo.h"
28 #include "llvm/MC/MCParser/MCAsmLexer.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/MC/MCValue.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/RISCVAttributes.h"
38 #include "llvm/Support/TargetRegistry.h"
39 
40 #include <limits>
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-asm-parser"
45 
46 // Include the auto-generated portion of the compress emitter.
47 #define GEN_COMPRESS_INSTR
48 #include "RISCVGenCompressInstEmitter.inc"
49 
50 STATISTIC(RISCVNumInstrsCompressed,
51           "Number of RISC-V Compressed instructions emitted");
52 
53 namespace {
54 struct RISCVOperand;
55 
56 struct ParserOptionsSet {
57   bool IsPicEnabled;
58 };
59 
60 class RISCVAsmParser : public MCTargetAsmParser {
61   SmallVector<FeatureBitset, 4> FeatureBitStack;
62 
63   SmallVector<ParserOptionsSet, 4> ParserOptionsStack;
64   ParserOptionsSet ParserOptions;
65 
66   SMLoc getLoc() const { return getParser().getTok().getLoc(); }
67   bool isRV64() const { return getSTI().hasFeature(RISCV::Feature64Bit); }
68   bool isRV32E() const { return getSTI().hasFeature(RISCV::FeatureRV32E); }
69 
70   RISCVTargetStreamer &getTargetStreamer() {
71     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
72     return static_cast<RISCVTargetStreamer &>(TS);
73   }
74 
75   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
76                                       unsigned Kind) override;
77 
78   bool generateImmOutOfRangeError(OperandVector &Operands, uint64_t ErrorInfo,
79                                   int64_t Lower, int64_t Upper, Twine Msg);
80 
81   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
82                                OperandVector &Operands, MCStreamer &Out,
83                                uint64_t &ErrorInfo,
84                                bool MatchingInlineAsm) override;
85 
86   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
87   OperandMatchResultTy tryParseRegister(unsigned &RegNo, SMLoc &StartLoc,
88                                         SMLoc &EndLoc) override;
89 
90   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
91                         SMLoc NameLoc, OperandVector &Operands) override;
92 
93   bool ParseDirective(AsmToken DirectiveID) override;
94 
95   // Helper to actually emit an instruction to the MCStreamer. Also, when
96   // possible, compression of the instruction is performed.
97   void emitToStreamer(MCStreamer &S, const MCInst &Inst);
98 
99   // Helper to emit a combination of LUI, ADDI(W), and SLLI instructions that
100   // synthesize the desired immedate value into the destination register.
101   void emitLoadImm(MCRegister DestReg, int64_t Value, MCStreamer &Out);
102 
103   // Helper to emit a combination of AUIPC and SecondOpcode. Used to implement
104   // helpers such as emitLoadLocalAddress and emitLoadAddress.
105   void emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
106                          const MCExpr *Symbol, RISCVMCExpr::VariantKind VKHi,
107                          unsigned SecondOpcode, SMLoc IDLoc, MCStreamer &Out);
108 
109   // Helper to emit pseudo instruction "lla" used in PC-rel addressing.
110   void emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
111 
112   // Helper to emit pseudo instruction "la" used in GOT/PC-rel addressing.
113   void emitLoadAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
114 
115   // Helper to emit pseudo instruction "la.tls.ie" used in initial-exec TLS
116   // addressing.
117   void emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
118 
119   // Helper to emit pseudo instruction "la.tls.gd" used in global-dynamic TLS
120   // addressing.
121   void emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
122 
123   // Helper to emit pseudo load/store instruction with a symbol.
124   void emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
125                            MCStreamer &Out, bool HasTmpReg);
126 
127   // Helper to emit pseudo sign/zero extend instruction.
128   void emitPseudoExtend(MCInst &Inst, bool SignExtend, int64_t Width,
129                         SMLoc IDLoc, MCStreamer &Out);
130 
131   // Helper to emit pseudo vmsge{u}.vx instruction.
132   void emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc, MCStreamer &Out);
133 
134   // Checks that a PseudoAddTPRel is using x4/tp in its second input operand.
135   // Enforcing this using a restricted register class for the second input
136   // operand of PseudoAddTPRel results in a poor diagnostic due to the fact
137   // 'add' is an overloaded mnemonic.
138   bool checkPseudoAddTPRel(MCInst &Inst, OperandVector &Operands);
139 
140   // Check instruction constraints.
141   bool validateInstruction(MCInst &Inst, OperandVector &Operands);
142 
143   /// Helper for processing MC instructions that have been successfully matched
144   /// by MatchAndEmitInstruction. Modifications to the emitted instructions,
145   /// like the expansion of pseudo instructions (e.g., "li"), can be performed
146   /// in this method.
147   bool processInstruction(MCInst &Inst, SMLoc IDLoc, OperandVector &Operands,
148                           MCStreamer &Out);
149 
150 // Auto-generated instruction matching functions
151 #define GET_ASSEMBLER_HEADER
152 #include "RISCVGenAsmMatcher.inc"
153 
154   OperandMatchResultTy parseCSRSystemRegister(OperandVector &Operands);
155   OperandMatchResultTy parseImmediate(OperandVector &Operands);
156   OperandMatchResultTy parseRegister(OperandVector &Operands,
157                                      bool AllowParens = false);
158   OperandMatchResultTy parseMemOpBaseReg(OperandVector &Operands);
159   OperandMatchResultTy parseAtomicMemOp(OperandVector &Operands);
160   OperandMatchResultTy parseOperandWithModifier(OperandVector &Operands);
161   OperandMatchResultTy parseBareSymbol(OperandVector &Operands);
162   OperandMatchResultTy parseCallSymbol(OperandVector &Operands);
163   OperandMatchResultTy parsePseudoJumpSymbol(OperandVector &Operands);
164   OperandMatchResultTy parseJALOffset(OperandVector &Operands);
165   OperandMatchResultTy parseVTypeI(OperandVector &Operands);
166   OperandMatchResultTy parseMaskReg(OperandVector &Operands);
167 
168   bool parseOperand(OperandVector &Operands, StringRef Mnemonic);
169 
170   bool parseDirectiveOption();
171   bool parseDirectiveAttribute();
172 
173   void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
174     if (!(getSTI().getFeatureBits()[Feature])) {
175       MCSubtargetInfo &STI = copySTI();
176       setAvailableFeatures(
177           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
178     }
179   }
180 
181   bool getFeatureBits(uint64_t Feature) {
182     return getSTI().getFeatureBits()[Feature];
183   }
184 
185   void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
186     if (getSTI().getFeatureBits()[Feature]) {
187       MCSubtargetInfo &STI = copySTI();
188       setAvailableFeatures(
189           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
190     }
191   }
192 
193   void pushFeatureBits() {
194     assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
195            "These two stacks must be kept synchronized");
196     FeatureBitStack.push_back(getSTI().getFeatureBits());
197     ParserOptionsStack.push_back(ParserOptions);
198   }
199 
200   bool popFeatureBits() {
201     assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
202            "These two stacks must be kept synchronized");
203     if (FeatureBitStack.empty())
204       return true;
205 
206     FeatureBitset FeatureBits = FeatureBitStack.pop_back_val();
207     copySTI().setFeatureBits(FeatureBits);
208     setAvailableFeatures(ComputeAvailableFeatures(FeatureBits));
209 
210     ParserOptions = ParserOptionsStack.pop_back_val();
211 
212     return false;
213   }
214 
215   std::unique_ptr<RISCVOperand> defaultMaskRegOp() const;
216 
217 public:
218   enum RISCVMatchResultTy {
219     Match_Dummy = FIRST_TARGET_MATCH_RESULT_TY,
220 #define GET_OPERAND_DIAGNOSTIC_TYPES
221 #include "RISCVGenAsmMatcher.inc"
222 #undef GET_OPERAND_DIAGNOSTIC_TYPES
223   };
224 
225   static bool classifySymbolRef(const MCExpr *Expr,
226                                 RISCVMCExpr::VariantKind &Kind);
227 
228   RISCVAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
229                  const MCInstrInfo &MII, const MCTargetOptions &Options)
230       : MCTargetAsmParser(Options, STI, MII) {
231     Parser.addAliasForDirective(".half", ".2byte");
232     Parser.addAliasForDirective(".hword", ".2byte");
233     Parser.addAliasForDirective(".word", ".4byte");
234     Parser.addAliasForDirective(".dword", ".8byte");
235     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
236 
237     auto ABIName = StringRef(Options.ABIName);
238     if (ABIName.endswith("f") &&
239         !getSTI().getFeatureBits()[RISCV::FeatureStdExtF]) {
240       errs() << "Hard-float 'f' ABI can't be used for a target that "
241                 "doesn't support the F instruction set extension (ignoring "
242                 "target-abi)\n";
243     } else if (ABIName.endswith("d") &&
244                !getSTI().getFeatureBits()[RISCV::FeatureStdExtD]) {
245       errs() << "Hard-float 'd' ABI can't be used for a target that "
246                 "doesn't support the D instruction set extension (ignoring "
247                 "target-abi)\n";
248     }
249 
250     const MCObjectFileInfo *MOFI = Parser.getContext().getObjectFileInfo();
251     ParserOptions.IsPicEnabled = MOFI->isPositionIndependent();
252   }
253 };
254 
255 /// RISCVOperand - Instances of this class represent a parsed machine
256 /// instruction
257 struct RISCVOperand : public MCParsedAsmOperand {
258 
259   enum class KindTy {
260     Token,
261     Register,
262     Immediate,
263     SystemRegister,
264     VType,
265   } Kind;
266 
267   bool IsRV64;
268 
269   struct RegOp {
270     MCRegister RegNum;
271   };
272 
273   struct ImmOp {
274     const MCExpr *Val;
275   };
276 
277   struct SysRegOp {
278     const char *Data;
279     unsigned Length;
280     unsigned Encoding;
281     // FIXME: Add the Encoding parsed fields as needed for checks,
282     // e.g.: read/write or user/supervisor/machine privileges.
283   };
284 
285   struct VTypeOp {
286     unsigned Val;
287   };
288 
289   SMLoc StartLoc, EndLoc;
290   union {
291     StringRef Tok;
292     RegOp Reg;
293     ImmOp Imm;
294     struct SysRegOp SysReg;
295     struct VTypeOp VType;
296   };
297 
298   RISCVOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
299 
300 public:
301   RISCVOperand(const RISCVOperand &o) : MCParsedAsmOperand() {
302     Kind = o.Kind;
303     IsRV64 = o.IsRV64;
304     StartLoc = o.StartLoc;
305     EndLoc = o.EndLoc;
306     switch (Kind) {
307     case KindTy::Register:
308       Reg = o.Reg;
309       break;
310     case KindTy::Immediate:
311       Imm = o.Imm;
312       break;
313     case KindTy::Token:
314       Tok = o.Tok;
315       break;
316     case KindTy::SystemRegister:
317       SysReg = o.SysReg;
318       break;
319     case KindTy::VType:
320       VType = o.VType;
321       break;
322     }
323   }
324 
325   bool isToken() const override { return Kind == KindTy::Token; }
326   bool isReg() const override { return Kind == KindTy::Register; }
327   bool isV0Reg() const {
328     return Kind == KindTy::Register && Reg.RegNum == RISCV::V0;
329   }
330   bool isImm() const override { return Kind == KindTy::Immediate; }
331   bool isMem() const override { return false; }
332   bool isSystemRegister() const { return Kind == KindTy::SystemRegister; }
333   bool isVType() const { return Kind == KindTy::VType; }
334 
335   bool isGPR() const {
336     return Kind == KindTy::Register &&
337            RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg.RegNum);
338   }
339 
340   static bool evaluateConstantImm(const MCExpr *Expr, int64_t &Imm,
341                                   RISCVMCExpr::VariantKind &VK) {
342     if (auto *RE = dyn_cast<RISCVMCExpr>(Expr)) {
343       VK = RE->getKind();
344       return RE->evaluateAsConstant(Imm);
345     }
346 
347     if (auto CE = dyn_cast<MCConstantExpr>(Expr)) {
348       VK = RISCVMCExpr::VK_RISCV_None;
349       Imm = CE->getValue();
350       return true;
351     }
352 
353     return false;
354   }
355 
356   // True if operand is a symbol with no modifiers, or a constant with no
357   // modifiers and isShiftedInt<N-1, 1>(Op).
358   template <int N> bool isBareSimmNLsb0() const {
359     int64_t Imm;
360     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
361     if (!isImm())
362       return false;
363     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
364     bool IsValid;
365     if (!IsConstantImm)
366       IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
367     else
368       IsValid = isShiftedInt<N - 1, 1>(Imm);
369     return IsValid && VK == RISCVMCExpr::VK_RISCV_None;
370   }
371 
372   // Predicate methods for AsmOperands defined in RISCVInstrInfo.td
373 
374   bool isBareSymbol() const {
375     int64_t Imm;
376     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
377     // Must be of 'immediate' type but not a constant.
378     if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
379       return false;
380     return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
381            VK == RISCVMCExpr::VK_RISCV_None;
382   }
383 
384   bool isCallSymbol() const {
385     int64_t Imm;
386     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
387     // Must be of 'immediate' type but not a constant.
388     if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
389       return false;
390     return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
391            (VK == RISCVMCExpr::VK_RISCV_CALL ||
392             VK == RISCVMCExpr::VK_RISCV_CALL_PLT);
393   }
394 
395   bool isPseudoJumpSymbol() const {
396     int64_t Imm;
397     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
398     // Must be of 'immediate' type but not a constant.
399     if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
400       return false;
401     return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
402            VK == RISCVMCExpr::VK_RISCV_CALL;
403   }
404 
405   bool isTPRelAddSymbol() const {
406     int64_t Imm;
407     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
408     // Must be of 'immediate' type but not a constant.
409     if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
410       return false;
411     return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
412            VK == RISCVMCExpr::VK_RISCV_TPREL_ADD;
413   }
414 
415   bool isCSRSystemRegister() const { return isSystemRegister(); }
416 
417   bool isVTypeI() const { return isVType(); }
418 
419   /// Return true if the operand is a valid for the fence instruction e.g.
420   /// ('iorw').
421   bool isFenceArg() const {
422     if (!isImm())
423       return false;
424     const MCExpr *Val = getImm();
425     auto *SVal = dyn_cast<MCSymbolRefExpr>(Val);
426     if (!SVal || SVal->getKind() != MCSymbolRefExpr::VK_None)
427       return false;
428 
429     StringRef Str = SVal->getSymbol().getName();
430     // Letters must be unique, taken from 'iorw', and in ascending order. This
431     // holds as long as each individual character is one of 'iorw' and is
432     // greater than the previous character.
433     char Prev = '\0';
434     for (char c : Str) {
435       if (c != 'i' && c != 'o' && c != 'r' && c != 'w')
436         return false;
437       if (c <= Prev)
438         return false;
439       Prev = c;
440     }
441     return true;
442   }
443 
444   /// Return true if the operand is a valid floating point rounding mode.
445   bool isFRMArg() const {
446     if (!isImm())
447       return false;
448     const MCExpr *Val = getImm();
449     auto *SVal = dyn_cast<MCSymbolRefExpr>(Val);
450     if (!SVal || SVal->getKind() != MCSymbolRefExpr::VK_None)
451       return false;
452 
453     StringRef Str = SVal->getSymbol().getName();
454 
455     return RISCVFPRndMode::stringToRoundingMode(Str) != RISCVFPRndMode::Invalid;
456   }
457 
458   bool isImmXLenLI() const {
459     int64_t Imm;
460     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
461     if (!isImm())
462       return false;
463     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
464     if (VK == RISCVMCExpr::VK_RISCV_LO || VK == RISCVMCExpr::VK_RISCV_PCREL_LO)
465       return true;
466     // Given only Imm, ensuring that the actually specified constant is either
467     // a signed or unsigned 64-bit number is unfortunately impossible.
468     return IsConstantImm && VK == RISCVMCExpr::VK_RISCV_None &&
469            (isRV64() || (isInt<32>(Imm) || isUInt<32>(Imm)));
470   }
471 
472   bool isUImmLog2XLen() const {
473     int64_t Imm;
474     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
475     if (!isImm())
476       return false;
477     if (!evaluateConstantImm(getImm(), Imm, VK) ||
478         VK != RISCVMCExpr::VK_RISCV_None)
479       return false;
480     return (isRV64() && isUInt<6>(Imm)) || isUInt<5>(Imm);
481   }
482 
483   bool isUImmLog2XLenNonZero() const {
484     int64_t Imm;
485     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
486     if (!isImm())
487       return false;
488     if (!evaluateConstantImm(getImm(), Imm, VK) ||
489         VK != RISCVMCExpr::VK_RISCV_None)
490       return false;
491     if (Imm == 0)
492       return false;
493     return (isRV64() && isUInt<6>(Imm)) || isUInt<5>(Imm);
494   }
495 
496   bool isUImmLog2XLenHalf() const {
497     int64_t Imm;
498     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
499     if (!isImm())
500       return false;
501     if (!evaluateConstantImm(getImm(), Imm, VK) ||
502         VK != RISCVMCExpr::VK_RISCV_None)
503       return false;
504     return (isRV64() && isUInt<5>(Imm)) || isUInt<4>(Imm);
505   }
506 
507   bool isUImm5() const {
508     int64_t Imm;
509     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
510     if (!isImm())
511       return false;
512     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
513     return IsConstantImm && isUInt<5>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
514   }
515 
516   bool isSImm5() const {
517     if (!isImm())
518       return false;
519     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
520     int64_t Imm;
521     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
522     return IsConstantImm && isInt<5>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
523   }
524 
525   bool isSImm6() const {
526     if (!isImm())
527       return false;
528     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
529     int64_t Imm;
530     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
531     return IsConstantImm && isInt<6>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
532   }
533 
534   bool isSImm6NonZero() const {
535     if (!isImm())
536       return false;
537     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
538     int64_t Imm;
539     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
540     return IsConstantImm && isInt<6>(Imm) && (Imm != 0) &&
541            VK == RISCVMCExpr::VK_RISCV_None;
542   }
543 
544   bool isCLUIImm() const {
545     if (!isImm())
546       return false;
547     int64_t Imm;
548     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
549     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
550     return IsConstantImm && (Imm != 0) &&
551            (isUInt<5>(Imm) || (Imm >= 0xfffe0 && Imm <= 0xfffff)) &&
552            VK == RISCVMCExpr::VK_RISCV_None;
553   }
554 
555   bool isUImm7Lsb00() const {
556     if (!isImm())
557       return false;
558     int64_t Imm;
559     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
560     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
561     return IsConstantImm && isShiftedUInt<5, 2>(Imm) &&
562            VK == RISCVMCExpr::VK_RISCV_None;
563   }
564 
565   bool isUImm8Lsb00() const {
566     if (!isImm())
567       return false;
568     int64_t Imm;
569     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
570     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
571     return IsConstantImm && isShiftedUInt<6, 2>(Imm) &&
572            VK == RISCVMCExpr::VK_RISCV_None;
573   }
574 
575   bool isUImm8Lsb000() const {
576     if (!isImm())
577       return false;
578     int64_t Imm;
579     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
580     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
581     return IsConstantImm && isShiftedUInt<5, 3>(Imm) &&
582            VK == RISCVMCExpr::VK_RISCV_None;
583   }
584 
585   bool isSImm9Lsb0() const { return isBareSimmNLsb0<9>(); }
586 
587   bool isUImm9Lsb000() const {
588     if (!isImm())
589       return false;
590     int64_t Imm;
591     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
592     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
593     return IsConstantImm && isShiftedUInt<6, 3>(Imm) &&
594            VK == RISCVMCExpr::VK_RISCV_None;
595   }
596 
597   bool isUImm10Lsb00NonZero() const {
598     if (!isImm())
599       return false;
600     int64_t Imm;
601     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
602     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
603     return IsConstantImm && isShiftedUInt<8, 2>(Imm) && (Imm != 0) &&
604            VK == RISCVMCExpr::VK_RISCV_None;
605   }
606 
607   bool isSImm12() const {
608     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
609     int64_t Imm;
610     bool IsValid;
611     if (!isImm())
612       return false;
613     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
614     if (!IsConstantImm)
615       IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
616     else
617       IsValid = isInt<12>(Imm);
618     return IsValid && ((IsConstantImm && VK == RISCVMCExpr::VK_RISCV_None) ||
619                        VK == RISCVMCExpr::VK_RISCV_LO ||
620                        VK == RISCVMCExpr::VK_RISCV_PCREL_LO ||
621                        VK == RISCVMCExpr::VK_RISCV_TPREL_LO);
622   }
623 
624   bool isSImm12Lsb0() const { return isBareSimmNLsb0<12>(); }
625 
626   bool isSImm13Lsb0() const { return isBareSimmNLsb0<13>(); }
627 
628   bool isSImm10Lsb0000NonZero() const {
629     if (!isImm())
630       return false;
631     int64_t Imm;
632     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
633     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
634     return IsConstantImm && (Imm != 0) && isShiftedInt<6, 4>(Imm) &&
635            VK == RISCVMCExpr::VK_RISCV_None;
636   }
637 
638   bool isUImm20LUI() const {
639     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
640     int64_t Imm;
641     bool IsValid;
642     if (!isImm())
643       return false;
644     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
645     if (!IsConstantImm) {
646       IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
647       return IsValid && (VK == RISCVMCExpr::VK_RISCV_HI ||
648                          VK == RISCVMCExpr::VK_RISCV_TPREL_HI);
649     } else {
650       return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
651                                  VK == RISCVMCExpr::VK_RISCV_HI ||
652                                  VK == RISCVMCExpr::VK_RISCV_TPREL_HI);
653     }
654   }
655 
656   bool isUImm20AUIPC() const {
657     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
658     int64_t Imm;
659     bool IsValid;
660     if (!isImm())
661       return false;
662     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
663     if (!IsConstantImm) {
664       IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK);
665       return IsValid && (VK == RISCVMCExpr::VK_RISCV_PCREL_HI ||
666                          VK == RISCVMCExpr::VK_RISCV_GOT_HI ||
667                          VK == RISCVMCExpr::VK_RISCV_TLS_GOT_HI ||
668                          VK == RISCVMCExpr::VK_RISCV_TLS_GD_HI);
669     } else {
670       return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
671                                  VK == RISCVMCExpr::VK_RISCV_PCREL_HI ||
672                                  VK == RISCVMCExpr::VK_RISCV_GOT_HI ||
673                                  VK == RISCVMCExpr::VK_RISCV_TLS_GOT_HI ||
674                                  VK == RISCVMCExpr::VK_RISCV_TLS_GD_HI);
675     }
676   }
677 
678   bool isSImm21Lsb0JAL() const { return isBareSimmNLsb0<21>(); }
679 
680   bool isImmZero() const {
681     if (!isImm())
682       return false;
683     int64_t Imm;
684     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
685     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
686     return IsConstantImm && (Imm == 0) && VK == RISCVMCExpr::VK_RISCV_None;
687   }
688 
689   bool isSImm5Plus1() const {
690     if (!isImm())
691       return false;
692     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
693     int64_t Imm;
694     bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
695     return IsConstantImm && isInt<5>(Imm - 1) &&
696            VK == RISCVMCExpr::VK_RISCV_None;
697   }
698 
699   /// getStartLoc - Gets location of the first token of this operand
700   SMLoc getStartLoc() const override { return StartLoc; }
701   /// getEndLoc - Gets location of the last token of this operand
702   SMLoc getEndLoc() const override { return EndLoc; }
703   /// True if this operand is for an RV64 instruction
704   bool isRV64() const { return IsRV64; }
705 
706   unsigned getReg() const override {
707     assert(Kind == KindTy::Register && "Invalid type access!");
708     return Reg.RegNum.id();
709   }
710 
711   StringRef getSysReg() const {
712     assert(Kind == KindTy::SystemRegister && "Invalid type access!");
713     return StringRef(SysReg.Data, SysReg.Length);
714   }
715 
716   const MCExpr *getImm() const {
717     assert(Kind == KindTy::Immediate && "Invalid type access!");
718     return Imm.Val;
719   }
720 
721   StringRef getToken() const {
722     assert(Kind == KindTy::Token && "Invalid type access!");
723     return Tok;
724   }
725 
726   unsigned getVType() const {
727     assert(Kind == KindTy::VType && "Invalid type access!");
728     return VType.Val;
729   }
730 
731   void print(raw_ostream &OS) const override {
732     auto RegName = [](unsigned Reg) {
733       if (Reg)
734         return RISCVInstPrinter::getRegisterName(Reg);
735       else
736         return "noreg";
737     };
738 
739     switch (Kind) {
740     case KindTy::Immediate:
741       OS << *getImm();
742       break;
743     case KindTy::Register:
744       OS << "<register " << RegName(getReg()) << ">";
745       break;
746     case KindTy::Token:
747       OS << "'" << getToken() << "'";
748       break;
749     case KindTy::SystemRegister:
750       OS << "<sysreg: " << getSysReg() << '>';
751       break;
752     case KindTy::VType:
753       OS << "<vtype: ";
754       RISCVVType::printVType(getVType(), OS);
755       OS << '>';
756       break;
757     }
758   }
759 
760   static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S,
761                                                    bool IsRV64) {
762     auto Op = std::make_unique<RISCVOperand>(KindTy::Token);
763     Op->Tok = Str;
764     Op->StartLoc = S;
765     Op->EndLoc = S;
766     Op->IsRV64 = IsRV64;
767     return Op;
768   }
769 
770   static std::unique_ptr<RISCVOperand> createReg(unsigned RegNo, SMLoc S,
771                                                  SMLoc E, bool IsRV64) {
772     auto Op = std::make_unique<RISCVOperand>(KindTy::Register);
773     Op->Reg.RegNum = RegNo;
774     Op->StartLoc = S;
775     Op->EndLoc = E;
776     Op->IsRV64 = IsRV64;
777     return Op;
778   }
779 
780   static std::unique_ptr<RISCVOperand> createImm(const MCExpr *Val, SMLoc S,
781                                                  SMLoc E, bool IsRV64) {
782     auto Op = std::make_unique<RISCVOperand>(KindTy::Immediate);
783     Op->Imm.Val = Val;
784     Op->StartLoc = S;
785     Op->EndLoc = E;
786     Op->IsRV64 = IsRV64;
787     return Op;
788   }
789 
790   static std::unique_ptr<RISCVOperand>
791   createSysReg(StringRef Str, SMLoc S, unsigned Encoding, bool IsRV64) {
792     auto Op = std::make_unique<RISCVOperand>(KindTy::SystemRegister);
793     Op->SysReg.Data = Str.data();
794     Op->SysReg.Length = Str.size();
795     Op->SysReg.Encoding = Encoding;
796     Op->StartLoc = S;
797     Op->IsRV64 = IsRV64;
798     return Op;
799   }
800 
801   static std::unique_ptr<RISCVOperand> createVType(unsigned VTypeI, SMLoc S,
802                                                    bool IsRV64) {
803     auto Op = std::make_unique<RISCVOperand>(KindTy::VType);
804     Op->VType.Val = VTypeI;
805     Op->StartLoc = S;
806     Op->IsRV64 = IsRV64;
807     return Op;
808   }
809 
810   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
811     assert(Expr && "Expr shouldn't be null!");
812     int64_t Imm = 0;
813     RISCVMCExpr::VariantKind VK = RISCVMCExpr::VK_RISCV_None;
814     bool IsConstant = evaluateConstantImm(Expr, Imm, VK);
815 
816     if (IsConstant)
817       Inst.addOperand(MCOperand::createImm(Imm));
818     else
819       Inst.addOperand(MCOperand::createExpr(Expr));
820   }
821 
822   // Used by the TableGen Code
823   void addRegOperands(MCInst &Inst, unsigned N) const {
824     assert(N == 1 && "Invalid number of operands!");
825     Inst.addOperand(MCOperand::createReg(getReg()));
826   }
827 
828   void addImmOperands(MCInst &Inst, unsigned N) const {
829     assert(N == 1 && "Invalid number of operands!");
830     addExpr(Inst, getImm());
831   }
832 
833   void addFenceArgOperands(MCInst &Inst, unsigned N) const {
834     assert(N == 1 && "Invalid number of operands!");
835     // isFenceArg has validated the operand, meaning this cast is safe
836     auto SE = cast<MCSymbolRefExpr>(getImm());
837 
838     unsigned Imm = 0;
839     for (char c : SE->getSymbol().getName()) {
840       switch (c) {
841       default:
842         llvm_unreachable("FenceArg must contain only [iorw]");
843       case 'i':
844         Imm |= RISCVFenceField::I;
845         break;
846       case 'o':
847         Imm |= RISCVFenceField::O;
848         break;
849       case 'r':
850         Imm |= RISCVFenceField::R;
851         break;
852       case 'w':
853         Imm |= RISCVFenceField::W;
854         break;
855       }
856     }
857     Inst.addOperand(MCOperand::createImm(Imm));
858   }
859 
860   void addCSRSystemRegisterOperands(MCInst &Inst, unsigned N) const {
861     assert(N == 1 && "Invalid number of operands!");
862     Inst.addOperand(MCOperand::createImm(SysReg.Encoding));
863   }
864 
865   void addVTypeIOperands(MCInst &Inst, unsigned N) const {
866     assert(N == 1 && "Invalid number of operands!");
867     Inst.addOperand(MCOperand::createImm(getVType()));
868   }
869 
870   // Returns the rounding mode represented by this RISCVOperand. Should only
871   // be called after checking isFRMArg.
872   RISCVFPRndMode::RoundingMode getRoundingMode() const {
873     // isFRMArg has validated the operand, meaning this cast is safe.
874     auto SE = cast<MCSymbolRefExpr>(getImm());
875     RISCVFPRndMode::RoundingMode FRM =
876         RISCVFPRndMode::stringToRoundingMode(SE->getSymbol().getName());
877     assert(FRM != RISCVFPRndMode::Invalid && "Invalid rounding mode");
878     return FRM;
879   }
880 
881   void addFRMArgOperands(MCInst &Inst, unsigned N) const {
882     assert(N == 1 && "Invalid number of operands!");
883     Inst.addOperand(MCOperand::createImm(getRoundingMode()));
884   }
885 };
886 } // end anonymous namespace.
887 
888 #define GET_REGISTER_MATCHER
889 #define GET_SUBTARGET_FEATURE_NAME
890 #define GET_MATCHER_IMPLEMENTATION
891 #define GET_MNEMONIC_SPELL_CHECKER
892 #include "RISCVGenAsmMatcher.inc"
893 
894 static MCRegister convertFPR64ToFPR16(MCRegister Reg) {
895   assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
896   return Reg - RISCV::F0_D + RISCV::F0_H;
897 }
898 
899 static MCRegister convertFPR64ToFPR32(MCRegister Reg) {
900   assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
901   return Reg - RISCV::F0_D + RISCV::F0_F;
902 }
903 
904 static MCRegister convertVRToVRMx(const MCRegisterInfo &RI, MCRegister Reg,
905                                   unsigned Kind) {
906   unsigned RegClassID;
907   if (Kind == MCK_VRM2)
908     RegClassID = RISCV::VRM2RegClassID;
909   else if (Kind == MCK_VRM4)
910     RegClassID = RISCV::VRM4RegClassID;
911   else if (Kind == MCK_VRM8)
912     RegClassID = RISCV::VRM8RegClassID;
913   else
914     return 0;
915   return RI.getMatchingSuperReg(Reg, RISCV::sub_vrm1_0,
916                                 &RISCVMCRegisterClasses[RegClassID]);
917 }
918 
919 unsigned RISCVAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
920                                                     unsigned Kind) {
921   RISCVOperand &Op = static_cast<RISCVOperand &>(AsmOp);
922   if (!Op.isReg())
923     return Match_InvalidOperand;
924 
925   MCRegister Reg = Op.getReg();
926   bool IsRegFPR64 =
927       RISCVMCRegisterClasses[RISCV::FPR64RegClassID].contains(Reg);
928   bool IsRegFPR64C =
929       RISCVMCRegisterClasses[RISCV::FPR64CRegClassID].contains(Reg);
930   bool IsRegVR = RISCVMCRegisterClasses[RISCV::VRRegClassID].contains(Reg);
931 
932   // As the parser couldn't differentiate an FPR32 from an FPR64, coerce the
933   // register from FPR64 to FPR32 or FPR64C to FPR32C if necessary.
934   if ((IsRegFPR64 && Kind == MCK_FPR32) ||
935       (IsRegFPR64C && Kind == MCK_FPR32C)) {
936     Op.Reg.RegNum = convertFPR64ToFPR32(Reg);
937     return Match_Success;
938   }
939   // As the parser couldn't differentiate an FPR16 from an FPR64, coerce the
940   // register from FPR64 to FPR16 if necessary.
941   if (IsRegFPR64 && Kind == MCK_FPR16) {
942     Op.Reg.RegNum = convertFPR64ToFPR16(Reg);
943     return Match_Success;
944   }
945   // As the parser couldn't differentiate an VRM2/VRM4/VRM8 from an VR, coerce
946   // the register from VR to VRM2/VRM4/VRM8 if necessary.
947   if (IsRegVR && (Kind == MCK_VRM2 || Kind == MCK_VRM4 || Kind == MCK_VRM8)) {
948     Op.Reg.RegNum = convertVRToVRMx(*getContext().getRegisterInfo(), Reg, Kind);
949     if (Op.Reg.RegNum == 0)
950       return Match_InvalidOperand;
951     return Match_Success;
952   }
953   return Match_InvalidOperand;
954 }
955 
956 bool RISCVAsmParser::generateImmOutOfRangeError(
957     OperandVector &Operands, uint64_t ErrorInfo, int64_t Lower, int64_t Upper,
958     Twine Msg = "immediate must be an integer in the range") {
959   SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
960   return Error(ErrorLoc, Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
961 }
962 
963 static std::string RISCVMnemonicSpellCheck(StringRef S,
964                                            const FeatureBitset &FBS,
965                                            unsigned VariantID = 0);
966 
967 bool RISCVAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
968                                              OperandVector &Operands,
969                                              MCStreamer &Out,
970                                              uint64_t &ErrorInfo,
971                                              bool MatchingInlineAsm) {
972   MCInst Inst;
973   FeatureBitset MissingFeatures;
974 
975   auto Result = MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,
976                                      MatchingInlineAsm);
977   switch (Result) {
978   default:
979     break;
980   case Match_Success:
981     if (validateInstruction(Inst, Operands))
982       return true;
983     return processInstruction(Inst, IDLoc, Operands, Out);
984   case Match_MissingFeature: {
985     assert(MissingFeatures.any() && "Unknown missing features!");
986     bool FirstFeature = true;
987     std::string Msg = "instruction requires the following:";
988     for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i) {
989       if (MissingFeatures[i]) {
990         Msg += FirstFeature ? " " : ", ";
991         Msg += getSubtargetFeatureName(i);
992         FirstFeature = false;
993       }
994     }
995     return Error(IDLoc, Msg);
996   }
997   case Match_MnemonicFail: {
998     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
999     std::string Suggestion =
1000         RISCVMnemonicSpellCheck(((RISCVOperand &)*Operands[0]).getToken(), FBS);
1001     return Error(IDLoc, "unrecognized instruction mnemonic" + Suggestion);
1002   }
1003   case Match_InvalidOperand: {
1004     SMLoc ErrorLoc = IDLoc;
1005     if (ErrorInfo != ~0U) {
1006       if (ErrorInfo >= Operands.size())
1007         return Error(ErrorLoc, "too few operands for instruction");
1008 
1009       ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1010       if (ErrorLoc == SMLoc())
1011         ErrorLoc = IDLoc;
1012     }
1013     return Error(ErrorLoc, "invalid operand for instruction");
1014   }
1015   }
1016 
1017   // Handle the case when the error message is of specific type
1018   // other than the generic Match_InvalidOperand, and the
1019   // corresponding operand is missing.
1020   if (Result > FIRST_TARGET_MATCH_RESULT_TY) {
1021     SMLoc ErrorLoc = IDLoc;
1022     if (ErrorInfo != ~0U && ErrorInfo >= Operands.size())
1023       return Error(ErrorLoc, "too few operands for instruction");
1024   }
1025 
1026   switch (Result) {
1027   default:
1028     break;
1029   case Match_InvalidImmXLenLI:
1030     if (isRV64()) {
1031       SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1032       return Error(ErrorLoc, "operand must be a constant 64-bit integer");
1033     }
1034     return generateImmOutOfRangeError(Operands, ErrorInfo,
1035                                       std::numeric_limits<int32_t>::min(),
1036                                       std::numeric_limits<uint32_t>::max());
1037   case Match_InvalidImmZero: {
1038     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1039     return Error(ErrorLoc, "immediate must be zero");
1040   }
1041   case Match_InvalidUImmLog2XLen:
1042     if (isRV64())
1043       return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
1044     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1045   case Match_InvalidUImmLog2XLenNonZero:
1046     if (isRV64())
1047       return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 6) - 1);
1048     return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5) - 1);
1049   case Match_InvalidUImmLog2XLenHalf:
1050     if (isRV64())
1051       return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1052     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 4) - 1);
1053   case Match_InvalidUImm5:
1054     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
1055   case Match_InvalidSImm5:
1056     return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 4),
1057                                       (1 << 4) - 1);
1058   case Match_InvalidSImm6:
1059     return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
1060                                       (1 << 5) - 1);
1061   case Match_InvalidSImm6NonZero:
1062     return generateImmOutOfRangeError(
1063         Operands, ErrorInfo, -(1 << 5), (1 << 5) - 1,
1064         "immediate must be non-zero in the range");
1065   case Match_InvalidCLUIImm:
1066     return generateImmOutOfRangeError(
1067         Operands, ErrorInfo, 1, (1 << 5) - 1,
1068         "immediate must be in [0xfffe0, 0xfffff] or");
1069   case Match_InvalidUImm7Lsb00:
1070     return generateImmOutOfRangeError(
1071         Operands, ErrorInfo, 0, (1 << 7) - 4,
1072         "immediate must be a multiple of 4 bytes in the range");
1073   case Match_InvalidUImm8Lsb00:
1074     return generateImmOutOfRangeError(
1075         Operands, ErrorInfo, 0, (1 << 8) - 4,
1076         "immediate must be a multiple of 4 bytes in the range");
1077   case Match_InvalidUImm8Lsb000:
1078     return generateImmOutOfRangeError(
1079         Operands, ErrorInfo, 0, (1 << 8) - 8,
1080         "immediate must be a multiple of 8 bytes in the range");
1081   case Match_InvalidSImm9Lsb0:
1082     return generateImmOutOfRangeError(
1083         Operands, ErrorInfo, -(1 << 8), (1 << 8) - 2,
1084         "immediate must be a multiple of 2 bytes in the range");
1085   case Match_InvalidUImm9Lsb000:
1086     return generateImmOutOfRangeError(
1087         Operands, ErrorInfo, 0, (1 << 9) - 8,
1088         "immediate must be a multiple of 8 bytes in the range");
1089   case Match_InvalidUImm10Lsb00NonZero:
1090     return generateImmOutOfRangeError(
1091         Operands, ErrorInfo, 4, (1 << 10) - 4,
1092         "immediate must be a multiple of 4 bytes in the range");
1093   case Match_InvalidSImm10Lsb0000NonZero:
1094     return generateImmOutOfRangeError(
1095         Operands, ErrorInfo, -(1 << 9), (1 << 9) - 16,
1096         "immediate must be a multiple of 16 bytes and non-zero in the range");
1097   case Match_InvalidSImm12:
1098     return generateImmOutOfRangeError(
1099         Operands, ErrorInfo, -(1 << 11), (1 << 11) - 1,
1100         "operand must be a symbol with %lo/%pcrel_lo/%tprel_lo modifier or an "
1101         "integer in the range");
1102   case Match_InvalidSImm12Lsb0:
1103     return generateImmOutOfRangeError(
1104         Operands, ErrorInfo, -(1 << 11), (1 << 11) - 2,
1105         "immediate must be a multiple of 2 bytes in the range");
1106   case Match_InvalidSImm13Lsb0:
1107     return generateImmOutOfRangeError(
1108         Operands, ErrorInfo, -(1 << 12), (1 << 12) - 2,
1109         "immediate must be a multiple of 2 bytes in the range");
1110   case Match_InvalidUImm20LUI:
1111     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1,
1112                                       "operand must be a symbol with "
1113                                       "%hi/%tprel_hi modifier or an integer in "
1114                                       "the range");
1115   case Match_InvalidUImm20AUIPC:
1116     return generateImmOutOfRangeError(
1117         Operands, ErrorInfo, 0, (1 << 20) - 1,
1118         "operand must be a symbol with a "
1119         "%pcrel_hi/%got_pcrel_hi/%tls_ie_pcrel_hi/%tls_gd_pcrel_hi modifier or "
1120         "an integer in the range");
1121   case Match_InvalidSImm21Lsb0JAL:
1122     return generateImmOutOfRangeError(
1123         Operands, ErrorInfo, -(1 << 20), (1 << 20) - 2,
1124         "immediate must be a multiple of 2 bytes in the range");
1125   case Match_InvalidCSRSystemRegister: {
1126     return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 12) - 1,
1127                                       "operand must be a valid system register "
1128                                       "name or an integer in the range");
1129   }
1130   case Match_InvalidFenceArg: {
1131     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1132     return Error(
1133         ErrorLoc,
1134         "operand must be formed of letters selected in-order from 'iorw'");
1135   }
1136   case Match_InvalidFRMArg: {
1137     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1138     return Error(
1139         ErrorLoc,
1140         "operand must be a valid floating point rounding mode mnemonic");
1141   }
1142   case Match_InvalidBareSymbol: {
1143     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1144     return Error(ErrorLoc, "operand must be a bare symbol name");
1145   }
1146   case Match_InvalidPseudoJumpSymbol: {
1147     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1148     return Error(ErrorLoc, "operand must be a valid jump target");
1149   }
1150   case Match_InvalidCallSymbol: {
1151     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1152     return Error(ErrorLoc, "operand must be a bare symbol name");
1153   }
1154   case Match_InvalidTPRelAddSymbol: {
1155     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1156     return Error(ErrorLoc, "operand must be a symbol with %tprel_add modifier");
1157   }
1158   case Match_InvalidVTypeI: {
1159     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1160     return Error(
1161         ErrorLoc,
1162         "operand must be "
1163         "e[8|16|32|64|128|256|512|1024],m[1|2|4|8|f2|f4|f8],[ta|tu],[ma|mu]");
1164   }
1165   case Match_InvalidVMaskRegister: {
1166     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
1167     return Error(ErrorLoc, "operand must be v0.t");
1168   }
1169   case Match_InvalidSImm5Plus1: {
1170     return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 4) + 1,
1171                                       (1 << 4),
1172                                       "immediate must be in the range");
1173   }
1174   }
1175 
1176   llvm_unreachable("Unknown match type detected!");
1177 }
1178 
1179 // Attempts to match Name as a register (either using the default name or
1180 // alternative ABI names), setting RegNo to the matching register. Upon
1181 // failure, returns true and sets RegNo to 0. If IsRV32E then registers
1182 // x16-x31 will be rejected.
1183 static bool matchRegisterNameHelper(bool IsRV32E, MCRegister &RegNo,
1184                                     StringRef Name) {
1185   RegNo = MatchRegisterName(Name);
1186   // The 16-/32- and 64-bit FPRs have the same asm name. Check that the initial
1187   // match always matches the 64-bit variant, and not the 16/32-bit one.
1188   assert(!(RegNo >= RISCV::F0_H && RegNo <= RISCV::F31_H));
1189   assert(!(RegNo >= RISCV::F0_F && RegNo <= RISCV::F31_F));
1190   // The default FPR register class is based on the tablegen enum ordering.
1191   static_assert(RISCV::F0_D < RISCV::F0_H, "FPR matching must be updated");
1192   static_assert(RISCV::F0_D < RISCV::F0_F, "FPR matching must be updated");
1193   if (RegNo == RISCV::NoRegister)
1194     RegNo = MatchRegisterAltName(Name);
1195   if (IsRV32E && RegNo >= RISCV::X16 && RegNo <= RISCV::X31)
1196     RegNo = RISCV::NoRegister;
1197   return RegNo == RISCV::NoRegister;
1198 }
1199 
1200 bool RISCVAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1201                                    SMLoc &EndLoc) {
1202   if (tryParseRegister(RegNo, StartLoc, EndLoc) != MatchOperand_Success)
1203     return Error(StartLoc, "invalid register name");
1204   return false;
1205 }
1206 
1207 OperandMatchResultTy RISCVAsmParser::tryParseRegister(unsigned &RegNo,
1208                                                       SMLoc &StartLoc,
1209                                                       SMLoc &EndLoc) {
1210   const AsmToken &Tok = getParser().getTok();
1211   StartLoc = Tok.getLoc();
1212   EndLoc = Tok.getEndLoc();
1213   RegNo = 0;
1214   StringRef Name = getLexer().getTok().getIdentifier();
1215 
1216   if (matchRegisterNameHelper(isRV32E(), (MCRegister &)RegNo, Name))
1217     return MatchOperand_NoMatch;
1218 
1219   getParser().Lex(); // Eat identifier token.
1220   return MatchOperand_Success;
1221 }
1222 
1223 OperandMatchResultTy RISCVAsmParser::parseRegister(OperandVector &Operands,
1224                                                    bool AllowParens) {
1225   SMLoc FirstS = getLoc();
1226   bool HadParens = false;
1227   AsmToken LParen;
1228 
1229   // If this is an LParen and a parenthesised register name is allowed, parse it
1230   // atomically.
1231   if (AllowParens && getLexer().is(AsmToken::LParen)) {
1232     AsmToken Buf[2];
1233     size_t ReadCount = getLexer().peekTokens(Buf);
1234     if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
1235       HadParens = true;
1236       LParen = getParser().getTok();
1237       getParser().Lex(); // Eat '('
1238     }
1239   }
1240 
1241   switch (getLexer().getKind()) {
1242   default:
1243     if (HadParens)
1244       getLexer().UnLex(LParen);
1245     return MatchOperand_NoMatch;
1246   case AsmToken::Identifier:
1247     StringRef Name = getLexer().getTok().getIdentifier();
1248     MCRegister RegNo;
1249     matchRegisterNameHelper(isRV32E(), RegNo, Name);
1250 
1251     if (RegNo == RISCV::NoRegister) {
1252       if (HadParens)
1253         getLexer().UnLex(LParen);
1254       return MatchOperand_NoMatch;
1255     }
1256     if (HadParens)
1257       Operands.push_back(RISCVOperand::createToken("(", FirstS, isRV64()));
1258     SMLoc S = getLoc();
1259     SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1260     getLexer().Lex();
1261     Operands.push_back(RISCVOperand::createReg(RegNo, S, E, isRV64()));
1262   }
1263 
1264   if (HadParens) {
1265     getParser().Lex(); // Eat ')'
1266     Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
1267   }
1268 
1269   return MatchOperand_Success;
1270 }
1271 
1272 OperandMatchResultTy
1273 RISCVAsmParser::parseCSRSystemRegister(OperandVector &Operands) {
1274   SMLoc S = getLoc();
1275   const MCExpr *Res;
1276 
1277   switch (getLexer().getKind()) {
1278   default:
1279     return MatchOperand_NoMatch;
1280   case AsmToken::LParen:
1281   case AsmToken::Minus:
1282   case AsmToken::Plus:
1283   case AsmToken::Exclaim:
1284   case AsmToken::Tilde:
1285   case AsmToken::Integer:
1286   case AsmToken::String: {
1287     if (getParser().parseExpression(Res))
1288       return MatchOperand_ParseFail;
1289 
1290     auto *CE = dyn_cast<MCConstantExpr>(Res);
1291     if (CE) {
1292       int64_t Imm = CE->getValue();
1293       if (isUInt<12>(Imm)) {
1294         auto SysReg = RISCVSysReg::lookupSysRegByEncoding(Imm);
1295         // Accept an immediate representing a named or un-named Sys Reg
1296         // if the range is valid, regardless of the required features.
1297         Operands.push_back(RISCVOperand::createSysReg(
1298             SysReg ? SysReg->Name : "", S, Imm, isRV64()));
1299         return MatchOperand_Success;
1300       }
1301     }
1302 
1303     Twine Msg = "immediate must be an integer in the range";
1304     Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 12) - 1) + "]");
1305     return MatchOperand_ParseFail;
1306   }
1307   case AsmToken::Identifier: {
1308     StringRef Identifier;
1309     if (getParser().parseIdentifier(Identifier))
1310       return MatchOperand_ParseFail;
1311 
1312     auto SysReg = RISCVSysReg::lookupSysRegByName(Identifier);
1313     if (!SysReg)
1314       SysReg = RISCVSysReg::lookupSysRegByAltName(Identifier);
1315     // Accept a named Sys Reg if the required features are present.
1316     if (SysReg) {
1317       if (!SysReg->haveRequiredFeatures(getSTI().getFeatureBits())) {
1318         Error(S, "system register use requires an option to be enabled");
1319         return MatchOperand_ParseFail;
1320       }
1321       Operands.push_back(RISCVOperand::createSysReg(
1322           Identifier, S, SysReg->Encoding, isRV64()));
1323       return MatchOperand_Success;
1324     }
1325 
1326     Twine Msg = "operand must be a valid system register name "
1327                 "or an integer in the range";
1328     Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 12) - 1) + "]");
1329     return MatchOperand_ParseFail;
1330   }
1331   case AsmToken::Percent: {
1332     // Discard operand with modifier.
1333     Twine Msg = "immediate must be an integer in the range";
1334     Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 12) - 1) + "]");
1335     return MatchOperand_ParseFail;
1336   }
1337   }
1338 
1339   return MatchOperand_NoMatch;
1340 }
1341 
1342 OperandMatchResultTy RISCVAsmParser::parseImmediate(OperandVector &Operands) {
1343   SMLoc S = getLoc();
1344   SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1345   const MCExpr *Res;
1346 
1347   switch (getLexer().getKind()) {
1348   default:
1349     return MatchOperand_NoMatch;
1350   case AsmToken::LParen:
1351   case AsmToken::Dot:
1352   case AsmToken::Minus:
1353   case AsmToken::Plus:
1354   case AsmToken::Exclaim:
1355   case AsmToken::Tilde:
1356   case AsmToken::Integer:
1357   case AsmToken::String:
1358   case AsmToken::Identifier:
1359     if (getParser().parseExpression(Res))
1360       return MatchOperand_ParseFail;
1361     break;
1362   case AsmToken::Percent:
1363     return parseOperandWithModifier(Operands);
1364   }
1365 
1366   Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1367   return MatchOperand_Success;
1368 }
1369 
1370 OperandMatchResultTy
1371 RISCVAsmParser::parseOperandWithModifier(OperandVector &Operands) {
1372   SMLoc S = getLoc();
1373   SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1374 
1375   if (getLexer().getKind() != AsmToken::Percent) {
1376     Error(getLoc(), "expected '%' for operand modifier");
1377     return MatchOperand_ParseFail;
1378   }
1379 
1380   getParser().Lex(); // Eat '%'
1381 
1382   if (getLexer().getKind() != AsmToken::Identifier) {
1383     Error(getLoc(), "expected valid identifier for operand modifier");
1384     return MatchOperand_ParseFail;
1385   }
1386   StringRef Identifier = getParser().getTok().getIdentifier();
1387   RISCVMCExpr::VariantKind VK = RISCVMCExpr::getVariantKindForName(Identifier);
1388   if (VK == RISCVMCExpr::VK_RISCV_Invalid) {
1389     Error(getLoc(), "unrecognized operand modifier");
1390     return MatchOperand_ParseFail;
1391   }
1392 
1393   getParser().Lex(); // Eat the identifier
1394   if (getLexer().getKind() != AsmToken::LParen) {
1395     Error(getLoc(), "expected '('");
1396     return MatchOperand_ParseFail;
1397   }
1398   getParser().Lex(); // Eat '('
1399 
1400   const MCExpr *SubExpr;
1401   if (getParser().parseParenExpression(SubExpr, E)) {
1402     return MatchOperand_ParseFail;
1403   }
1404 
1405   const MCExpr *ModExpr = RISCVMCExpr::create(SubExpr, VK, getContext());
1406   Operands.push_back(RISCVOperand::createImm(ModExpr, S, E, isRV64()));
1407   return MatchOperand_Success;
1408 }
1409 
1410 OperandMatchResultTy RISCVAsmParser::parseBareSymbol(OperandVector &Operands) {
1411   SMLoc S = getLoc();
1412   SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1413   const MCExpr *Res;
1414 
1415   if (getLexer().getKind() != AsmToken::Identifier)
1416     return MatchOperand_NoMatch;
1417 
1418   StringRef Identifier;
1419   AsmToken Tok = getLexer().getTok();
1420 
1421   if (getParser().parseIdentifier(Identifier))
1422     return MatchOperand_ParseFail;
1423 
1424   if (Identifier.consume_back("@plt")) {
1425     Error(getLoc(), "'@plt' operand not valid for instruction");
1426     return MatchOperand_ParseFail;
1427   }
1428 
1429   MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
1430 
1431   if (Sym->isVariable()) {
1432     const MCExpr *V = Sym->getVariableValue(/*SetUsed=*/false);
1433     if (!isa<MCSymbolRefExpr>(V)) {
1434       getLexer().UnLex(Tok); // Put back if it's not a bare symbol.
1435       return MatchOperand_NoMatch;
1436     }
1437     Res = V;
1438   } else
1439     Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1440 
1441   MCBinaryExpr::Opcode Opcode;
1442   switch (getLexer().getKind()) {
1443   default:
1444     Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1445     return MatchOperand_Success;
1446   case AsmToken::Plus:
1447     Opcode = MCBinaryExpr::Add;
1448     break;
1449   case AsmToken::Minus:
1450     Opcode = MCBinaryExpr::Sub;
1451     break;
1452   }
1453 
1454   const MCExpr *Expr;
1455   if (getParser().parseExpression(Expr))
1456     return MatchOperand_ParseFail;
1457   Res = MCBinaryExpr::create(Opcode, Res, Expr, getContext());
1458   Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1459   return MatchOperand_Success;
1460 }
1461 
1462 OperandMatchResultTy RISCVAsmParser::parseCallSymbol(OperandVector &Operands) {
1463   SMLoc S = getLoc();
1464   SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1465   const MCExpr *Res;
1466 
1467   if (getLexer().getKind() != AsmToken::Identifier)
1468     return MatchOperand_NoMatch;
1469 
1470   // Avoid parsing the register in `call rd, foo` as a call symbol.
1471   if (getLexer().peekTok().getKind() != AsmToken::EndOfStatement)
1472     return MatchOperand_NoMatch;
1473 
1474   StringRef Identifier;
1475   if (getParser().parseIdentifier(Identifier))
1476     return MatchOperand_ParseFail;
1477 
1478   RISCVMCExpr::VariantKind Kind = RISCVMCExpr::VK_RISCV_CALL;
1479   if (Identifier.consume_back("@plt"))
1480     Kind = RISCVMCExpr::VK_RISCV_CALL_PLT;
1481 
1482   MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
1483   Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1484   Res = RISCVMCExpr::create(Res, Kind, getContext());
1485   Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1486   return MatchOperand_Success;
1487 }
1488 
1489 OperandMatchResultTy
1490 RISCVAsmParser::parsePseudoJumpSymbol(OperandVector &Operands) {
1491   SMLoc S = getLoc();
1492   SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1493   const MCExpr *Res;
1494 
1495   if (getParser().parseExpression(Res))
1496     return MatchOperand_ParseFail;
1497 
1498   if (Res->getKind() != MCExpr::ExprKind::SymbolRef ||
1499       cast<MCSymbolRefExpr>(Res)->getKind() ==
1500           MCSymbolRefExpr::VariantKind::VK_PLT) {
1501     Error(S, "operand must be a valid jump target");
1502     return MatchOperand_ParseFail;
1503   }
1504 
1505   Res = RISCVMCExpr::create(Res, RISCVMCExpr::VK_RISCV_CALL, getContext());
1506   Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1507   return MatchOperand_Success;
1508 }
1509 
1510 OperandMatchResultTy RISCVAsmParser::parseJALOffset(OperandVector &Operands) {
1511   // Parsing jal operands is fiddly due to the `jal foo` and `jal ra, foo`
1512   // both being acceptable forms. When parsing `jal ra, foo` this function
1513   // will be called for the `ra` register operand in an attempt to match the
1514   // single-operand alias. parseJALOffset must fail for this case. It would
1515   // seem logical to try parse the operand using parseImmediate and return
1516   // NoMatch if the next token is a comma (meaning we must be parsing a jal in
1517   // the second form rather than the first). We can't do this as there's no
1518   // way of rewinding the lexer state. Instead, return NoMatch if this operand
1519   // is an identifier and is followed by a comma.
1520   if (getLexer().is(AsmToken::Identifier) &&
1521       getLexer().peekTok().is(AsmToken::Comma))
1522     return MatchOperand_NoMatch;
1523 
1524   return parseImmediate(Operands);
1525 }
1526 
1527 OperandMatchResultTy RISCVAsmParser::parseVTypeI(OperandVector &Operands) {
1528   SMLoc S = getLoc();
1529   if (getLexer().isNot(AsmToken::Identifier))
1530     return MatchOperand_NoMatch;
1531 
1532   SmallVector<AsmToken, 7> VTypeIElements;
1533   // Put all the tokens for vtypei operand into VTypeIElements vector.
1534   while (getLexer().isNot(AsmToken::EndOfStatement)) {
1535     VTypeIElements.push_back(getLexer().getTok());
1536     getLexer().Lex();
1537     if (getLexer().is(AsmToken::EndOfStatement))
1538       break;
1539     if (getLexer().isNot(AsmToken::Comma))
1540       goto MatchFail;
1541     AsmToken Comma = getLexer().getTok();
1542     VTypeIElements.push_back(Comma);
1543     getLexer().Lex();
1544   }
1545 
1546   if (VTypeIElements.size() == 7) {
1547     // The VTypeIElements layout is:
1548     // SEW comma LMUL comma TA comma MA
1549     //  0    1    2     3    4   5    6
1550     StringRef Name = VTypeIElements[0].getIdentifier();
1551     if (!Name.consume_front("e"))
1552       goto MatchFail;
1553     unsigned Sew;
1554     if (Name.getAsInteger(10, Sew))
1555       goto MatchFail;
1556     if (!RISCVVType::isValidSEW(Sew))
1557       goto MatchFail;
1558 
1559     Name = VTypeIElements[2].getIdentifier();
1560     if (!Name.consume_front("m"))
1561       goto MatchFail;
1562     // "m" or "mf"
1563     bool Fractional = Name.consume_front("f");
1564     unsigned Lmul;
1565     if (Name.getAsInteger(10, Lmul))
1566       goto MatchFail;
1567     if (!RISCVVType::isValidLMUL(Lmul, Fractional))
1568       goto MatchFail;
1569 
1570     // ta or tu
1571     Name = VTypeIElements[4].getIdentifier();
1572     bool TailAgnostic;
1573     if (Name == "ta")
1574       TailAgnostic = true;
1575     else if (Name == "tu")
1576       TailAgnostic = false;
1577     else
1578       goto MatchFail;
1579 
1580     // ma or mu
1581     Name = VTypeIElements[6].getIdentifier();
1582     bool MaskAgnostic;
1583     if (Name == "ma")
1584       MaskAgnostic = true;
1585     else if (Name == "mu")
1586       MaskAgnostic = false;
1587     else
1588       goto MatchFail;
1589 
1590     unsigned SewLog2 = Log2_32(Sew / 8);
1591     unsigned LmulLog2 = Log2_32(Lmul);
1592     RISCVVSEW VSEW = static_cast<RISCVVSEW>(SewLog2);
1593     RISCVVLMUL VLMUL =
1594         static_cast<RISCVVLMUL>(Fractional ? 8 - LmulLog2 : LmulLog2);
1595 
1596     unsigned VTypeI =
1597         RISCVVType::encodeVTYPE(VLMUL, VSEW, TailAgnostic, MaskAgnostic);
1598     Operands.push_back(RISCVOperand::createVType(VTypeI, S, isRV64()));
1599     return MatchOperand_Success;
1600   }
1601 
1602 // If NoMatch, unlex all the tokens that comprise a vtypei operand
1603 MatchFail:
1604   while (!VTypeIElements.empty())
1605     getLexer().UnLex(VTypeIElements.pop_back_val());
1606   return MatchOperand_NoMatch;
1607 }
1608 
1609 OperandMatchResultTy RISCVAsmParser::parseMaskReg(OperandVector &Operands) {
1610   switch (getLexer().getKind()) {
1611   default:
1612     return MatchOperand_NoMatch;
1613   case AsmToken::Identifier:
1614     StringRef Name = getLexer().getTok().getIdentifier();
1615     if (!Name.consume_back(".t")) {
1616       Error(getLoc(), "expected '.t' suffix");
1617       return MatchOperand_ParseFail;
1618     }
1619     MCRegister RegNo;
1620     matchRegisterNameHelper(isRV32E(), RegNo, Name);
1621 
1622     if (RegNo == RISCV::NoRegister)
1623       return MatchOperand_NoMatch;
1624     if (RegNo != RISCV::V0)
1625       return MatchOperand_NoMatch;
1626     SMLoc S = getLoc();
1627     SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1628     getLexer().Lex();
1629     Operands.push_back(RISCVOperand::createReg(RegNo, S, E, isRV64()));
1630   }
1631 
1632   return MatchOperand_Success;
1633 }
1634 
1635 OperandMatchResultTy
1636 RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
1637   if (getLexer().isNot(AsmToken::LParen)) {
1638     Error(getLoc(), "expected '('");
1639     return MatchOperand_ParseFail;
1640   }
1641 
1642   getParser().Lex(); // Eat '('
1643   Operands.push_back(RISCVOperand::createToken("(", getLoc(), isRV64()));
1644 
1645   if (parseRegister(Operands) != MatchOperand_Success) {
1646     Error(getLoc(), "expected register");
1647     return MatchOperand_ParseFail;
1648   }
1649 
1650   if (getLexer().isNot(AsmToken::RParen)) {
1651     Error(getLoc(), "expected ')'");
1652     return MatchOperand_ParseFail;
1653   }
1654 
1655   getParser().Lex(); // Eat ')'
1656   Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
1657 
1658   return MatchOperand_Success;
1659 }
1660 
1661 OperandMatchResultTy RISCVAsmParser::parseAtomicMemOp(OperandVector &Operands) {
1662   // Atomic operations such as lr.w, sc.w, and amo*.w accept a "memory operand"
1663   // as one of their register operands, such as `(a0)`. This just denotes that
1664   // the register (in this case `a0`) contains a memory address.
1665   //
1666   // Normally, we would be able to parse these by putting the parens into the
1667   // instruction string. However, GNU as also accepts a zero-offset memory
1668   // operand (such as `0(a0)`), and ignores the 0. Normally this would be parsed
1669   // with parseImmediate followed by parseMemOpBaseReg, but these instructions
1670   // do not accept an immediate operand, and we do not want to add a "dummy"
1671   // operand that is silently dropped.
1672   //
1673   // Instead, we use this custom parser. This will: allow (and discard) an
1674   // offset if it is zero; require (and discard) parentheses; and add only the
1675   // parsed register operand to `Operands`.
1676   //
1677   // These operands are printed with RISCVInstPrinter::printAtomicMemOp, which
1678   // will only print the register surrounded by parentheses (which GNU as also
1679   // uses as its canonical representation for these operands).
1680   std::unique_ptr<RISCVOperand> OptionalImmOp;
1681 
1682   if (getLexer().isNot(AsmToken::LParen)) {
1683     // Parse an Integer token. We do not accept arbritrary constant expressions
1684     // in the offset field (because they may include parens, which complicates
1685     // parsing a lot).
1686     int64_t ImmVal;
1687     SMLoc ImmStart = getLoc();
1688     if (getParser().parseIntToken(ImmVal,
1689                                   "expected '(' or optional integer offset"))
1690       return MatchOperand_ParseFail;
1691 
1692     // Create a RISCVOperand for checking later (so the error messages are
1693     // nicer), but we don't add it to Operands.
1694     SMLoc ImmEnd = getLoc();
1695     OptionalImmOp =
1696         RISCVOperand::createImm(MCConstantExpr::create(ImmVal, getContext()),
1697                                 ImmStart, ImmEnd, isRV64());
1698   }
1699 
1700   if (getLexer().isNot(AsmToken::LParen)) {
1701     Error(getLoc(), OptionalImmOp ? "expected '(' after optional integer offset"
1702                                   : "expected '(' or optional integer offset");
1703     return MatchOperand_ParseFail;
1704   }
1705   getParser().Lex(); // Eat '('
1706 
1707   if (parseRegister(Operands) != MatchOperand_Success) {
1708     Error(getLoc(), "expected register");
1709     return MatchOperand_ParseFail;
1710   }
1711 
1712   if (getLexer().isNot(AsmToken::RParen)) {
1713     Error(getLoc(), "expected ')'");
1714     return MatchOperand_ParseFail;
1715   }
1716   getParser().Lex(); // Eat ')'
1717 
1718   // Deferred Handling of non-zero offsets. This makes the error messages nicer.
1719   if (OptionalImmOp && !OptionalImmOp->isImmZero()) {
1720     Error(OptionalImmOp->getStartLoc(), "optional integer offset must be 0",
1721           SMRange(OptionalImmOp->getStartLoc(), OptionalImmOp->getEndLoc()));
1722     return MatchOperand_ParseFail;
1723   }
1724 
1725   return MatchOperand_Success;
1726 }
1727 
1728 /// Looks at a token type and creates the relevant operand from this
1729 /// information, adding to Operands. If operand was parsed, returns false, else
1730 /// true.
1731 bool RISCVAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
1732   // Check if the current operand has a custom associated parser, if so, try to
1733   // custom parse the operand, or fallback to the general approach.
1734   OperandMatchResultTy Result =
1735       MatchOperandParserImpl(Operands, Mnemonic, /*ParseForAllFeatures=*/true);
1736   if (Result == MatchOperand_Success)
1737     return false;
1738   if (Result == MatchOperand_ParseFail)
1739     return true;
1740 
1741   // Attempt to parse token as a register.
1742   if (parseRegister(Operands, true) == MatchOperand_Success)
1743     return false;
1744 
1745   // Attempt to parse token as an immediate
1746   if (parseImmediate(Operands) == MatchOperand_Success) {
1747     // Parse memory base register if present
1748     if (getLexer().is(AsmToken::LParen))
1749       return parseMemOpBaseReg(Operands) != MatchOperand_Success;
1750     return false;
1751   }
1752 
1753   // Finally we have exhausted all options and must declare defeat.
1754   Error(getLoc(), "unknown operand");
1755   return true;
1756 }
1757 
1758 bool RISCVAsmParser::ParseInstruction(ParseInstructionInfo &Info,
1759                                       StringRef Name, SMLoc NameLoc,
1760                                       OperandVector &Operands) {
1761   // Ensure that if the instruction occurs when relaxation is enabled,
1762   // relocations are forced for the file. Ideally this would be done when there
1763   // is enough information to reliably determine if the instruction itself may
1764   // cause relaxations. Unfortunately instruction processing stage occurs in the
1765   // same pass as relocation emission, so it's too late to set a 'sticky bit'
1766   // for the entire file.
1767   if (getSTI().getFeatureBits()[RISCV::FeatureRelax]) {
1768     auto *Assembler = getTargetStreamer().getStreamer().getAssemblerPtr();
1769     if (Assembler != nullptr) {
1770       RISCVAsmBackend &MAB =
1771           static_cast<RISCVAsmBackend &>(Assembler->getBackend());
1772       MAB.setForceRelocs();
1773     }
1774   }
1775 
1776   // First operand is token for instruction
1777   Operands.push_back(RISCVOperand::createToken(Name, NameLoc, isRV64()));
1778 
1779   // If there are no more operands, then finish
1780   if (getLexer().is(AsmToken::EndOfStatement))
1781     return false;
1782 
1783   // Parse first operand
1784   if (parseOperand(Operands, Name))
1785     return true;
1786 
1787   // Parse until end of statement, consuming commas between operands
1788   unsigned OperandIdx = 1;
1789   while (getLexer().is(AsmToken::Comma)) {
1790     // Consume comma token
1791     getLexer().Lex();
1792 
1793     // Parse next operand
1794     if (parseOperand(Operands, Name))
1795       return true;
1796 
1797     ++OperandIdx;
1798   }
1799 
1800   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1801     SMLoc Loc = getLexer().getLoc();
1802     getParser().eatToEndOfStatement();
1803     return Error(Loc, "unexpected token");
1804   }
1805 
1806   getParser().Lex(); // Consume the EndOfStatement.
1807   return false;
1808 }
1809 
1810 bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
1811                                        RISCVMCExpr::VariantKind &Kind) {
1812   Kind = RISCVMCExpr::VK_RISCV_None;
1813 
1814   if (const RISCVMCExpr *RE = dyn_cast<RISCVMCExpr>(Expr)) {
1815     Kind = RE->getKind();
1816     Expr = RE->getSubExpr();
1817   }
1818 
1819   MCValue Res;
1820   MCFixup Fixup;
1821   if (Expr->evaluateAsRelocatable(Res, nullptr, &Fixup))
1822     return Res.getRefKind() == RISCVMCExpr::VK_RISCV_None;
1823   return false;
1824 }
1825 
1826 bool RISCVAsmParser::ParseDirective(AsmToken DirectiveID) {
1827   // This returns false if this function recognizes the directive
1828   // regardless of whether it is successfully handles or reports an
1829   // error. Otherwise it returns true to give the generic parser a
1830   // chance at recognizing it.
1831   StringRef IDVal = DirectiveID.getString();
1832 
1833   if (IDVal == ".option")
1834     return parseDirectiveOption();
1835   else if (IDVal == ".attribute")
1836     return parseDirectiveAttribute();
1837 
1838   return true;
1839 }
1840 
1841 bool RISCVAsmParser::parseDirectiveOption() {
1842   MCAsmParser &Parser = getParser();
1843   // Get the option token.
1844   AsmToken Tok = Parser.getTok();
1845   // At the moment only identifiers are supported.
1846   if (Tok.isNot(AsmToken::Identifier))
1847     return Error(Parser.getTok().getLoc(),
1848                  "unexpected token, expected identifier");
1849 
1850   StringRef Option = Tok.getIdentifier();
1851 
1852   if (Option == "push") {
1853     getTargetStreamer().emitDirectiveOptionPush();
1854 
1855     Parser.Lex();
1856     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1857       return Error(Parser.getTok().getLoc(),
1858                    "unexpected token, expected end of statement");
1859 
1860     pushFeatureBits();
1861     return false;
1862   }
1863 
1864   if (Option == "pop") {
1865     SMLoc StartLoc = Parser.getTok().getLoc();
1866     getTargetStreamer().emitDirectiveOptionPop();
1867 
1868     Parser.Lex();
1869     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1870       return Error(Parser.getTok().getLoc(),
1871                    "unexpected token, expected end of statement");
1872 
1873     if (popFeatureBits())
1874       return Error(StartLoc, ".option pop with no .option push");
1875 
1876     return false;
1877   }
1878 
1879   if (Option == "rvc") {
1880     getTargetStreamer().emitDirectiveOptionRVC();
1881 
1882     Parser.Lex();
1883     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1884       return Error(Parser.getTok().getLoc(),
1885                    "unexpected token, expected end of statement");
1886 
1887     setFeatureBits(RISCV::FeatureStdExtC, "c");
1888     return false;
1889   }
1890 
1891   if (Option == "norvc") {
1892     getTargetStreamer().emitDirectiveOptionNoRVC();
1893 
1894     Parser.Lex();
1895     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1896       return Error(Parser.getTok().getLoc(),
1897                    "unexpected token, expected end of statement");
1898 
1899     clearFeatureBits(RISCV::FeatureStdExtC, "c");
1900     return false;
1901   }
1902 
1903   if (Option == "pic") {
1904     getTargetStreamer().emitDirectiveOptionPIC();
1905 
1906     Parser.Lex();
1907     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1908       return Error(Parser.getTok().getLoc(),
1909                    "unexpected token, expected end of statement");
1910 
1911     ParserOptions.IsPicEnabled = true;
1912     return false;
1913   }
1914 
1915   if (Option == "nopic") {
1916     getTargetStreamer().emitDirectiveOptionNoPIC();
1917 
1918     Parser.Lex();
1919     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1920       return Error(Parser.getTok().getLoc(),
1921                    "unexpected token, expected end of statement");
1922 
1923     ParserOptions.IsPicEnabled = false;
1924     return false;
1925   }
1926 
1927   if (Option == "relax") {
1928     getTargetStreamer().emitDirectiveOptionRelax();
1929 
1930     Parser.Lex();
1931     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1932       return Error(Parser.getTok().getLoc(),
1933                    "unexpected token, expected end of statement");
1934 
1935     setFeatureBits(RISCV::FeatureRelax, "relax");
1936     return false;
1937   }
1938 
1939   if (Option == "norelax") {
1940     getTargetStreamer().emitDirectiveOptionNoRelax();
1941 
1942     Parser.Lex();
1943     if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1944       return Error(Parser.getTok().getLoc(),
1945                    "unexpected token, expected end of statement");
1946 
1947     clearFeatureBits(RISCV::FeatureRelax, "relax");
1948     return false;
1949   }
1950 
1951   // Unknown option.
1952   Warning(Parser.getTok().getLoc(),
1953           "unknown option, expected 'push', 'pop', 'rvc', 'norvc', 'relax' or "
1954           "'norelax'");
1955   Parser.eatToEndOfStatement();
1956   return false;
1957 }
1958 
1959 /// parseDirectiveAttribute
1960 ///  ::= .attribute expression ',' ( expression | "string" )
1961 ///  ::= .attribute identifier ',' ( expression | "string" )
1962 bool RISCVAsmParser::parseDirectiveAttribute() {
1963   MCAsmParser &Parser = getParser();
1964   int64_t Tag;
1965   SMLoc TagLoc;
1966   TagLoc = Parser.getTok().getLoc();
1967   if (Parser.getTok().is(AsmToken::Identifier)) {
1968     StringRef Name = Parser.getTok().getIdentifier();
1969     Optional<unsigned> Ret =
1970         ELFAttrs::attrTypeFromString(Name, RISCVAttrs::RISCVAttributeTags);
1971     if (!Ret.hasValue()) {
1972       Error(TagLoc, "attribute name not recognised: " + Name);
1973       return false;
1974     }
1975     Tag = Ret.getValue();
1976     Parser.Lex();
1977   } else {
1978     const MCExpr *AttrExpr;
1979 
1980     TagLoc = Parser.getTok().getLoc();
1981     if (Parser.parseExpression(AttrExpr))
1982       return true;
1983 
1984     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
1985     if (check(!CE, TagLoc, "expected numeric constant"))
1986       return true;
1987 
1988     Tag = CE->getValue();
1989   }
1990 
1991   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
1992     return true;
1993 
1994   StringRef StringValue;
1995   int64_t IntegerValue = 0;
1996   bool IsIntegerValue = true;
1997 
1998   // RISC-V attributes have a string value if the tag number is odd
1999   // and an integer value if the tag number is even.
2000   if (Tag % 2)
2001     IsIntegerValue = false;
2002 
2003   SMLoc ValueExprLoc = Parser.getTok().getLoc();
2004   if (IsIntegerValue) {
2005     const MCExpr *ValueExpr;
2006     if (Parser.parseExpression(ValueExpr))
2007       return true;
2008 
2009     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
2010     if (!CE)
2011       return Error(ValueExprLoc, "expected numeric constant");
2012     IntegerValue = CE->getValue();
2013   } else {
2014     if (Parser.getTok().isNot(AsmToken::String))
2015       return Error(Parser.getTok().getLoc(), "expected string constant");
2016 
2017     StringValue = Parser.getTok().getStringContents();
2018     Parser.Lex();
2019   }
2020 
2021   if (Parser.parseToken(AsmToken::EndOfStatement,
2022                         "unexpected token in '.attribute' directive"))
2023     return true;
2024 
2025   if (Tag == RISCVAttrs::ARCH) {
2026     StringRef Arch = StringValue;
2027     if (Arch.consume_front("rv32"))
2028       clearFeatureBits(RISCV::Feature64Bit, "64bit");
2029     else if (Arch.consume_front("rv64"))
2030       setFeatureBits(RISCV::Feature64Bit, "64bit");
2031     else
2032       return Error(ValueExprLoc, "bad arch string " + Arch);
2033 
2034     // .attribute arch overrides the current architecture, so unset all
2035     // currently enabled extensions
2036     clearFeatureBits(RISCV::FeatureRV32E, "e");
2037     clearFeatureBits(RISCV::FeatureStdExtM, "m");
2038     clearFeatureBits(RISCV::FeatureStdExtA, "a");
2039     clearFeatureBits(RISCV::FeatureStdExtF, "f");
2040     clearFeatureBits(RISCV::FeatureStdExtD, "d");
2041     clearFeatureBits(RISCV::FeatureStdExtC, "c");
2042     clearFeatureBits(RISCV::FeatureStdExtB, "experimental-b");
2043     clearFeatureBits(RISCV::FeatureStdExtV, "experimental-v");
2044     clearFeatureBits(RISCV::FeatureExtZfh, "experimental-zfh");
2045     clearFeatureBits(RISCV::FeatureExtZba, "experimental-zba");
2046     clearFeatureBits(RISCV::FeatureExtZbb, "experimental-zbb");
2047     clearFeatureBits(RISCV::FeatureExtZbc, "experimental-zbc");
2048     clearFeatureBits(RISCV::FeatureExtZbe, "experimental-zbe");
2049     clearFeatureBits(RISCV::FeatureExtZbf, "experimental-zbf");
2050     clearFeatureBits(RISCV::FeatureExtZbm, "experimental-zbm");
2051     clearFeatureBits(RISCV::FeatureExtZbp, "experimental-zbp");
2052     clearFeatureBits(RISCV::FeatureExtZbproposedc, "experimental-zbproposedc");
2053     clearFeatureBits(RISCV::FeatureExtZbr, "experimental-zbr");
2054     clearFeatureBits(RISCV::FeatureExtZbs, "experimental-zbs");
2055     clearFeatureBits(RISCV::FeatureExtZbt, "experimental-zbt");
2056     clearFeatureBits(RISCV::FeatureExtZvamo, "experimental-zvamo");
2057     clearFeatureBits(RISCV::FeatureStdExtZvlsseg, "experimental-zvlsseg");
2058 
2059     while (!Arch.empty()) {
2060       bool DropFirst = true;
2061       if (Arch[0] == 'i')
2062         clearFeatureBits(RISCV::FeatureRV32E, "e");
2063       else if (Arch[0] == 'e')
2064         setFeatureBits(RISCV::FeatureRV32E, "e");
2065       else if (Arch[0] == 'g') {
2066         clearFeatureBits(RISCV::FeatureRV32E, "e");
2067         setFeatureBits(RISCV::FeatureStdExtM, "m");
2068         setFeatureBits(RISCV::FeatureStdExtA, "a");
2069         setFeatureBits(RISCV::FeatureStdExtF, "f");
2070         setFeatureBits(RISCV::FeatureStdExtD, "d");
2071       } else if (Arch[0] == 'm')
2072         setFeatureBits(RISCV::FeatureStdExtM, "m");
2073       else if (Arch[0] == 'a')
2074         setFeatureBits(RISCV::FeatureStdExtA, "a");
2075       else if (Arch[0] == 'f')
2076         setFeatureBits(RISCV::FeatureStdExtF, "f");
2077       else if (Arch[0] == 'd') {
2078         setFeatureBits(RISCV::FeatureStdExtF, "f");
2079         setFeatureBits(RISCV::FeatureStdExtD, "d");
2080       } else if (Arch[0] == 'c') {
2081         setFeatureBits(RISCV::FeatureStdExtC, "c");
2082       } else if (Arch[0] == 'b') {
2083         setFeatureBits(RISCV::FeatureStdExtB, "experimental-b");
2084       } else if (Arch[0] == 'v') {
2085         setFeatureBits(RISCV::FeatureStdExtV, "experimental-v");
2086       } else if (Arch[0] == 's' || Arch[0] == 'x' || Arch[0] == 'z') {
2087         StringRef Ext =
2088             Arch.take_until([](char c) { return ::isdigit(c) || c == '_'; });
2089         if (Ext == "zba")
2090           setFeatureBits(RISCV::FeatureExtZba, "experimental-zba");
2091         else if (Ext == "zbb")
2092           setFeatureBits(RISCV::FeatureExtZbb, "experimental-zbb");
2093         else if (Ext == "zbc")
2094           setFeatureBits(RISCV::FeatureExtZbc, "experimental-zbc");
2095         else if (Ext == "zbe")
2096           setFeatureBits(RISCV::FeatureExtZbe, "experimental-zbe");
2097         else if (Ext == "zbf")
2098           setFeatureBits(RISCV::FeatureExtZbf, "experimental-zbf");
2099         else if (Ext == "zbm")
2100           setFeatureBits(RISCV::FeatureExtZbm, "experimental-zbm");
2101         else if (Ext == "zbp")
2102           setFeatureBits(RISCV::FeatureExtZbp, "experimental-zbp");
2103         else if (Ext == "zbproposedc")
2104           setFeatureBits(RISCV::FeatureExtZbproposedc,
2105                          "experimental-zbproposedc");
2106         else if (Ext == "zbr")
2107           setFeatureBits(RISCV::FeatureExtZbr, "experimental-zbr");
2108         else if (Ext == "zbs")
2109           setFeatureBits(RISCV::FeatureExtZbs, "experimental-zbs");
2110         else if (Ext == "zbt")
2111           setFeatureBits(RISCV::FeatureExtZbt, "experimental-zbt");
2112         else if (Ext == "zfh")
2113           setFeatureBits(RISCV::FeatureExtZfh, "experimental-zfh");
2114         else if (Ext == "zvamo")
2115           setFeatureBits(RISCV::FeatureExtZvamo, "experimental-zvamo");
2116         else if (Ext == "zvlsseg")
2117           setFeatureBits(RISCV::FeatureStdExtZvlsseg, "experimental-zvlsseg");
2118         else
2119           return Error(ValueExprLoc, "bad arch string " + Ext);
2120         Arch = Arch.drop_until([](char c) { return ::isdigit(c) || c == '_'; });
2121         DropFirst = false;
2122       } else
2123         return Error(ValueExprLoc, "bad arch string " + Arch);
2124 
2125       if (DropFirst)
2126         Arch = Arch.drop_front(1);
2127       int major = 0;
2128       int minor = 0;
2129       Arch.consumeInteger(10, major);
2130       Arch.consume_front("p");
2131       Arch.consumeInteger(10, minor);
2132       Arch = Arch.drop_while([](char c) { return c == '_'; });
2133     }
2134   }
2135 
2136   if (IsIntegerValue)
2137     getTargetStreamer().emitAttribute(Tag, IntegerValue);
2138   else {
2139     if (Tag != RISCVAttrs::ARCH) {
2140       getTargetStreamer().emitTextAttribute(Tag, StringValue);
2141     } else {
2142       std::string formalArchStr = "rv32";
2143       if (getFeatureBits(RISCV::Feature64Bit))
2144         formalArchStr = "rv64";
2145       if (getFeatureBits(RISCV::FeatureRV32E))
2146         formalArchStr = (Twine(formalArchStr) + "e1p9").str();
2147       else
2148         formalArchStr = (Twine(formalArchStr) + "i2p0").str();
2149 
2150       if (getFeatureBits(RISCV::FeatureStdExtM))
2151         formalArchStr = (Twine(formalArchStr) + "_m2p0").str();
2152       if (getFeatureBits(RISCV::FeatureStdExtA))
2153         formalArchStr = (Twine(formalArchStr) + "_a2p0").str();
2154       if (getFeatureBits(RISCV::FeatureStdExtF))
2155         formalArchStr = (Twine(formalArchStr) + "_f2p0").str();
2156       if (getFeatureBits(RISCV::FeatureStdExtD))
2157         formalArchStr = (Twine(formalArchStr) + "_d2p0").str();
2158       if (getFeatureBits(RISCV::FeatureStdExtC))
2159         formalArchStr = (Twine(formalArchStr) + "_c2p0").str();
2160       if (getFeatureBits(RISCV::FeatureStdExtB))
2161         formalArchStr = (Twine(formalArchStr) + "_b0p93").str();
2162       if (getFeatureBits(RISCV::FeatureStdExtV))
2163         formalArchStr = (Twine(formalArchStr) + "_v0p10").str();
2164       if (getFeatureBits(RISCV::FeatureExtZfh))
2165         formalArchStr = (Twine(formalArchStr) + "_zfh0p1").str();
2166       if (getFeatureBits(RISCV::FeatureExtZba))
2167         formalArchStr = (Twine(formalArchStr) + "_zba0p93").str();
2168       if (getFeatureBits(RISCV::FeatureExtZbb))
2169         formalArchStr = (Twine(formalArchStr) + "_zbb0p93").str();
2170       if (getFeatureBits(RISCV::FeatureExtZbc))
2171         formalArchStr = (Twine(formalArchStr) + "_zbc0p93").str();
2172       if (getFeatureBits(RISCV::FeatureExtZbe))
2173         formalArchStr = (Twine(formalArchStr) + "_zbe0p93").str();
2174       if (getFeatureBits(RISCV::FeatureExtZbf))
2175         formalArchStr = (Twine(formalArchStr) + "_zbf0p93").str();
2176       if (getFeatureBits(RISCV::FeatureExtZbm))
2177         formalArchStr = (Twine(formalArchStr) + "_zbm0p93").str();
2178       if (getFeatureBits(RISCV::FeatureExtZbp))
2179         formalArchStr = (Twine(formalArchStr) + "_zbp0p93").str();
2180       if (getFeatureBits(RISCV::FeatureExtZbproposedc))
2181         formalArchStr = (Twine(formalArchStr) + "_zbproposedc0p93").str();
2182       if (getFeatureBits(RISCV::FeatureExtZbr))
2183         formalArchStr = (Twine(formalArchStr) + "_zbr0p93").str();
2184       if (getFeatureBits(RISCV::FeatureExtZbs))
2185         formalArchStr = (Twine(formalArchStr) + "_zbs0p93").str();
2186       if (getFeatureBits(RISCV::FeatureExtZbt))
2187         formalArchStr = (Twine(formalArchStr) + "_zbt0p93").str();
2188       if (getFeatureBits(RISCV::FeatureExtZvamo))
2189         formalArchStr = (Twine(formalArchStr) + "_zvamo0p10").str();
2190       if (getFeatureBits(RISCV::FeatureStdExtZvlsseg))
2191         formalArchStr = (Twine(formalArchStr) + "_zvlsseg0p10").str();
2192 
2193       getTargetStreamer().emitTextAttribute(Tag, formalArchStr);
2194     }
2195   }
2196 
2197   return false;
2198 }
2199 
2200 void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
2201   MCInst CInst;
2202   bool Res = compressInst(CInst, Inst, getSTI(), S.getContext());
2203   if (Res)
2204     ++RISCVNumInstrsCompressed;
2205   S.emitInstruction((Res ? CInst : Inst), getSTI());
2206 }
2207 
2208 void RISCVAsmParser::emitLoadImm(MCRegister DestReg, int64_t Value,
2209                                  MCStreamer &Out) {
2210   RISCVMatInt::InstSeq Seq = RISCVMatInt::generateInstSeq(Value, isRV64());
2211 
2212   MCRegister SrcReg = RISCV::X0;
2213   for (RISCVMatInt::Inst &Inst : Seq) {
2214     if (Inst.Opc == RISCV::LUI) {
2215       emitToStreamer(
2216           Out, MCInstBuilder(RISCV::LUI).addReg(DestReg).addImm(Inst.Imm));
2217     } else {
2218       emitToStreamer(
2219           Out, MCInstBuilder(Inst.Opc).addReg(DestReg).addReg(SrcReg).addImm(
2220                    Inst.Imm));
2221     }
2222 
2223     // Only the first instruction has X0 as its source.
2224     SrcReg = DestReg;
2225   }
2226 }
2227 
2228 void RISCVAsmParser::emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
2229                                        const MCExpr *Symbol,
2230                                        RISCVMCExpr::VariantKind VKHi,
2231                                        unsigned SecondOpcode, SMLoc IDLoc,
2232                                        MCStreamer &Out) {
2233   // A pair of instructions for PC-relative addressing; expands to
2234   //   TmpLabel: AUIPC TmpReg, VKHi(symbol)
2235   //             OP DestReg, TmpReg, %pcrel_lo(TmpLabel)
2236   MCContext &Ctx = getContext();
2237 
2238   MCSymbol *TmpLabel = Ctx.createNamedTempSymbol("pcrel_hi");
2239   Out.emitLabel(TmpLabel);
2240 
2241   const RISCVMCExpr *SymbolHi = RISCVMCExpr::create(Symbol, VKHi, Ctx);
2242   emitToStreamer(
2243       Out, MCInstBuilder(RISCV::AUIPC).addOperand(TmpReg).addExpr(SymbolHi));
2244 
2245   const MCExpr *RefToLinkTmpLabel =
2246       RISCVMCExpr::create(MCSymbolRefExpr::create(TmpLabel, Ctx),
2247                           RISCVMCExpr::VK_RISCV_PCREL_LO, Ctx);
2248 
2249   emitToStreamer(Out, MCInstBuilder(SecondOpcode)
2250                           .addOperand(DestReg)
2251                           .addOperand(TmpReg)
2252                           .addExpr(RefToLinkTmpLabel));
2253 }
2254 
2255 void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
2256                                           MCStreamer &Out) {
2257   // The load local address pseudo-instruction "lla" is used in PC-relative
2258   // addressing of local symbols:
2259   //   lla rdest, symbol
2260   // expands to
2261   //   TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
2262   //             ADDI rdest, rdest, %pcrel_lo(TmpLabel)
2263   MCOperand DestReg = Inst.getOperand(0);
2264   const MCExpr *Symbol = Inst.getOperand(1).getExpr();
2265   emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
2266                     RISCV::ADDI, IDLoc, Out);
2267 }
2268 
2269 void RISCVAsmParser::emitLoadAddress(MCInst &Inst, SMLoc IDLoc,
2270                                      MCStreamer &Out) {
2271   // The load address pseudo-instruction "la" is used in PC-relative and
2272   // GOT-indirect addressing of global symbols:
2273   //   la rdest, symbol
2274   // expands to either (for non-PIC)
2275   //   TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
2276   //             ADDI rdest, rdest, %pcrel_lo(TmpLabel)
2277   // or (for PIC)
2278   //   TmpLabel: AUIPC rdest, %got_pcrel_hi(symbol)
2279   //             Lx rdest, %pcrel_lo(TmpLabel)(rdest)
2280   MCOperand DestReg = Inst.getOperand(0);
2281   const MCExpr *Symbol = Inst.getOperand(1).getExpr();
2282   unsigned SecondOpcode;
2283   RISCVMCExpr::VariantKind VKHi;
2284   if (ParserOptions.IsPicEnabled) {
2285     SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
2286     VKHi = RISCVMCExpr::VK_RISCV_GOT_HI;
2287   } else {
2288     SecondOpcode = RISCV::ADDI;
2289     VKHi = RISCVMCExpr::VK_RISCV_PCREL_HI;
2290   }
2291   emitAuipcInstPair(DestReg, DestReg, Symbol, VKHi, SecondOpcode, IDLoc, Out);
2292 }
2293 
2294 void RISCVAsmParser::emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc,
2295                                           MCStreamer &Out) {
2296   // The load TLS IE address pseudo-instruction "la.tls.ie" is used in
2297   // initial-exec TLS model addressing of global symbols:
2298   //   la.tls.ie rdest, symbol
2299   // expands to
2300   //   TmpLabel: AUIPC rdest, %tls_ie_pcrel_hi(symbol)
2301   //             Lx rdest, %pcrel_lo(TmpLabel)(rdest)
2302   MCOperand DestReg = Inst.getOperand(0);
2303   const MCExpr *Symbol = Inst.getOperand(1).getExpr();
2304   unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
2305   emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GOT_HI,
2306                     SecondOpcode, IDLoc, Out);
2307 }
2308 
2309 void RISCVAsmParser::emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc,
2310                                           MCStreamer &Out) {
2311   // The load TLS GD address pseudo-instruction "la.tls.gd" is used in
2312   // global-dynamic TLS model addressing of global symbols:
2313   //   la.tls.gd rdest, symbol
2314   // expands to
2315   //   TmpLabel: AUIPC rdest, %tls_gd_pcrel_hi(symbol)
2316   //             ADDI rdest, rdest, %pcrel_lo(TmpLabel)
2317   MCOperand DestReg = Inst.getOperand(0);
2318   const MCExpr *Symbol = Inst.getOperand(1).getExpr();
2319   emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GD_HI,
2320                     RISCV::ADDI, IDLoc, Out);
2321 }
2322 
2323 void RISCVAsmParser::emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode,
2324                                          SMLoc IDLoc, MCStreamer &Out,
2325                                          bool HasTmpReg) {
2326   // The load/store pseudo-instruction does a pc-relative load with
2327   // a symbol.
2328   //
2329   // The expansion looks like this
2330   //
2331   //   TmpLabel: AUIPC tmp, %pcrel_hi(symbol)
2332   //             [S|L]X    rd, %pcrel_lo(TmpLabel)(tmp)
2333   MCOperand DestReg = Inst.getOperand(0);
2334   unsigned SymbolOpIdx = HasTmpReg ? 2 : 1;
2335   unsigned TmpRegOpIdx = HasTmpReg ? 1 : 0;
2336   MCOperand TmpReg = Inst.getOperand(TmpRegOpIdx);
2337   const MCExpr *Symbol = Inst.getOperand(SymbolOpIdx).getExpr();
2338   emitAuipcInstPair(DestReg, TmpReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
2339                     Opcode, IDLoc, Out);
2340 }
2341 
2342 void RISCVAsmParser::emitPseudoExtend(MCInst &Inst, bool SignExtend,
2343                                       int64_t Width, SMLoc IDLoc,
2344                                       MCStreamer &Out) {
2345   // The sign/zero extend pseudo-instruction does two shifts, with the shift
2346   // amounts dependent on the XLEN.
2347   //
2348   // The expansion looks like this
2349   //
2350   //    SLLI rd, rs, XLEN - Width
2351   //    SR[A|R]I rd, rd, XLEN - Width
2352   MCOperand DestReg = Inst.getOperand(0);
2353   MCOperand SourceReg = Inst.getOperand(1);
2354 
2355   unsigned SecondOpcode = SignExtend ? RISCV::SRAI : RISCV::SRLI;
2356   int64_t ShAmt = (isRV64() ? 64 : 32) - Width;
2357 
2358   assert(ShAmt > 0 && "Shift amount must be non-zero.");
2359 
2360   emitToStreamer(Out, MCInstBuilder(RISCV::SLLI)
2361                           .addOperand(DestReg)
2362                           .addOperand(SourceReg)
2363                           .addImm(ShAmt));
2364 
2365   emitToStreamer(Out, MCInstBuilder(SecondOpcode)
2366                           .addOperand(DestReg)
2367                           .addOperand(DestReg)
2368                           .addImm(ShAmt));
2369 }
2370 
2371 void RISCVAsmParser::emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
2372                                MCStreamer &Out) {
2373   if (Inst.getNumOperands() == 3) {
2374     // unmasked va >= x
2375     //
2376     //  pseudoinstruction: vmsge{u}.vx vd, va, x
2377     //  expansion: vmslt{u}.vx vd, va, x; vmnand.mm vd, vd, vd
2378     emitToStreamer(Out, MCInstBuilder(Opcode)
2379                             .addOperand(Inst.getOperand(0))
2380                             .addOperand(Inst.getOperand(1))
2381                             .addOperand(Inst.getOperand(2))
2382                             .addReg(RISCV::NoRegister));
2383     emitToStreamer(Out, MCInstBuilder(RISCV::VMNAND_MM)
2384                             .addOperand(Inst.getOperand(0))
2385                             .addOperand(Inst.getOperand(0))
2386                             .addOperand(Inst.getOperand(0)));
2387   } else if (Inst.getNumOperands() == 4) {
2388     // masked va >= x, vd != v0
2389     //
2390     //  pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t
2391     //  expansion: vmslt{u}.vx vd, va, x, v0.t; vmxor.mm vd, vd, v0
2392     assert(Inst.getOperand(0).getReg() != RISCV::V0 &&
2393            "The destination register should not be V0.");
2394     emitToStreamer(Out, MCInstBuilder(Opcode)
2395                             .addOperand(Inst.getOperand(0))
2396                             .addOperand(Inst.getOperand(1))
2397                             .addOperand(Inst.getOperand(2))
2398                             .addOperand(Inst.getOperand(3)));
2399     emitToStreamer(Out, MCInstBuilder(RISCV::VMXOR_MM)
2400                             .addOperand(Inst.getOperand(0))
2401                             .addOperand(Inst.getOperand(0))
2402                             .addReg(RISCV::V0));
2403   } else if (Inst.getNumOperands() == 5 &&
2404              Inst.getOperand(0).getReg() == RISCV::V0) {
2405     // masked va >= x, vd == v0
2406     //
2407     //  pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
2408     //  expansion: vmslt{u}.vx vt, va, x;  vmandnot.mm vd, vd, vt
2409     assert(Inst.getOperand(0).getReg() == RISCV::V0 &&
2410            "The destination register should be V0.");
2411     assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
2412            "The temporary vector register should not be V0.");
2413     emitToStreamer(Out, MCInstBuilder(Opcode)
2414                             .addOperand(Inst.getOperand(1))
2415                             .addOperand(Inst.getOperand(2))
2416                             .addOperand(Inst.getOperand(3))
2417                             .addOperand(Inst.getOperand(4)));
2418     emitToStreamer(Out, MCInstBuilder(RISCV::VMANDNOT_MM)
2419                             .addOperand(Inst.getOperand(0))
2420                             .addOperand(Inst.getOperand(0))
2421                             .addOperand(Inst.getOperand(1)));
2422   } else if (Inst.getNumOperands() == 5) {
2423     // masked va >= x, any vd
2424     //
2425     // pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
2426     // expansion: vmslt{u}.vx vt, va, x; vmandnot.mm vt, v0, vt; vmandnot.mm vd,
2427     // vd, v0; vmor.mm vd, vt, vd
2428     assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
2429            "The temporary vector register should not be V0.");
2430     emitToStreamer(Out, MCInstBuilder(Opcode)
2431                             .addOperand(Inst.getOperand(1))
2432                             .addOperand(Inst.getOperand(2))
2433                             .addOperand(Inst.getOperand(3))
2434                             .addReg(RISCV::NoRegister));
2435     emitToStreamer(Out, MCInstBuilder(RISCV::VMANDNOT_MM)
2436                             .addOperand(Inst.getOperand(1))
2437                             .addReg(RISCV::V0)
2438                             .addOperand(Inst.getOperand(1)));
2439     emitToStreamer(Out, MCInstBuilder(RISCV::VMANDNOT_MM)
2440                             .addOperand(Inst.getOperand(0))
2441                             .addOperand(Inst.getOperand(0))
2442                             .addReg(RISCV::V0));
2443     emitToStreamer(Out, MCInstBuilder(RISCV::VMOR_MM)
2444                             .addOperand(Inst.getOperand(0))
2445                             .addOperand(Inst.getOperand(1))
2446                             .addOperand(Inst.getOperand(0)));
2447   }
2448 }
2449 
2450 bool RISCVAsmParser::checkPseudoAddTPRel(MCInst &Inst,
2451                                          OperandVector &Operands) {
2452   assert(Inst.getOpcode() == RISCV::PseudoAddTPRel && "Invalid instruction");
2453   assert(Inst.getOperand(2).isReg() && "Unexpected second operand kind");
2454   if (Inst.getOperand(2).getReg() != RISCV::X4) {
2455     SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
2456     return Error(ErrorLoc, "the second input operand must be tp/x4 when using "
2457                            "%tprel_add modifier");
2458   }
2459 
2460   return false;
2461 }
2462 
2463 std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultMaskRegOp() const {
2464   return RISCVOperand::createReg(RISCV::NoRegister, llvm::SMLoc(),
2465                                  llvm::SMLoc(), isRV64());
2466 }
2467 
2468 bool RISCVAsmParser::validateInstruction(MCInst &Inst,
2469                                          OperandVector &Operands) {
2470   if (Inst.getOpcode() == RISCV::PseudoVMSGEU_VX_M_T ||
2471       Inst.getOpcode() == RISCV::PseudoVMSGE_VX_M_T) {
2472     unsigned DestReg = Inst.getOperand(0).getReg();
2473     unsigned TempReg = Inst.getOperand(1).getReg();
2474     if (DestReg == TempReg) {
2475       SMLoc Loc = Operands.back()->getStartLoc();
2476       return Error(Loc, "The temporary vector register cannot be the same as "
2477                         "the destination register.");
2478     }
2479   }
2480 
2481   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
2482   unsigned Constraints =
2483       (MCID.TSFlags & RISCVII::ConstraintMask) >> RISCVII::ConstraintShift;
2484   if (Constraints == RISCVII::NoConstraint)
2485     return false;
2486 
2487   unsigned DestReg = Inst.getOperand(0).getReg();
2488   // Operands[1] will be the first operand, DestReg.
2489   SMLoc Loc = Operands[1]->getStartLoc();
2490   if (Constraints & RISCVII::VS2Constraint) {
2491     unsigned CheckReg = Inst.getOperand(1).getReg();
2492     if (DestReg == CheckReg)
2493       return Error(Loc, "The destination vector register group cannot overlap"
2494                         " the source vector register group.");
2495   }
2496   if ((Constraints & RISCVII::VS1Constraint) && (Inst.getOperand(2).isReg())) {
2497     unsigned CheckReg = Inst.getOperand(2).getReg();
2498     if (DestReg == CheckReg)
2499       return Error(Loc, "The destination vector register group cannot overlap"
2500                         " the source vector register group.");
2501   }
2502   if ((Constraints & RISCVII::VMConstraint) && (DestReg == RISCV::V0)) {
2503     // vadc, vsbc are special cases. These instructions have no mask register.
2504     // The destination register could not be V0.
2505     unsigned Opcode = Inst.getOpcode();
2506     if (Opcode == RISCV::VADC_VVM || Opcode == RISCV::VADC_VXM ||
2507         Opcode == RISCV::VADC_VIM || Opcode == RISCV::VSBC_VVM ||
2508         Opcode == RISCV::VSBC_VXM || Opcode == RISCV::VFMERGE_VFM ||
2509         Opcode == RISCV::VMERGE_VIM || Opcode == RISCV::VMERGE_VVM ||
2510         Opcode == RISCV::VMERGE_VXM)
2511       return Error(Loc, "The destination vector register group cannot be V0.");
2512 
2513     // Regardless masked or unmasked version, the number of operands is the
2514     // same. For example, "viota.m v0, v2" is "viota.m v0, v2, NoRegister"
2515     // actually. We need to check the last operand to ensure whether it is
2516     // masked or not.
2517     unsigned CheckReg = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
2518     assert((CheckReg == RISCV::V0 || CheckReg == RISCV::NoRegister) &&
2519            "Unexpected register for mask operand");
2520 
2521     if (DestReg == CheckReg)
2522       return Error(Loc, "The destination vector register group cannot overlap"
2523                         " the mask register.");
2524   }
2525   return false;
2526 }
2527 
2528 bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
2529                                         OperandVector &Operands,
2530                                         MCStreamer &Out) {
2531   Inst.setLoc(IDLoc);
2532 
2533   switch (Inst.getOpcode()) {
2534   default:
2535     break;
2536   case RISCV::PseudoLI: {
2537     MCRegister Reg = Inst.getOperand(0).getReg();
2538     const MCOperand &Op1 = Inst.getOperand(1);
2539     if (Op1.isExpr()) {
2540       // We must have li reg, %lo(sym) or li reg, %pcrel_lo(sym) or similar.
2541       // Just convert to an addi. This allows compatibility with gas.
2542       emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
2543                               .addReg(Reg)
2544                               .addReg(RISCV::X0)
2545                               .addExpr(Op1.getExpr()));
2546       return false;
2547     }
2548     int64_t Imm = Inst.getOperand(1).getImm();
2549     // On RV32 the immediate here can either be a signed or an unsigned
2550     // 32-bit number. Sign extension has to be performed to ensure that Imm
2551     // represents the expected signed 64-bit number.
2552     if (!isRV64())
2553       Imm = SignExtend64<32>(Imm);
2554     emitLoadImm(Reg, Imm, Out);
2555     return false;
2556   }
2557   case RISCV::PseudoLLA:
2558     emitLoadLocalAddress(Inst, IDLoc, Out);
2559     return false;
2560   case RISCV::PseudoLA:
2561     emitLoadAddress(Inst, IDLoc, Out);
2562     return false;
2563   case RISCV::PseudoLA_TLS_IE:
2564     emitLoadTLSIEAddress(Inst, IDLoc, Out);
2565     return false;
2566   case RISCV::PseudoLA_TLS_GD:
2567     emitLoadTLSGDAddress(Inst, IDLoc, Out);
2568     return false;
2569   case RISCV::PseudoLB:
2570     emitLoadStoreSymbol(Inst, RISCV::LB, IDLoc, Out, /*HasTmpReg=*/false);
2571     return false;
2572   case RISCV::PseudoLBU:
2573     emitLoadStoreSymbol(Inst, RISCV::LBU, IDLoc, Out, /*HasTmpReg=*/false);
2574     return false;
2575   case RISCV::PseudoLH:
2576     emitLoadStoreSymbol(Inst, RISCV::LH, IDLoc, Out, /*HasTmpReg=*/false);
2577     return false;
2578   case RISCV::PseudoLHU:
2579     emitLoadStoreSymbol(Inst, RISCV::LHU, IDLoc, Out, /*HasTmpReg=*/false);
2580     return false;
2581   case RISCV::PseudoLW:
2582     emitLoadStoreSymbol(Inst, RISCV::LW, IDLoc, Out, /*HasTmpReg=*/false);
2583     return false;
2584   case RISCV::PseudoLWU:
2585     emitLoadStoreSymbol(Inst, RISCV::LWU, IDLoc, Out, /*HasTmpReg=*/false);
2586     return false;
2587   case RISCV::PseudoLD:
2588     emitLoadStoreSymbol(Inst, RISCV::LD, IDLoc, Out, /*HasTmpReg=*/false);
2589     return false;
2590   case RISCV::PseudoFLH:
2591     emitLoadStoreSymbol(Inst, RISCV::FLH, IDLoc, Out, /*HasTmpReg=*/true);
2592     return false;
2593   case RISCV::PseudoFLW:
2594     emitLoadStoreSymbol(Inst, RISCV::FLW, IDLoc, Out, /*HasTmpReg=*/true);
2595     return false;
2596   case RISCV::PseudoFLD:
2597     emitLoadStoreSymbol(Inst, RISCV::FLD, IDLoc, Out, /*HasTmpReg=*/true);
2598     return false;
2599   case RISCV::PseudoSB:
2600     emitLoadStoreSymbol(Inst, RISCV::SB, IDLoc, Out, /*HasTmpReg=*/true);
2601     return false;
2602   case RISCV::PseudoSH:
2603     emitLoadStoreSymbol(Inst, RISCV::SH, IDLoc, Out, /*HasTmpReg=*/true);
2604     return false;
2605   case RISCV::PseudoSW:
2606     emitLoadStoreSymbol(Inst, RISCV::SW, IDLoc, Out, /*HasTmpReg=*/true);
2607     return false;
2608   case RISCV::PseudoSD:
2609     emitLoadStoreSymbol(Inst, RISCV::SD, IDLoc, Out, /*HasTmpReg=*/true);
2610     return false;
2611   case RISCV::PseudoFSH:
2612     emitLoadStoreSymbol(Inst, RISCV::FSH, IDLoc, Out, /*HasTmpReg=*/true);
2613     return false;
2614   case RISCV::PseudoFSW:
2615     emitLoadStoreSymbol(Inst, RISCV::FSW, IDLoc, Out, /*HasTmpReg=*/true);
2616     return false;
2617   case RISCV::PseudoFSD:
2618     emitLoadStoreSymbol(Inst, RISCV::FSD, IDLoc, Out, /*HasTmpReg=*/true);
2619     return false;
2620   case RISCV::PseudoAddTPRel:
2621     if (checkPseudoAddTPRel(Inst, Operands))
2622       return true;
2623     break;
2624   case RISCV::PseudoSEXT_B:
2625     emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/8, IDLoc, Out);
2626     return false;
2627   case RISCV::PseudoSEXT_H:
2628     emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/16, IDLoc, Out);
2629     return false;
2630   case RISCV::PseudoZEXT_H:
2631     emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/16, IDLoc, Out);
2632     return false;
2633   case RISCV::PseudoZEXT_W:
2634     emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/32, IDLoc, Out);
2635     return false;
2636   case RISCV::PseudoVMSGEU_VX:
2637   case RISCV::PseudoVMSGEU_VX_M:
2638   case RISCV::PseudoVMSGEU_VX_M_T:
2639     emitVMSGE(Inst, RISCV::VMSLTU_VX, IDLoc, Out);
2640     return false;
2641   case RISCV::PseudoVMSGE_VX:
2642   case RISCV::PseudoVMSGE_VX_M:
2643   case RISCV::PseudoVMSGE_VX_M_T:
2644     emitVMSGE(Inst, RISCV::VMSLT_VX, IDLoc, Out);
2645     return false;
2646   case RISCV::PseudoVMSGE_VI:
2647   case RISCV::PseudoVMSLT_VI: {
2648     // These instructions are signed and so is immediate so we can subtract one
2649     // and change the opcode.
2650     int64_t Imm = Inst.getOperand(2).getImm();
2651     unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGE_VI ? RISCV::VMSGT_VI
2652                                                              : RISCV::VMSLE_VI;
2653     emitToStreamer(Out, MCInstBuilder(Opc)
2654                             .addOperand(Inst.getOperand(0))
2655                             .addOperand(Inst.getOperand(1))
2656                             .addImm(Imm - 1)
2657                             .addOperand(Inst.getOperand(3)));
2658     return false;
2659   }
2660   case RISCV::PseudoVMSGEU_VI:
2661   case RISCV::PseudoVMSLTU_VI: {
2662     int64_t Imm = Inst.getOperand(2).getImm();
2663     // Unsigned comparisons are tricky because the immediate is signed. If the
2664     // immediate is 0 we can't just subtract one. vmsltu.vi v0, v1, 0 is always
2665     // false, but vmsle.vi v0, v1, -1 is always true. Instead we use
2666     // vmsne v0, v1, v1 which is always false.
2667     if (Imm == 0) {
2668       unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
2669                          ? RISCV::VMSEQ_VV
2670                          : RISCV::VMSNE_VV;
2671       emitToStreamer(Out, MCInstBuilder(Opc)
2672                               .addOperand(Inst.getOperand(0))
2673                               .addOperand(Inst.getOperand(1))
2674                               .addOperand(Inst.getOperand(1))
2675                               .addOperand(Inst.getOperand(3)));
2676     } else {
2677       // Other immediate values can subtract one like signed.
2678       unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
2679                          ? RISCV::VMSGTU_VI
2680                          : RISCV::VMSLEU_VI;
2681       emitToStreamer(Out, MCInstBuilder(Opc)
2682                               .addOperand(Inst.getOperand(0))
2683                               .addOperand(Inst.getOperand(1))
2684                               .addImm(Imm - 1)
2685                               .addOperand(Inst.getOperand(3)));
2686     }
2687 
2688     return false;
2689   }
2690   }
2691 
2692   emitToStreamer(Out, Inst);
2693   return false;
2694 }
2695 
2696 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVAsmParser() {
2697   RegisterMCAsmParser<RISCVAsmParser> X(getTheRISCV32Target());
2698   RegisterMCAsmParser<RISCVAsmParser> Y(getTheRISCV64Target());
2699 }
2700