blob: 36a3e595b55d5e9e54c9ae4502a967d42f87dd87 [file] [log] [blame]
Alex Bradbury04f06d92017-08-08 14:43:36 +00001//===-- RISCVAsmParser.cpp - Parse RISCV assembly to MCInst instructions --===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Alex Bradbury04f06d92017-08-08 14:43:36 +00006//
7//===----------------------------------------------------------------------===//
8
Alex Bradbury9c03e4c2018-11-12 14:25:07 +00009#include "MCTargetDesc/RISCVAsmBackend.h"
Alex Bradbury9d3f1252017-09-28 08:26:24 +000010#include "MCTargetDesc/RISCVMCExpr.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000011#include "MCTargetDesc/RISCVMCTargetDesc.h"
Alex Bradburybca0c3c2018-05-11 17:30:28 +000012#include "MCTargetDesc/RISCVTargetStreamer.h"
Ana Pazos9d6c5532018-10-04 21:50:54 +000013#include "Utils/RISCVBaseInfo.h"
Alex Bradbury22c091f2018-11-15 10:11:31 +000014#include "Utils/RISCVMatInt.h"
Alex Bradbury4f7f0da2017-09-06 09:21:21 +000015#include "llvm/ADT/STLExtras.h"
Alex Bradbury893e5bc2018-11-28 16:39:14 +000016#include "llvm/ADT/SmallVector.h"
Alex Bradbury4f7f0da2017-09-06 09:21:21 +000017#include "llvm/ADT/StringSwitch.h"
Alex Bradbury9c03e4c2018-11-12 14:25:07 +000018#include "llvm/MC/MCAssembler.h"
Alex Bradbury4f7f0da2017-09-06 09:21:21 +000019#include "llvm/MC/MCContext.h"
20#include "llvm/MC/MCExpr.h"
21#include "llvm/MC/MCInst.h"
Alex Bradbury6a4b5442018-06-07 15:35:47 +000022#include "llvm/MC/MCInstBuilder.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000023#include "llvm/MC/MCParser/MCAsmLexer.h"
24#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
25#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000026#include "llvm/MC/MCRegisterInfo.h"
27#include "llvm/MC/MCStreamer.h"
28#include "llvm/MC/MCSubtargetInfo.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000029#include "llvm/Support/Casting.h"
Alex Bradbury6a4b5442018-06-07 15:35:47 +000030#include "llvm/Support/MathExtras.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000031#include "llvm/Support/TargetRegistry.h"
32
Alex Bradbury6a4b5442018-06-07 15:35:47 +000033#include <limits>
34
Alex Bradbury04f06d92017-08-08 14:43:36 +000035using namespace llvm;
36
Sameer AbuAsalc1b0e662018-04-06 21:07:05 +000037// Include the auto-generated portion of the compress emitter.
38#define GEN_COMPRESS_INSTR
39#include "RISCVGenCompressInstEmitter.inc"
40
Alex Bradbury04f06d92017-08-08 14:43:36 +000041namespace {
42struct RISCVOperand;
43
44class RISCVAsmParser : public MCTargetAsmParser {
Alex Bradbury893e5bc2018-11-28 16:39:14 +000045 SmallVector<FeatureBitset, 4> FeatureBitStack;
46
Alex Bradbury04f06d92017-08-08 14:43:36 +000047 SMLoc getLoc() const { return getParser().getTok().getLoc(); }
Alex Bradburya6e62482017-12-07 10:53:48 +000048 bool isRV64() const { return getSTI().hasFeature(RISCV::Feature64Bit); }
Alex Bradbury04f06d92017-08-08 14:43:36 +000049
Alex Bradburybca0c3c2018-05-11 17:30:28 +000050 RISCVTargetStreamer &getTargetStreamer() {
51 MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
52 return static_cast<RISCVTargetStreamer &>(TS);
53 }
54
Alex Bradbury7bc2a952017-12-07 10:46:23 +000055 unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
56 unsigned Kind) override;
57
Alex Bradbury6758ecb2017-09-17 14:27:35 +000058 bool generateImmOutOfRangeError(OperandVector &Operands, uint64_t ErrorInfo,
Alex Bradbury6a4b5442018-06-07 15:35:47 +000059 int64_t Lower, int64_t Upper, Twine Msg);
Alex Bradbury6758ecb2017-09-17 14:27:35 +000060
Alex Bradbury04f06d92017-08-08 14:43:36 +000061 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
62 OperandVector &Operands, MCStreamer &Out,
63 uint64_t &ErrorInfo,
64 bool MatchingInlineAsm) override;
65
66 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
67
68 bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
69 SMLoc NameLoc, OperandVector &Operands) override;
70
71 bool ParseDirective(AsmToken DirectiveID) override;
72
Alex Bradbury6a4b5442018-06-07 15:35:47 +000073 // Helper to actually emit an instruction to the MCStreamer. Also, when
74 // possible, compression of the instruction is performed.
75 void emitToStreamer(MCStreamer &S, const MCInst &Inst);
76
77 // Helper to emit a combination of LUI, ADDI(W), and SLLI instructions that
78 // synthesize the desired immedate value into the destination register.
79 void emitLoadImm(unsigned DestReg, int64_t Value, MCStreamer &Out);
80
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +000081 // Helper to emit pseudo instruction "lla" used in PC-rel addressing.
82 void emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
83
Alex Bradbury6a4b5442018-06-07 15:35:47 +000084 /// Helper for processing MC instructions that have been successfully matched
85 /// by MatchAndEmitInstruction. Modifications to the emitted instructions,
86 /// like the expansion of pseudo instructions (e.g., "li"), can be performed
87 /// in this method.
88 bool processInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
89
Alex Bradbury04f06d92017-08-08 14:43:36 +000090// Auto-generated instruction matching functions
91#define GET_ASSEMBLER_HEADER
92#include "RISCVGenAsmMatcher.inc"
93
Ana Pazos9d6c5532018-10-04 21:50:54 +000094 OperandMatchResultTy parseCSRSystemRegister(OperandVector &Operands);
Alex Bradbury04f06d92017-08-08 14:43:36 +000095 OperandMatchResultTy parseImmediate(OperandVector &Operands);
Alex Bradbury8c345c52017-11-09 15:00:03 +000096 OperandMatchResultTy parseRegister(OperandVector &Operands,
97 bool AllowParens = false);
Alex Bradbury6758ecb2017-09-17 14:27:35 +000098 OperandMatchResultTy parseMemOpBaseReg(OperandVector &Operands);
Alex Bradbury9d3f1252017-09-28 08:26:24 +000099 OperandMatchResultTy parseOperandWithModifier(OperandVector &Operands);
Alex Bradbury68f73c12018-09-18 15:18:16 +0000100 OperandMatchResultTy parseBareSymbol(OperandVector &Operands);
Alex Bradbury226f3ef2018-09-20 08:10:35 +0000101 OperandMatchResultTy parseJALOffset(OperandVector &Operands);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000102
Alex Bradbury68f73c12018-09-18 15:18:16 +0000103 bool parseOperand(OperandVector &Operands, StringRef Mnemonic);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000104
Alex Bradburybca0c3c2018-05-11 17:30:28 +0000105 bool parseDirectiveOption();
106
107 void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
108 if (!(getSTI().getFeatureBits()[Feature])) {
109 MCSubtargetInfo &STI = copySTI();
110 setAvailableFeatures(
111 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
112 }
113 }
114
115 void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
116 if (getSTI().getFeatureBits()[Feature]) {
117 MCSubtargetInfo &STI = copySTI();
118 setAvailableFeatures(
119 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
120 }
121 }
Ana Pazos9d6c5532018-10-04 21:50:54 +0000122
Alex Bradbury893e5bc2018-11-28 16:39:14 +0000123 void pushFeatureBits() {
124 FeatureBitStack.push_back(getSTI().getFeatureBits());
125 }
126
127 bool popFeatureBits() {
128 if (FeatureBitStack.empty())
129 return true;
130
131 FeatureBitset FeatureBits = FeatureBitStack.pop_back_val();
132 copySTI().setFeatureBits(FeatureBits);
133 setAvailableFeatures(ComputeAvailableFeatures(FeatureBits));
134
135 return false;
136 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000137public:
138 enum RISCVMatchResultTy {
139 Match_Dummy = FIRST_TARGET_MATCH_RESULT_TY,
140#define GET_OPERAND_DIAGNOSTIC_TYPES
141#include "RISCVGenAsmMatcher.inc"
142#undef GET_OPERAND_DIAGNOSTIC_TYPES
143 };
144
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000145 static bool classifySymbolRef(const MCExpr *Expr,
146 RISCVMCExpr::VariantKind &Kind,
147 int64_t &Addend);
148
Alex Bradbury04f06d92017-08-08 14:43:36 +0000149 RISCVAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
150 const MCInstrInfo &MII, const MCTargetOptions &Options)
Oliver Stannard4191b9e2017-10-11 09:17:43 +0000151 : MCTargetAsmParser(Options, STI, MII) {
Alex Bradburycea6db02018-05-17 05:58:08 +0000152 Parser.addAliasForDirective(".half", ".2byte");
153 Parser.addAliasForDirective(".hword", ".2byte");
154 Parser.addAliasForDirective(".word", ".4byte");
155 Parser.addAliasForDirective(".dword", ".8byte");
Alex Bradbury04f06d92017-08-08 14:43:36 +0000156 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
157 }
158};
159
160/// RISCVOperand - Instances of this class represent a parsed machine
161/// instruction
162struct RISCVOperand : public MCParsedAsmOperand {
163
164 enum KindTy {
165 Token,
166 Register,
167 Immediate,
Ana Pazos9d6c5532018-10-04 21:50:54 +0000168 SystemRegister
Alex Bradbury04f06d92017-08-08 14:43:36 +0000169 } Kind;
170
Alex Bradburya6e62482017-12-07 10:53:48 +0000171 bool IsRV64;
172
Alex Bradbury04f06d92017-08-08 14:43:36 +0000173 struct RegOp {
174 unsigned RegNum;
175 };
176
177 struct ImmOp {
178 const MCExpr *Val;
179 };
180
Ana Pazos9d6c5532018-10-04 21:50:54 +0000181 struct SysRegOp {
182 const char *Data;
183 unsigned Length;
184 unsigned Encoding;
185 // FIXME: Add the Encoding parsed fields as needed for checks,
186 // e.g.: read/write or user/supervisor/machine privileges.
187 };
188
Alex Bradbury04f06d92017-08-08 14:43:36 +0000189 SMLoc StartLoc, EndLoc;
190 union {
191 StringRef Tok;
192 RegOp Reg;
193 ImmOp Imm;
Ana Pazos9d6c5532018-10-04 21:50:54 +0000194 struct SysRegOp SysReg;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000195 };
196
197 RISCVOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
198
199public:
200 RISCVOperand(const RISCVOperand &o) : MCParsedAsmOperand() {
201 Kind = o.Kind;
Alex Bradburya6e62482017-12-07 10:53:48 +0000202 IsRV64 = o.IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000203 StartLoc = o.StartLoc;
204 EndLoc = o.EndLoc;
205 switch (Kind) {
206 case Register:
207 Reg = o.Reg;
208 break;
209 case Immediate:
210 Imm = o.Imm;
211 break;
212 case Token:
213 Tok = o.Tok;
214 break;
Ana Pazos9d6c5532018-10-04 21:50:54 +0000215 case SystemRegister:
216 SysReg = o.SysReg;
217 break;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000218 }
219 }
220
221 bool isToken() const override { return Kind == Token; }
222 bool isReg() const override { return Kind == Register; }
223 bool isImm() const override { return Kind == Immediate; }
224 bool isMem() const override { return false; }
Ana Pazos9d6c5532018-10-04 21:50:54 +0000225 bool isSystemRegister() const { return Kind == SystemRegister; }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000226
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000227 static bool evaluateConstantImm(const MCExpr *Expr, int64_t &Imm,
228 RISCVMCExpr::VariantKind &VK) {
229 if (auto *RE = dyn_cast<RISCVMCExpr>(Expr)) {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000230 VK = RE->getKind();
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000231 return RE->evaluateAsConstant(Imm);
232 }
233
234 if (auto CE = dyn_cast<MCConstantExpr>(Expr)) {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000235 VK = RISCVMCExpr::VK_RISCV_None;
236 Imm = CE->getValue();
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000237 return true;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000238 }
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000239
240 return false;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000241 }
242
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000243 // True if operand is a symbol with no modifiers, or a constant with no
244 // modifiers and isShiftedInt<N-1, 1>(Op).
245 template <int N> bool isBareSimmNLsb0() const {
246 int64_t Imm;
247 RISCVMCExpr::VariantKind VK;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000248 if (!isImm())
249 return false;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000250 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000251 bool IsValid;
252 if (!IsConstantImm)
253 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
254 else
255 IsValid = isShiftedInt<N - 1, 1>(Imm);
256 return IsValid && VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000257 }
258
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000259 // Predicate methods for AsmOperands defined in RISCVInstrInfo.td
260
Shiva Chen98f93892018-04-25 14:18:55 +0000261 bool isBareSymbol() const {
262 int64_t Imm;
263 RISCVMCExpr::VariantKind VK;
264 // Must be of 'immediate' type but not a constant.
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000265 if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
Shiva Chen98f93892018-04-25 14:18:55 +0000266 return false;
267 return RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm) &&
268 VK == RISCVMCExpr::VK_RISCV_None;
269 }
270
Ana Pazos9d6c5532018-10-04 21:50:54 +0000271 bool isCSRSystemRegister() const { return isSystemRegister(); }
272
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000273 /// Return true if the operand is a valid for the fence instruction e.g.
274 /// ('iorw').
275 bool isFenceArg() const {
276 if (!isImm())
277 return false;
278 const MCExpr *Val = getImm();
279 auto *SVal = dyn_cast<MCSymbolRefExpr>(Val);
280 if (!SVal || SVal->getKind() != MCSymbolRefExpr::VK_None)
281 return false;
282
283 StringRef Str = SVal->getSymbol().getName();
284 // Letters must be unique, taken from 'iorw', and in ascending order. This
285 // holds as long as each individual character is one of 'iorw' and is
286 // greater than the previous character.
287 char Prev = '\0';
288 for (char c : Str) {
289 if (c != 'i' && c != 'o' && c != 'r' && c != 'w')
290 return false;
291 if (c <= Prev)
292 return false;
293 Prev = c;
294 }
295 return true;
296 }
297
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000298 /// Return true if the operand is a valid floating point rounding mode.
299 bool isFRMArg() const {
300 if (!isImm())
301 return false;
302 const MCExpr *Val = getImm();
303 auto *SVal = dyn_cast<MCSymbolRefExpr>(Val);
304 if (!SVal || SVal->getKind() != MCSymbolRefExpr::VK_None)
305 return false;
306
307 StringRef Str = SVal->getSymbol().getName();
308
309 return RISCVFPRndMode::stringToRoundingMode(Str) != RISCVFPRndMode::Invalid;
310 }
311
Alex Bradbury2ba76be2019-01-03 14:41:41 +0000312 bool isImmXLenLI() const {
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000313 int64_t Imm;
314 RISCVMCExpr::VariantKind VK;
315 if (!isImm())
316 return false;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000317 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Alex Bradbury2ba76be2019-01-03 14:41:41 +0000318 if (VK == RISCVMCExpr::VK_RISCV_LO || VK == RISCVMCExpr::VK_RISCV_PCREL_LO)
319 return true;
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000320 // Given only Imm, ensuring that the actually specified constant is either
321 // a signed or unsigned 64-bit number is unfortunately impossible.
322 bool IsInRange = isRV64() ? true : isInt<32>(Imm) || isUInt<32>(Imm);
323 return IsConstantImm && IsInRange && VK == RISCVMCExpr::VK_RISCV_None;
324 }
325
Alex Bradburya6e62482017-12-07 10:53:48 +0000326 bool isUImmLog2XLen() const {
327 int64_t Imm;
328 RISCVMCExpr::VariantKind VK;
329 if (!isImm())
330 return false;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000331 if (!evaluateConstantImm(getImm(), Imm, VK) ||
332 VK != RISCVMCExpr::VK_RISCV_None)
Alex Bradburya6e62482017-12-07 10:53:48 +0000333 return false;
334 return (isRV64() && isUInt<6>(Imm)) || isUInt<5>(Imm);
335 }
336
Alex Bradbury0ad4c262017-12-15 10:20:51 +0000337 bool isUImmLog2XLenNonZero() const {
338 int64_t Imm;
339 RISCVMCExpr::VariantKind VK;
340 if (!isImm())
341 return false;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000342 if (!evaluateConstantImm(getImm(), Imm, VK) ||
343 VK != RISCVMCExpr::VK_RISCV_None)
Alex Bradbury0ad4c262017-12-15 10:20:51 +0000344 return false;
345 if (Imm == 0)
346 return false;
347 return (isRV64() && isUInt<6>(Imm)) || isUInt<5>(Imm);
348 }
349
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000350 bool isUImm5() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000351 int64_t Imm;
352 RISCVMCExpr::VariantKind VK;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000353 if (!isImm())
354 return false;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000355 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000356 return IsConstantImm && isUInt<5>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000357 }
358
Alex Bradbury60714f92017-12-13 09:32:55 +0000359 bool isUImm5NonZero() const {
360 int64_t Imm;
361 RISCVMCExpr::VariantKind VK;
362 if (!isImm())
363 return false;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000364 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Alex Bradbury60714f92017-12-13 09:32:55 +0000365 return IsConstantImm && isUInt<5>(Imm) && (Imm != 0) &&
366 VK == RISCVMCExpr::VK_RISCV_None;
367 }
368
Alex Bradbury581d6b02017-12-13 09:41:21 +0000369 bool isSImm6() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000370 if (!isImm())
371 return false;
Alex Bradbury581d6b02017-12-13 09:41:21 +0000372 RISCVMCExpr::VariantKind VK;
373 int64_t Imm;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000374 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Ana Pazos065b0882018-09-13 18:37:23 +0000375 return IsConstantImm && isInt<6>(Imm) &&
376 VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury581d6b02017-12-13 09:41:21 +0000377 }
378
Shiva Chenb22c1d22018-02-02 02:43:23 +0000379 bool isSImm6NonZero() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000380 if (!isImm())
381 return false;
Shiva Chenb22c1d22018-02-02 02:43:23 +0000382 RISCVMCExpr::VariantKind VK;
383 int64_t Imm;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000384 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Ana Pazos065b0882018-09-13 18:37:23 +0000385 return IsConstantImm && isInt<6>(Imm) && (Imm != 0) &&
386 VK == RISCVMCExpr::VK_RISCV_None;
Shiva Chenb22c1d22018-02-02 02:43:23 +0000387 }
388
Shiva Chen7c172422018-02-22 15:02:28 +0000389 bool isCLUIImm() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000390 if (!isImm())
391 return false;
Alex Bradbury60714f92017-12-13 09:32:55 +0000392 int64_t Imm;
393 RISCVMCExpr::VariantKind VK;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000394 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Shiva Chen7c172422018-02-22 15:02:28 +0000395 return IsConstantImm && (Imm != 0) &&
396 (isUInt<5>(Imm) || (Imm >= 0xfffe0 && Imm <= 0xfffff)) &&
Ana Pazos9d6c5532018-10-04 21:50:54 +0000397 VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury60714f92017-12-13 09:32:55 +0000398 }
399
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000400 bool isUImm7Lsb00() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000401 if (!isImm())
402 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000403 int64_t Imm;
404 RISCVMCExpr::VariantKind VK;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000405 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000406 return IsConstantImm && isShiftedUInt<5, 2>(Imm) &&
407 VK == RISCVMCExpr::VK_RISCV_None;
408 }
409
410 bool isUImm8Lsb00() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000411 if (!isImm())
412 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000413 int64_t Imm;
414 RISCVMCExpr::VariantKind VK;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000415 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000416 return IsConstantImm && isShiftedUInt<6, 2>(Imm) &&
417 VK == RISCVMCExpr::VK_RISCV_None;
418 }
419
420 bool isUImm8Lsb000() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000421 if (!isImm())
422 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000423 int64_t Imm;
424 RISCVMCExpr::VariantKind VK;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000425 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000426 return IsConstantImm && isShiftedUInt<5, 3>(Imm) &&
427 VK == RISCVMCExpr::VK_RISCV_None;
428 }
429
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000430 bool isSImm9Lsb0() const { return isBareSimmNLsb0<9>(); }
431
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000432 bool isUImm9Lsb000() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000433 if (!isImm())
434 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000435 int64_t Imm;
436 RISCVMCExpr::VariantKind VK;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000437 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000438 return IsConstantImm && isShiftedUInt<6, 3>(Imm) &&
439 VK == RISCVMCExpr::VK_RISCV_None;
440 }
441
Alex Bradbury60714f92017-12-13 09:32:55 +0000442 bool isUImm10Lsb00NonZero() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000443 if (!isImm())
444 return false;
Alex Bradbury60714f92017-12-13 09:32:55 +0000445 int64_t Imm;
446 RISCVMCExpr::VariantKind VK;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000447 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Alex Bradbury60714f92017-12-13 09:32:55 +0000448 return IsConstantImm && isShiftedUInt<8, 2>(Imm) && (Imm != 0) &&
449 VK == RISCVMCExpr::VK_RISCV_None;
450 }
451
Alex Bradbury04f06d92017-08-08 14:43:36 +0000452 bool isSImm12() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000453 RISCVMCExpr::VariantKind VK;
454 int64_t Imm;
455 bool IsValid;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000456 if (!isImm())
457 return false;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000458 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000459 if (!IsConstantImm)
460 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
461 else
462 IsValid = isInt<12>(Imm);
Alex Bradbury7d0e18d2018-09-18 15:13:29 +0000463 return IsValid && ((IsConstantImm && VK == RISCVMCExpr::VK_RISCV_None) ||
Ahmed Charles646ab872018-02-06 00:55:23 +0000464 VK == RISCVMCExpr::VK_RISCV_LO ||
465 VK == RISCVMCExpr::VK_RISCV_PCREL_LO);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000466 }
467
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000468 bool isSImm12Lsb0() const { return isBareSimmNLsb0<12>(); }
469
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000470 bool isSImm13Lsb0() const { return isBareSimmNLsb0<13>(); }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000471
Shiva Chenb22c1d22018-02-02 02:43:23 +0000472 bool isSImm10Lsb0000NonZero() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000473 if (!isImm())
474 return false;
Alex Bradbury60714f92017-12-13 09:32:55 +0000475 int64_t Imm;
476 RISCVMCExpr::VariantKind VK;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000477 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Shiva Chenb22c1d22018-02-02 02:43:23 +0000478 return IsConstantImm && (Imm != 0) && isShiftedInt<6, 4>(Imm) &&
Alex Bradbury60714f92017-12-13 09:32:55 +0000479 VK == RISCVMCExpr::VK_RISCV_None;
480 }
481
Alex Bradbury74340f12018-09-18 15:08:35 +0000482 bool isUImm20LUI() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000483 RISCVMCExpr::VariantKind VK;
484 int64_t Imm;
485 bool IsValid;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000486 if (!isImm())
487 return false;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000488 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Alex Bradbury74340f12018-09-18 15:08:35 +0000489 if (!IsConstantImm) {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000490 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
Alex Bradbury74340f12018-09-18 15:08:35 +0000491 return IsValid && VK == RISCVMCExpr::VK_RISCV_HI;
492 } else {
493 return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
494 VK == RISCVMCExpr::VK_RISCV_HI);
495 }
496 }
497
498 bool isUImm20AUIPC() const {
499 RISCVMCExpr::VariantKind VK;
500 int64_t Imm;
501 bool IsValid;
502 if (!isImm())
503 return false;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000504 bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
Alex Bradbury74340f12018-09-18 15:08:35 +0000505 if (!IsConstantImm) {
506 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
507 return IsValid && VK == RISCVMCExpr::VK_RISCV_PCREL_HI;
508 } else {
509 return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
510 VK == RISCVMCExpr::VK_RISCV_PCREL_HI);
511 }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000512 }
513
Alex Bradbury226f3ef2018-09-20 08:10:35 +0000514 bool isSImm21Lsb0JAL() const { return isBareSimmNLsb0<21>(); }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000515
Alex Bradbury04f06d92017-08-08 14:43:36 +0000516 /// getStartLoc - Gets location of the first token of this operand
517 SMLoc getStartLoc() const override { return StartLoc; }
518 /// getEndLoc - Gets location of the last token of this operand
519 SMLoc getEndLoc() const override { return EndLoc; }
Alex Bradburya6e62482017-12-07 10:53:48 +0000520 /// True if this operand is for an RV64 instruction
521 bool isRV64() const { return IsRV64; }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000522
523 unsigned getReg() const override {
524 assert(Kind == Register && "Invalid type access!");
525 return Reg.RegNum;
526 }
527
Ana Pazos9d6c5532018-10-04 21:50:54 +0000528 StringRef getSysReg() const {
529 assert(Kind == SystemRegister && "Invalid access!");
530 return StringRef(SysReg.Data, SysReg.Length);
531 }
532
Alex Bradbury04f06d92017-08-08 14:43:36 +0000533 const MCExpr *getImm() const {
534 assert(Kind == Immediate && "Invalid type access!");
535 return Imm.Val;
536 }
537
538 StringRef getToken() const {
539 assert(Kind == Token && "Invalid type access!");
540 return Tok;
541 }
542
543 void print(raw_ostream &OS) const override {
544 switch (Kind) {
545 case Immediate:
546 OS << *getImm();
547 break;
548 case Register:
549 OS << "<register x";
550 OS << getReg() << ">";
551 break;
552 case Token:
553 OS << "'" << getToken() << "'";
554 break;
Ana Pazos9d6c5532018-10-04 21:50:54 +0000555 case SystemRegister:
556 OS << "<sysreg: " << getSysReg() << '>';
557 break;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000558 }
559 }
560
Alex Bradburya6e62482017-12-07 10:53:48 +0000561 static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S,
562 bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000563 auto Op = make_unique<RISCVOperand>(Token);
564 Op->Tok = Str;
565 Op->StartLoc = S;
566 Op->EndLoc = S;
Alex Bradburya6e62482017-12-07 10:53:48 +0000567 Op->IsRV64 = IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000568 return Op;
569 }
570
571 static std::unique_ptr<RISCVOperand> createReg(unsigned RegNo, SMLoc S,
Alex Bradburya6e62482017-12-07 10:53:48 +0000572 SMLoc E, bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000573 auto Op = make_unique<RISCVOperand>(Register);
574 Op->Reg.RegNum = RegNo;
575 Op->StartLoc = S;
576 Op->EndLoc = E;
Alex Bradburya6e62482017-12-07 10:53:48 +0000577 Op->IsRV64 = IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000578 return Op;
579 }
580
581 static std::unique_ptr<RISCVOperand> createImm(const MCExpr *Val, SMLoc S,
Alex Bradburya6e62482017-12-07 10:53:48 +0000582 SMLoc E, bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000583 auto Op = make_unique<RISCVOperand>(Immediate);
584 Op->Imm.Val = Val;
585 Op->StartLoc = S;
586 Op->EndLoc = E;
Alex Bradburya6e62482017-12-07 10:53:48 +0000587 Op->IsRV64 = IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000588 return Op;
589 }
590
Ana Pazos9d6c5532018-10-04 21:50:54 +0000591 static std::unique_ptr<RISCVOperand>
592 createSysReg(StringRef Str, SMLoc S, unsigned Encoding, bool IsRV64) {
593 auto Op = make_unique<RISCVOperand>(SystemRegister);
594 Op->SysReg.Data = Str.data();
595 Op->SysReg.Length = Str.size();
596 Op->SysReg.Encoding = Encoding;
597 Op->StartLoc = S;
598 Op->IsRV64 = IsRV64;
599 return Op;
600 }
601
Alex Bradbury04f06d92017-08-08 14:43:36 +0000602 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
603 assert(Expr && "Expr shouldn't be null!");
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000604 int64_t Imm = 0;
Alex Bradbury96ed75d2018-09-20 11:40:43 +0000605 RISCVMCExpr::VariantKind VK;
606 bool IsConstant = evaluateConstantImm(Expr, Imm, VK);
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000607
608 if (IsConstant)
609 Inst.addOperand(MCOperand::createImm(Imm));
Alex Bradbury04f06d92017-08-08 14:43:36 +0000610 else
611 Inst.addOperand(MCOperand::createExpr(Expr));
612 }
613
614 // Used by the TableGen Code
615 void addRegOperands(MCInst &Inst, unsigned N) const {
616 assert(N == 1 && "Invalid number of operands!");
617 Inst.addOperand(MCOperand::createReg(getReg()));
618 }
619
620 void addImmOperands(MCInst &Inst, unsigned N) const {
621 assert(N == 1 && "Invalid number of operands!");
622 addExpr(Inst, getImm());
623 }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000624
625 void addFenceArgOperands(MCInst &Inst, unsigned N) const {
626 assert(N == 1 && "Invalid number of operands!");
627 // isFenceArg has validated the operand, meaning this cast is safe
628 auto SE = cast<MCSymbolRefExpr>(getImm());
629
630 unsigned Imm = 0;
631 for (char c : SE->getSymbol().getName()) {
632 switch (c) {
Ana Pazos9d6c5532018-10-04 21:50:54 +0000633 default:
634 llvm_unreachable("FenceArg must contain only [iorw]");
635 case 'i': Imm |= RISCVFenceField::I; break;
636 case 'o': Imm |= RISCVFenceField::O; break;
637 case 'r': Imm |= RISCVFenceField::R; break;
638 case 'w': Imm |= RISCVFenceField::W; break;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000639 }
640 }
641 Inst.addOperand(MCOperand::createImm(Imm));
642 }
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000643
Ana Pazos9d6c5532018-10-04 21:50:54 +0000644 void addCSRSystemRegisterOperands(MCInst &Inst, unsigned N) const {
645 assert(N == 1 && "Invalid number of operands!");
646 Inst.addOperand(MCOperand::createImm(SysReg.Encoding));
647 }
648
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000649 // Returns the rounding mode represented by this RISCVOperand. Should only
650 // be called after checking isFRMArg.
651 RISCVFPRndMode::RoundingMode getRoundingMode() const {
652 // isFRMArg has validated the operand, meaning this cast is safe.
653 auto SE = cast<MCSymbolRefExpr>(getImm());
654 RISCVFPRndMode::RoundingMode FRM =
655 RISCVFPRndMode::stringToRoundingMode(SE->getSymbol().getName());
656 assert(FRM != RISCVFPRndMode::Invalid && "Invalid rounding mode");
657 return FRM;
658 }
659
660 void addFRMArgOperands(MCInst &Inst, unsigned N) const {
661 assert(N == 1 && "Invalid number of operands!");
662 Inst.addOperand(MCOperand::createImm(getRoundingMode()));
663 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000664};
665} // end anonymous namespace.
666
667#define GET_REGISTER_MATCHER
668#define GET_MATCHER_IMPLEMENTATION
Alex Bradbury04f06d92017-08-08 14:43:36 +0000669#include "RISCVGenAsmMatcher.inc"
670
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000671// Return the matching FPR64 register for the given FPR32.
672// FIXME: Ideally this function could be removed in favour of using
673// information from TableGen.
674unsigned convertFPR32ToFPR64(unsigned Reg) {
675 switch (Reg) {
Ana Pazos9d6c5532018-10-04 21:50:54 +0000676 default:
677 llvm_unreachable("Not a recognised FPR32 register");
678 case RISCV::F0_32: return RISCV::F0_64;
679 case RISCV::F1_32: return RISCV::F1_64;
680 case RISCV::F2_32: return RISCV::F2_64;
681 case RISCV::F3_32: return RISCV::F3_64;
682 case RISCV::F4_32: return RISCV::F4_64;
683 case RISCV::F5_32: return RISCV::F5_64;
684 case RISCV::F6_32: return RISCV::F6_64;
685 case RISCV::F7_32: return RISCV::F7_64;
686 case RISCV::F8_32: return RISCV::F8_64;
687 case RISCV::F9_32: return RISCV::F9_64;
688 case RISCV::F10_32: return RISCV::F10_64;
689 case RISCV::F11_32: return RISCV::F11_64;
690 case RISCV::F12_32: return RISCV::F12_64;
691 case RISCV::F13_32: return RISCV::F13_64;
692 case RISCV::F14_32: return RISCV::F14_64;
693 case RISCV::F15_32: return RISCV::F15_64;
694 case RISCV::F16_32: return RISCV::F16_64;
695 case RISCV::F17_32: return RISCV::F17_64;
696 case RISCV::F18_32: return RISCV::F18_64;
697 case RISCV::F19_32: return RISCV::F19_64;
698 case RISCV::F20_32: return RISCV::F20_64;
699 case RISCV::F21_32: return RISCV::F21_64;
700 case RISCV::F22_32: return RISCV::F22_64;
701 case RISCV::F23_32: return RISCV::F23_64;
702 case RISCV::F24_32: return RISCV::F24_64;
703 case RISCV::F25_32: return RISCV::F25_64;
704 case RISCV::F26_32: return RISCV::F26_64;
705 case RISCV::F27_32: return RISCV::F27_64;
706 case RISCV::F28_32: return RISCV::F28_64;
707 case RISCV::F29_32: return RISCV::F29_64;
708 case RISCV::F30_32: return RISCV::F30_64;
709 case RISCV::F31_32: return RISCV::F31_64;
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000710 }
711}
712
713unsigned RISCVAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
714 unsigned Kind) {
715 RISCVOperand &Op = static_cast<RISCVOperand &>(AsmOp);
716 if (!Op.isReg())
717 return Match_InvalidOperand;
718
719 unsigned Reg = Op.getReg();
720 bool IsRegFPR32 =
721 RISCVMCRegisterClasses[RISCV::FPR32RegClassID].contains(Reg);
Alex Bradbury60714f92017-12-13 09:32:55 +0000722 bool IsRegFPR32C =
723 RISCVMCRegisterClasses[RISCV::FPR32CRegClassID].contains(Reg);
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000724
725 // As the parser couldn't differentiate an FPR32 from an FPR64, coerce the
Alex Bradbury60714f92017-12-13 09:32:55 +0000726 // register from FPR32 to FPR64 or FPR32C to FPR64C if necessary.
727 if ((IsRegFPR32 && Kind == MCK_FPR64) ||
728 (IsRegFPR32C && Kind == MCK_FPR64C)) {
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000729 Op.Reg.RegNum = convertFPR32ToFPR64(Reg);
730 return Match_Success;
731 }
732 return Match_InvalidOperand;
733}
734
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000735bool RISCVAsmParser::generateImmOutOfRangeError(
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000736 OperandVector &Operands, uint64_t ErrorInfo, int64_t Lower, int64_t Upper,
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000737 Twine Msg = "immediate must be an integer in the range") {
738 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
739 return Error(ErrorLoc, Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
740}
741
Alex Bradbury04f06d92017-08-08 14:43:36 +0000742bool RISCVAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
743 OperandVector &Operands,
744 MCStreamer &Out,
745 uint64_t &ErrorInfo,
746 bool MatchingInlineAsm) {
747 MCInst Inst;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000748
Ana Pazos6b34051b2018-08-30 19:43:19 +0000749 auto Result =
750 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
751 switch (Result) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000752 default:
753 break;
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000754 case Match_Success:
755 return processInstruction(Inst, IDLoc, Out);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000756 case Match_MissingFeature:
757 return Error(IDLoc, "instruction use requires an option to be enabled");
758 case Match_MnemonicFail:
759 return Error(IDLoc, "unrecognized instruction mnemonic");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000760 case Match_InvalidOperand: {
761 SMLoc ErrorLoc = IDLoc;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000762 if (ErrorInfo != ~0U) {
763 if (ErrorInfo >= Operands.size())
764 return Error(ErrorLoc, "too few operands for instruction");
765
766 ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
767 if (ErrorLoc == SMLoc())
768 ErrorLoc = IDLoc;
769 }
770 return Error(ErrorLoc, "invalid operand for instruction");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000771 }
Ana Pazos6b34051b2018-08-30 19:43:19 +0000772 }
773
774 // Handle the case when the error message is of specific type
775 // other than the generic Match_InvalidOperand, and the
776 // corresponding operand is missing.
777 if (Result > FIRST_TARGET_MATCH_RESULT_TY) {
778 SMLoc ErrorLoc = IDLoc;
779 if (ErrorInfo != ~0U && ErrorInfo >= Operands.size())
780 return Error(ErrorLoc, "too few operands for instruction");
781 }
782
783 switch(Result) {
784 default:
785 break;
Alex Bradbury2ba76be2019-01-03 14:41:41 +0000786 case Match_InvalidImmXLenLI:
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000787 if (isRV64()) {
788 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
789 return Error(ErrorLoc, "operand must be a constant 64-bit integer");
790 }
791 return generateImmOutOfRangeError(Operands, ErrorInfo,
792 std::numeric_limits<int32_t>::min(),
793 std::numeric_limits<uint32_t>::max());
Alex Bradburya6e62482017-12-07 10:53:48 +0000794 case Match_InvalidUImmLog2XLen:
795 if (isRV64())
796 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
797 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
Alex Bradbury0ad4c262017-12-15 10:20:51 +0000798 case Match_InvalidUImmLog2XLenNonZero:
799 if (isRV64())
800 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 6) - 1);
801 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5) - 1);
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000802 case Match_InvalidUImm5:
803 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
Alex Bradbury581d6b02017-12-13 09:41:21 +0000804 case Match_InvalidSImm6:
805 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
806 (1 << 5) - 1);
Shiva Chenb22c1d22018-02-02 02:43:23 +0000807 case Match_InvalidSImm6NonZero:
Ana Pazos9d6c5532018-10-04 21:50:54 +0000808 return generateImmOutOfRangeError(
809 Operands, ErrorInfo, -(1 << 5), (1 << 5) - 1,
Shiva Chenb22c1d22018-02-02 02:43:23 +0000810 "immediate must be non-zero in the range");
Shiva Chen7c172422018-02-22 15:02:28 +0000811 case Match_InvalidCLUIImm:
812 return generateImmOutOfRangeError(
813 Operands, ErrorInfo, 1, (1 << 5) - 1,
814 "immediate must be in [0xfffe0, 0xfffff] or");
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000815 case Match_InvalidUImm7Lsb00:
816 return generateImmOutOfRangeError(
817 Operands, ErrorInfo, 0, (1 << 7) - 4,
818 "immediate must be a multiple of 4 bytes in the range");
819 case Match_InvalidUImm8Lsb00:
820 return generateImmOutOfRangeError(
821 Operands, ErrorInfo, 0, (1 << 8) - 4,
822 "immediate must be a multiple of 4 bytes in the range");
823 case Match_InvalidUImm8Lsb000:
824 return generateImmOutOfRangeError(
825 Operands, ErrorInfo, 0, (1 << 8) - 8,
826 "immediate must be a multiple of 8 bytes in the range");
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000827 case Match_InvalidSImm9Lsb0:
828 return generateImmOutOfRangeError(
829 Operands, ErrorInfo, -(1 << 8), (1 << 8) - 2,
830 "immediate must be a multiple of 2 bytes in the range");
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000831 case Match_InvalidUImm9Lsb000:
832 return generateImmOutOfRangeError(
833 Operands, ErrorInfo, 0, (1 << 9) - 8,
834 "immediate must be a multiple of 8 bytes in the range");
Alex Bradbury60714f92017-12-13 09:32:55 +0000835 case Match_InvalidUImm10Lsb00NonZero:
836 return generateImmOutOfRangeError(
837 Operands, ErrorInfo, 4, (1 << 10) - 4,
838 "immediate must be a multiple of 4 bytes in the range");
Shiva Chenb22c1d22018-02-02 02:43:23 +0000839 case Match_InvalidSImm10Lsb0000NonZero:
Alex Bradbury60714f92017-12-13 09:32:55 +0000840 return generateImmOutOfRangeError(
841 Operands, ErrorInfo, -(1 << 9), (1 << 9) - 16,
Shiva Chenb22c1d22018-02-02 02:43:23 +0000842 "immediate must be a multiple of 16 bytes and non-zero in the range");
Alex Bradbury04f06d92017-08-08 14:43:36 +0000843 case Match_InvalidSImm12:
Alex Bradbury7d0e18d2018-09-18 15:13:29 +0000844 return generateImmOutOfRangeError(
845 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 1,
846 "operand must be a symbol with %lo/%pcrel_lo modifier or an integer in "
847 "the range");
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000848 case Match_InvalidSImm12Lsb0:
849 return generateImmOutOfRangeError(
850 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 2,
851 "immediate must be a multiple of 2 bytes in the range");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000852 case Match_InvalidSImm13Lsb0:
853 return generateImmOutOfRangeError(
854 Operands, ErrorInfo, -(1 << 12), (1 << 12) - 2,
855 "immediate must be a multiple of 2 bytes in the range");
Alex Bradbury74340f12018-09-18 15:08:35 +0000856 case Match_InvalidUImm20LUI:
857 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1,
858 "operand must be a symbol with %hi() "
859 "modifier or an integer in the range");
860 case Match_InvalidUImm20AUIPC:
861 return generateImmOutOfRangeError(
862 Operands, ErrorInfo, 0, (1 << 20) - 1,
863 "operand must be a symbol with %pcrel_hi() modifier or an integer in "
864 "the range");
Alex Bradbury226f3ef2018-09-20 08:10:35 +0000865 case Match_InvalidSImm21Lsb0JAL:
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000866 return generateImmOutOfRangeError(
867 Operands, ErrorInfo, -(1 << 20), (1 << 20) - 2,
868 "immediate must be a multiple of 2 bytes in the range");
Ana Pazos9d6c5532018-10-04 21:50:54 +0000869 case Match_InvalidCSRSystemRegister: {
870 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 12) - 1,
871 "operand must be a valid system register "
872 "name or an integer in the range");
873 }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000874 case Match_InvalidFenceArg: {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000875 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000876 return Error(
877 ErrorLoc,
878 "operand must be formed of letters selected in-order from 'iorw'");
879 }
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000880 case Match_InvalidFRMArg: {
881 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
882 return Error(
883 ErrorLoc,
884 "operand must be a valid floating point rounding mode mnemonic");
885 }
Shiva Chen98f93892018-04-25 14:18:55 +0000886 case Match_InvalidBareSymbol: {
887 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
888 return Error(ErrorLoc, "operand must be a bare symbol name");
889 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000890 }
891
892 llvm_unreachable("Unknown match type detected!");
893}
894
895bool RISCVAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
896 SMLoc &EndLoc) {
897 const AsmToken &Tok = getParser().getTok();
898 StartLoc = Tok.getLoc();
899 EndLoc = Tok.getEndLoc();
900 RegNo = 0;
901 StringRef Name = getLexer().getTok().getIdentifier();
902
903 if (!MatchRegisterName(Name) || !MatchRegisterAltName(Name)) {
904 getParser().Lex(); // Eat identifier token.
905 return false;
906 }
907
908 return Error(StartLoc, "invalid register name");
909}
910
Alex Bradbury8c345c52017-11-09 15:00:03 +0000911OperandMatchResultTy RISCVAsmParser::parseRegister(OperandVector &Operands,
912 bool AllowParens) {
913 SMLoc FirstS = getLoc();
914 bool HadParens = false;
915 AsmToken Buf[2];
916
917 // If this a parenthesised register name is allowed, parse it atomically
918 if (AllowParens && getLexer().is(AsmToken::LParen)) {
919 size_t ReadCount = getLexer().peekTokens(Buf);
920 if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
921 HadParens = true;
922 getParser().Lex(); // Eat '('
923 }
924 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000925
926 switch (getLexer().getKind()) {
927 default:
928 return MatchOperand_NoMatch;
929 case AsmToken::Identifier:
930 StringRef Name = getLexer().getTok().getIdentifier();
931 unsigned RegNo = MatchRegisterName(Name);
932 if (RegNo == 0) {
933 RegNo = MatchRegisterAltName(Name);
Alex Bradbury8c345c52017-11-09 15:00:03 +0000934 if (RegNo == 0) {
935 if (HadParens)
936 getLexer().UnLex(Buf[0]);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000937 return MatchOperand_NoMatch;
Alex Bradbury8c345c52017-11-09 15:00:03 +0000938 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000939 }
Alex Bradbury8c345c52017-11-09 15:00:03 +0000940 if (HadParens)
Alex Bradburya6e62482017-12-07 10:53:48 +0000941 Operands.push_back(RISCVOperand::createToken("(", FirstS, isRV64()));
Alex Bradbury8c345c52017-11-09 15:00:03 +0000942 SMLoc S = getLoc();
943 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000944 getLexer().Lex();
Alex Bradburya6e62482017-12-07 10:53:48 +0000945 Operands.push_back(RISCVOperand::createReg(RegNo, S, E, isRV64()));
Alex Bradbury04f06d92017-08-08 14:43:36 +0000946 }
Alex Bradbury8c345c52017-11-09 15:00:03 +0000947
948 if (HadParens) {
949 getParser().Lex(); // Eat ')'
Alex Bradburya6e62482017-12-07 10:53:48 +0000950 Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
Alex Bradbury8c345c52017-11-09 15:00:03 +0000951 }
952
Alex Bradbury04f06d92017-08-08 14:43:36 +0000953 return MatchOperand_Success;
954}
955
Ana Pazos9d6c5532018-10-04 21:50:54 +0000956OperandMatchResultTy
957RISCVAsmParser::parseCSRSystemRegister(OperandVector &Operands) {
958 SMLoc S = getLoc();
959 const MCExpr *Res;
960
961 switch (getLexer().getKind()) {
962 default:
963 return MatchOperand_NoMatch;
964 case AsmToken::LParen:
965 case AsmToken::Minus:
966 case AsmToken::Plus:
967 case AsmToken::Integer:
968 case AsmToken::String: {
969 if (getParser().parseExpression(Res))
970 return MatchOperand_ParseFail;
971
972 auto *CE = dyn_cast<MCConstantExpr>(Res);
973 if (CE) {
974 int64_t Imm = CE->getValue();
975 if (isUInt<12>(Imm)) {
976 auto SysReg = RISCVSysReg::lookupSysRegByEncoding(Imm);
977 // Accept an immediate representing a named or un-named Sys Reg
978 // if the range is valid, regardless of the required features.
979 Operands.push_back(RISCVOperand::createSysReg(
980 SysReg ? SysReg->Name : "", S, Imm, isRV64()));
981 return MatchOperand_Success;
982 }
983 }
984
985 Twine Msg = "immediate must be an integer in the range";
986 Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 12) - 1) + "]");
987 return MatchOperand_ParseFail;
988 }
989 case AsmToken::Identifier: {
990 StringRef Identifier;
991 if (getParser().parseIdentifier(Identifier))
992 return MatchOperand_ParseFail;
993
994 auto SysReg = RISCVSysReg::lookupSysRegByName(Identifier);
995 // Accept a named Sys Reg if the required features are present.
996 if (SysReg) {
997 if (!SysReg->haveRequiredFeatures(getSTI().getFeatureBits())) {
998 Error(S, "system register use requires an option to be enabled");
999 return MatchOperand_ParseFail;
1000 }
1001 Operands.push_back(RISCVOperand::createSysReg(
1002 Identifier, S, SysReg->Encoding, isRV64()));
1003 return MatchOperand_Success;
1004 }
1005
1006 Twine Msg = "operand must be a valid system register name "
1007 "or an integer in the range";
1008 Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 12) - 1) + "]");
1009 return MatchOperand_ParseFail;
1010 }
1011 case AsmToken::Percent: {
1012 // Discard operand with modifier.
1013 Twine Msg = "immediate must be an integer in the range";
1014 Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 12) - 1) + "]");
1015 return MatchOperand_ParseFail;
1016 }
1017 }
1018
1019 return MatchOperand_NoMatch;
1020}
1021
Alex Bradbury04f06d92017-08-08 14:43:36 +00001022OperandMatchResultTy RISCVAsmParser::parseImmediate(OperandVector &Operands) {
Alex Bradbury6758ecb2017-09-17 14:27:35 +00001023 SMLoc S = getLoc();
1024 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1025 const MCExpr *Res;
1026
Alex Bradbury04f06d92017-08-08 14:43:36 +00001027 switch (getLexer().getKind()) {
1028 default:
1029 return MatchOperand_NoMatch;
1030 case AsmToken::LParen:
1031 case AsmToken::Minus:
1032 case AsmToken::Plus:
1033 case AsmToken::Integer:
1034 case AsmToken::String:
Alex Bradbury6f302b82019-01-10 15:33:17 +00001035 case AsmToken::Identifier:
Alex Bradbury6758ecb2017-09-17 14:27:35 +00001036 if (getParser().parseExpression(Res))
1037 return MatchOperand_ParseFail;
1038 break;
Alex Bradbury9d3f1252017-09-28 08:26:24 +00001039 case AsmToken::Percent:
1040 return parseOperandWithModifier(Operands);
Alex Bradbury6758ecb2017-09-17 14:27:35 +00001041 }
Alex Bradbury04f06d92017-08-08 14:43:36 +00001042
Alex Bradburya6e62482017-12-07 10:53:48 +00001043 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
Alex Bradbury9d3f1252017-09-28 08:26:24 +00001044 return MatchOperand_Success;
1045}
1046
1047OperandMatchResultTy
1048RISCVAsmParser::parseOperandWithModifier(OperandVector &Operands) {
1049 SMLoc S = getLoc();
1050 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1051
1052 if (getLexer().getKind() != AsmToken::Percent) {
1053 Error(getLoc(), "expected '%' for operand modifier");
1054 return MatchOperand_ParseFail;
1055 }
1056
1057 getParser().Lex(); // Eat '%'
1058
1059 if (getLexer().getKind() != AsmToken::Identifier) {
1060 Error(getLoc(), "expected valid identifier for operand modifier");
1061 return MatchOperand_ParseFail;
1062 }
1063 StringRef Identifier = getParser().getTok().getIdentifier();
1064 RISCVMCExpr::VariantKind VK = RISCVMCExpr::getVariantKindForName(Identifier);
1065 if (VK == RISCVMCExpr::VK_RISCV_Invalid) {
1066 Error(getLoc(), "unrecognized operand modifier");
1067 return MatchOperand_ParseFail;
1068 }
1069
1070 getParser().Lex(); // Eat the identifier
1071 if (getLexer().getKind() != AsmToken::LParen) {
1072 Error(getLoc(), "expected '('");
1073 return MatchOperand_ParseFail;
1074 }
1075 getParser().Lex(); // Eat '('
1076
1077 const MCExpr *SubExpr;
1078 if (getParser().parseParenExpression(SubExpr, E)) {
1079 return MatchOperand_ParseFail;
1080 }
1081
1082 const MCExpr *ModExpr = RISCVMCExpr::create(SubExpr, VK, getContext());
Alex Bradburya6e62482017-12-07 10:53:48 +00001083 Operands.push_back(RISCVOperand::createImm(ModExpr, S, E, isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +00001084 return MatchOperand_Success;
1085}
1086
Alex Bradbury68f73c12018-09-18 15:18:16 +00001087OperandMatchResultTy RISCVAsmParser::parseBareSymbol(OperandVector &Operands) {
1088 SMLoc S = getLoc();
1089 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1090 const MCExpr *Res;
1091
1092 if (getLexer().getKind() != AsmToken::Identifier)
1093 return MatchOperand_NoMatch;
1094
1095 StringRef Identifier;
1096 if (getParser().parseIdentifier(Identifier))
1097 return MatchOperand_ParseFail;
1098
1099 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
1100 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1101 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1102 return MatchOperand_Success;
1103}
1104
Alex Bradbury226f3ef2018-09-20 08:10:35 +00001105OperandMatchResultTy RISCVAsmParser::parseJALOffset(OperandVector &Operands) {
1106 // Parsing jal operands is fiddly due to the `jal foo` and `jal ra, foo`
1107 // both being acceptable forms. When parsing `jal ra, foo` this function
1108 // will be called for the `ra` register operand in an attempt to match the
1109 // single-operand alias. parseJALOffset must fail for this case. It would
1110 // seem logical to try parse the operand using parseImmediate and return
1111 // NoMatch if the next token is a comma (meaning we must be parsing a jal in
1112 // the second form rather than the first). We can't do this as there's no
1113 // way of rewinding the lexer state. Instead, return NoMatch if this operand
1114 // is an identifier and is followed by a comma.
1115 if (getLexer().is(AsmToken::Identifier) &&
1116 getLexer().peekTok().is(AsmToken::Comma))
1117 return MatchOperand_NoMatch;
1118
1119 return parseImmediate(Operands);
1120}
1121
Alex Bradbury6758ecb2017-09-17 14:27:35 +00001122OperandMatchResultTy
1123RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
1124 if (getLexer().isNot(AsmToken::LParen)) {
1125 Error(getLoc(), "expected '('");
Alex Bradbury04f06d92017-08-08 14:43:36 +00001126 return MatchOperand_ParseFail;
Alex Bradbury6758ecb2017-09-17 14:27:35 +00001127 }
Alex Bradbury04f06d92017-08-08 14:43:36 +00001128
Alex Bradbury6758ecb2017-09-17 14:27:35 +00001129 getParser().Lex(); // Eat '('
Alex Bradburya6e62482017-12-07 10:53:48 +00001130 Operands.push_back(RISCVOperand::createToken("(", getLoc(), isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +00001131
1132 if (parseRegister(Operands) != MatchOperand_Success) {
1133 Error(getLoc(), "expected register");
1134 return MatchOperand_ParseFail;
1135 }
1136
1137 if (getLexer().isNot(AsmToken::RParen)) {
1138 Error(getLoc(), "expected ')'");
1139 return MatchOperand_ParseFail;
1140 }
1141
1142 getParser().Lex(); // Eat ')'
Alex Bradburya6e62482017-12-07 10:53:48 +00001143 Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +00001144
Alex Bradbury04f06d92017-08-08 14:43:36 +00001145 return MatchOperand_Success;
1146}
1147
Alex Bradburycd8688a2018-04-25 17:25:29 +00001148/// Looks at a token type and creates the relevant operand from this
1149/// information, adding to Operands. If operand was parsed, returns false, else
Alex Bradbury68f73c12018-09-18 15:18:16 +00001150/// true.
1151bool RISCVAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
1152 // Check if the current operand has a custom associated parser, if so, try to
1153 // custom parse the operand, or fallback to the general approach.
1154 OperandMatchResultTy Result =
1155 MatchOperandParserImpl(Operands, Mnemonic, /*ParseForAllFeatures=*/true);
1156 if (Result == MatchOperand_Success)
1157 return false;
1158 if (Result == MatchOperand_ParseFail)
1159 return true;
1160
1161 // Attempt to parse token as a register.
1162 if (parseRegister(Operands, true) == MatchOperand_Success)
Alex Bradbury04f06d92017-08-08 14:43:36 +00001163 return false;
1164
1165 // Attempt to parse token as an immediate
Alex Bradbury6758ecb2017-09-17 14:27:35 +00001166 if (parseImmediate(Operands) == MatchOperand_Success) {
1167 // Parse memory base register if present
1168 if (getLexer().is(AsmToken::LParen))
1169 return parseMemOpBaseReg(Operands) != MatchOperand_Success;
Alex Bradbury04f06d92017-08-08 14:43:36 +00001170 return false;
Alex Bradbury6758ecb2017-09-17 14:27:35 +00001171 }
Alex Bradbury04f06d92017-08-08 14:43:36 +00001172
1173 // Finally we have exhausted all options and must declare defeat.
1174 Error(getLoc(), "unknown operand");
1175 return true;
1176}
1177
1178bool RISCVAsmParser::ParseInstruction(ParseInstructionInfo &Info,
1179 StringRef Name, SMLoc NameLoc,
1180 OperandVector &Operands) {
Alex Bradbury9c03e4c2018-11-12 14:25:07 +00001181 // Ensure that if the instruction occurs when relaxation is enabled,
1182 // relocations are forced for the file. Ideally this would be done when there
1183 // is enough information to reliably determine if the instruction itself may
1184 // cause relaxations. Unfortunately instruction processing stage occurs in the
1185 // same pass as relocation emission, so it's too late to set a 'sticky bit'
1186 // for the entire file.
1187 if (getSTI().getFeatureBits()[RISCV::FeatureRelax]) {
1188 auto *Assembler = getTargetStreamer().getStreamer().getAssemblerPtr();
1189 if (Assembler != nullptr) {
1190 RISCVAsmBackend &MAB =
1191 static_cast<RISCVAsmBackend &>(Assembler->getBackend());
1192 MAB.setForceRelocs();
1193 }
1194 }
1195
Alex Bradbury04f06d92017-08-08 14:43:36 +00001196 // First operand is token for instruction
Alex Bradburya6e62482017-12-07 10:53:48 +00001197 Operands.push_back(RISCVOperand::createToken(Name, NameLoc, isRV64()));
Alex Bradbury04f06d92017-08-08 14:43:36 +00001198
1199 // If there are no more operands, then finish
1200 if (getLexer().is(AsmToken::EndOfStatement))
1201 return false;
1202
1203 // Parse first operand
Alex Bradbury68f73c12018-09-18 15:18:16 +00001204 if (parseOperand(Operands, Name))
Alex Bradbury04f06d92017-08-08 14:43:36 +00001205 return true;
1206
1207 // Parse until end of statement, consuming commas between operands
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001208 unsigned OperandIdx = 1;
Alex Bradbury04f06d92017-08-08 14:43:36 +00001209 while (getLexer().is(AsmToken::Comma)) {
1210 // Consume comma token
1211 getLexer().Lex();
1212
1213 // Parse next operand
Alex Bradbury68f73c12018-09-18 15:18:16 +00001214 if (parseOperand(Operands, Name))
Alex Bradbury04f06d92017-08-08 14:43:36 +00001215 return true;
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001216
1217 ++OperandIdx;
Alex Bradbury04f06d92017-08-08 14:43:36 +00001218 }
1219
1220 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1221 SMLoc Loc = getLexer().getLoc();
1222 getParser().eatToEndOfStatement();
1223 return Error(Loc, "unexpected token");
1224 }
1225
1226 getParser().Lex(); // Consume the EndOfStatement.
1227 return false;
1228}
1229
Alex Bradbury9d3f1252017-09-28 08:26:24 +00001230bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
1231 RISCVMCExpr::VariantKind &Kind,
1232 int64_t &Addend) {
1233 Kind = RISCVMCExpr::VK_RISCV_None;
1234 Addend = 0;
1235
1236 if (const RISCVMCExpr *RE = dyn_cast<RISCVMCExpr>(Expr)) {
1237 Kind = RE->getKind();
1238 Expr = RE->getSubExpr();
1239 }
1240
1241 // It's a simple symbol reference or constant with no addend.
1242 if (isa<MCConstantExpr>(Expr) || isa<MCSymbolRefExpr>(Expr))
1243 return true;
1244
1245 const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr);
1246 if (!BE)
1247 return false;
1248
1249 if (!isa<MCSymbolRefExpr>(BE->getLHS()))
1250 return false;
1251
1252 if (BE->getOpcode() != MCBinaryExpr::Add &&
1253 BE->getOpcode() != MCBinaryExpr::Sub)
1254 return false;
1255
1256 // We are able to support the subtraction of two symbol references
1257 if (BE->getOpcode() == MCBinaryExpr::Sub &&
1258 isa<MCSymbolRefExpr>(BE->getRHS()))
1259 return true;
1260
Hiroshi Inoue9ff23802018-04-09 04:37:53 +00001261 // See if the addend is a constant, otherwise there's more going
Alex Bradbury9d3f1252017-09-28 08:26:24 +00001262 // on here than we can deal with.
1263 auto AddendExpr = dyn_cast<MCConstantExpr>(BE->getRHS());
1264 if (!AddendExpr)
1265 return false;
1266
1267 Addend = AddendExpr->getValue();
1268 if (BE->getOpcode() == MCBinaryExpr::Sub)
1269 Addend = -Addend;
1270
1271 // It's some symbol reference + a constant addend
1272 return Kind != RISCVMCExpr::VK_RISCV_Invalid;
1273}
1274
Alex Bradburybca0c3c2018-05-11 17:30:28 +00001275bool RISCVAsmParser::ParseDirective(AsmToken DirectiveID) {
1276 // This returns false if this function recognizes the directive
1277 // regardless of whether it is successfully handles or reports an
1278 // error. Otherwise it returns true to give the generic parser a
1279 // chance at recognizing it.
1280 StringRef IDVal = DirectiveID.getString();
1281
1282 if (IDVal == ".option")
1283 return parseDirectiveOption();
1284
1285 return true;
1286}
1287
1288bool RISCVAsmParser::parseDirectiveOption() {
1289 MCAsmParser &Parser = getParser();
1290 // Get the option token.
1291 AsmToken Tok = Parser.getTok();
1292 // At the moment only identifiers are supported.
1293 if (Tok.isNot(AsmToken::Identifier))
1294 return Error(Parser.getTok().getLoc(),
1295 "unexpected token, expected identifier");
1296
1297 StringRef Option = Tok.getIdentifier();
1298
Alex Bradbury893e5bc2018-11-28 16:39:14 +00001299 if (Option == "push") {
1300 getTargetStreamer().emitDirectiveOptionPush();
1301
1302 Parser.Lex();
1303 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1304 return Error(Parser.getTok().getLoc(),
1305 "unexpected token, expected end of statement");
1306
1307 pushFeatureBits();
1308 return false;
1309 }
1310
1311 if (Option == "pop") {
1312 SMLoc StartLoc = Parser.getTok().getLoc();
1313 getTargetStreamer().emitDirectiveOptionPop();
1314
1315 Parser.Lex();
1316 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1317 return Error(Parser.getTok().getLoc(),
1318 "unexpected token, expected end of statement");
1319
1320 if (popFeatureBits())
1321 return Error(StartLoc, ".option pop with no .option push");
1322
1323 return false;
1324 }
1325
Alex Bradburybca0c3c2018-05-11 17:30:28 +00001326 if (Option == "rvc") {
1327 getTargetStreamer().emitDirectiveOptionRVC();
1328
1329 Parser.Lex();
1330 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1331 return Error(Parser.getTok().getLoc(),
1332 "unexpected token, expected end of statement");
1333
1334 setFeatureBits(RISCV::FeatureStdExtC, "c");
1335 return false;
1336 }
1337
1338 if (Option == "norvc") {
1339 getTargetStreamer().emitDirectiveOptionNoRVC();
1340
1341 Parser.Lex();
1342 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1343 return Error(Parser.getTok().getLoc(),
1344 "unexpected token, expected end of statement");
1345
1346 clearFeatureBits(RISCV::FeatureStdExtC, "c");
1347 return false;
1348 }
1349
Alex Bradbury9c03e4c2018-11-12 14:25:07 +00001350 if (Option == "relax") {
1351 getTargetStreamer().emitDirectiveOptionRelax();
1352
1353 Parser.Lex();
1354 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1355 return Error(Parser.getTok().getLoc(),
1356 "unexpected token, expected end of statement");
1357
1358 setFeatureBits(RISCV::FeatureRelax, "relax");
1359 return false;
1360 }
1361
1362 if (Option == "norelax") {
1363 getTargetStreamer().emitDirectiveOptionNoRelax();
1364
1365 Parser.Lex();
1366 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1367 return Error(Parser.getTok().getLoc(),
1368 "unexpected token, expected end of statement");
1369
1370 clearFeatureBits(RISCV::FeatureRelax, "relax");
1371 return false;
1372 }
1373
Alex Bradburybca0c3c2018-05-11 17:30:28 +00001374 // Unknown option.
1375 Warning(Parser.getTok().getLoc(),
Alex Bradbury893e5bc2018-11-28 16:39:14 +00001376 "unknown option, expected 'push', 'pop', 'rvc', 'norvc', 'relax' or "
1377 "'norelax'");
Alex Bradburybca0c3c2018-05-11 17:30:28 +00001378 Parser.eatToEndOfStatement();
1379 return false;
1380}
Alex Bradbury04f06d92017-08-08 14:43:36 +00001381
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001382void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
1383 MCInst CInst;
1384 bool Res = compressInst(CInst, Inst, getSTI(), S.getContext());
1385 CInst.setLoc(Inst.getLoc());
1386 S.EmitInstruction((Res ? CInst : Inst), getSTI());
1387}
1388
1389void RISCVAsmParser::emitLoadImm(unsigned DestReg, int64_t Value,
1390 MCStreamer &Out) {
Alex Bradbury22c091f2018-11-15 10:11:31 +00001391 RISCVMatInt::InstSeq Seq;
1392 RISCVMatInt::generateInstSeq(Value, isRV64(), Seq);
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001393
Alex Bradbury22c091f2018-11-15 10:11:31 +00001394 unsigned SrcReg = RISCV::X0;
1395 for (RISCVMatInt::Inst &Inst : Seq) {
1396 if (Inst.Opc == RISCV::LUI) {
1397 emitToStreamer(
1398 Out, MCInstBuilder(RISCV::LUI).addReg(DestReg).addImm(Inst.Imm));
1399 } else {
1400 emitToStreamer(
1401 Out, MCInstBuilder(Inst.Opc).addReg(DestReg).addReg(SrcReg).addImm(
1402 Inst.Imm));
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001403 }
1404
Alex Bradbury22c091f2018-11-15 10:11:31 +00001405 // Only the first instruction has X0 as its source.
1406 SrcReg = DestReg;
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001407 }
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001408}
1409
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001410void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
1411 MCStreamer &Out) {
1412 // The local load address pseudo-instruction "lla" is used in PC-relative
1413 // addressing of symbols:
1414 // lla rdest, symbol
1415 // expands to
1416 // TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
1417 // ADDI rdest, %pcrel_lo(TmpLabel)
1418 MCContext &Ctx = getContext();
1419
1420 MCSymbol *TmpLabel = Ctx.createTempSymbol(
1421 "pcrel_hi", /* AlwaysAddSuffix */ true, /* CanBeUnnamed */ false);
1422 Out.EmitLabel(TmpLabel);
1423
1424 MCOperand DestReg = Inst.getOperand(0);
1425 const RISCVMCExpr *Symbol = RISCVMCExpr::create(
1426 Inst.getOperand(1).getExpr(), RISCVMCExpr::VK_RISCV_PCREL_HI, Ctx);
1427
Roger Ferrer Ibanezc8f4dbb2018-08-14 08:30:42 +00001428 emitToStreamer(
1429 Out, MCInstBuilder(RISCV::AUIPC).addOperand(DestReg).addExpr(Symbol));
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001430
1431 const MCExpr *RefToLinkTmpLabel =
1432 RISCVMCExpr::create(MCSymbolRefExpr::create(TmpLabel, Ctx),
1433 RISCVMCExpr::VK_RISCV_PCREL_LO, Ctx);
1434
Roger Ferrer Ibanezc8f4dbb2018-08-14 08:30:42 +00001435 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
1436 .addOperand(DestReg)
1437 .addOperand(DestReg)
1438 .addExpr(RefToLinkTmpLabel));
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001439}
1440
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001441bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
1442 MCStreamer &Out) {
1443 Inst.setLoc(IDLoc);
1444
1445 if (Inst.getOpcode() == RISCV::PseudoLI) {
Alex Bradbury2ba76be2019-01-03 14:41:41 +00001446 unsigned Reg = Inst.getOperand(0).getReg();
1447 const MCOperand &Op1 = Inst.getOperand(1);
1448 if (Op1.isExpr()) {
1449 // We must have li reg, %lo(sym) or li reg, %pcrel_lo(sym) or similar.
1450 // Just convert to an addi. This allows compatibility with gas.
1451 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
1452 .addReg(Reg)
1453 .addReg(RISCV::X0)
1454 .addExpr(Op1.getExpr()));
1455 return false;
1456 }
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001457 int64_t Imm = Inst.getOperand(1).getImm();
1458 // On RV32 the immediate here can either be a signed or an unsigned
1459 // 32-bit number. Sign extension has to be performed to ensure that Imm
1460 // represents the expected signed 64-bit number.
1461 if (!isRV64())
1462 Imm = SignExtend64<32>(Imm);
1463 emitLoadImm(Reg, Imm, Out);
1464 return false;
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001465 } else if (Inst.getOpcode() == RISCV::PseudoLLA) {
1466 emitLoadLocalAddress(Inst, IDLoc, Out);
1467 return false;
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001468 }
1469
1470 emitToStreamer(Out, Inst);
1471 return false;
1472}
1473
Alex Bradbury04f06d92017-08-08 14:43:36 +00001474extern "C" void LLVMInitializeRISCVAsmParser() {
1475 RegisterMCAsmParser<RISCVAsmParser> X(getTheRISCV32Target());
1476 RegisterMCAsmParser<RISCVAsmParser> Y(getTheRISCV64Target());
1477}