Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- RISCVAsmParser.cpp - Parse RISCV assembly to MCInst instructions --===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include "MCTargetDesc/RISCVAsmBackend.h"
10
#include "MCTargetDesc/RISCVMCExpr.h"
11
#include "MCTargetDesc/RISCVMCTargetDesc.h"
12
#include "MCTargetDesc/RISCVTargetStreamer.h"
13
#include "TargetInfo/RISCVTargetInfo.h"
14
#include "Utils/RISCVBaseInfo.h"
15
#include "Utils/RISCVMatInt.h"
16
#include "llvm/ADT/STLExtras.h"
17
#include "llvm/ADT/SmallVector.h"
18
#include "llvm/ADT/StringSwitch.h"
19
#include "llvm/MC/MCAssembler.h"
20
#include "llvm/MC/MCContext.h"
21
#include "llvm/MC/MCExpr.h"
22
#include "llvm/MC/MCInst.h"
23
#include "llvm/MC/MCInstBuilder.h"
24
#include "llvm/MC/MCObjectFileInfo.h"
25
#include "llvm/MC/MCParser/MCAsmLexer.h"
26
#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
27
#include "llvm/MC/MCParser/MCTargetAsmParser.h"
28
#include "llvm/MC/MCRegisterInfo.h"
29
#include "llvm/MC/MCStreamer.h"
30
#include "llvm/MC/MCSubtargetInfo.h"
31
#include "llvm/Support/Casting.h"
32
#include "llvm/Support/MathExtras.h"
33
#include "llvm/Support/TargetRegistry.h"
34
35
#include <limits>
36
37
using namespace llvm;
38
39
// Include the auto-generated portion of the compress emitter.
40
#define GEN_COMPRESS_INSTR
41
#include "RISCVGenCompressInstEmitter.inc"
42
43
namespace {
44
struct RISCVOperand;
45
46
class RISCVAsmParser : public MCTargetAsmParser {
47
  SmallVector<FeatureBitset, 4> FeatureBitStack;
48
49
33.8k
  SMLoc getLoc() const { return getParser().getTok().getLoc(); }
50
26.1k
  bool isRV64() const { return getSTI().hasFeature(RISCV::Feature64Bit); }
51
12.4k
  bool isRV32E() const { return getSTI().hasFeature(RISCV::FeatureRV32E); }
52
53
360
  RISCVTargetStreamer &getTargetStreamer() {
54
360
    MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
55
360
    return static_cast<RISCVTargetStreamer &>(TS);
56
360
  }
57
58
  unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
59
                                      unsigned Kind) override;
60
61
  bool generateImmOutOfRangeError(OperandVector &Operands, uint64_t ErrorInfo,
62
                                  int64_t Lower, int64_t Upper, Twine Msg);
63
64
  bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
65
                               OperandVector &Operands, MCStreamer &Out,
66
                               uint64_t &ErrorInfo,
67
                               bool MatchingInlineAsm) override;
68
69
  bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
70
71
  bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
72
                        SMLoc NameLoc, OperandVector &Operands) override;
73
74
  bool ParseDirective(AsmToken DirectiveID) override;
75
76
  // Helper to actually emit an instruction to the MCStreamer. Also, when
77
  // possible, compression of the instruction is performed.
78
  void emitToStreamer(MCStreamer &S, const MCInst &Inst);
79
80
  // Helper to emit a combination of LUI, ADDI(W), and SLLI instructions that
81
  // synthesize the desired immedate value into the destination register.
82
  void emitLoadImm(unsigned DestReg, int64_t Value, MCStreamer &Out);
83
84
  // Helper to emit a combination of AUIPC and SecondOpcode. Used to implement
85
  // helpers such as emitLoadLocalAddress and emitLoadAddress.
86
  void emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
87
                         const MCExpr *Symbol, RISCVMCExpr::VariantKind VKHi,
88
                         unsigned SecondOpcode, SMLoc IDLoc, MCStreamer &Out);
89
90
  // Helper to emit pseudo instruction "lla" used in PC-rel addressing.
91
  void emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
92
93
  // Helper to emit pseudo instruction "la" used in GOT/PC-rel addressing.
94
  void emitLoadAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
95
96
  // Helper to emit pseudo instruction "la.tls.ie" used in initial-exec TLS
97
  // addressing.
98
  void emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
99
100
  // Helper to emit pseudo instruction "la.tls.gd" used in global-dynamic TLS
101
  // addressing.
102
  void emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
103
104
  // Helper to emit pseudo load/store instruction with a symbol.
105
  void emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
106
                           MCStreamer &Out, bool HasTmpReg);
107
108
  // Checks that a PseudoAddTPRel is using x4/tp in its second input operand.
109
  // Enforcing this using a restricted register class for the second input
110
  // operand of PseudoAddTPRel results in a poor diagnostic due to the fact
111
  // 'add' is an overloaded mnemonic.
112
  bool checkPseudoAddTPRel(MCInst &Inst, OperandVector &Operands);
113
114
  /// Helper for processing MC instructions that have been successfully matched
115
  /// by MatchAndEmitInstruction. Modifications to the emitted instructions,
116
  /// like the expansion of pseudo instructions (e.g., "li"), can be performed
117
  /// in this method.
118
  bool processInstruction(MCInst &Inst, SMLoc IDLoc, OperandVector &Operands,
119
                          MCStreamer &Out);
120
121
// Auto-generated instruction matching functions
122
#define GET_ASSEMBLER_HEADER
123
#include "RISCVGenAsmMatcher.inc"
124
125
  OperandMatchResultTy parseCSRSystemRegister(OperandVector &Operands);
126
  OperandMatchResultTy parseImmediate(OperandVector &Operands);
127
  OperandMatchResultTy parseRegister(OperandVector &Operands,
128
                                     bool AllowParens = false);
129
  OperandMatchResultTy parseMemOpBaseReg(OperandVector &Operands);
130
  OperandMatchResultTy parseOperandWithModifier(OperandVector &Operands);
131
  OperandMatchResultTy parseBareSymbol(OperandVector &Operands);
132
  OperandMatchResultTy parseCallSymbol(OperandVector &Operands);
133
  OperandMatchResultTy parseJALOffset(OperandVector &Operands);
134
135
  bool parseOperand(OperandVector &Operands, StringRef Mnemonic);
136
137
  bool parseDirectiveOption();
138
139
34
  void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
140
34
    if (!(getSTI().getFeatureBits()[Feature])) {
141
34
      MCSubtargetInfo &STI = copySTI();
142
34
      setAvailableFeatures(
143
34
          ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
144
34
    }
145
34
  }
146
147
34
  void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
148
34
    if (getSTI().getFeatureBits()[Feature]) {
149
22
      MCSubtargetInfo &STI = copySTI();
150
22
      setAvailableFeatures(
151
22
          ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
152
22
    }
153
34
  }
154
155
20
  void pushFeatureBits() {
156
20
    FeatureBitStack.push_back(getSTI().getFeatureBits());
157
20
  }
158
159
21
  bool popFeatureBits() {
160
21
    if (FeatureBitStack.empty())
161
1
      return true;
162
20
163
20
    FeatureBitset FeatureBits = FeatureBitStack.pop_back_val();
164
20
    copySTI().setFeatureBits(FeatureBits);
165
20
    setAvailableFeatures(ComputeAvailableFeatures(FeatureBits));
166
20
167
20
    return false;
168
20
  }
169
public:
170
  enum RISCVMatchResultTy {
171
    Match_Dummy = FIRST_TARGET_MATCH_RESULT_TY,
172
#define GET_OPERAND_DIAGNOSTIC_TYPES
173
#include "RISCVGenAsmMatcher.inc"
174
#undef GET_OPERAND_DIAGNOSTIC_TYPES
175
  };
176
177
  static bool classifySymbolRef(const MCExpr *Expr,
178
                                RISCVMCExpr::VariantKind &Kind,
179
                                int64_t &Addend);
180
181
  RISCVAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
182
                 const MCInstrInfo &MII, const MCTargetOptions &Options)
183
417
      : MCTargetAsmParser(Options, STI, MII) {
184
417
    Parser.addAliasForDirective(".half", ".2byte");
185
417
    Parser.addAliasForDirective(".hword", ".2byte");
186
417
    Parser.addAliasForDirective(".word", ".4byte");
187
417
    Parser.addAliasForDirective(".dword", ".8byte");
188
417
    setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
189
417
  }
190
};
191
192
/// RISCVOperand - Instances of this class represent a parsed machine
193
/// instruction
194
struct RISCVOperand : public MCParsedAsmOperand {
195
196
  enum KindTy {
197
    Token,
198
    Register,
199
    Immediate,
200
    SystemRegister
201
  } Kind;
202
203
  bool IsRV64;
204
205
  struct RegOp {
206
    unsigned RegNum;
207
  };
208
209
  struct ImmOp {
210
    const MCExpr *Val;
211
  };
212
213
  struct SysRegOp {
214
    const char *Data;
215
    unsigned Length;
216
    unsigned Encoding;
217
    // FIXME: Add the Encoding parsed fields as needed for checks,
218
    // e.g.: read/write or user/supervisor/machine privileges.
219
  };
220
221
  SMLoc StartLoc, EndLoc;
222
  union {
223
    StringRef Tok;
224
    RegOp Reg;
225
    ImmOp Imm;
226
    struct SysRegOp SysReg;
227
  };
228
229
25.3k
  RISCVOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
230
231
public:
232
0
  RISCVOperand(const RISCVOperand &o) : MCParsedAsmOperand() {
233
0
    Kind = o.Kind;
234
0
    IsRV64 = o.IsRV64;
235
0
    StartLoc = o.StartLoc;
236
0
    EndLoc = o.EndLoc;
237
0
    switch (Kind) {
238
0
    case Register:
239
0
      Reg = o.Reg;
240
0
      break;
241
0
    case Immediate:
242
0
      Imm = o.Imm;
243
0
      break;
244
0
    case Token:
245
0
      Tok = o.Tok;
246
0
      break;
247
0
    case SystemRegister:
248
0
      SysReg = o.SysReg;
249
0
      break;
250
0
    }
251
0
  }
252
253
22.1k
  bool isToken() const override { return Kind == Token; }
254
17.7k
  bool isReg() const override { return Kind == Register; }
255
3.77k
  bool isImm() const override { return Kind == Immediate; }
256
0
  bool isMem() const override { return false; }
257
1.88k
  bool isSystemRegister() const { return Kind == SystemRegister; }
258
259
  static bool evaluateConstantImm(const MCExpr *Expr, int64_t &Imm,
260
5.74k
                                  RISCVMCExpr::VariantKind &VK) {
261
5.74k
    if (auto *RE = dyn_cast<RISCVMCExpr>(Expr)) {
262
1.16k
      VK = RE->getKind();
263
1.16k
      return RE->evaluateAsConstant(Imm);
264
1.16k
    }
265
4.58k
266
4.58k
    if (auto CE = dyn_cast<MCConstantExpr>(Expr)) {
267
3.71k
      VK = RISCVMCExpr::VK_RISCV_None;
268
3.71k
      Imm = CE->getValue();
269
3.71k
      return true;
270
3.71k
    }
271
864
272
864
    return false;
273
864
  }
274
275
  // True if operand is a symbol with no modifiers, or a constant with no
276
  // modifiers and isShiftedInt<N-1, 1>(Op).
277
578
  template <int N> bool isBareSimmNLsb0() const {
278
578
    int64_t Imm;
279
578
    RISCVMCExpr::VariantKind VK;
280
578
    if (!isImm())
281
85
      return false;
282
493
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
283
493
    bool IsValid;
284
493
    if (!IsConstantImm)
285
274
      IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
286
219
    else
287
219
      IsValid = isShiftedInt<N - 1, 1>(Imm);
288
493
    return IsValid && 
VK == RISCVMCExpr::VK_RISCV_None476
;
289
493
  }
RISCVAsmParser.cpp:bool (anonymous namespace)::RISCVOperand::isBareSimmNLsb0<21>() const
Line
Count
Source
277
226
  template <int N> bool isBareSimmNLsb0() const {
278
226
    int64_t Imm;
279
226
    RISCVMCExpr::VariantKind VK;
280
226
    if (!isImm())
281
85
      return false;
282
141
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
283
141
    bool IsValid;
284
141
    if (!IsConstantImm)
285
84
      IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
286
57
    else
287
57
      IsValid = isShiftedInt<N - 1, 1>(Imm);
288
141
    return IsValid && 
VK == RISCVMCExpr::VK_RISCV_None135
;
289
141
  }
RISCVAsmParser.cpp:bool (anonymous namespace)::RISCVOperand::isBareSimmNLsb0<13>() const
Line
Count
Source
277
188
  template <int N> bool isBareSimmNLsb0() const {
278
188
    int64_t Imm;
279
188
    RISCVMCExpr::VariantKind VK;
280
188
    if (!isImm())
281
0
      return false;
282
188
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
283
188
    bool IsValid;
284
188
    if (!IsConstantImm)
285
46
      IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
286
142
    else
287
142
      IsValid = isShiftedInt<N - 1, 1>(Imm);
288
188
    return IsValid && 
VK == RISCVMCExpr::VK_RISCV_None181
;
289
188
  }
RISCVAsmParser.cpp:bool (anonymous namespace)::RISCVOperand::isBareSimmNLsb0<9>() const
Line
Count
Source
277
91
  template <int N> bool isBareSimmNLsb0() const {
278
91
    int64_t Imm;
279
91
    RISCVMCExpr::VariantKind VK;
280
91
    if (!isImm())
281
0
      return false;
282
91
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
283
91
    bool IsValid;
284
91
    if (!IsConstantImm)
285
81
      IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
286
10
    else
287
10
      IsValid = isShiftedInt<N - 1, 1>(Imm);
288
91
    return IsValid && 
VK == RISCVMCExpr::VK_RISCV_None89
;
289
91
  }
RISCVAsmParser.cpp:bool (anonymous namespace)::RISCVOperand::isBareSimmNLsb0<12>() const
Line
Count
Source
277
73
  template <int N> bool isBareSimmNLsb0() const {
278
73
    int64_t Imm;
279
73
    RISCVMCExpr::VariantKind VK;
280
73
    if (!isImm())
281
0
      return false;
282
73
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
283
73
    bool IsValid;
284
73
    if (!IsConstantImm)
285
63
      IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
286
10
    else
287
10
      IsValid = isShiftedInt<N - 1, 1>(Imm);
288
73
    return IsValid && 
VK == RISCVMCExpr::VK_RISCV_None71
;
289
73
  }
290
291
  // Predicate methods for AsmOperands defined in RISCVInstrInfo.td
292
293
664
  bool isBareSymbol() const {
294
664
    int64_t Imm;
295
664
    RISCVMCExpr::VariantKind VK;
296
664
    // Must be of 'immediate' type but not a constant.
297
664
    if (!isImm() || 
evaluateConstantImm(getImm(), Imm, VK)588
)
298
393
      return false;
299
271
    return RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm) &&
300
271
           VK == RISCVMCExpr::VK_RISCV_None;
301
271
  }
302
303
172
  bool isCallSymbol() const {
304
172
    int64_t Imm;
305
172
    RISCVMCExpr::VariantKind VK;
306
172
    // Must be of 'immediate' type but not a constant.
307
172
    if (!isImm() || 
evaluateConstantImm(getImm(), Imm, VK)166
)
308
15
      return false;
309
157
    return RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm) &&
310
157
           (VK == RISCVMCExpr::VK_RISCV_CALL ||
311
157
            
VK == RISCVMCExpr::VK_RISCV_CALL_PLT39
);
312
157
  }
313
314
8
  bool isTPRelAddSymbol() const {
315
8
    int64_t Imm;
316
8
    RISCVMCExpr::VariantKind VK;
317
8
    // Must be of 'immediate' type but not a constant.
318
8
    if (!isImm() || evaluateConstantImm(getImm(), Imm, VK))
319
0
      return false;
320
8
    return RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm) &&
321
8
           VK == RISCVMCExpr::VK_RISCV_TPREL_ADD;
322
8
  }
323
324
1.88k
  bool isCSRSystemRegister() const { return isSystemRegister(); }
325
326
  /// Return true if the operand is a valid for the fence instruction e.g.
327
  /// ('iorw').
328
47
  bool isFenceArg() const {
329
47
    if (!isImm())
330
0
      return false;
331
47
    const MCExpr *Val = getImm();
332
47
    auto *SVal = dyn_cast<MCSymbolRefExpr>(Val);
333
47
    if (!SVal || 
SVal->getKind() != MCSymbolRefExpr::VK_None42
)
334
5
      return false;
335
42
336
42
    StringRef Str = SVal->getSymbol().getName();
337
42
    // Letters must be unique, taken from 'iorw', and in ascending order. This
338
42
    // holds as long as each individual character is one of 'iorw' and is
339
42
    // greater than the previous character.
340
42
    char Prev = '\0';
341
99
    for (char c : Str) {
342
99
      if (c != 'i' && 
c != 'o'77
&&
c != 'r'59
&&
c != 'w'29
)
343
2
        return false;
344
97
      if (c <= Prev)
345
2
        return false;
346
95
      Prev = c;
347
95
    }
348
42
    
return true38
;
349
42
  }
350
351
  /// Return true if the operand is a valid floating point rounding mode.
352
255
  bool isFRMArg() const {
353
255
    if (!isImm())
354
0
      return false;
355
255
    const MCExpr *Val = getImm();
356
255
    auto *SVal = dyn_cast<MCSymbolRefExpr>(Val);
357
255
    if (!SVal || 
SVal->getKind() != MCSymbolRefExpr::VK_None253
)
358
2
      return false;
359
253
360
253
    StringRef Str = SVal->getSymbol().getName();
361
253
362
253
    return RISCVFPRndMode::stringToRoundingMode(Str) != RISCVFPRndMode::Invalid;
363
253
  }
364
365
354
  bool isImmXLenLI() const {
366
354
    int64_t Imm;
367
354
    RISCVMCExpr::VariantKind VK;
368
354
    if (!isImm())
369
0
      return false;
370
354
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
371
354
    if (VK == RISCVMCExpr::VK_RISCV_LO || 
VK == RISCVMCExpr::VK_RISCV_PCREL_LO338
)
372
32
      return true;
373
322
    // Given only Imm, ensuring that the actually specified constant is either
374
322
    // a signed or unsigned 64-bit number is unfortunately impossible.
375
322
    bool IsInRange = isRV64() ? 
true178
:
isInt<32>(Imm)144
||
isUInt<32>(Imm)18
;
376
322
    return IsConstantImm && 
IsInRange318
&&
VK == RISCVMCExpr::VK_RISCV_None314
;
377
322
  }
378
379
110
  bool isUImmLog2XLen() const {
380
110
    int64_t Imm;
381
110
    RISCVMCExpr::VariantKind VK;
382
110
    if (!isImm())
383
0
      return false;
384
110
    if (!evaluateConstantImm(getImm(), Imm, VK) ||
385
110
        
VK != RISCVMCExpr::VK_RISCV_None109
)
386
3
      return false;
387
107
    return (isRV64() && 
isUInt<6>(Imm)52
) ||
isUInt<5>(Imm)67
;
388
107
  }
389
390
30
  bool isUImmLog2XLenNonZero() const {
391
30
    int64_t Imm;
392
30
    RISCVMCExpr::VariantKind VK;
393
30
    if (!isImm())
394
0
      return false;
395
30
    if (!evaluateConstantImm(getImm(), Imm, VK) ||
396
30
        VK != RISCVMCExpr::VK_RISCV_None)
397
0
      return false;
398
30
    if (Imm == 0)
399
2
      return false;
400
28
    return (isRV64() && 
isUInt<6>(Imm)17
) ||
isUInt<5>(Imm)13
;
401
28
  }
402
403
239
  bool isUImm5() const {
404
239
    int64_t Imm;
405
239
    RISCVMCExpr::VariantKind VK;
406
239
    if (!isImm())
407
17
      return false;
408
222
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
409
222
    return IsConstantImm && 
isUInt<5>(Imm)216
&&
VK == RISCVMCExpr::VK_RISCV_None198
;
410
222
  }
411
412
0
  bool isUImm5NonZero() const {
413
0
    int64_t Imm;
414
0
    RISCVMCExpr::VariantKind VK;
415
0
    if (!isImm())
416
0
      return false;
417
0
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
418
0
    return IsConstantImm && isUInt<5>(Imm) && (Imm != 0) &&
419
0
           VK == RISCVMCExpr::VK_RISCV_None;
420
0
  }
421
422
29
  bool isSImm6() const {
423
29
    if (!isImm())
424
0
      return false;
425
29
    RISCVMCExpr::VariantKind VK;
426
29
    int64_t Imm;
427
29
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
428
29
    return IsConstantImm && 
isInt<6>(Imm)20
&&
429
29
           
VK == RISCVMCExpr::VK_RISCV_None16
;
430
29
  }
431
432
11
  bool isSImm6NonZero() const {
433
11
    if (!isImm())
434
0
      return false;
435
11
    RISCVMCExpr::VariantKind VK;
436
11
    int64_t Imm;
437
11
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
438
11
    return IsConstantImm && 
isInt<6>(Imm)8
&&
(Imm != 0)6
&&
439
11
           
VK == RISCVMCExpr::VK_RISCV_None5
;
440
11
  }
441
442
20
  bool isCLUIImm() const {
443
20
    if (!isImm())
444
0
      return false;
445
20
    int64_t Imm;
446
20
    RISCVMCExpr::VariantKind VK;
447
20
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
448
20
    return IsConstantImm && (Imm != 0) &&
449
20
           
(19
isUInt<5>(Imm)19
||
(11
Imm >= 0xfffe011
&&
Imm <= 0xfffff10
)) &&
450
20
           
VK == RISCVMCExpr::VK_RISCV_None16
;
451
20
  }
452
453
24
  bool isUImm7Lsb00() const {
454
24
    if (!isImm())
455
0
      return false;
456
24
    int64_t Imm;
457
24
    RISCVMCExpr::VariantKind VK;
458
24
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
459
24
    return IsConstantImm && isShiftedUInt<5, 2>(Imm) &&
460
24
           
VK == RISCVMCExpr::VK_RISCV_None20
;
461
24
  }
462
463
22
  bool isUImm8Lsb00() const {
464
22
    if (!isImm())
465
0
      return false;
466
22
    int64_t Imm;
467
22
    RISCVMCExpr::VariantKind VK;
468
22
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
469
22
    return IsConstantImm && isShiftedUInt<6, 2>(Imm) &&
470
22
           
VK == RISCVMCExpr::VK_RISCV_None18
;
471
22
  }
472
473
28
  bool isUImm8Lsb000() const {
474
28
    if (!isImm())
475
0
      return false;
476
28
    int64_t Imm;
477
28
    RISCVMCExpr::VariantKind VK;
478
28
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
479
28
    return IsConstantImm && isShiftedUInt<5, 3>(Imm) &&
480
28
           
VK == RISCVMCExpr::VK_RISCV_None24
;
481
28
  }
482
483
91
  bool isSImm9Lsb0() const { return isBareSimmNLsb0<9>(); }
484
485
28
  bool isUImm9Lsb000() const {
486
28
    if (!isImm())
487
0
      return false;
488
28
    int64_t Imm;
489
28
    RISCVMCExpr::VariantKind VK;
490
28
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
491
28
    return IsConstantImm && isShiftedUInt<6, 3>(Imm) &&
492
28
           
VK == RISCVMCExpr::VK_RISCV_None24
;
493
28
  }
494
495
10
  bool isUImm10Lsb00NonZero() const {
496
10
    if (!isImm())
497
0
      return false;
498
10
    int64_t Imm;
499
10
    RISCVMCExpr::VariantKind VK;
500
10
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
501
10
    return IsConstantImm && isShiftedUInt<8, 2>(Imm) && 
(Imm != 0)9
&&
502
10
           
VK == RISCVMCExpr::VK_RISCV_None8
;
503
10
  }
504
505
930
  bool isSImm12() const {
506
930
    RISCVMCExpr::VariantKind VK;
507
930
    int64_t Imm;
508
930
    bool IsValid;
509
930
    if (!isImm())
510
55
      return false;
511
875
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
512
875
    if (!IsConstantImm)
513
167
      IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
514
708
    else
515
708
      IsValid = isInt<12>(Imm);
516
875
    return IsValid && 
(867
(867
IsConstantImm867
&&
VK == RISCVMCExpr::VK_RISCV_None700
) ||
517
867
                       
VK == RISCVMCExpr::VK_RISCV_LO212
||
518
867
                       
VK == RISCVMCExpr::VK_RISCV_PCREL_LO103
||
519
867
                       
VK == RISCVMCExpr::VK_RISCV_TPREL_LO26
);
520
875
  }
521
522
73
  bool isSImm12Lsb0() const { return isBareSimmNLsb0<12>(); }
523
524
188
  bool isSImm13Lsb0() const { return isBareSimmNLsb0<13>(); }
525
526
11
  bool isSImm10Lsb0000NonZero() const {
527
11
    if (!isImm())
528
0
      return false;
529
11
    int64_t Imm;
530
11
    RISCVMCExpr::VariantKind VK;
531
11
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
532
11
    return IsConstantImm && (Imm != 0) && 
isShiftedInt<6, 4>(Imm)10
&&
533
11
           
VK == RISCVMCExpr::VK_RISCV_None8
;
534
11
  }
535
536
112
  bool isUImm20LUI() const {
537
112
    RISCVMCExpr::VariantKind VK;
538
112
    int64_t Imm;
539
112
    bool IsValid;
540
112
    if (!isImm())
541
0
      return false;
542
112
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
543
112
    if (!IsConstantImm) {
544
45
      IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
545
45
      return IsValid && (VK == RISCVMCExpr::VK_RISCV_HI ||
546
45
                         
VK == RISCVMCExpr::VK_RISCV_TPREL_HI12
);
547
67
    } else {
548
67
      return isUInt<20>(Imm) && 
(65
VK == RISCVMCExpr::VK_RISCV_None65
||
549
65
                                 
VK == RISCVMCExpr::VK_RISCV_HI11
||
550
65
                                 
VK == RISCVMCExpr::VK_RISCV_TPREL_HI1
);
551
67
    }
552
112
  }
553
554
91
  bool isUImm20AUIPC() const {
555
91
    RISCVMCExpr::VariantKind VK;
556
91
    int64_t Imm;
557
91
    bool IsValid;
558
91
    if (!isImm())
559
0
      return false;
560
91
    bool IsConstantImm = evaluateConstantImm(getImm(), Imm, VK);
561
91
    if (!IsConstantImm) {
562
52
      IsValid = RISCVAsmParser::classifySymbolRef(getImm(), VK, Imm);
563
52
      return IsValid && (VK == RISCVMCExpr::VK_RISCV_PCREL_HI ||
564
52
                         
VK == RISCVMCExpr::VK_RISCV_GOT_HI13
||
565
52
                         
VK == RISCVMCExpr::VK_RISCV_TLS_GOT_HI9
||
566
52
                         
VK == RISCVMCExpr::VK_RISCV_TLS_GD_HI7
);
567
52
    } else {
568
39
      return isUInt<20>(Imm) && 
(38
VK == RISCVMCExpr::VK_RISCV_None38
||
569
38
                                 
VK == RISCVMCExpr::VK_RISCV_PCREL_HI0
||
570
38
                                 
VK == RISCVMCExpr::VK_RISCV_GOT_HI0
||
571
38
                                 
VK == RISCVMCExpr::VK_RISCV_TLS_GOT_HI0
||
572
38
                                 
VK == RISCVMCExpr::VK_RISCV_TLS_GD_HI0
);
573
39
    }
574
91
  }
575
576
226
  bool isSImm21Lsb0JAL() const { return isBareSimmNLsb0<21>(); }
577
578
  /// getStartLoc - Gets location of the first token of this operand
579
375
  SMLoc getStartLoc() const override { return StartLoc; }
580
  /// getEndLoc - Gets location of the last token of this operand
581
0
  SMLoc getEndLoc() const override { return EndLoc; }
582
  /// True if this operand is for an RV64 instruction
583
457
  bool isRV64() const { return IsRV64; }
584
585
25.8k
  unsigned getReg() const override {
586
25.8k
    assert(Kind == Register && "Invalid type access!");
587
25.8k
    return Reg.RegNum;
588
25.8k
  }
589
590
0
  StringRef getSysReg() const {
591
0
    assert(Kind == SystemRegister && "Invalid access!");
592
0
    return StringRef(SysReg.Data, SysReg.Length);
593
0
  }
594
595
7.28k
  const MCExpr *getImm() const {
596
7.28k
    assert(Kind == Immediate && "Invalid type access!");
597
7.28k
    return Imm.Val;
598
7.28k
  }
599
600
8.45k
  StringRef getToken() const {
601
8.45k
    assert(Kind == Token && "Invalid type access!");
602
8.45k
    return Tok;
603
8.45k
  }
604
605
  void print(raw_ostream &OS) const override {
606
    switch (Kind) {
607
    case Immediate:
608
      OS << *getImm();
609
      break;
610
    case Register:
611
      OS << "<register x";
612
      OS << getReg() << ">";
613
      break;
614
    case Token:
615
      OS << "'" << getToken() << "'";
616
      break;
617
    case SystemRegister:
618
      OS << "<sysreg: " << getSysReg() << '>';
619
      break;
620
    }
621
  }
622
623
  static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S,
624
8.63k
                                                   bool IsRV64) {
625
8.63k
    auto Op = make_unique<RISCVOperand>(Token);
626
8.63k
    Op->Tok = Str;
627
8.63k
    Op->StartLoc = S;
628
8.63k
    Op->EndLoc = S;
629
8.63k
    Op->IsRV64 = IsRV64;
630
8.63k
    return Op;
631
8.63k
  }
632
633
  static std::unique_ptr<RISCVOperand> createReg(unsigned RegNo, SMLoc S,
634
11.6k
                                                 SMLoc E, bool IsRV64) {
635
11.6k
    auto Op = make_unique<RISCVOperand>(Register);
636
11.6k
    Op->Reg.RegNum = RegNo;
637
11.6k
    Op->StartLoc = S;
638
11.6k
    Op->EndLoc = E;
639
11.6k
    Op->IsRV64 = IsRV64;
640
11.6k
    return Op;
641
11.6k
  }
642
643
  static std::unique_ptr<RISCVOperand> createImm(const MCExpr *Val, SMLoc S,
644
3.24k
                                                 SMLoc E, bool IsRV64) {
645
3.24k
    auto Op = make_unique<RISCVOperand>(Immediate);
646
3.24k
    Op->Imm.Val = Val;
647
3.24k
    Op->StartLoc = S;
648
3.24k
    Op->EndLoc = E;
649
3.24k
    Op->IsRV64 = IsRV64;
650
3.24k
    return Op;
651
3.24k
  }
652
653
  static std::unique_ptr<RISCVOperand>
654
1.84k
  createSysReg(StringRef Str, SMLoc S, unsigned Encoding, bool IsRV64) {
655
1.84k
    auto Op = make_unique<RISCVOperand>(SystemRegister);
656
1.84k
    Op->SysReg.Data = Str.data();
657
1.84k
    Op->SysReg.Length = Str.size();
658
1.84k
    Op->SysReg.Encoding = Encoding;
659
1.84k
    Op->StartLoc = S;
660
1.84k
    Op->IsRV64 = IsRV64;
661
1.84k
    return Op;
662
1.84k
  }
663
664
2.50k
  void addExpr(MCInst &Inst, const MCExpr *Expr) const {
665
2.50k
    assert(Expr && "Expr shouldn't be null!");
666
2.50k
    int64_t Imm = 0;
667
2.50k
    RISCVMCExpr::VariantKind VK;
668
2.50k
    bool IsConstant = evaluateConstantImm(Expr, Imm, VK);
669
2.50k
670
2.50k
    if (IsConstant)
671
1.68k
      Inst.addOperand(MCOperand::createImm(Imm));
672
828
    else
673
828
      Inst.addOperand(MCOperand::createExpr(Expr));
674
2.50k
  }
675
676
  // Used by the TableGen Code
677
10.8k
  void addRegOperands(MCInst &Inst, unsigned N) const {
678
10.8k
    assert(N == 1 && "Invalid number of operands!");
679
10.8k
    Inst.addOperand(MCOperand::createReg(getReg()));
680
10.8k
  }
681
682
2.50k
  void addImmOperands(MCInst &Inst, unsigned N) const {
683
2.50k
    assert(N == 1 && "Invalid number of operands!");
684
2.50k
    addExpr(Inst, getImm());
685
2.50k
  }
686
687
36
  void addFenceArgOperands(MCInst &Inst, unsigned N) const {
688
36
    assert(N == 1 && "Invalid number of operands!");
689
36
    // isFenceArg has validated the operand, meaning this cast is safe
690
36
    auto SE = cast<MCSymbolRefExpr>(getImm());
691
36
692
36
    unsigned Imm = 0;
693
84
    for (char c : SE->getSymbol().getName()) {
694
84
      switch (c) {
695
84
      default:
696
0
        llvm_unreachable("FenceArg must contain only [iorw]");
697
84
      
case 'i': Imm |= RISCVFenceField::I; break20
;
698
84
      
case 'o': Imm |= RISCVFenceField::O; break16
;
699
84
      
case 'r': Imm |= RISCVFenceField::R; break24
;
700
84
      
case 'w': Imm |= RISCVFenceField::W; break24
;
701
84
      }
702
84
    }
703
36
    Inst.addOperand(MCOperand::createImm(Imm));
704
36
  }
705
706
1.83k
  void addCSRSystemRegisterOperands(MCInst &Inst, unsigned N) const {
707
1.83k
    assert(N == 1 && "Invalid number of operands!");
708
1.83k
    Inst.addOperand(MCOperand::createImm(SysReg.Encoding));
709
1.83k
  }
710
711
  // Returns the rounding mode represented by this RISCVOperand. Should only
712
  // be called after checking isFRMArg.
713
236
  RISCVFPRndMode::RoundingMode getRoundingMode() const {
714
236
    // isFRMArg has validated the operand, meaning this cast is safe.
715
236
    auto SE = cast<MCSymbolRefExpr>(getImm());
716
236
    RISCVFPRndMode::RoundingMode FRM =
717
236
        RISCVFPRndMode::stringToRoundingMode(SE->getSymbol().getName());
718
236
    assert(FRM != RISCVFPRndMode::Invalid && "Invalid rounding mode");
719
236
    return FRM;
720
236
  }
721
722
236
  void addFRMArgOperands(MCInst &Inst, unsigned N) const {
723
236
    assert(N == 1 && "Invalid number of operands!");
724
236
    Inst.addOperand(MCOperand::createImm(getRoundingMode()));
725
236
  }
726
};
727
} // end anonymous namespace.
728
729
#define GET_REGISTER_MATCHER
730
#define GET_MATCHER_IMPLEMENTATION
731
#include "RISCVGenAsmMatcher.inc"
732
733
// Return the matching FPR64 register for the given FPR32.
734
// FIXME: Ideally this function could be removed in favour of using
735
// information from TableGen.
736
901
unsigned convertFPR32ToFPR64(unsigned Reg) {
737
901
  switch (Reg) {
738
901
  default:
739
0
    llvm_unreachable("Not a recognised FPR32 register");
740
901
  
case RISCV::F0_32: return RISCV::F0_6475
;
741
901
  
case RISCV::F1_32: return RISCV::F1_6453
;
742
901
  
case RISCV::F2_32: return RISCV::F2_6442
;
743
901
  
case RISCV::F3_32: return RISCV::F3_6438
;
744
901
  
case RISCV::F4_32: return RISCV::F4_6430
;
745
901
  
case RISCV::F5_32: return RISCV::F5_6431
;
746
901
  
case RISCV::F6_32: return RISCV::F6_6428
;
747
901
  
case RISCV::F7_32: return RISCV::F7_6420
;
748
901
  
case RISCV::F8_32: return RISCV::F8_6453
;
749
901
  
case RISCV::F9_32: return RISCV::F9_6418
;
750
901
  
case RISCV::F10_32: return RISCV::F10_6420
;
751
901
  
case RISCV::F11_32: return RISCV::F11_6428
;
752
901
  
case RISCV::F12_32: return RISCV::F12_6432
;
753
901
  
case RISCV::F13_32: return RISCV::F13_6432
;
754
901
  
case RISCV::F14_32: return RISCV::F14_6420
;
755
901
  
case RISCV::F15_32: return RISCV::F15_6420
;
756
901
  
case RISCV::F16_32: return RISCV::F16_6420
;
757
901
  
case RISCV::F17_32: return RISCV::F17_6428
;
758
901
  
case RISCV::F18_32: return RISCV::F18_6421
;
759
901
  
case RISCV::F19_32: return RISCV::F19_6420
;
760
901
  
case RISCV::F20_32: return RISCV::F20_6420
;
761
901
  
case RISCV::F21_32: return RISCV::F21_6416
;
762
901
  
case RISCV::F22_32: return RISCV::F22_6432
;
763
901
  
case RISCV::F23_32: return RISCV::F23_6420
;
764
901
  
case RISCV::F24_32: return RISCV::F24_6420
;
765
901
  
case RISCV::F25_32: return RISCV::F25_6420
;
766
901
  
case RISCV::F26_32: return RISCV::F26_6420
;
767
901
  
case RISCV::F27_32: return RISCV::F27_6420
;
768
901
  
case RISCV::F28_32: return RISCV::F28_6420
;
769
901
  
case RISCV::F29_32: return RISCV::F29_6420
;
770
901
  
case RISCV::F30_32: return RISCV::F30_6432
;
771
901
  
case RISCV::F31_32: return RISCV::F31_6432
;
772
901
  }
773
901
}
774
775
unsigned RISCVAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
776
3.18k
                                                    unsigned Kind) {
777
3.18k
  RISCVOperand &Op = static_cast<RISCVOperand &>(AsmOp);
778
3.18k
  if (!Op.isReg())
779
1.93k
    return Match_InvalidOperand;
780
1.24k
781
1.24k
  unsigned Reg = Op.getReg();
782
1.24k
  bool IsRegFPR32 =
783
1.24k
      RISCVMCRegisterClasses[RISCV::FPR32RegClassID].contains(Reg);
784
1.24k
  bool IsRegFPR32C =
785
1.24k
      RISCVMCRegisterClasses[RISCV::FPR32CRegClassID].contains(Reg);
786
1.24k
787
1.24k
  // As the parser couldn't differentiate an FPR32 from an FPR64, coerce the
788
1.24k
  // register from FPR32 to FPR64 or FPR32C to FPR64C if necessary.
789
1.24k
  if ((IsRegFPR32 && 
Kind == MCK_FPR64933
) ||
790
1.24k
      
(391
IsRegFPR32C391
&&
Kind == MCK_FPR64C43
)) {
791
901
    Op.Reg.RegNum = convertFPR32ToFPR64(Reg);
792
901
    return Match_Success;
793
901
  }
794
348
  return Match_InvalidOperand;
795
348
}
796
797
bool RISCVAsmParser::generateImmOutOfRangeError(
798
    OperandVector &Operands, uint64_t ErrorInfo, int64_t Lower, int64_t Upper,
799
174
    Twine Msg = "immediate must be an integer in the range") {
800
174
  SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
801
174
  return Error(ErrorLoc, Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
802
174
}
803
804
bool RISCVAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
805
                                             OperandVector &Operands,
806
                                             MCStreamer &Out,
807
                                             uint64_t &ErrorInfo,
808
6.56k
                                             bool MatchingInlineAsm) {
809
6.56k
  MCInst Inst;
810
6.56k
811
6.56k
  auto Result =
812
6.56k
    MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
813
6.56k
  switch (Result) {
814
6.56k
  default:
815
257
    break;
816
6.56k
  case Match_Success:
817
6.04k
    return processInstruction(Inst, IDLoc, Operands, Out);
818
6.56k
  case Match_MissingFeature:
819
132
    return Error(IDLoc, "instruction use requires an option to be enabled");
820
6.56k
  case Match_MnemonicFail:
821
9
    return Error(IDLoc, "unrecognized instruction mnemonic");
822
6.56k
  case Match_InvalidOperand: {
823
121
    SMLoc ErrorLoc = IDLoc;
824
121
    if (ErrorInfo != ~0U) {
825
121
      if (ErrorInfo >= Operands.size())
826
4
        return Error(ErrorLoc, "too few operands for instruction");
827
117
828
117
      ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
829
117
      if (ErrorLoc == SMLoc())
830
0
        ErrorLoc = IDLoc;
831
117
    }
832
121
    
return Error(ErrorLoc, "invalid operand for instruction")117
;
833
257
  }
834
257
  }
835
257
836
257
  // Handle the case when the error message is of specific type
837
257
  // other than the generic Match_InvalidOperand, and the
838
257
  // corresponding operand is missing.
839
257
  if (Result > FIRST_TARGET_MATCH_RESULT_TY) {
840
257
    SMLoc ErrorLoc = IDLoc;
841
257
    if (ErrorInfo != ~0U && ErrorInfo >= Operands.size())
842
0
        return Error(ErrorLoc, "too few operands for instruction");
843
257
  }
844
257
845
257
  switch(Result) {
846
257
  default:
847
0
    break;
848
257
  case Match_InvalidImmXLenLI:
849
8
    if (isRV64()) {
850
2
      SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
851
2
      return Error(ErrorLoc, "operand must be a constant 64-bit integer");
852
2
    }
853
6
    return generateImmOutOfRangeError(Operands, ErrorInfo,
854
6
                                      std::numeric_limits<int32_t>::min(),
855
6
                                      std::numeric_limits<uint32_t>::max());
856
30
  case Match_InvalidUImmLog2XLen:
857
30
    if (isRV64())
858
12
      return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
859
18
    return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
860
18
  case Match_InvalidUImmLog2XLenNonZero:
861
8
    if (isRV64())
862
3
      return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 6) - 1);
863
5
    return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5) - 1);
864
26
  case Match_InvalidUImm5:
865
26
    return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
866
13
  case Match_InvalidSImm6:
867
13
    return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
868
13
                                      (1 << 5) - 1);
869
6
  case Match_InvalidSImm6NonZero:
870
6
    return generateImmOutOfRangeError(
871
6
        Operands, ErrorInfo, -(1 << 5), (1 << 5) - 1,
872
6
        "immediate must be non-zero in the range");
873
5
  case Match_InvalidCLUIImm:
874
4
    return generateImmOutOfRangeError(
875
4
        Operands, ErrorInfo, 1, (1 << 5) - 1,
876
4
        "immediate must be in [0xfffe0, 0xfffff] or");
877
5
  case Match_InvalidUImm7Lsb00:
878
4
    return generateImmOutOfRangeError(
879
4
        Operands, ErrorInfo, 0, (1 << 7) - 4,
880
4
        "immediate must be a multiple of 4 bytes in the range");
881
5
  case Match_InvalidUImm8Lsb00:
882
4
    return generateImmOutOfRangeError(
883
4
        Operands, ErrorInfo, 0, (1 << 8) - 4,
884
4
        "immediate must be a multiple of 4 bytes in the range");
885
5
  case Match_InvalidUImm8Lsb000:
886
4
    return generateImmOutOfRangeError(
887
4
        Operands, ErrorInfo, 0, (1 << 8) - 8,
888
4
        "immediate must be a multiple of 8 bytes in the range");
889
5
  case Match_InvalidSImm9Lsb0:
890
2
    return generateImmOutOfRangeError(
891
2
        Operands, ErrorInfo, -(1 << 8), (1 << 8) - 2,
892
2
        "immediate must be a multiple of 2 bytes in the range");
893
5
  case Match_InvalidUImm9Lsb000:
894
4
    return generateImmOutOfRangeError(
895
4
        Operands, ErrorInfo, 0, (1 << 9) - 8,
896
4
        "immediate must be a multiple of 8 bytes in the range");
897
5
  case Match_InvalidUImm10Lsb00NonZero:
898
2
    return generateImmOutOfRangeError(
899
2
        Operands, ErrorInfo, 4, (1 << 10) - 4,
900
2
        "immediate must be a multiple of 4 bytes in the range");
901
5
  case Match_InvalidSImm10Lsb0000NonZero:
902
3
    return generateImmOutOfRangeError(
903
3
        Operands, ErrorInfo, -(1 << 9), (1 << 9) - 16,
904
3
        "immediate must be a multiple of 16 bytes and non-zero in the range");
905
16
  case Match_InvalidSImm12:
906
16
    return generateImmOutOfRangeError(
907
16
        Operands, ErrorInfo, -(1 << 11), (1 << 11) - 1,
908
16
        "operand must be a symbol with %lo/%pcrel_lo/%tprel_lo modifier or an "
909
16
        "integer in the range");
910
5
  case Match_InvalidSImm12Lsb0:
911
2
    return generateImmOutOfRangeError(
912
2
        Operands, ErrorInfo, -(1 << 11), (1 << 11) - 2,
913
2
        "immediate must be a multiple of 2 bytes in the range");
914
14
  case Match_InvalidSImm13Lsb0:
915
14
    return generateImmOutOfRangeError(
916
14
        Operands, ErrorInfo, -(1 << 12), (1 << 12) - 2,
917
14
        "immediate must be a multiple of 2 bytes in the range");
918
7
  case Match_InvalidUImm20LUI:
919
7
    return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1,
920
7
                                      "operand must be a symbol with "
921
7
                                      "%hi/%tprel_hi modifier or an integer in "
922
7
                                      "the range");
923
6
  case Match_InvalidUImm20AUIPC:
924
6
    return generateImmOutOfRangeError(
925
6
        Operands, ErrorInfo, 0, (1 << 20) - 1,
926
6
        "operand must be a symbol with a "
927
6
        "%pcrel_hi/%got_pcrel_hi/%tls_ie_pcrel_hi/%tls_gd_pcrel_hi modifier or "
928
6
        "an integer in the range");
929
13
  case Match_InvalidSImm21Lsb0JAL:
930
13
    return generateImmOutOfRangeError(
931
13
        Operands, ErrorInfo, -(1 << 20), (1 << 20) - 2,
932
13
        "immediate must be a multiple of 2 bytes in the range");
933
5
  case Match_InvalidCSRSystemRegister: {
934
0
    return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 12) - 1,
935
0
                                      "operand must be a valid system register "
936
0
                                      "name or an integer in the range");
937
5
  }
938
9
  case Match_InvalidFenceArg: {
939
9
    SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
940
9
    return Error(
941
9
        ErrorLoc,
942
9
        "operand must be formed of letters selected in-order from 'iorw'");
943
5
  }
944
5
  case Match_InvalidFRMArg: {
945
3
    SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
946
3
    return Error(
947
3
        ErrorLoc,
948
3
        "operand must be a valid floating point rounding mode mnemonic");
949
5
  }
950
40
  case Match_InvalidBareSymbol: {
951
40
    SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
952
40
    return Error(ErrorLoc, "operand must be a bare symbol name");
953
5
  }
954
28
  case Match_InvalidCallSymbol: {
955
28
    SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
956
28
    return Error(ErrorLoc, "operand must be a bare symbol name");
957
5
  }
958
5
  case Match_InvalidTPRelAddSymbol: {
959
1
    SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
960
1
    return Error(ErrorLoc, "operand must be a symbol with %tprel_add modifier");
961
0
  }
962
0
  }
963
0
964
0
  llvm_unreachable("Unknown match type detected!");
965
0
}
966
967
// Attempts to match Name as a register (either using the default name or
968
// alternative ABI names), setting RegNo to the matching register. Upon
969
// failure, returns true and sets RegNo to 0. If IsRV32E then registers
970
// x16-x31 will be rejected.
971
static bool matchRegisterNameHelper(bool IsRV32E, unsigned &RegNo,
972
12.4k
                                    StringRef Name) {
973
12.4k
  RegNo = MatchRegisterName(Name);
974
12.4k
  if (RegNo == 0)
975
9.89k
    RegNo = MatchRegisterAltName(Name);
976
12.4k
  if (IsRV32E && 
RegNo >= RISCV::X16216
&&
RegNo <= RISCV::X3132
)
977
32
    RegNo = 0;
978
12.4k
  return RegNo == 0;
979
12.4k
}
980
981
bool RISCVAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
982
132
                                   SMLoc &EndLoc) {
983
132
  const AsmToken &Tok = getParser().getTok();
984
132
  StartLoc = Tok.getLoc();
985
132
  EndLoc = Tok.getEndLoc();
986
132
  RegNo = 0;
987
132
  StringRef Name = getLexer().getTok().getIdentifier();
988
132
989
132
  if (matchRegisterNameHelper(isRV32E(), RegNo, Name))
990
4
    return Error(StartLoc, "invalid register name");
991
128
992
128
  getParser().Lex(); // Eat identifier token.
993
128
  return false;
994
128
}
995
996
OperandMatchResultTy RISCVAsmParser::parseRegister(OperandVector &Operands,
997
14.4k
                                                   bool AllowParens) {
998
14.4k
  SMLoc FirstS = getLoc();
999
14.4k
  bool HadParens = false;
1000
14.4k
  AsmToken LParen;
1001
14.4k
1002
14.4k
  // If this is an LParen and a parenthesised register name is allowed, parse it
1003
14.4k
  // atomically.
1004
14.4k
  if (AllowParens && 
getLexer().is(AsmToken::LParen)13.9k
) {
1005
478
    AsmToken Buf[2];
1006
478
    size_t ReadCount = getLexer().peekTokens(Buf);
1007
478
    if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
1008
454
      HadParens = true;
1009
454
      LParen = getParser().getTok();
1010
454
      getParser().Lex(); // Eat '('
1011
454
    }
1012
478
  }
1013
14.4k
1014
14.4k
  switch (getLexer().getKind()) {
1015
14.4k
  default:
1016
2.19k
    if (HadParens)
1017
12
      getLexer().UnLex(LParen);
1018
2.19k
    return MatchOperand_NoMatch;
1019
14.4k
  case AsmToken::Identifier:
1020
12.2k
    StringRef Name = getLexer().getTok().getIdentifier();
1021
12.2k
    unsigned RegNo;
1022
12.2k
    matchRegisterNameHelper(isRV32E(), RegNo, Name);
1023
12.2k
1024
12.2k
    if (RegNo == 0) {
1025
605
      if (HadParens)
1026
0
        getLexer().UnLex(LParen);
1027
605
      return MatchOperand_NoMatch;
1028
605
    }
1029
11.6k
    if (HadParens)
1030
442
      Operands.push_back(RISCVOperand::createToken("(", FirstS, isRV64()));
1031
11.6k
    SMLoc S = getLoc();
1032
11.6k
    SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1033
11.6k
    getLexer().Lex();
1034
11.6k
    Operands.push_back(RISCVOperand::createReg(RegNo, S, E, isRV64()));
1035
14.4k
  }
1036
14.4k
1037
14.4k
  
if (11.6k
HadParens11.6k
) {
1038
442
    getParser().Lex(); // Eat ')'
1039
442
    Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
1040
442
  }
1041
11.6k
1042
11.6k
  return MatchOperand_Success;
1043
14.4k
}
1044
1045
OperandMatchResultTy
1046
1.92k
RISCVAsmParser::parseCSRSystemRegister(OperandVector &Operands) {
1047
1.92k
  SMLoc S = getLoc();
1048
1.92k
  const MCExpr *Res;
1049
1.92k
1050
1.92k
  switch (getLexer().getKind()) {
1051
1.92k
  default:
1052
0
    return MatchOperand_NoMatch;
1053
1.92k
  case AsmToken::LParen:
1054
1.15k
  case AsmToken::Minus:
1055
1.15k
  case AsmToken::Plus:
1056
1.15k
  case AsmToken::Exclaim:
1057
1.15k
  case AsmToken::Tilde:
1058
1.15k
  case AsmToken::Integer:
1059
1.15k
  case AsmToken::String: {
1060
1.15k
    if (getParser().parseExpression(Res))
1061
0
      return MatchOperand_ParseFail;
1062
1.15k
1063
1.15k
    auto *CE = dyn_cast<MCConstantExpr>(Res);
1064
1.15k
    if (CE) {
1065
1.15k
      int64_t Imm = CE->getValue();
1066
1.15k
      if (isUInt<12>(Imm)) {
1067
1.14k
        auto SysReg = RISCVSysReg::lookupSysRegByEncoding(Imm);
1068
1.14k
        // Accept an immediate representing a named or un-named Sys Reg
1069
1.14k
        // if the range is valid, regardless of the required features.
1070
1.14k
        Operands.push_back(RISCVOperand::createSysReg(
1071
1.14k
            SysReg ? 
SysReg->Name1.04k
:
""102
, S, Imm, isRV64()));
1072
1.14k
        return MatchOperand_Success;
1073
1.14k
      }
1074
7
    }
1075
7
1076
7
    Twine Msg = "immediate must be an integer in the range";
1077
7
    Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 12) - 1) + "]");
1078
7
    return MatchOperand_ParseFail;
1079
7
  }
1080
769
  case AsmToken::Identifier: {
1081
769
    StringRef Identifier;
1082
769
    if (getParser().parseIdentifier(Identifier))
1083
0
      return MatchOperand_ParseFail;
1084
769
1085
769
    auto SysReg = RISCVSysReg::lookupSysRegByName(Identifier);
1086
769
    // Accept a named Sys Reg if the required features are present.
1087
769
    if (SysReg) {
1088
761
      if (!SysReg->haveRequiredFeatures(getSTI().getFeatureBits())) {
1089
65
        Error(S, "system register use requires an option to be enabled");
1090
65
        return MatchOperand_ParseFail;
1091
65
      }
1092
696
      Operands.push_back(RISCVOperand::createSysReg(
1093
696
          Identifier, S, SysReg->Encoding, isRV64()));
1094
696
      return MatchOperand_Success;
1095
696
    }
1096
8
1097
8
    Twine Msg = "operand must be a valid system register name "
1098
8
                "or an integer in the range";
1099
8
    Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 12) - 1) + "]");
1100
8
    return MatchOperand_ParseFail;
1101
8
  }
1102
8
  case AsmToken::Percent: {
1103
8
    // Discard operand with modifier.
1104
8
    Twine Msg = "immediate must be an integer in the range";
1105
8
    Error(S, Msg + " [" + Twine(0) + ", " + Twine((1 << 12) - 1) + "]");
1106
8
    return MatchOperand_ParseFail;
1107
0
  }
1108
0
  }
1109
0
1110
0
  return MatchOperand_NoMatch;
1111
0
}
1112
1113
2.93k
OperandMatchResultTy RISCVAsmParser::parseImmediate(OperandVector &Operands) {
1114
2.93k
  SMLoc S = getLoc();
1115
2.93k
  SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1116
2.93k
  const MCExpr *Res;
1117
2.93k
1118
2.93k
  switch (getLexer().getKind()) {
1119
2.93k
  default:
1120
2
    return MatchOperand_NoMatch;
1121
2.93k
  case AsmToken::LParen:
1122
2.49k
  case AsmToken::Dot:
1123
2.49k
  case AsmToken::Minus:
1124
2.49k
  case AsmToken::Plus:
1125
2.49k
  case AsmToken::Exclaim:
1126
2.49k
  case AsmToken::Tilde:
1127
2.49k
  case AsmToken::Integer:
1128
2.49k
  case AsmToken::String:
1129
2.49k
  case AsmToken::Identifier:
1130
2.49k
    if (getParser().parseExpression(Res))
1131
0
      return MatchOperand_ParseFail;
1132
2.49k
    break;
1133
2.49k
  case AsmToken::Percent:
1134
441
    return parseOperandWithModifier(Operands);
1135
2.49k
  }
1136
2.49k
1137
2.49k
  Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1138
2.49k
  return MatchOperand_Success;
1139
2.49k
}
1140
1141
OperandMatchResultTy
1142
450
RISCVAsmParser::parseOperandWithModifier(OperandVector &Operands) {
1143
450
  SMLoc S = getLoc();
1144
450
  SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1145
450
1146
450
  if (getLexer().getKind() != AsmToken::Percent) {
1147
1
    Error(getLoc(), "expected '%' for operand modifier");
1148
1
    return MatchOperand_ParseFail;
1149
1
  }
1150
449
1151
449
  getParser().Lex(); // Eat '%'
1152
449
1153
449
  if (getLexer().getKind() != AsmToken::Identifier) {
1154
0
    Error(getLoc(), "expected valid identifier for operand modifier");
1155
0
    return MatchOperand_ParseFail;
1156
0
  }
1157
449
  StringRef Identifier = getParser().getTok().getIdentifier();
1158
449
  RISCVMCExpr::VariantKind VK = RISCVMCExpr::getVariantKindForName(Identifier);
1159
449
  if (VK == RISCVMCExpr::VK_RISCV_Invalid) {
1160
1
    Error(getLoc(), "unrecognized operand modifier");
1161
1
    return MatchOperand_ParseFail;
1162
1
  }
1163
448
1164
448
  getParser().Lex(); // Eat the identifier
1165
448
  if (getLexer().getKind() != AsmToken::LParen) {
1166
0
    Error(getLoc(), "expected '('");
1167
0
    return MatchOperand_ParseFail;
1168
0
  }
1169
448
  getParser().Lex(); // Eat '('
1170
448
1171
448
  const MCExpr *SubExpr;
1172
448
  if (getParser().parseParenExpression(SubExpr, E)) {
1173
0
    return MatchOperand_ParseFail;
1174
0
  }
1175
448
1176
448
  const MCExpr *ModExpr = RISCVMCExpr::create(SubExpr, VK, getContext());
1177
448
  Operands.push_back(RISCVOperand::createImm(ModExpr, S, E, isRV64()));
1178
448
  return MatchOperand_Success;
1179
448
}
1180
1181
672
OperandMatchResultTy RISCVAsmParser::parseBareSymbol(OperandVector &Operands) {
1182
672
  SMLoc S = getLoc();
1183
672
  SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1184
672
  const MCExpr *Res;
1185
672
1186
672
  if (getLexer().getKind() != AsmToken::Identifier)
1187
498
    return MatchOperand_NoMatch;
1188
174
1189
174
  StringRef Identifier;
1190
174
  AsmToken Tok = getLexer().getTok();
1191
174
1192
174
  if (getParser().parseIdentifier(Identifier))
1193
0
    return MatchOperand_ParseFail;
1194
174
1195
174
  if (Identifier.consume_back("@plt")) {
1196
2
    Error(getLoc(), "'@plt' operand not valid for instruction");
1197
2
    return MatchOperand_ParseFail;
1198
2
  }
1199
172
1200
172
  MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
1201
172
1202
172
  if (Sym->isVariable()) {
1203
8
    const MCExpr *V = Sym->getVariableValue(/*SetUsed=*/false);
1204
8
    if (!isa<MCSymbolRefExpr>(V)) {
1205
8
      getLexer().UnLex(Tok); // Put back if it's not a bare symbol.
1206
8
      return MatchOperand_NoMatch;
1207
8
    }
1208
0
    Res = V;
1209
0
  } else
1210
164
    Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1211
172
  Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1212
164
  return MatchOperand_Success;
1213
172
}
1214
1215
173
OperandMatchResultTy RISCVAsmParser::parseCallSymbol(OperandVector &Operands) {
1216
173
  SMLoc S = getLoc();
1217
173
  SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1218
173
  const MCExpr *Res;
1219
173
1220
173
  if (getLexer().getKind() != AsmToken::Identifier)
1221
27
    return MatchOperand_NoMatch;
1222
146
1223
146
  // Avoid parsing the register in `call rd, foo` as a call symbol.
1224
146
  if (getLexer().peekTok().getKind() != AsmToken::EndOfStatement)
1225
7
    return MatchOperand_NoMatch;
1226
139
1227
139
  StringRef Identifier;
1228
139
  if (getParser().parseIdentifier(Identifier))
1229
0
    return MatchOperand_ParseFail;
1230
139
1231
139
  RISCVMCExpr::VariantKind Kind = RISCVMCExpr::VK_RISCV_CALL;
1232
139
  if (Identifier.consume_back("@plt"))
1233
20
    Kind = RISCVMCExpr::VK_RISCV_CALL_PLT;
1234
139
1235
139
  MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
1236
139
  Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1237
139
  Res = RISCVMCExpr::create(Res, Kind, getContext());
1238
139
  Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
1239
139
  return MatchOperand_Success;
1240
139
}
1241
1242
226
OperandMatchResultTy RISCVAsmParser::parseJALOffset(OperandVector &Operands) {
1243
226
  // Parsing jal operands is fiddly due to the `jal foo` and `jal ra, foo`
1244
226
  // both being acceptable forms. When parsing `jal ra, foo` this function
1245
226
  // will be called for the `ra` register operand in an attempt to match the
1246
226
  // single-operand alias. parseJALOffset must fail for this case. It would
1247
226
  // seem logical to try parse the operand using parseImmediate and return
1248
226
  // NoMatch if the next token is a comma (meaning we must be parsing a jal in
1249
226
  // the second form rather than the first). We can't do this as there's no
1250
226
  // way of rewinding the lexer state. Instead, return NoMatch if this operand
1251
226
  // is an identifier and is followed by a comma.
1252
226
  if (getLexer().is(AsmToken::Identifier) &&
1253
226
      
getLexer().peekTok().is(AsmToken::Comma)155
)
1254
85
    return MatchOperand_NoMatch;
1255
141
1256
141
  return parseImmediate(Operands);
1257
141
}
1258
1259
OperandMatchResultTy
1260
546
RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
1261
546
  if (getLexer().isNot(AsmToken::LParen)) {
1262
0
    Error(getLoc(), "expected '('");
1263
0
    return MatchOperand_ParseFail;
1264
0
  }
1265
546
1266
546
  getParser().Lex(); // Eat '('
1267
546
  Operands.push_back(RISCVOperand::createToken("(", getLoc(), isRV64()));
1268
546
1269
546
  if (parseRegister(Operands) != MatchOperand_Success) {
1270
2
    Error(getLoc(), "expected register");
1271
2
    return MatchOperand_ParseFail;
1272
2
  }
1273
544
1274
544
  if (getLexer().isNot(AsmToken::RParen)) {
1275
0
    Error(getLoc(), "expected ')'");
1276
0
    return MatchOperand_ParseFail;
1277
0
  }
1278
544
1279
544
  getParser().Lex(); // Eat ')'
1280
544
  Operands.push_back(RISCVOperand::createToken(")", getLoc(), isRV64()));
1281
544
1282
544
  return MatchOperand_Success;
1283
544
}
1284
1285
/// Looks at a token type and creates the relevant operand from this
1286
/// information, adding to Operands. If operand was parsed, returns false, else
1287
/// true.
1288
16.2k
bool RISCVAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
1289
16.2k
  // Check if the current operand has a custom associated parser, if so, try to
1290
16.2k
  // custom parse the operand, or fallback to the general approach.
1291
16.2k
  OperandMatchResultTy Result =
1292
16.2k
      MatchOperandParserImpl(Operands, Mnemonic, /*ParseForAllFeatures=*/true);
1293
16.2k
  if (Result == MatchOperand_Success)
1294
2.29k
    return false;
1295
14.0k
  if (Result == MatchOperand_ParseFail)
1296
91
    return true;
1297
13.9k
1298
13.9k
  // Attempt to parse token as a register.
1299
13.9k
  if (parseRegister(Operands, true) == MatchOperand_Success)
1300
11.1k
    return false;
1301
2.79k
1302
2.79k
  // Attempt to parse token as an immediate
1303
2.79k
  if (parseImmediate(Operands) == MatchOperand_Success) {
1304
2.79k
    // Parse memory base register if present
1305
2.79k
    if (getLexer().is(AsmToken::LParen))
1306
546
      return parseMemOpBaseReg(Operands) != MatchOperand_Success;
1307
2.24k
    return false;
1308
2.24k
  }
1309
3
1310
3
  // Finally we have exhausted all options and must declare defeat.
1311
3
  Error(getLoc(), "unknown operand");
1312
3
  return true;
1313
3
}
1314
1315
bool RISCVAsmParser::ParseInstruction(ParseInstructionInfo &Info,
1316
                                      StringRef Name, SMLoc NameLoc,
1317
6.66k
                                      OperandVector &Operands) {
1318
6.66k
  // Ensure that if the instruction occurs when relaxation is enabled,
1319
6.66k
  // relocations are forced for the file. Ideally this would be done when there
1320
6.66k
  // is enough information to reliably determine if the instruction itself may
1321
6.66k
  // cause relaxations. Unfortunately instruction processing stage occurs in the
1322
6.66k
  // same pass as relocation emission, so it's too late to set a 'sticky bit'
1323
6.66k
  // for the entire file.
1324
6.66k
  if (getSTI().getFeatureBits()[RISCV::FeatureRelax]) {
1325
248
    auto *Assembler = getTargetStreamer().getStreamer().getAssemblerPtr();
1326
248
    if (Assembler != nullptr) {
1327
204
      RISCVAsmBackend &MAB =
1328
204
          static_cast<RISCVAsmBackend &>(Assembler->getBackend());
1329
204
      MAB.setForceRelocs();
1330
204
    }
1331
248
  }
1332
6.66k
1333
6.66k
  // First operand is token for instruction
1334
6.66k
  Operands.push_back(RISCVOperand::createToken(Name, NameLoc, isRV64()));
1335
6.66k
1336
6.66k
  // If there are no more operands, then finish
1337
6.66k
  if (getLexer().is(AsmToken::EndOfStatement))
1338
228
    return false;
1339
6.43k
1340
6.43k
  // Parse first operand
1341
6.43k
  if (parseOperand(Operands, Name))
1342
0
    return true;
1343
6.43k
1344
6.43k
  // Parse until end of statement, consuming commas between operands
1345
6.43k
  unsigned OperandIdx = 1;
1346
16.2k
  while (getLexer().is(AsmToken::Comma)) {
1347
9.86k
    // Consume comma token
1348
9.86k
    getLexer().Lex();
1349
9.86k
1350
9.86k
    // Parse next operand
1351
9.86k
    if (parseOperand(Operands, Name))
1352
96
      return true;
1353
9.76k
1354
9.76k
    ++OperandIdx;
1355
9.76k
  }
1356
6.43k
1357
6.43k
  
if (6.33k
getLexer().isNot(AsmToken::EndOfStatement)6.33k
) {
1358
0
    SMLoc Loc = getLexer().getLoc();
1359
0
    getParser().eatToEndOfStatement();
1360
0
    return Error(Loc, "unexpected token");
1361
0
  }
1362
6.33k
1363
6.33k
  getParser().Lex(); // Consume the EndOfStatement.
1364
6.33k
  return false;
1365
6.33k
}
1366
1367
bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
1368
                                       RISCVMCExpr::VariantKind &Kind,
1369
974
                                       int64_t &Addend) {
1370
974
  Kind = RISCVMCExpr::VK_RISCV_None;
1371
974
  Addend = 0;
1372
974
1373
974
  if (const RISCVMCExpr *RE = dyn_cast<RISCVMCExpr>(Expr)) {
1374
537
    Kind = RE->getKind();
1375
537
    Expr = RE->getSubExpr();
1376
537
  }
1377
974
1378
974
  // It's a simple symbol reference or constant with no addend.
1379
974
  if (isa<MCConstantExpr>(Expr) || 
isa<MCSymbolRefExpr>(Expr)955
)
1380
938
    return true;
1381
36
1382
36
  const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr);
1383
36
  if (!BE)
1384
0
    return false;
1385
36
1386
36
  if (!isa<MCSymbolRefExpr>(BE->getLHS()))
1387
0
    return false;
1388
36
1389
36
  if (BE->getOpcode() != MCBinaryExpr::Add &&
1390
36
      
BE->getOpcode() != MCBinaryExpr::Sub18
)
1391
0
    return false;
1392
36
1393
36
  // We are able to support the subtraction of two symbol references
1394
36
  if (BE->getOpcode() == MCBinaryExpr::Sub &&
1395
36
      
isa<MCSymbolRefExpr>(BE->getRHS())18
)
1396
18
    return true;
1397
18
1398
18
  // See if the addend is a constant, otherwise there's more going
1399
18
  // on here than we can deal with.
1400
18
  auto AddendExpr = dyn_cast<MCConstantExpr>(BE->getRHS());
1401
18
  if (!AddendExpr)
1402
0
    return false;
1403
18
1404
18
  Addend = AddendExpr->getValue();
1405
18
  if (BE->getOpcode() == MCBinaryExpr::Sub)
1406
0
    Addend = -Addend;
1407
18
1408
18
  // It's some symbol reference + a constant addend
1409
18
  return Kind != RISCVMCExpr::VK_RISCV_Invalid;
1410
18
}
1411
1412
723
bool RISCVAsmParser::ParseDirective(AsmToken DirectiveID) {
1413
723
  // This returns false if this function recognizes the directive
1414
723
  // regardless of whether it is successfully handles or reports an
1415
723
  // error. Otherwise it returns true to give the generic parser a
1416
723
  // chance at recognizing it.
1417
723
  StringRef IDVal = DirectiveID.getString();
1418
723
1419
723
  if (IDVal == ".option")
1420
116
    return parseDirectiveOption();
1421
607
1422
607
  return true;
1423
607
}
1424
1425
116
bool RISCVAsmParser::parseDirectiveOption() {
1426
116
  MCAsmParser &Parser = getParser();
1427
116
  // Get the option token.
1428
116
  AsmToken Tok = Parser.getTok();
1429
116
  // At the moment only identifiers are supported.
1430
116
  if (Tok.isNot(AsmToken::Identifier))
1431
3
    return Error(Parser.getTok().getLoc(),
1432
3
                 "unexpected token, expected identifier");
1433
113
1434
113
  StringRef Option = Tok.getIdentifier();
1435
113
1436
113
  if (Option == "push") {
1437
21
    getTargetStreamer().emitDirectiveOptionPush();
1438
21
1439
21
    Parser.Lex();
1440
21
    if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1441
1
      return Error(Parser.getTok().getLoc(),
1442
1
                   "unexpected token, expected end of statement");
1443
20
1444
20
    pushFeatureBits();
1445
20
    return false;
1446
20
  }
1447
92
1448
92
  if (Option == "pop") {
1449
22
    SMLoc StartLoc = Parser.getTok().getLoc();
1450
22
    getTargetStreamer().emitDirectiveOptionPop();
1451
22
1452
22
    Parser.Lex();
1453
22
    if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1454
1
      return Error(Parser.getTok().getLoc(),
1455
1
                   "unexpected token, expected end of statement");
1456
21
1457
21
    if (popFeatureBits())
1458
1
      return Error(StartLoc, ".option pop with no .option push");
1459
20
1460
20
    return false;
1461
20
  }
1462
70
1463
70
  if (Option == "rvc") {
1464
24
    getTargetStreamer().emitDirectiveOptionRVC();
1465
24
1466
24
    Parser.Lex();
1467
24
    if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1468
1
      return Error(Parser.getTok().getLoc(),
1469
1
                   "unexpected token, expected end of statement");
1470
23
1471
23
    setFeatureBits(RISCV::FeatureStdExtC, "c");
1472
23
    return false;
1473
23
  }
1474
46
1475
46
  if (Option == "norvc") {
1476
17
    getTargetStreamer().emitDirectiveOptionNoRVC();
1477
17
1478
17
    Parser.Lex();
1479
17
    if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1480
0
      return Error(Parser.getTok().getLoc(),
1481
0
                   "unexpected token, expected end of statement");
1482
17
1483
17
    clearFeatureBits(RISCV::FeatureStdExtC, "c");
1484
17
    return false;
1485
17
  }
1486
29
1487
29
  if (Option == "relax") {
1488
11
    getTargetStreamer().emitDirectiveOptionRelax();
1489
11
1490
11
    Parser.Lex();
1491
11
    if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1492
0
      return Error(Parser.getTok().getLoc(),
1493
0
                   "unexpected token, expected end of statement");
1494
11
1495
11
    setFeatureBits(RISCV::FeatureRelax, "relax");
1496
11
    return false;
1497
11
  }
1498
18
1499
18
  if (Option == "norelax") {
1500
17
    getTargetStreamer().emitDirectiveOptionNoRelax();
1501
17
1502
17
    Parser.Lex();
1503
17
    if (Parser.getTok().isNot(AsmToken::EndOfStatement))
1504
0
      return Error(Parser.getTok().getLoc(),
1505
0
                   "unexpected token, expected end of statement");
1506
17
1507
17
    clearFeatureBits(RISCV::FeatureRelax, "relax");
1508
17
    return false;
1509
17
  }
1510
1
1511
1
  // Unknown option.
1512
1
  Warning(Parser.getTok().getLoc(),
1513
1
          "unknown option, expected 'push', 'pop', 'rvc', 'norvc', 'relax' or "
1514
1
          "'norelax'");
1515
1
  Parser.eatToEndOfStatement();
1516
1
  return false;
1517
1
}
1518
1519
6.44k
void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
1520
6.44k
  MCInst CInst;
1521
6.44k
  bool Res = compressInst(CInst, Inst, getSTI(), S.getContext());
1522
6.44k
  CInst.setLoc(Inst.getLoc());
1523
6.44k
  S.EmitInstruction((Res ? 
CInst539
:
Inst5.90k
), getSTI());
1524
6.44k
}
1525
1526
void RISCVAsmParser::emitLoadImm(unsigned DestReg, int64_t Value,
1527
322
                                 MCStreamer &Out) {
1528
322
  RISCVMatInt::InstSeq Seq;
1529
322
  RISCVMatInt::generateInstSeq(Value, isRV64(), Seq);
1530
322
1531
322
  unsigned SrcReg = RISCV::X0;
1532
564
  for (RISCVMatInt::Inst &Inst : Seq) {
1533
564
    if (Inst.Opc == RISCV::LUI) {
1534
194
      emitToStreamer(
1535
194
          Out, MCInstBuilder(RISCV::LUI).addReg(DestReg).addImm(Inst.Imm));
1536
370
    } else {
1537
370
      emitToStreamer(
1538
370
          Out, MCInstBuilder(Inst.Opc).addReg(DestReg).addReg(SrcReg).addImm(
1539
370
                   Inst.Imm));
1540
370
    }
1541
564
1542
564
    // Only the first instruction has X0 as its source.
1543
564
    SrcReg = DestReg;
1544
564
  }
1545
322
}
1546
1547
void RISCVAsmParser::emitAuipcInstPair(MCOperand DestReg, MCOperand TmpReg,
1548
                                       const MCExpr *Symbol,
1549
                                       RISCVMCExpr::VariantKind VKHi,
1550
                                       unsigned SecondOpcode, SMLoc IDLoc,
1551
157
                                       MCStreamer &Out) {
1552
157
  // A pair of instructions for PC-relative addressing; expands to
1553
157
  //   TmpLabel: AUIPC TmpReg, VKHi(symbol)
1554
157
  //             OP DestReg, TmpReg, %pcrel_lo(TmpLabel)
1555
157
  MCContext &Ctx = getContext();
1556
157
1557
157
  MCSymbol *TmpLabel = Ctx.createTempSymbol(
1558
157
      "pcrel_hi", /* AlwaysAddSuffix */ true, /* CanBeUnnamed */ false);
1559
157
  Out.EmitLabel(TmpLabel);
1560
157
1561
157
  const RISCVMCExpr *SymbolHi = RISCVMCExpr::create(Symbol, VKHi, Ctx);
1562
157
  emitToStreamer(
1563
157
      Out, MCInstBuilder(RISCV::AUIPC).addOperand(TmpReg).addExpr(SymbolHi));
1564
157
1565
157
  const MCExpr *RefToLinkTmpLabel =
1566
157
      RISCVMCExpr::create(MCSymbolRefExpr::create(TmpLabel, Ctx),
1567
157
                          RISCVMCExpr::VK_RISCV_PCREL_LO, Ctx);
1568
157
1569
157
  emitToStreamer(Out, MCInstBuilder(SecondOpcode)
1570
157
                          .addOperand(DestReg)
1571
157
                          .addOperand(TmpReg)
1572
157
                          .addExpr(RefToLinkTmpLabel));
1573
157
}
1574
1575
void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
1576
24
                                          MCStreamer &Out) {
1577
24
  // The load local address pseudo-instruction "lla" is used in PC-relative
1578
24
  // addressing of local symbols:
1579
24
  //   lla rdest, symbol
1580
24
  // expands to
1581
24
  //   TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
1582
24
  //             ADDI rdest, rdest, %pcrel_lo(TmpLabel)
1583
24
  MCOperand DestReg = Inst.getOperand(0);
1584
24
  const MCExpr *Symbol = Inst.getOperand(1).getExpr();
1585
24
  emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
1586
24
                    RISCV::ADDI, IDLoc, Out);
1587
24
}
1588
1589
void RISCVAsmParser::emitLoadAddress(MCInst &Inst, SMLoc IDLoc,
1590
36
                                     MCStreamer &Out) {
1591
36
  // The load address pseudo-instruction "la" is used in PC-relative and
1592
36
  // GOT-indirect addressing of global symbols:
1593
36
  //   la rdest, symbol
1594
36
  // expands to either (for non-PIC)
1595
36
  //   TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
1596
36
  //             ADDI rdest, rdest, %pcrel_lo(TmpLabel)
1597
36
  // or (for PIC)
1598
36
  //   TmpLabel: AUIPC rdest, %got_pcrel_hi(symbol)
1599
36
  //             Lx rdest, %pcrel_lo(TmpLabel)(rdest)
1600
36
  MCOperand DestReg = Inst.getOperand(0);
1601
36
  const MCExpr *Symbol = Inst.getOperand(1).getExpr();
1602
36
  unsigned SecondOpcode;
1603
36
  RISCVMCExpr::VariantKind VKHi;
1604
36
  // FIXME: Should check .option (no)pic when implemented
1605
36
  if (getContext().getObjectFileInfo()->isPositionIndependent()) {
1606
16
    SecondOpcode = isRV64() ? 
RISCV::LD8
:
RISCV::LW8
;
1607
16
    VKHi = RISCVMCExpr::VK_RISCV_GOT_HI;
1608
20
  } else {
1609
20
    SecondOpcode = RISCV::ADDI;
1610
20
    VKHi = RISCVMCExpr::VK_RISCV_PCREL_HI;
1611
20
  }
1612
36
  emitAuipcInstPair(DestReg, DestReg, Symbol, VKHi, SecondOpcode, IDLoc, Out);
1613
36
}
1614
1615
void RISCVAsmParser::emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc,
1616
24
                                          MCStreamer &Out) {
1617
24
  // The load TLS IE address pseudo-instruction "la.tls.ie" is used in
1618
24
  // initial-exec TLS model addressing of global symbols:
1619
24
  //   la.tls.ie rdest, symbol
1620
24
  // expands to
1621
24
  //   TmpLabel: AUIPC rdest, %tls_ie_pcrel_hi(symbol)
1622
24
  //             Lx rdest, %pcrel_lo(TmpLabel)(rdest)
1623
24
  MCOperand DestReg = Inst.getOperand(0);
1624
24
  const MCExpr *Symbol = Inst.getOperand(1).getExpr();
1625
24
  unsigned SecondOpcode = isRV64() ? 
RISCV::LD12
:
RISCV::LW12
;
1626
24
  emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GOT_HI,
1627
24
                    SecondOpcode, IDLoc, Out);
1628
24
}
1629
1630
void RISCVAsmParser::emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc,
1631
26
                                          MCStreamer &Out) {
1632
26
  // The load TLS GD address pseudo-instruction "la.tls.gd" is used in
1633
26
  // global-dynamic TLS model addressing of global symbols:
1634
26
  //   la.tls.gd rdest, symbol
1635
26
  // expands to
1636
26
  //   TmpLabel: AUIPC rdest, %tls_gd_pcrel_hi(symbol)
1637
26
  //             ADDI rdest, rdest, %pcrel_lo(TmpLabel)
1638
26
  MCOperand DestReg = Inst.getOperand(0);
1639
26
  const MCExpr *Symbol = Inst.getOperand(1).getExpr();
1640
26
  emitAuipcInstPair(DestReg, DestReg, Symbol, RISCVMCExpr::VK_RISCV_TLS_GD_HI,
1641
26
                    RISCV::ADDI, IDLoc, Out);
1642
26
}
1643
1644
void RISCVAsmParser::emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode,
1645
                                         SMLoc IDLoc, MCStreamer &Out,
1646
47
                                         bool HasTmpReg) {
1647
47
  // The load/store pseudo-instruction does a pc-relative load with
1648
47
  // a symbol.
1649
47
  //
1650
47
  // The expansion looks like this
1651
47
  //
1652
47
  //   TmpLabel: AUIPC tmp, %pcrel_hi(symbol)
1653
47
  //             [S|L]X    rd, %pcrel_lo(TmpLabel)(tmp)
1654
47
  MCOperand DestReg = Inst.getOperand(0);
1655
47
  unsigned SymbolOpIdx = HasTmpReg ? 
225
:
122
;
1656
47
  unsigned TmpRegOpIdx = HasTmpReg ? 
125
:
022
;
1657
47
  MCOperand TmpReg = Inst.getOperand(TmpRegOpIdx);
1658
47
  const MCExpr *Symbol = Inst.getOperand(SymbolOpIdx).getExpr();
1659
47
  emitAuipcInstPair(DestReg, TmpReg, Symbol, RISCVMCExpr::VK_RISCV_PCREL_HI,
1660
47
                    Opcode, IDLoc, Out);
1661
47
}
1662
1663
bool RISCVAsmParser::checkPseudoAddTPRel(MCInst &Inst,
1664
7
                                         OperandVector &Operands) {
1665
7
  assert(Inst.getOpcode() == RISCV::PseudoAddTPRel && "Invalid instruction");
1666
7
  assert(Inst.getOperand(2).isReg() && "Unexpected second operand kind");
1667
7
  if (Inst.getOperand(2).getReg() != RISCV::X4) {
1668
1
    SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
1669
1
    return Error(ErrorLoc, "the second input operand must be tp/x4 when using "
1670
1
                           "%tprel_add modifier");
1671
1
  }
1672
6
1673
6
  return false;
1674
6
}
1675
1676
bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
1677
                                        OperandVector &Operands,
1678
6.04k
                                        MCStreamer &Out) {
1679
6.04k
  Inst.setLoc(IDLoc);
1680
6.04k
1681
6.04k
  switch (Inst.getOpcode()) {
1682
6.04k
  default:
1683
5.53k
    break;
1684
6.04k
  case RISCV::PseudoLI: {
1685
346
    unsigned Reg = Inst.getOperand(0).getReg();
1686
346
    const MCOperand &Op1 = Inst.getOperand(1);
1687
346
    if (Op1.isExpr()) {
1688
24
      // We must have li reg, %lo(sym) or li reg, %pcrel_lo(sym) or similar.
1689
24
      // Just convert to an addi. This allows compatibility with gas.
1690
24
      emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
1691
24
                              .addReg(Reg)
1692
24
                              .addReg(RISCV::X0)
1693
24
                              .addExpr(Op1.getExpr()));
1694
24
      return false;
1695
24
    }
1696
322
    int64_t Imm = Inst.getOperand(1).getImm();
1697
322
    // On RV32 the immediate here can either be a signed or an unsigned
1698
322
    // 32-bit number. Sign extension has to be performed to ensure that Imm
1699
322
    // represents the expected signed 64-bit number.
1700
322
    if (!isRV64())
1701
142
      Imm = SignExtend64<32>(Imm);
1702
322
    emitLoadImm(Reg, Imm, Out);
1703
322
    return false;
1704
322
  }
1705
322
  case RISCV::PseudoLLA:
1706
24
    emitLoadLocalAddress(Inst, IDLoc, Out);
1707
24
    return false;
1708
322
  case RISCV::PseudoLA:
1709
36
    emitLoadAddress(Inst, IDLoc, Out);
1710
36
    return false;
1711
322
  case RISCV::PseudoLA_TLS_IE:
1712
24
    emitLoadTLSIEAddress(Inst, IDLoc, Out);
1713
24
    return false;
1714
322
  case RISCV::PseudoLA_TLS_GD:
1715
26
    emitLoadTLSGDAddress(Inst, IDLoc, Out);
1716
26
    return false;
1717
322
  case RISCV::PseudoLB:
1718
4
    emitLoadStoreSymbol(Inst, RISCV::LB, IDLoc, Out, /*HasTmpReg=*/false);
1719
4
    return false;
1720
322
  case RISCV::PseudoLBU:
1721
0
    emitLoadStoreSymbol(Inst, RISCV::LBU, IDLoc, Out, /*HasTmpReg=*/false);
1722
0
    return false;
1723
322
  case RISCV::PseudoLH:
1724
4
    emitLoadStoreSymbol(Inst, RISCV::LH, IDLoc, Out, /*HasTmpReg=*/false);
1725
4
    return false;
1726
322
  case RISCV::PseudoLHU:
1727
4
    emitLoadStoreSymbol(Inst, RISCV::LHU, IDLoc, Out, /*HasTmpReg=*/false);
1728
4
    return false;
1729
322
  case RISCV::PseudoLW:
1730
8
    emitLoadStoreSymbol(Inst, RISCV::LW, IDLoc, Out, /*HasTmpReg=*/false);
1731
8
    return false;
1732
322
  case RISCV::PseudoLWU:
1733
1
    emitLoadStoreSymbol(Inst, RISCV::LWU, IDLoc, Out, /*HasTmpReg=*/false);
1734
1
    return false;
1735
322
  case RISCV::PseudoLD:
1736
1
    emitLoadStoreSymbol(Inst, RISCV::LD, IDLoc, Out, /*HasTmpReg=*/false);
1737
1
    return false;
1738
322
  case RISCV::PseudoFLW:
1739
2
    emitLoadStoreSymbol(Inst, RISCV::FLW, IDLoc, Out, /*HasTmpReg=*/true);
1740
2
    return false;
1741
322
  case RISCV::PseudoFLD:
1742
2
    emitLoadStoreSymbol(Inst, RISCV::FLD, IDLoc, Out, /*HasTmpReg=*/true);
1743
2
    return false;
1744
322
  case RISCV::PseudoSB:
1745
4
    emitLoadStoreSymbol(Inst, RISCV::SB, IDLoc, Out, /*HasTmpReg=*/true);
1746
4
    return false;
1747
322
  case RISCV::PseudoSH:
1748
4
    emitLoadStoreSymbol(Inst, RISCV::SH, IDLoc, Out, /*HasTmpReg=*/true);
1749
4
    return false;
1750
322
  case RISCV::PseudoSW:
1751
8
    emitLoadStoreSymbol(Inst, RISCV::SW, IDLoc, Out, /*HasTmpReg=*/true);
1752
8
    return false;
1753
322
  case RISCV::PseudoSD:
1754
1
    emitLoadStoreSymbol(Inst, RISCV::SD, IDLoc, Out, /*HasTmpReg=*/true);
1755
1
    return false;
1756
322
  case RISCV::PseudoFSW:
1757
2
    emitLoadStoreSymbol(Inst, RISCV::FSW, IDLoc, Out, /*HasTmpReg=*/true);
1758
2
    return false;
1759
322
  case RISCV::PseudoFSD:
1760
2
    emitLoadStoreSymbol(Inst, RISCV::FSD, IDLoc, Out, /*HasTmpReg=*/true);
1761
2
    return false;
1762
322
  case RISCV::PseudoAddTPRel:
1763
7
    if (checkPseudoAddTPRel(Inst, Operands))
1764
1
      return true;
1765
6
    break;
1766
5.54k
  }
1767
5.54k
1768
5.54k
  emitToStreamer(Out, Inst);
1769
5.54k
  return false;
1770
5.54k
}
1771
1772
91.7k
extern "C" void LLVMInitializeRISCVAsmParser() {
1773
91.7k
  RegisterMCAsmParser<RISCVAsmParser> X(getTheRISCV32Target());
1774
91.7k
  RegisterMCAsmParser<RISCVAsmParser> Y(getTheRISCV64Target());
1775
91.7k
}