blob: f54d4a586274ef6858f3e3b826098aa10edf8b44 [file] [log] [blame]
Alex Bradbury04f06d92017-08-08 14:43:36 +00001//===-- RISCVAsmParser.cpp - Parse RISCV assembly to MCInst instructions --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Alex Bradbury6758ecb2017-09-17 14:27:35 +000010#include "MCTargetDesc/RISCVBaseInfo.h"
Alex Bradbury9d3f1252017-09-28 08:26:24 +000011#include "MCTargetDesc/RISCVMCExpr.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000012#include "MCTargetDesc/RISCVMCTargetDesc.h"
Alex Bradburybca0c3c2018-05-11 17:30:28 +000013#include "MCTargetDesc/RISCVTargetStreamer.h"
Alex Bradbury4f7f0da2017-09-06 09:21:21 +000014#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/StringSwitch.h"
16#include "llvm/MC/MCContext.h"
17#include "llvm/MC/MCExpr.h"
18#include "llvm/MC/MCInst.h"
Alex Bradbury6a4b5442018-06-07 15:35:47 +000019#include "llvm/MC/MCInstBuilder.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000020#include "llvm/MC/MCParser/MCAsmLexer.h"
21#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
22#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000023#include "llvm/MC/MCRegisterInfo.h"
24#include "llvm/MC/MCStreamer.h"
25#include "llvm/MC/MCSubtargetInfo.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000026#include "llvm/Support/Casting.h"
Alex Bradbury6a4b5442018-06-07 15:35:47 +000027#include "llvm/Support/MathExtras.h"
Alex Bradbury04f06d92017-08-08 14:43:36 +000028#include "llvm/Support/TargetRegistry.h"
29
Alex Bradbury6a4b5442018-06-07 15:35:47 +000030#include <limits>
31
Alex Bradbury04f06d92017-08-08 14:43:36 +000032using namespace llvm;
33
Sameer AbuAsalc1b0e662018-04-06 21:07:05 +000034// Include the auto-generated portion of the compress emitter.
35#define GEN_COMPRESS_INSTR
36#include "RISCVGenCompressInstEmitter.inc"
37
Alex Bradbury04f06d92017-08-08 14:43:36 +000038namespace {
39struct RISCVOperand;
40
41class RISCVAsmParser : public MCTargetAsmParser {
42 SMLoc getLoc() const { return getParser().getTok().getLoc(); }
Alex Bradburya6e62482017-12-07 10:53:48 +000043 bool isRV64() const { return getSTI().hasFeature(RISCV::Feature64Bit); }
Alex Bradbury04f06d92017-08-08 14:43:36 +000044
Alex Bradburybca0c3c2018-05-11 17:30:28 +000045 RISCVTargetStreamer &getTargetStreamer() {
46 MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
47 return static_cast<RISCVTargetStreamer &>(TS);
48 }
49
Alex Bradbury7bc2a952017-12-07 10:46:23 +000050 unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
51 unsigned Kind) override;
52
Alex Bradbury6758ecb2017-09-17 14:27:35 +000053 bool generateImmOutOfRangeError(OperandVector &Operands, uint64_t ErrorInfo,
Alex Bradbury6a4b5442018-06-07 15:35:47 +000054 int64_t Lower, int64_t Upper, Twine Msg);
Alex Bradbury6758ecb2017-09-17 14:27:35 +000055
Alex Bradbury04f06d92017-08-08 14:43:36 +000056 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
57 OperandVector &Operands, MCStreamer &Out,
58 uint64_t &ErrorInfo,
59 bool MatchingInlineAsm) override;
60
61 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
62
63 bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
64 SMLoc NameLoc, OperandVector &Operands) override;
65
66 bool ParseDirective(AsmToken DirectiveID) override;
67
Alex Bradbury6a4b5442018-06-07 15:35:47 +000068 // Helper to actually emit an instruction to the MCStreamer. Also, when
69 // possible, compression of the instruction is performed.
70 void emitToStreamer(MCStreamer &S, const MCInst &Inst);
71
72 // Helper to emit a combination of LUI, ADDI(W), and SLLI instructions that
73 // synthesize the desired immedate value into the destination register.
74 void emitLoadImm(unsigned DestReg, int64_t Value, MCStreamer &Out);
75
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +000076 // Helper to emit pseudo instruction "lla" used in PC-rel addressing.
77 void emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
78
Alex Bradbury6a4b5442018-06-07 15:35:47 +000079 /// Helper for processing MC instructions that have been successfully matched
80 /// by MatchAndEmitInstruction. Modifications to the emitted instructions,
81 /// like the expansion of pseudo instructions (e.g., "li"), can be performed
82 /// in this method.
83 bool processInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
84
Alex Bradbury04f06d92017-08-08 14:43:36 +000085// Auto-generated instruction matching functions
86#define GET_ASSEMBLER_HEADER
87#include "RISCVGenAsmMatcher.inc"
88
89 OperandMatchResultTy parseImmediate(OperandVector &Operands);
Alex Bradbury8c345c52017-11-09 15:00:03 +000090 OperandMatchResultTy parseRegister(OperandVector &Operands,
91 bool AllowParens = false);
Alex Bradbury6758ecb2017-09-17 14:27:35 +000092 OperandMatchResultTy parseMemOpBaseReg(OperandVector &Operands);
Alex Bradbury9d3f1252017-09-28 08:26:24 +000093 OperandMatchResultTy parseOperandWithModifier(OperandVector &Operands);
Alex Bradbury04f06d92017-08-08 14:43:36 +000094
Alex Bradburycd8688a2018-04-25 17:25:29 +000095 bool parseOperand(OperandVector &Operands, bool ForceImmediate);
Alex Bradbury04f06d92017-08-08 14:43:36 +000096
Alex Bradburybca0c3c2018-05-11 17:30:28 +000097 bool parseDirectiveOption();
98
99 void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
100 if (!(getSTI().getFeatureBits()[Feature])) {
101 MCSubtargetInfo &STI = copySTI();
102 setAvailableFeatures(
103 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
104 }
105 }
106
107 void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
108 if (getSTI().getFeatureBits()[Feature]) {
109 MCSubtargetInfo &STI = copySTI();
110 setAvailableFeatures(
111 ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
112 }
113 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000114public:
115 enum RISCVMatchResultTy {
116 Match_Dummy = FIRST_TARGET_MATCH_RESULT_TY,
117#define GET_OPERAND_DIAGNOSTIC_TYPES
118#include "RISCVGenAsmMatcher.inc"
119#undef GET_OPERAND_DIAGNOSTIC_TYPES
120 };
121
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000122 static bool classifySymbolRef(const MCExpr *Expr,
123 RISCVMCExpr::VariantKind &Kind,
124 int64_t &Addend);
125
Alex Bradbury04f06d92017-08-08 14:43:36 +0000126 RISCVAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
127 const MCInstrInfo &MII, const MCTargetOptions &Options)
Oliver Stannard4191b9e2017-10-11 09:17:43 +0000128 : MCTargetAsmParser(Options, STI, MII) {
Alex Bradburycea6db02018-05-17 05:58:08 +0000129 Parser.addAliasForDirective(".half", ".2byte");
130 Parser.addAliasForDirective(".hword", ".2byte");
131 Parser.addAliasForDirective(".word", ".4byte");
132 Parser.addAliasForDirective(".dword", ".8byte");
Alex Bradbury04f06d92017-08-08 14:43:36 +0000133 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
134 }
135};
136
137/// RISCVOperand - Instances of this class represent a parsed machine
138/// instruction
139struct RISCVOperand : public MCParsedAsmOperand {
140
141 enum KindTy {
142 Token,
143 Register,
144 Immediate,
145 } Kind;
146
Alex Bradburya6e62482017-12-07 10:53:48 +0000147 bool IsRV64;
148
Alex Bradbury04f06d92017-08-08 14:43:36 +0000149 struct RegOp {
150 unsigned RegNum;
151 };
152
153 struct ImmOp {
154 const MCExpr *Val;
155 };
156
157 SMLoc StartLoc, EndLoc;
158 union {
159 StringRef Tok;
160 RegOp Reg;
161 ImmOp Imm;
162 };
163
164 RISCVOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
165
166public:
167 RISCVOperand(const RISCVOperand &o) : MCParsedAsmOperand() {
168 Kind = o.Kind;
Alex Bradburya6e62482017-12-07 10:53:48 +0000169 IsRV64 = o.IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000170 StartLoc = o.StartLoc;
171 EndLoc = o.EndLoc;
172 switch (Kind) {
173 case Register:
174 Reg = o.Reg;
175 break;
176 case Immediate:
177 Imm = o.Imm;
178 break;
179 case Token:
180 Tok = o.Tok;
181 break;
182 }
183 }
184
185 bool isToken() const override { return Kind == Token; }
186 bool isReg() const override { return Kind == Register; }
187 bool isImm() const override { return Kind == Immediate; }
188 bool isMem() const override { return false; }
189
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000190 bool evaluateConstantImm(int64_t &Imm, RISCVMCExpr::VariantKind &VK) const {
191 const MCExpr *Val = getImm();
192 bool Ret = false;
193 if (auto *RE = dyn_cast<RISCVMCExpr>(Val)) {
194 Ret = RE->evaluateAsConstant(Imm);
195 VK = RE->getKind();
196 } else if (auto CE = dyn_cast<MCConstantExpr>(Val)) {
197 Ret = true;
198 VK = RISCVMCExpr::VK_RISCV_None;
199 Imm = CE->getValue();
200 }
201 return Ret;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000202 }
203
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000204 // True if operand is a symbol with no modifiers, or a constant with no
205 // modifiers and isShiftedInt<N-1, 1>(Op).
206 template <int N> bool isBareSimmNLsb0() const {
207 int64_t Imm;
208 RISCVMCExpr::VariantKind VK;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000209 if (!isImm())
210 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000211 bool IsConstantImm = evaluateConstantImm(Imm, VK);
212 bool IsValid;
213 if (!IsConstantImm)
214 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
215 else
216 IsValid = isShiftedInt<N - 1, 1>(Imm);
217 return IsValid && VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000218 }
219
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000220 // Predicate methods for AsmOperands defined in RISCVInstrInfo.td
221
Shiva Chen98f93892018-04-25 14:18:55 +0000222 bool isBareSymbol() const {
223 int64_t Imm;
224 RISCVMCExpr::VariantKind VK;
225 // Must be of 'immediate' type but not a constant.
226 if (!isImm() || evaluateConstantImm(Imm, VK))
227 return false;
228 return RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm) &&
229 VK == RISCVMCExpr::VK_RISCV_None;
230 }
231
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000232 /// Return true if the operand is a valid for the fence instruction e.g.
233 /// ('iorw').
234 bool isFenceArg() const {
235 if (!isImm())
236 return false;
237 const MCExpr *Val = getImm();
238 auto *SVal = dyn_cast<MCSymbolRefExpr>(Val);
239 if (!SVal || SVal->getKind() != MCSymbolRefExpr::VK_None)
240 return false;
241
242 StringRef Str = SVal->getSymbol().getName();
243 // Letters must be unique, taken from 'iorw', and in ascending order. This
244 // holds as long as each individual character is one of 'iorw' and is
245 // greater than the previous character.
246 char Prev = '\0';
247 for (char c : Str) {
248 if (c != 'i' && c != 'o' && c != 'r' && c != 'w')
249 return false;
250 if (c <= Prev)
251 return false;
252 Prev = c;
253 }
254 return true;
255 }
256
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000257 /// Return true if the operand is a valid floating point rounding mode.
258 bool isFRMArg() const {
259 if (!isImm())
260 return false;
261 const MCExpr *Val = getImm();
262 auto *SVal = dyn_cast<MCSymbolRefExpr>(Val);
263 if (!SVal || SVal->getKind() != MCSymbolRefExpr::VK_None)
264 return false;
265
266 StringRef Str = SVal->getSymbol().getName();
267
268 return RISCVFPRndMode::stringToRoundingMode(Str) != RISCVFPRndMode::Invalid;
269 }
270
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000271 bool isImmXLen() const {
272 int64_t Imm;
273 RISCVMCExpr::VariantKind VK;
274 if (!isImm())
275 return false;
276 bool IsConstantImm = evaluateConstantImm(Imm, VK);
277 // Given only Imm, ensuring that the actually specified constant is either
278 // a signed or unsigned 64-bit number is unfortunately impossible.
279 bool IsInRange = isRV64() ? true : isInt<32>(Imm) || isUInt<32>(Imm);
280 return IsConstantImm && IsInRange && VK == RISCVMCExpr::VK_RISCV_None;
281 }
282
Alex Bradburya6e62482017-12-07 10:53:48 +0000283 bool isUImmLog2XLen() const {
284 int64_t Imm;
285 RISCVMCExpr::VariantKind VK;
286 if (!isImm())
287 return false;
288 if (!evaluateConstantImm(Imm, VK) || VK != RISCVMCExpr::VK_RISCV_None)
289 return false;
290 return (isRV64() && isUInt<6>(Imm)) || isUInt<5>(Imm);
291 }
292
Alex Bradbury0ad4c262017-12-15 10:20:51 +0000293 bool isUImmLog2XLenNonZero() const {
294 int64_t Imm;
295 RISCVMCExpr::VariantKind VK;
296 if (!isImm())
297 return false;
298 if (!evaluateConstantImm(Imm, VK) || VK != RISCVMCExpr::VK_RISCV_None)
299 return false;
300 if (Imm == 0)
301 return false;
302 return (isRV64() && isUInt<6>(Imm)) || isUInt<5>(Imm);
303 }
304
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000305 bool isUImm5() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000306 int64_t Imm;
307 RISCVMCExpr::VariantKind VK;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000308 if (!isImm())
309 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000310 bool IsConstantImm = evaluateConstantImm(Imm, VK);
311 return IsConstantImm && isUInt<5>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000312 }
313
Alex Bradbury60714f92017-12-13 09:32:55 +0000314 bool isUImm5NonZero() const {
315 int64_t Imm;
316 RISCVMCExpr::VariantKind VK;
317 if (!isImm())
318 return false;
319 bool IsConstantImm = evaluateConstantImm(Imm, VK);
320 return IsConstantImm && isUInt<5>(Imm) && (Imm != 0) &&
321 VK == RISCVMCExpr::VK_RISCV_None;
322 }
323
Alex Bradbury581d6b02017-12-13 09:41:21 +0000324 bool isSImm6() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000325 if (!isImm())
326 return false;
Alex Bradbury581d6b02017-12-13 09:41:21 +0000327 RISCVMCExpr::VariantKind VK;
328 int64_t Imm;
Alex Bradbury581d6b02017-12-13 09:41:21 +0000329 bool IsConstantImm = evaluateConstantImm(Imm, VK);
Ana Pazos065b0882018-09-13 18:37:23 +0000330 return IsConstantImm && isInt<6>(Imm) &&
331 VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury581d6b02017-12-13 09:41:21 +0000332 }
333
Shiva Chenb22c1d22018-02-02 02:43:23 +0000334 bool isSImm6NonZero() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000335 if (!isImm())
336 return false;
Shiva Chenb22c1d22018-02-02 02:43:23 +0000337 RISCVMCExpr::VariantKind VK;
338 int64_t Imm;
Shiva Chenb22c1d22018-02-02 02:43:23 +0000339 bool IsConstantImm = evaluateConstantImm(Imm, VK);
Ana Pazos065b0882018-09-13 18:37:23 +0000340 return IsConstantImm && isInt<6>(Imm) && (Imm != 0) &&
341 VK == RISCVMCExpr::VK_RISCV_None;
Shiva Chenb22c1d22018-02-02 02:43:23 +0000342 }
343
Shiva Chen7c172422018-02-22 15:02:28 +0000344 bool isCLUIImm() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000345 if (!isImm())
346 return false;
Alex Bradbury60714f92017-12-13 09:32:55 +0000347 int64_t Imm;
348 RISCVMCExpr::VariantKind VK;
349 bool IsConstantImm = evaluateConstantImm(Imm, VK);
Shiva Chen7c172422018-02-22 15:02:28 +0000350 return IsConstantImm && (Imm != 0) &&
351 (isUInt<5>(Imm) || (Imm >= 0xfffe0 && Imm <= 0xfffff)) &&
352 VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury60714f92017-12-13 09:32:55 +0000353 }
354
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000355 bool isUImm7Lsb00() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000356 if (!isImm())
357 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000358 int64_t Imm;
359 RISCVMCExpr::VariantKind VK;
360 bool IsConstantImm = evaluateConstantImm(Imm, VK);
361 return IsConstantImm && isShiftedUInt<5, 2>(Imm) &&
362 VK == RISCVMCExpr::VK_RISCV_None;
363 }
364
365 bool isUImm8Lsb00() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000366 if (!isImm())
367 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000368 int64_t Imm;
369 RISCVMCExpr::VariantKind VK;
370 bool IsConstantImm = evaluateConstantImm(Imm, VK);
371 return IsConstantImm && isShiftedUInt<6, 2>(Imm) &&
372 VK == RISCVMCExpr::VK_RISCV_None;
373 }
374
375 bool isUImm8Lsb000() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000376 if (!isImm())
377 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000378 int64_t Imm;
379 RISCVMCExpr::VariantKind VK;
380 bool IsConstantImm = evaluateConstantImm(Imm, VK);
381 return IsConstantImm && isShiftedUInt<5, 3>(Imm) &&
382 VK == RISCVMCExpr::VK_RISCV_None;
383 }
384
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000385 bool isSImm9Lsb0() const { return isBareSimmNLsb0<9>(); }
386
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000387 bool isUImm9Lsb000() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000388 if (!isImm())
389 return false;
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000390 int64_t Imm;
391 RISCVMCExpr::VariantKind VK;
392 bool IsConstantImm = evaluateConstantImm(Imm, VK);
393 return IsConstantImm && isShiftedUInt<6, 3>(Imm) &&
394 VK == RISCVMCExpr::VK_RISCV_None;
395 }
396
Alex Bradbury60714f92017-12-13 09:32:55 +0000397 bool isUImm10Lsb00NonZero() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000398 if (!isImm())
399 return false;
Alex Bradbury60714f92017-12-13 09:32:55 +0000400 int64_t Imm;
401 RISCVMCExpr::VariantKind VK;
402 bool IsConstantImm = evaluateConstantImm(Imm, VK);
403 return IsConstantImm && isShiftedUInt<8, 2>(Imm) && (Imm != 0) &&
404 VK == RISCVMCExpr::VK_RISCV_None;
405 }
406
Alex Bradbury04f06d92017-08-08 14:43:36 +0000407 bool isSImm12() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000408 RISCVMCExpr::VariantKind VK;
409 int64_t Imm;
410 bool IsValid;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000411 if (!isImm())
412 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000413 bool IsConstantImm = evaluateConstantImm(Imm, VK);
414 if (!IsConstantImm)
415 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
416 else
417 IsValid = isInt<12>(Imm);
Ahmed Charles646ab872018-02-06 00:55:23 +0000418 return IsValid && (VK == RISCVMCExpr::VK_RISCV_None ||
419 VK == RISCVMCExpr::VK_RISCV_LO ||
420 VK == RISCVMCExpr::VK_RISCV_PCREL_LO);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000421 }
422
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000423 bool isSImm12Lsb0() const { return isBareSimmNLsb0<12>(); }
424
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000425 bool isUImm12() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000426 int64_t Imm;
427 RISCVMCExpr::VariantKind VK;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000428 if (!isImm())
429 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000430 bool IsConstantImm = evaluateConstantImm(Imm, VK);
431 return IsConstantImm && isUInt<12>(Imm) && VK == RISCVMCExpr::VK_RISCV_None;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000432 }
433
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000434 bool isSImm13Lsb0() const { return isBareSimmNLsb0<13>(); }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000435
Shiva Chenb22c1d22018-02-02 02:43:23 +0000436 bool isSImm10Lsb0000NonZero() const {
Ana Pazosecc65ed2018-08-24 23:47:49 +0000437 if (!isImm())
438 return false;
Alex Bradbury60714f92017-12-13 09:32:55 +0000439 int64_t Imm;
440 RISCVMCExpr::VariantKind VK;
441 bool IsConstantImm = evaluateConstantImm(Imm, VK);
Shiva Chenb22c1d22018-02-02 02:43:23 +0000442 return IsConstantImm && (Imm != 0) && isShiftedInt<6, 4>(Imm) &&
Alex Bradbury60714f92017-12-13 09:32:55 +0000443 VK == RISCVMCExpr::VK_RISCV_None;
444 }
445
Alex Bradbury74340f12018-09-18 15:08:35 +0000446 bool isUImm20LUI() const {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000447 RISCVMCExpr::VariantKind VK;
448 int64_t Imm;
449 bool IsValid;
Alex Bradbury3c941e72017-10-19 16:22:51 +0000450 if (!isImm())
451 return false;
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000452 bool IsConstantImm = evaluateConstantImm(Imm, VK);
Alex Bradbury74340f12018-09-18 15:08:35 +0000453 if (!IsConstantImm) {
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000454 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
Alex Bradbury74340f12018-09-18 15:08:35 +0000455 return IsValid && VK == RISCVMCExpr::VK_RISCV_HI;
456 } else {
457 return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
458 VK == RISCVMCExpr::VK_RISCV_HI);
459 }
460 }
461
462 bool isUImm20AUIPC() const {
463 RISCVMCExpr::VariantKind VK;
464 int64_t Imm;
465 bool IsValid;
466 if (!isImm())
467 return false;
468 bool IsConstantImm = evaluateConstantImm(Imm, VK);
469 if (!IsConstantImm) {
470 IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
471 return IsValid && VK == RISCVMCExpr::VK_RISCV_PCREL_HI;
472 } else {
473 return isUInt<20>(Imm) && (VK == RISCVMCExpr::VK_RISCV_None ||
474 VK == RISCVMCExpr::VK_RISCV_PCREL_HI);
475 }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000476 }
477
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000478 bool isSImm21Lsb0() const { return isBareSimmNLsb0<21>(); }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000479
Alex Bradbury04f06d92017-08-08 14:43:36 +0000480 /// getStartLoc - Gets location of the first token of this operand
481 SMLoc getStartLoc() const override { return StartLoc; }
482 /// getEndLoc - Gets location of the last token of this operand
483 SMLoc getEndLoc() const override { return EndLoc; }
Alex Bradburya6e62482017-12-07 10:53:48 +0000484 /// True if this operand is for an RV64 instruction
485 bool isRV64() const { return IsRV64; }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000486
487 unsigned getReg() const override {
488 assert(Kind == Register && "Invalid type access!");
489 return Reg.RegNum;
490 }
491
492 const MCExpr *getImm() const {
493 assert(Kind == Immediate && "Invalid type access!");
494 return Imm.Val;
495 }
496
497 StringRef getToken() const {
498 assert(Kind == Token && "Invalid type access!");
499 return Tok;
500 }
501
502 void print(raw_ostream &OS) const override {
503 switch (Kind) {
504 case Immediate:
505 OS << *getImm();
506 break;
507 case Register:
508 OS << "<register x";
509 OS << getReg() << ">";
510 break;
511 case Token:
512 OS << "'" << getToken() << "'";
513 break;
514 }
515 }
516
Alex Bradburya6e62482017-12-07 10:53:48 +0000517 static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S,
518 bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000519 auto Op = make_unique<RISCVOperand>(Token);
520 Op->Tok = Str;
521 Op->StartLoc = S;
522 Op->EndLoc = S;
Alex Bradburya6e62482017-12-07 10:53:48 +0000523 Op->IsRV64 = IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000524 return Op;
525 }
526
527 static std::unique_ptr<RISCVOperand> createReg(unsigned RegNo, SMLoc S,
Alex Bradburya6e62482017-12-07 10:53:48 +0000528 SMLoc E, bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000529 auto Op = make_unique<RISCVOperand>(Register);
530 Op->Reg.RegNum = RegNo;
531 Op->StartLoc = S;
532 Op->EndLoc = E;
Alex Bradburya6e62482017-12-07 10:53:48 +0000533 Op->IsRV64 = IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000534 return Op;
535 }
536
537 static std::unique_ptr<RISCVOperand> createImm(const MCExpr *Val, SMLoc S,
Alex Bradburya6e62482017-12-07 10:53:48 +0000538 SMLoc E, bool IsRV64) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000539 auto Op = make_unique<RISCVOperand>(Immediate);
540 Op->Imm.Val = Val;
541 Op->StartLoc = S;
542 Op->EndLoc = E;
Alex Bradburya6e62482017-12-07 10:53:48 +0000543 Op->IsRV64 = IsRV64;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000544 return Op;
545 }
546
547 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
548 assert(Expr && "Expr shouldn't be null!");
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000549 int64_t Imm = 0;
550 bool IsConstant = false;
551 if (auto *RE = dyn_cast<RISCVMCExpr>(Expr)) {
552 IsConstant = RE->evaluateAsConstant(Imm);
553 } else if (auto *CE = dyn_cast<MCConstantExpr>(Expr)) {
554 IsConstant = true;
555 Imm = CE->getValue();
556 }
557
558 if (IsConstant)
559 Inst.addOperand(MCOperand::createImm(Imm));
Alex Bradbury04f06d92017-08-08 14:43:36 +0000560 else
561 Inst.addOperand(MCOperand::createExpr(Expr));
562 }
563
564 // Used by the TableGen Code
565 void addRegOperands(MCInst &Inst, unsigned N) const {
566 assert(N == 1 && "Invalid number of operands!");
567 Inst.addOperand(MCOperand::createReg(getReg()));
568 }
569
570 void addImmOperands(MCInst &Inst, unsigned N) const {
571 assert(N == 1 && "Invalid number of operands!");
572 addExpr(Inst, getImm());
573 }
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000574
575 void addFenceArgOperands(MCInst &Inst, unsigned N) const {
576 assert(N == 1 && "Invalid number of operands!");
577 // isFenceArg has validated the operand, meaning this cast is safe
578 auto SE = cast<MCSymbolRefExpr>(getImm());
579
580 unsigned Imm = 0;
581 for (char c : SE->getSymbol().getName()) {
582 switch (c) {
583 default: llvm_unreachable("FenceArg must contain only [iorw]");
584 case 'i': Imm |= RISCVFenceField::I; break;
585 case 'o': Imm |= RISCVFenceField::O; break;
586 case 'r': Imm |= RISCVFenceField::R; break;
587 case 'w': Imm |= RISCVFenceField::W; break;
588 }
589 }
590 Inst.addOperand(MCOperand::createImm(Imm));
591 }
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000592
593 // Returns the rounding mode represented by this RISCVOperand. Should only
594 // be called after checking isFRMArg.
595 RISCVFPRndMode::RoundingMode getRoundingMode() const {
596 // isFRMArg has validated the operand, meaning this cast is safe.
597 auto SE = cast<MCSymbolRefExpr>(getImm());
598 RISCVFPRndMode::RoundingMode FRM =
599 RISCVFPRndMode::stringToRoundingMode(SE->getSymbol().getName());
600 assert(FRM != RISCVFPRndMode::Invalid && "Invalid rounding mode");
601 return FRM;
602 }
603
604 void addFRMArgOperands(MCInst &Inst, unsigned N) const {
605 assert(N == 1 && "Invalid number of operands!");
606 Inst.addOperand(MCOperand::createImm(getRoundingMode()));
607 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000608};
609} // end anonymous namespace.
610
611#define GET_REGISTER_MATCHER
612#define GET_MATCHER_IMPLEMENTATION
Alex Bradbury04f06d92017-08-08 14:43:36 +0000613#include "RISCVGenAsmMatcher.inc"
614
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000615// Return the matching FPR64 register for the given FPR32.
616// FIXME: Ideally this function could be removed in favour of using
617// information from TableGen.
618unsigned convertFPR32ToFPR64(unsigned Reg) {
619 switch (Reg) {
620 default:
621 llvm_unreachable("Not a recognised FPR32 register");
622 case RISCV::F0_32: return RISCV::F0_64;
623 case RISCV::F1_32: return RISCV::F1_64;
624 case RISCV::F2_32: return RISCV::F2_64;
625 case RISCV::F3_32: return RISCV::F3_64;
626 case RISCV::F4_32: return RISCV::F4_64;
627 case RISCV::F5_32: return RISCV::F5_64;
628 case RISCV::F6_32: return RISCV::F6_64;
629 case RISCV::F7_32: return RISCV::F7_64;
630 case RISCV::F8_32: return RISCV::F8_64;
631 case RISCV::F9_32: return RISCV::F9_64;
632 case RISCV::F10_32: return RISCV::F10_64;
633 case RISCV::F11_32: return RISCV::F11_64;
634 case RISCV::F12_32: return RISCV::F12_64;
635 case RISCV::F13_32: return RISCV::F13_64;
636 case RISCV::F14_32: return RISCV::F14_64;
637 case RISCV::F15_32: return RISCV::F15_64;
638 case RISCV::F16_32: return RISCV::F16_64;
639 case RISCV::F17_32: return RISCV::F17_64;
640 case RISCV::F18_32: return RISCV::F18_64;
641 case RISCV::F19_32: return RISCV::F19_64;
642 case RISCV::F20_32: return RISCV::F20_64;
643 case RISCV::F21_32: return RISCV::F21_64;
644 case RISCV::F22_32: return RISCV::F22_64;
645 case RISCV::F23_32: return RISCV::F23_64;
646 case RISCV::F24_32: return RISCV::F24_64;
647 case RISCV::F25_32: return RISCV::F25_64;
648 case RISCV::F26_32: return RISCV::F26_64;
649 case RISCV::F27_32: return RISCV::F27_64;
650 case RISCV::F28_32: return RISCV::F28_64;
651 case RISCV::F29_32: return RISCV::F29_64;
652 case RISCV::F30_32: return RISCV::F30_64;
653 case RISCV::F31_32: return RISCV::F31_64;
654 }
655}
656
657unsigned RISCVAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
658 unsigned Kind) {
659 RISCVOperand &Op = static_cast<RISCVOperand &>(AsmOp);
660 if (!Op.isReg())
661 return Match_InvalidOperand;
662
663 unsigned Reg = Op.getReg();
664 bool IsRegFPR32 =
665 RISCVMCRegisterClasses[RISCV::FPR32RegClassID].contains(Reg);
Alex Bradbury60714f92017-12-13 09:32:55 +0000666 bool IsRegFPR32C =
667 RISCVMCRegisterClasses[RISCV::FPR32CRegClassID].contains(Reg);
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000668
669 // As the parser couldn't differentiate an FPR32 from an FPR64, coerce the
Alex Bradbury60714f92017-12-13 09:32:55 +0000670 // register from FPR32 to FPR64 or FPR32C to FPR64C if necessary.
671 if ((IsRegFPR32 && Kind == MCK_FPR64) ||
672 (IsRegFPR32C && Kind == MCK_FPR64C)) {
Alex Bradbury7bc2a952017-12-07 10:46:23 +0000673 Op.Reg.RegNum = convertFPR32ToFPR64(Reg);
674 return Match_Success;
675 }
676 return Match_InvalidOperand;
677}
678
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000679bool RISCVAsmParser::generateImmOutOfRangeError(
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000680 OperandVector &Operands, uint64_t ErrorInfo, int64_t Lower, int64_t Upper,
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000681 Twine Msg = "immediate must be an integer in the range") {
682 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
683 return Error(ErrorLoc, Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
684}
685
Alex Bradbury04f06d92017-08-08 14:43:36 +0000686bool RISCVAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
687 OperandVector &Operands,
688 MCStreamer &Out,
689 uint64_t &ErrorInfo,
690 bool MatchingInlineAsm) {
691 MCInst Inst;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000692
Ana Pazos6b34051b2018-08-30 19:43:19 +0000693 auto Result =
694 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
695 switch (Result) {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000696 default:
697 break;
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000698 case Match_Success:
699 return processInstruction(Inst, IDLoc, Out);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000700 case Match_MissingFeature:
701 return Error(IDLoc, "instruction use requires an option to be enabled");
702 case Match_MnemonicFail:
703 return Error(IDLoc, "unrecognized instruction mnemonic");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000704 case Match_InvalidOperand: {
705 SMLoc ErrorLoc = IDLoc;
Alex Bradbury04f06d92017-08-08 14:43:36 +0000706 if (ErrorInfo != ~0U) {
707 if (ErrorInfo >= Operands.size())
708 return Error(ErrorLoc, "too few operands for instruction");
709
710 ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
711 if (ErrorLoc == SMLoc())
712 ErrorLoc = IDLoc;
713 }
714 return Error(ErrorLoc, "invalid operand for instruction");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000715 }
Ana Pazos6b34051b2018-08-30 19:43:19 +0000716 }
717
718 // Handle the case when the error message is of specific type
719 // other than the generic Match_InvalidOperand, and the
720 // corresponding operand is missing.
721 if (Result > FIRST_TARGET_MATCH_RESULT_TY) {
722 SMLoc ErrorLoc = IDLoc;
723 if (ErrorInfo != ~0U && ErrorInfo >= Operands.size())
724 return Error(ErrorLoc, "too few operands for instruction");
725 }
726
727 switch(Result) {
728 default:
729 break;
Alex Bradbury6a4b5442018-06-07 15:35:47 +0000730 case Match_InvalidImmXLen:
731 if (isRV64()) {
732 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
733 return Error(ErrorLoc, "operand must be a constant 64-bit integer");
734 }
735 return generateImmOutOfRangeError(Operands, ErrorInfo,
736 std::numeric_limits<int32_t>::min(),
737 std::numeric_limits<uint32_t>::max());
Alex Bradburya6e62482017-12-07 10:53:48 +0000738 case Match_InvalidUImmLog2XLen:
739 if (isRV64())
740 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
741 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
Alex Bradbury0ad4c262017-12-15 10:20:51 +0000742 case Match_InvalidUImmLog2XLenNonZero:
743 if (isRV64())
744 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 6) - 1);
745 return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5) - 1);
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000746 case Match_InvalidUImm5:
747 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
Alex Bradbury581d6b02017-12-13 09:41:21 +0000748 case Match_InvalidSImm6:
749 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
750 (1 << 5) - 1);
Shiva Chenb22c1d22018-02-02 02:43:23 +0000751 case Match_InvalidSImm6NonZero:
752 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
753 (1 << 5) - 1,
754 "immediate must be non-zero in the range");
Shiva Chen7c172422018-02-22 15:02:28 +0000755 case Match_InvalidCLUIImm:
756 return generateImmOutOfRangeError(
757 Operands, ErrorInfo, 1, (1 << 5) - 1,
758 "immediate must be in [0xfffe0, 0xfffff] or");
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000759 case Match_InvalidUImm7Lsb00:
760 return generateImmOutOfRangeError(
761 Operands, ErrorInfo, 0, (1 << 7) - 4,
762 "immediate must be a multiple of 4 bytes in the range");
763 case Match_InvalidUImm8Lsb00:
764 return generateImmOutOfRangeError(
765 Operands, ErrorInfo, 0, (1 << 8) - 4,
766 "immediate must be a multiple of 4 bytes in the range");
767 case Match_InvalidUImm8Lsb000:
768 return generateImmOutOfRangeError(
769 Operands, ErrorInfo, 0, (1 << 8) - 8,
770 "immediate must be a multiple of 8 bytes in the range");
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000771 case Match_InvalidSImm9Lsb0:
772 return generateImmOutOfRangeError(
773 Operands, ErrorInfo, -(1 << 8), (1 << 8) - 2,
774 "immediate must be a multiple of 2 bytes in the range");
Alex Bradbury9f6aec42017-12-07 12:50:32 +0000775 case Match_InvalidUImm9Lsb000:
776 return generateImmOutOfRangeError(
777 Operands, ErrorInfo, 0, (1 << 9) - 8,
778 "immediate must be a multiple of 8 bytes in the range");
Alex Bradbury60714f92017-12-13 09:32:55 +0000779 case Match_InvalidUImm10Lsb00NonZero:
780 return generateImmOutOfRangeError(
781 Operands, ErrorInfo, 4, (1 << 10) - 4,
782 "immediate must be a multiple of 4 bytes in the range");
Shiva Chenb22c1d22018-02-02 02:43:23 +0000783 case Match_InvalidSImm10Lsb0000NonZero:
Alex Bradbury60714f92017-12-13 09:32:55 +0000784 return generateImmOutOfRangeError(
785 Operands, ErrorInfo, -(1 << 9), (1 << 9) - 16,
Shiva Chenb22c1d22018-02-02 02:43:23 +0000786 "immediate must be a multiple of 16 bytes and non-zero in the range");
Alex Bradbury04f06d92017-08-08 14:43:36 +0000787 case Match_InvalidSImm12:
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000788 return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 11),
789 (1 << 11) - 1);
Alex Bradburyf8f4b902017-12-07 13:19:57 +0000790 case Match_InvalidSImm12Lsb0:
791 return generateImmOutOfRangeError(
792 Operands, ErrorInfo, -(1 << 11), (1 << 11) - 2,
793 "immediate must be a multiple of 2 bytes in the range");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000794 case Match_InvalidUImm12:
795 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 12) - 1);
796 case Match_InvalidSImm13Lsb0:
797 return generateImmOutOfRangeError(
798 Operands, ErrorInfo, -(1 << 12), (1 << 12) - 2,
799 "immediate must be a multiple of 2 bytes in the range");
Alex Bradbury74340f12018-09-18 15:08:35 +0000800 case Match_InvalidUImm20LUI:
801 return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1,
802 "operand must be a symbol with %hi() "
803 "modifier or an integer in the range");
804 case Match_InvalidUImm20AUIPC:
805 return generateImmOutOfRangeError(
806 Operands, ErrorInfo, 0, (1 << 20) - 1,
807 "operand must be a symbol with %pcrel_hi() modifier or an integer in "
808 "the range");
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000809 case Match_InvalidSImm21Lsb0:
810 return generateImmOutOfRangeError(
811 Operands, ErrorInfo, -(1 << 20), (1 << 20) - 2,
812 "immediate must be a multiple of 2 bytes in the range");
813 case Match_InvalidFenceArg: {
Alex Bradbury04f06d92017-08-08 14:43:36 +0000814 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000815 return Error(
816 ErrorLoc,
817 "operand must be formed of letters selected in-order from 'iorw'");
818 }
Alex Bradbury0d6cf902017-12-07 10:26:05 +0000819 case Match_InvalidFRMArg: {
820 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
821 return Error(
822 ErrorLoc,
823 "operand must be a valid floating point rounding mode mnemonic");
824 }
Shiva Chen98f93892018-04-25 14:18:55 +0000825 case Match_InvalidBareSymbol: {
826 SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
827 return Error(ErrorLoc, "operand must be a bare symbol name");
828 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000829 }
830
831 llvm_unreachable("Unknown match type detected!");
832}
833
834bool RISCVAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
835 SMLoc &EndLoc) {
836 const AsmToken &Tok = getParser().getTok();
837 StartLoc = Tok.getLoc();
838 EndLoc = Tok.getEndLoc();
839 RegNo = 0;
840 StringRef Name = getLexer().getTok().getIdentifier();
841
842 if (!MatchRegisterName(Name) || !MatchRegisterAltName(Name)) {
843 getParser().Lex(); // Eat identifier token.
844 return false;
845 }
846
847 return Error(StartLoc, "invalid register name");
848}
849
Alex Bradbury8c345c52017-11-09 15:00:03 +0000850OperandMatchResultTy RISCVAsmParser::parseRegister(OperandVector &Operands,
851 bool AllowParens) {
852 SMLoc FirstS = getLoc();
853 bool HadParens = false;
854 AsmToken Buf[2];
855
856 // If this a parenthesised register name is allowed, parse it atomically
857 if (AllowParens && getLexer().is(AsmToken::LParen)) {
858 size_t ReadCount = getLexer().peekTokens(Buf);
859 if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
860 HadParens = true;
861 getParser().Lex(); // Eat '('
862 }
863 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000864
865 switch (getLexer().getKind()) {
866 default:
867 return MatchOperand_NoMatch;
868 case AsmToken::Identifier:
869 StringRef Name = getLexer().getTok().getIdentifier();
870 unsigned RegNo = MatchRegisterName(Name);
871 if (RegNo == 0) {
872 RegNo = MatchRegisterAltName(Name);
Alex Bradbury8c345c52017-11-09 15:00:03 +0000873 if (RegNo == 0) {
874 if (HadParens)
875 getLexer().UnLex(Buf[0]);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000876 return MatchOperand_NoMatch;
Alex Bradbury8c345c52017-11-09 15:00:03 +0000877 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000878 }
Alex Bradbury8c345c52017-11-09 15:00:03 +0000879 if (HadParens)
Alex Bradburya6e62482017-12-07 10:53:48 +0000880 Operands.push_back(RISCVOperand::createToken("(", FirstS, isRV64()));
Alex Bradbury8c345c52017-11-09 15:00:03 +0000881 SMLoc S = getLoc();
882 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
Alex Bradbury04f06d92017-08-08 14:43:36 +0000883 getLexer().Lex();
Alex Bradburya6e62482017-12-07 10:53:48 +0000884 Operands.push_back(RISCVOperand::createReg(RegNo, S, E, isRV64()));
Alex Bradbury04f06d92017-08-08 14:43:36 +0000885 }
Alex Bradbury8c345c52017-11-09 15:00:03 +0000886
887 if (HadParens) {
888 getParser().Lex(); // Eat ')'
Alex Bradburya6e62482017-12-07 10:53:48 +0000889 Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
Alex Bradbury8c345c52017-11-09 15:00:03 +0000890 }
891
Alex Bradbury04f06d92017-08-08 14:43:36 +0000892 return MatchOperand_Success;
893}
894
895OperandMatchResultTy RISCVAsmParser::parseImmediate(OperandVector &Operands) {
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000896 SMLoc S = getLoc();
897 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
898 const MCExpr *Res;
899
Alex Bradbury04f06d92017-08-08 14:43:36 +0000900 switch (getLexer().getKind()) {
901 default:
902 return MatchOperand_NoMatch;
903 case AsmToken::LParen:
904 case AsmToken::Minus:
905 case AsmToken::Plus:
906 case AsmToken::Integer:
907 case AsmToken::String:
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000908 if (getParser().parseExpression(Res))
909 return MatchOperand_ParseFail;
910 break;
911 case AsmToken::Identifier: {
912 StringRef Identifier;
913 if (getParser().parseIdentifier(Identifier))
914 return MatchOperand_ParseFail;
915 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
916 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Alex Bradbury04f06d92017-08-08 14:43:36 +0000917 break;
918 }
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000919 case AsmToken::Percent:
920 return parseOperandWithModifier(Operands);
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000921 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000922
Alex Bradburya6e62482017-12-07 10:53:48 +0000923 Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
Alex Bradbury9d3f1252017-09-28 08:26:24 +0000924 return MatchOperand_Success;
925}
926
927OperandMatchResultTy
928RISCVAsmParser::parseOperandWithModifier(OperandVector &Operands) {
929 SMLoc S = getLoc();
930 SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
931
932 if (getLexer().getKind() != AsmToken::Percent) {
933 Error(getLoc(), "expected '%' for operand modifier");
934 return MatchOperand_ParseFail;
935 }
936
937 getParser().Lex(); // Eat '%'
938
939 if (getLexer().getKind() != AsmToken::Identifier) {
940 Error(getLoc(), "expected valid identifier for operand modifier");
941 return MatchOperand_ParseFail;
942 }
943 StringRef Identifier = getParser().getTok().getIdentifier();
944 RISCVMCExpr::VariantKind VK = RISCVMCExpr::getVariantKindForName(Identifier);
945 if (VK == RISCVMCExpr::VK_RISCV_Invalid) {
946 Error(getLoc(), "unrecognized operand modifier");
947 return MatchOperand_ParseFail;
948 }
949
950 getParser().Lex(); // Eat the identifier
951 if (getLexer().getKind() != AsmToken::LParen) {
952 Error(getLoc(), "expected '('");
953 return MatchOperand_ParseFail;
954 }
955 getParser().Lex(); // Eat '('
956
957 const MCExpr *SubExpr;
958 if (getParser().parseParenExpression(SubExpr, E)) {
959 return MatchOperand_ParseFail;
960 }
961
962 const MCExpr *ModExpr = RISCVMCExpr::create(SubExpr, VK, getContext());
Alex Bradburya6e62482017-12-07 10:53:48 +0000963 Operands.push_back(RISCVOperand::createImm(ModExpr, S, E, isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000964 return MatchOperand_Success;
965}
966
967OperandMatchResultTy
968RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
969 if (getLexer().isNot(AsmToken::LParen)) {
970 Error(getLoc(), "expected '('");
Alex Bradbury04f06d92017-08-08 14:43:36 +0000971 return MatchOperand_ParseFail;
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000972 }
Alex Bradbury04f06d92017-08-08 14:43:36 +0000973
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000974 getParser().Lex(); // Eat '('
Alex Bradburya6e62482017-12-07 10:53:48 +0000975 Operands.push_back(RISCVOperand::createToken("(", getLoc(), isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000976
977 if (parseRegister(Operands) != MatchOperand_Success) {
978 Error(getLoc(), "expected register");
979 return MatchOperand_ParseFail;
980 }
981
982 if (getLexer().isNot(AsmToken::RParen)) {
983 Error(getLoc(), "expected ')'");
984 return MatchOperand_ParseFail;
985 }
986
987 getParser().Lex(); // Eat ')'
Alex Bradburya6e62482017-12-07 10:53:48 +0000988 Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
Alex Bradbury6758ecb2017-09-17 14:27:35 +0000989
Alex Bradbury04f06d92017-08-08 14:43:36 +0000990 return MatchOperand_Success;
991}
992
Alex Bradburycd8688a2018-04-25 17:25:29 +0000993/// Looks at a token type and creates the relevant operand from this
994/// information, adding to Operands. If operand was parsed, returns false, else
995/// true. If ForceImmediate is true, no attempt will be made to parse the
996/// operand as a register, which is needed for pseudoinstructions such as
997/// call.
998bool RISCVAsmParser::parseOperand(OperandVector &Operands,
999 bool ForceImmediate) {
1000 // Attempt to parse token as register, unless ForceImmediate.
1001 if (!ForceImmediate && parseRegister(Operands, true) == MatchOperand_Success)
Alex Bradbury04f06d92017-08-08 14:43:36 +00001002 return false;
1003
1004 // Attempt to parse token as an immediate
Alex Bradbury6758ecb2017-09-17 14:27:35 +00001005 if (parseImmediate(Operands) == MatchOperand_Success) {
1006 // Parse memory base register if present
1007 if (getLexer().is(AsmToken::LParen))
1008 return parseMemOpBaseReg(Operands) != MatchOperand_Success;
Alex Bradbury04f06d92017-08-08 14:43:36 +00001009 return false;
Alex Bradbury6758ecb2017-09-17 14:27:35 +00001010 }
Alex Bradbury04f06d92017-08-08 14:43:36 +00001011
1012 // Finally we have exhausted all options and must declare defeat.
1013 Error(getLoc(), "unknown operand");
1014 return true;
1015}
1016
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001017/// Return true if the operand at the OperandIdx for opcode Name should be
1018/// 'forced' to be parsed as an immediate. This is required for
1019/// pseudoinstructions such as tail or call, which allow bare symbols to be used
1020/// that could clash with register names.
1021static bool shouldForceImediateOperand(StringRef Name, unsigned OperandIdx) {
1022 // FIXME: This may not scale so perhaps we want to use a data-driven approach
1023 // instead.
1024 switch (OperandIdx) {
1025 case 0:
1026 // call imm
1027 // tail imm
1028 return Name == "tail" || Name == "call";
1029 case 1:
1030 // lla rdest, imm
1031 return Name == "lla";
1032 default:
1033 return false;
1034 }
1035}
1036
Alex Bradbury04f06d92017-08-08 14:43:36 +00001037bool RISCVAsmParser::ParseInstruction(ParseInstructionInfo &Info,
1038 StringRef Name, SMLoc NameLoc,
1039 OperandVector &Operands) {
1040 // First operand is token for instruction
Alex Bradburya6e62482017-12-07 10:53:48 +00001041 Operands.push_back(RISCVOperand::createToken(Name, NameLoc, isRV64()));
Alex Bradbury04f06d92017-08-08 14:43:36 +00001042
1043 // If there are no more operands, then finish
1044 if (getLexer().is(AsmToken::EndOfStatement))
1045 return false;
1046
1047 // Parse first operand
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001048 if (parseOperand(Operands, shouldForceImediateOperand(Name, 0)))
Alex Bradbury04f06d92017-08-08 14:43:36 +00001049 return true;
1050
1051 // Parse until end of statement, consuming commas between operands
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001052 unsigned OperandIdx = 1;
Alex Bradbury04f06d92017-08-08 14:43:36 +00001053 while (getLexer().is(AsmToken::Comma)) {
1054 // Consume comma token
1055 getLexer().Lex();
1056
1057 // Parse next operand
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001058 if (parseOperand(Operands, shouldForceImediateOperand(Name, OperandIdx)))
Alex Bradbury04f06d92017-08-08 14:43:36 +00001059 return true;
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001060
1061 ++OperandIdx;
Alex Bradbury04f06d92017-08-08 14:43:36 +00001062 }
1063
1064 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1065 SMLoc Loc = getLexer().getLoc();
1066 getParser().eatToEndOfStatement();
1067 return Error(Loc, "unexpected token");
1068 }
1069
1070 getParser().Lex(); // Consume the EndOfStatement.
1071 return false;
1072}
1073
Alex Bradbury9d3f1252017-09-28 08:26:24 +00001074bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
1075 RISCVMCExpr::VariantKind &Kind,
1076 int64_t &Addend) {
1077 Kind = RISCVMCExpr::VK_RISCV_None;
1078 Addend = 0;
1079
1080 if (const RISCVMCExpr *RE = dyn_cast<RISCVMCExpr>(Expr)) {
1081 Kind = RE->getKind();
1082 Expr = RE->getSubExpr();
1083 }
1084
1085 // It's a simple symbol reference or constant with no addend.
1086 if (isa<MCConstantExpr>(Expr) || isa<MCSymbolRefExpr>(Expr))
1087 return true;
1088
1089 const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr);
1090 if (!BE)
1091 return false;
1092
1093 if (!isa<MCSymbolRefExpr>(BE->getLHS()))
1094 return false;
1095
1096 if (BE->getOpcode() != MCBinaryExpr::Add &&
1097 BE->getOpcode() != MCBinaryExpr::Sub)
1098 return false;
1099
1100 // We are able to support the subtraction of two symbol references
1101 if (BE->getOpcode() == MCBinaryExpr::Sub &&
1102 isa<MCSymbolRefExpr>(BE->getRHS()))
1103 return true;
1104
Hiroshi Inoue9ff23802018-04-09 04:37:53 +00001105 // See if the addend is a constant, otherwise there's more going
Alex Bradbury9d3f1252017-09-28 08:26:24 +00001106 // on here than we can deal with.
1107 auto AddendExpr = dyn_cast<MCConstantExpr>(BE->getRHS());
1108 if (!AddendExpr)
1109 return false;
1110
1111 Addend = AddendExpr->getValue();
1112 if (BE->getOpcode() == MCBinaryExpr::Sub)
1113 Addend = -Addend;
1114
1115 // It's some symbol reference + a constant addend
1116 return Kind != RISCVMCExpr::VK_RISCV_Invalid;
1117}
1118
Alex Bradburybca0c3c2018-05-11 17:30:28 +00001119bool RISCVAsmParser::ParseDirective(AsmToken DirectiveID) {
1120 // This returns false if this function recognizes the directive
1121 // regardless of whether it is successfully handles or reports an
1122 // error. Otherwise it returns true to give the generic parser a
1123 // chance at recognizing it.
1124 StringRef IDVal = DirectiveID.getString();
1125
1126 if (IDVal == ".option")
1127 return parseDirectiveOption();
1128
1129 return true;
1130}
1131
1132bool RISCVAsmParser::parseDirectiveOption() {
1133 MCAsmParser &Parser = getParser();
1134 // Get the option token.
1135 AsmToken Tok = Parser.getTok();
1136 // At the moment only identifiers are supported.
1137 if (Tok.isNot(AsmToken::Identifier))
1138 return Error(Parser.getTok().getLoc(),
1139 "unexpected token, expected identifier");
1140
1141 StringRef Option = Tok.getIdentifier();
1142
1143 if (Option == "rvc") {
1144 getTargetStreamer().emitDirectiveOptionRVC();
1145
1146 Parser.Lex();
1147 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1148 return Error(Parser.getTok().getLoc(),
1149 "unexpected token, expected end of statement");
1150
1151 setFeatureBits(RISCV::FeatureStdExtC, "c");
1152 return false;
1153 }
1154
1155 if (Option == "norvc") {
1156 getTargetStreamer().emitDirectiveOptionNoRVC();
1157
1158 Parser.Lex();
1159 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1160 return Error(Parser.getTok().getLoc(),
1161 "unexpected token, expected end of statement");
1162
1163 clearFeatureBits(RISCV::FeatureStdExtC, "c");
1164 return false;
1165 }
1166
1167 // Unknown option.
1168 Warning(Parser.getTok().getLoc(),
1169 "unknown option, expected 'rvc' or 'norvc'");
1170 Parser.eatToEndOfStatement();
1171 return false;
1172}
Alex Bradbury04f06d92017-08-08 14:43:36 +00001173
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001174void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
1175 MCInst CInst;
1176 bool Res = compressInst(CInst, Inst, getSTI(), S.getContext());
1177 CInst.setLoc(Inst.getLoc());
1178 S.EmitInstruction((Res ? CInst : Inst), getSTI());
1179}
1180
1181void RISCVAsmParser::emitLoadImm(unsigned DestReg, int64_t Value,
1182 MCStreamer &Out) {
1183 if (isInt<32>(Value)) {
1184 // Emits the MC instructions for loading a 32-bit constant into a register.
1185 //
1186 // Depending on the active bits in the immediate Value v, the following
1187 // instruction sequences are emitted:
1188 //
1189 // v == 0 : ADDI(W)
1190 // v[0,12) != 0 && v[12,32) == 0 : ADDI(W)
1191 // v[0,12) == 0 && v[12,32) != 0 : LUI
1192 // v[0,32) != 0 : LUI+ADDI(W)
1193 //
1194 int64_t Hi20 = ((Value + 0x800) >> 12) & 0xFFFFF;
1195 int64_t Lo12 = SignExtend64<12>(Value);
1196 unsigned SrcReg = RISCV::X0;
1197
1198 if (Hi20) {
1199 emitToStreamer(Out,
1200 MCInstBuilder(RISCV::LUI).addReg(DestReg).addImm(Hi20));
1201 SrcReg = DestReg;
1202 }
1203
1204 if (Lo12 || Hi20 == 0) {
1205 unsigned AddiOpcode =
1206 STI->hasFeature(RISCV::Feature64Bit) ? RISCV::ADDIW : RISCV::ADDI;
1207 emitToStreamer(Out, MCInstBuilder(AddiOpcode)
1208 .addReg(DestReg)
1209 .addReg(SrcReg)
1210 .addImm(Lo12));
1211 }
1212 return;
1213 }
1214 assert(STI->hasFeature(RISCV::Feature64Bit) &&
1215 "Target must be 64-bit to support a >32-bit constant");
1216
1217 // In the worst case, for a full 64-bit constant, a sequence of 8 instructions
1218 // (i.e., LUI+ADDIW+SLLI+ADDI+SLLI+ADDI+SLLI+ADDI) has to be emmitted. Note
1219 // that the first two instructions (LUI+ADDIW) can contribute up to 32 bits
1220 // while the following ADDI instructions contribute up to 12 bits each.
1221 //
1222 // On the first glance, implementing this seems to be possible by simply
1223 // emitting the most significant 32 bits (LUI+ADDIW) followed by as many left
1224 // shift (SLLI) and immediate additions (ADDI) as needed. However, due to the
1225 // fact that ADDI performs a sign extended addition, doing it like that would
1226 // only be possible when at most 11 bits of the ADDI instructions are used.
1227 // Using all 12 bits of the ADDI instructions, like done by GAS, actually
1228 // requires that the constant is processed starting with the least significant
1229 // bit.
1230 //
1231 // In the following, constants are processed from LSB to MSB but instruction
1232 // emission is performed from MSB to LSB by recursively calling
1233 // emitLoadImm. In each recursion, first the lowest 12 bits are removed
1234 // from the constant and the optimal shift amount, which can be greater than
1235 // 12 bits if the constant is sparse, is determined. Then, the shifted
1236 // remaining constant is processed recursively and gets emitted as soon as it
1237 // fits into 32 bits. The emission of the shifts and additions is subsequently
1238 // performed when the recursion returns.
1239 //
1240 int64_t Lo12 = SignExtend64<12>(Value);
1241 int64_t Hi52 = (Value + 0x800) >> 12;
1242 int ShiftAmount = 12 + findFirstSet((uint64_t)Hi52);
1243 Hi52 = SignExtend64(Hi52 >> (ShiftAmount - 12), 64 - ShiftAmount);
1244
1245 emitLoadImm(DestReg, Hi52, Out);
1246
1247 emitToStreamer(Out, MCInstBuilder(RISCV::SLLI)
1248 .addReg(DestReg)
1249 .addReg(DestReg)
1250 .addImm(ShiftAmount));
1251
1252 if (Lo12)
1253 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
1254 .addReg(DestReg)
1255 .addReg(DestReg)
1256 .addImm(Lo12));
1257}
1258
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001259void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
1260 MCStreamer &Out) {
1261 // The local load address pseudo-instruction "lla" is used in PC-relative
1262 // addressing of symbols:
1263 // lla rdest, symbol
1264 // expands to
1265 // TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
1266 // ADDI rdest, %pcrel_lo(TmpLabel)
1267 MCContext &Ctx = getContext();
1268
1269 MCSymbol *TmpLabel = Ctx.createTempSymbol(
1270 "pcrel_hi", /* AlwaysAddSuffix */ true, /* CanBeUnnamed */ false);
1271 Out.EmitLabel(TmpLabel);
1272
1273 MCOperand DestReg = Inst.getOperand(0);
1274 const RISCVMCExpr *Symbol = RISCVMCExpr::create(
1275 Inst.getOperand(1).getExpr(), RISCVMCExpr::VK_RISCV_PCREL_HI, Ctx);
1276
Roger Ferrer Ibanezc8f4dbb2018-08-14 08:30:42 +00001277 emitToStreamer(
1278 Out, MCInstBuilder(RISCV::AUIPC).addOperand(DestReg).addExpr(Symbol));
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001279
1280 const MCExpr *RefToLinkTmpLabel =
1281 RISCVMCExpr::create(MCSymbolRefExpr::create(TmpLabel, Ctx),
1282 RISCVMCExpr::VK_RISCV_PCREL_LO, Ctx);
1283
Roger Ferrer Ibanezc8f4dbb2018-08-14 08:30:42 +00001284 emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
1285 .addOperand(DestReg)
1286 .addOperand(DestReg)
1287 .addExpr(RefToLinkTmpLabel));
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001288}
1289
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001290bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
1291 MCStreamer &Out) {
1292 Inst.setLoc(IDLoc);
1293
1294 if (Inst.getOpcode() == RISCV::PseudoLI) {
1295 auto Reg = Inst.getOperand(0).getReg();
1296 int64_t Imm = Inst.getOperand(1).getImm();
1297 // On RV32 the immediate here can either be a signed or an unsigned
1298 // 32-bit number. Sign extension has to be performed to ensure that Imm
1299 // represents the expected signed 64-bit number.
1300 if (!isRV64())
1301 Imm = SignExtend64<32>(Imm);
1302 emitLoadImm(Reg, Imm, Out);
1303 return false;
Roger Ferrer Ibanez577a97e2018-08-09 07:08:20 +00001304 } else if (Inst.getOpcode() == RISCV::PseudoLLA) {
1305 emitLoadLocalAddress(Inst, IDLoc, Out);
1306 return false;
Alex Bradbury6a4b5442018-06-07 15:35:47 +00001307 }
1308
1309 emitToStreamer(Out, Inst);
1310 return false;
1311}
1312
Alex Bradbury04f06d92017-08-08 14:43:36 +00001313extern "C" void LLVMInitializeRISCVAsmParser() {
1314 RegisterMCAsmParser<RISCVAsmParser> X(getTheRISCV32Target());
1315 RegisterMCAsmParser<RISCVAsmParser> Y(getTheRISCV64Target());
1316}