xref: /llvm-project/llvm/lib/Target/SystemZ/AsmParser/SystemZAsmParser.cpp (revision deed1b0664e85cd3bb33451a81db52459d9f7663)
1 //===-- SystemZAsmParser.cpp - Parse SystemZ assembly 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/SystemZGNUInstPrinter.h"
10 #include "MCTargetDesc/SystemZMCAsmInfo.h"
11 #include "MCTargetDesc/SystemZMCTargetDesc.h"
12 #include "SystemZTargetStreamer.h"
13 #include "TargetInfo/SystemZTargetInfo.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstBuilder.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCParser/MCAsmLexer.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
28 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/MC/TargetRegistry.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/SMLoc.h"
35 #include <algorithm>
36 #include <cassert>
37 #include <cstddef>
38 #include <cstdint>
39 #include <iterator>
40 #include <memory>
41 #include <string>
42 
43 using namespace llvm;
44 
45 // Return true if Expr is in the range [MinValue, MaxValue]. If AllowSymbol
46 // is true any MCExpr is accepted (address displacement).
47 static bool inRange(const MCExpr *Expr, int64_t MinValue, int64_t MaxValue,
48                     bool AllowSymbol = false) {
49   if (auto *CE = dyn_cast<MCConstantExpr>(Expr)) {
50     int64_t Value = CE->getValue();
51     return Value >= MinValue && Value <= MaxValue;
52   }
53   return AllowSymbol;
54 }
55 
56 namespace {
57 
58 enum RegisterKind {
59   GR32Reg,
60   GRH32Reg,
61   GR64Reg,
62   GR128Reg,
63   FP32Reg,
64   FP64Reg,
65   FP128Reg,
66   VR32Reg,
67   VR64Reg,
68   VR128Reg,
69   AR32Reg,
70   CR64Reg,
71 };
72 
73 enum MemoryKind {
74   BDMem,
75   BDXMem,
76   BDLMem,
77   BDRMem,
78   BDVMem
79 };
80 
81 class SystemZOperand : public MCParsedAsmOperand {
82 private:
83   enum OperandKind {
84     KindInvalid,
85     KindToken,
86     KindReg,
87     KindImm,
88     KindImmTLS,
89     KindMem
90   };
91 
92   OperandKind Kind;
93   SMLoc StartLoc, EndLoc;
94 
95   // A string of length Length, starting at Data.
96   struct TokenOp {
97     const char *Data;
98     unsigned Length;
99   };
100 
101   // LLVM register Num, which has kind Kind.  In some ways it might be
102   // easier for this class to have a register bank (general, floating-point
103   // or access) and a raw register number (0-15).  This would postpone the
104   // interpretation of the operand to the add*() methods and avoid the need
105   // for context-dependent parsing.  However, we do things the current way
106   // because of the virtual getReg() method, which needs to distinguish
107   // between (say) %r0 used as a single register and %r0 used as a pair.
108   // Context-dependent parsing can also give us slightly better error
109   // messages when invalid pairs like %r1 are used.
110   struct RegOp {
111     RegisterKind Kind;
112     unsigned Num;
113   };
114 
115   // Base + Disp + Index, where Base and Index are LLVM registers or 0.
116   // MemKind says what type of memory this is and RegKind says what type
117   // the base register has (GR32Reg or GR64Reg).  Length is the operand
118   // length for D(L,B)-style operands, otherwise it is null.
119   struct MemOp {
120     unsigned Base : 12;
121     unsigned Index : 12;
122     unsigned MemKind : 4;
123     unsigned RegKind : 4;
124     const MCExpr *Disp;
125     union {
126       const MCExpr *Imm;
127       unsigned Reg;
128     } Length;
129   };
130 
131   // Imm is an immediate operand, and Sym is an optional TLS symbol
132   // for use with a __tls_get_offset marker relocation.
133   struct ImmTLSOp {
134     const MCExpr *Imm;
135     const MCExpr *Sym;
136   };
137 
138   union {
139     TokenOp Token;
140     RegOp Reg;
141     const MCExpr *Imm;
142     ImmTLSOp ImmTLS;
143     MemOp Mem;
144   };
145 
146   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
147     // Add as immediates when possible.  Null MCExpr = 0.
148     if (!Expr)
149       Inst.addOperand(MCOperand::createImm(0));
150     else if (auto *CE = dyn_cast<MCConstantExpr>(Expr))
151       Inst.addOperand(MCOperand::createImm(CE->getValue()));
152     else
153       Inst.addOperand(MCOperand::createExpr(Expr));
154   }
155 
156 public:
157   SystemZOperand(OperandKind Kind, SMLoc StartLoc, SMLoc EndLoc)
158       : Kind(Kind), StartLoc(StartLoc), EndLoc(EndLoc) {}
159 
160   // Create particular kinds of operand.
161   static std::unique_ptr<SystemZOperand> createInvalid(SMLoc StartLoc,
162                                                        SMLoc EndLoc) {
163     return std::make_unique<SystemZOperand>(KindInvalid, StartLoc, EndLoc);
164   }
165 
166   static std::unique_ptr<SystemZOperand> createToken(StringRef Str, SMLoc Loc) {
167     auto Op = std::make_unique<SystemZOperand>(KindToken, Loc, Loc);
168     Op->Token.Data = Str.data();
169     Op->Token.Length = Str.size();
170     return Op;
171   }
172 
173   static std::unique_ptr<SystemZOperand>
174   createReg(RegisterKind Kind, unsigned Num, SMLoc StartLoc, SMLoc EndLoc) {
175     auto Op = std::make_unique<SystemZOperand>(KindReg, StartLoc, EndLoc);
176     Op->Reg.Kind = Kind;
177     Op->Reg.Num = Num;
178     return Op;
179   }
180 
181   static std::unique_ptr<SystemZOperand>
182   createImm(const MCExpr *Expr, SMLoc StartLoc, SMLoc EndLoc) {
183     auto Op = std::make_unique<SystemZOperand>(KindImm, StartLoc, EndLoc);
184     Op->Imm = Expr;
185     return Op;
186   }
187 
188   static std::unique_ptr<SystemZOperand>
189   createMem(MemoryKind MemKind, RegisterKind RegKind, unsigned Base,
190             const MCExpr *Disp, unsigned Index, const MCExpr *LengthImm,
191             unsigned LengthReg, SMLoc StartLoc, SMLoc EndLoc) {
192     auto Op = std::make_unique<SystemZOperand>(KindMem, StartLoc, EndLoc);
193     Op->Mem.MemKind = MemKind;
194     Op->Mem.RegKind = RegKind;
195     Op->Mem.Base = Base;
196     Op->Mem.Index = Index;
197     Op->Mem.Disp = Disp;
198     if (MemKind == BDLMem)
199       Op->Mem.Length.Imm = LengthImm;
200     if (MemKind == BDRMem)
201       Op->Mem.Length.Reg = LengthReg;
202     return Op;
203   }
204 
205   static std::unique_ptr<SystemZOperand>
206   createImmTLS(const MCExpr *Imm, const MCExpr *Sym,
207                SMLoc StartLoc, SMLoc EndLoc) {
208     auto Op = std::make_unique<SystemZOperand>(KindImmTLS, StartLoc, EndLoc);
209     Op->ImmTLS.Imm = Imm;
210     Op->ImmTLS.Sym = Sym;
211     return Op;
212   }
213 
214   // Token operands
215   bool isToken() const override {
216     return Kind == KindToken;
217   }
218   StringRef getToken() const {
219     assert(Kind == KindToken && "Not a token");
220     return StringRef(Token.Data, Token.Length);
221   }
222 
223   // Register operands.
224   bool isReg() const override {
225     return Kind == KindReg;
226   }
227   bool isReg(RegisterKind RegKind) const {
228     return Kind == KindReg && Reg.Kind == RegKind;
229   }
230   MCRegister getReg() const override {
231     assert(Kind == KindReg && "Not a register");
232     return Reg.Num;
233   }
234 
235   // Immediate operands.
236   bool isImm() const override {
237     return Kind == KindImm;
238   }
239   bool isImm(int64_t MinValue, int64_t MaxValue) const {
240     return Kind == KindImm && inRange(Imm, MinValue, MaxValue, true);
241   }
242   const MCExpr *getImm() const {
243     assert(Kind == KindImm && "Not an immediate");
244     return Imm;
245   }
246 
247   // Immediate operands with optional TLS symbol.
248   bool isImmTLS() const {
249     return Kind == KindImmTLS;
250   }
251 
252   const ImmTLSOp getImmTLS() const {
253     assert(Kind == KindImmTLS && "Not a TLS immediate");
254     return ImmTLS;
255   }
256 
257   // Memory operands.
258   bool isMem() const override {
259     return Kind == KindMem;
260   }
261   bool isMem(MemoryKind MemKind) const {
262     return (Kind == KindMem &&
263             (Mem.MemKind == MemKind ||
264              // A BDMem can be treated as a BDXMem in which the index
265              // register field is 0.
266              (Mem.MemKind == BDMem && MemKind == BDXMem)));
267   }
268   bool isMem(MemoryKind MemKind, RegisterKind RegKind) const {
269     return isMem(MemKind) && Mem.RegKind == RegKind;
270   }
271   bool isMemDisp12(MemoryKind MemKind, RegisterKind RegKind) const {
272     return isMem(MemKind, RegKind) && inRange(Mem.Disp, 0, 0xfff, true);
273   }
274   bool isMemDisp20(MemoryKind MemKind, RegisterKind RegKind) const {
275     return isMem(MemKind, RegKind) && inRange(Mem.Disp, -524288, 524287, true);
276   }
277   bool isMemDisp12Len4(RegisterKind RegKind) const {
278     return isMemDisp12(BDLMem, RegKind) && inRange(Mem.Length.Imm, 1, 0x10);
279   }
280   bool isMemDisp12Len8(RegisterKind RegKind) const {
281     return isMemDisp12(BDLMem, RegKind) && inRange(Mem.Length.Imm, 1, 0x100);
282   }
283 
284   const MemOp& getMem() const {
285     assert(Kind == KindMem && "Not a Mem operand");
286     return Mem;
287   }
288 
289   // Override MCParsedAsmOperand.
290   SMLoc getStartLoc() const override { return StartLoc; }
291   SMLoc getEndLoc() const override { return EndLoc; }
292   void print(raw_ostream &OS) const override;
293 
294   /// getLocRange - Get the range between the first and last token of this
295   /// operand.
296   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
297 
298   // Used by the TableGen code to add particular types of operand
299   // to an instruction.
300   void addRegOperands(MCInst &Inst, unsigned N) const {
301     assert(N == 1 && "Invalid number of operands");
302     Inst.addOperand(MCOperand::createReg(getReg()));
303   }
304   void addImmOperands(MCInst &Inst, unsigned N) const {
305     assert(N == 1 && "Invalid number of operands");
306     addExpr(Inst, getImm());
307   }
308   void addBDAddrOperands(MCInst &Inst, unsigned N) const {
309     assert(N == 2 && "Invalid number of operands");
310     assert(isMem(BDMem) && "Invalid operand type");
311     Inst.addOperand(MCOperand::createReg(Mem.Base));
312     addExpr(Inst, Mem.Disp);
313   }
314   void addBDXAddrOperands(MCInst &Inst, unsigned N) const {
315     assert(N == 3 && "Invalid number of operands");
316     assert(isMem(BDXMem) && "Invalid operand type");
317     Inst.addOperand(MCOperand::createReg(Mem.Base));
318     addExpr(Inst, Mem.Disp);
319     Inst.addOperand(MCOperand::createReg(Mem.Index));
320   }
321   void addBDLAddrOperands(MCInst &Inst, unsigned N) const {
322     assert(N == 3 && "Invalid number of operands");
323     assert(isMem(BDLMem) && "Invalid operand type");
324     Inst.addOperand(MCOperand::createReg(Mem.Base));
325     addExpr(Inst, Mem.Disp);
326     addExpr(Inst, Mem.Length.Imm);
327   }
328   void addBDRAddrOperands(MCInst &Inst, unsigned N) const {
329     assert(N == 3 && "Invalid number of operands");
330     assert(isMem(BDRMem) && "Invalid operand type");
331     Inst.addOperand(MCOperand::createReg(Mem.Base));
332     addExpr(Inst, Mem.Disp);
333     Inst.addOperand(MCOperand::createReg(Mem.Length.Reg));
334   }
335   void addBDVAddrOperands(MCInst &Inst, unsigned N) const {
336     assert(N == 3 && "Invalid number of operands");
337     assert(isMem(BDVMem) && "Invalid operand type");
338     Inst.addOperand(MCOperand::createReg(Mem.Base));
339     addExpr(Inst, Mem.Disp);
340     Inst.addOperand(MCOperand::createReg(Mem.Index));
341   }
342   void addImmTLSOperands(MCInst &Inst, unsigned N) const {
343     assert(N == 2 && "Invalid number of operands");
344     assert(Kind == KindImmTLS && "Invalid operand type");
345     addExpr(Inst, ImmTLS.Imm);
346     if (ImmTLS.Sym)
347       addExpr(Inst, ImmTLS.Sym);
348   }
349 
350   // Used by the TableGen code to check for particular operand types.
351   bool isGR32() const { return isReg(GR32Reg); }
352   bool isGRH32() const { return isReg(GRH32Reg); }
353   bool isGRX32() const { return false; }
354   bool isGR64() const { return isReg(GR64Reg); }
355   bool isGR128() const { return isReg(GR128Reg); }
356   bool isADDR32() const { return isReg(GR32Reg); }
357   bool isADDR64() const { return isReg(GR64Reg); }
358   bool isADDR128() const { return false; }
359   bool isFP32() const { return isReg(FP32Reg); }
360   bool isFP64() const { return isReg(FP64Reg); }
361   bool isFP128() const { return isReg(FP128Reg); }
362   bool isVR32() const { return isReg(VR32Reg); }
363   bool isVR64() const { return isReg(VR64Reg); }
364   bool isVF128() const { return false; }
365   bool isVR128() const { return isReg(VR128Reg); }
366   bool isAR32() const { return isReg(AR32Reg); }
367   bool isCR64() const { return isReg(CR64Reg); }
368   bool isAnyReg() const { return (isReg() || isImm(0, 15)); }
369   bool isBDAddr32Disp12() const { return isMemDisp12(BDMem, GR32Reg); }
370   bool isBDAddr32Disp20() const { return isMemDisp20(BDMem, GR32Reg); }
371   bool isBDAddr64Disp12() const { return isMemDisp12(BDMem, GR64Reg); }
372   bool isBDAddr64Disp20() const { return isMemDisp20(BDMem, GR64Reg); }
373   bool isBDXAddr64Disp12() const { return isMemDisp12(BDXMem, GR64Reg); }
374   bool isBDXAddr64Disp20() const { return isMemDisp20(BDXMem, GR64Reg); }
375   bool isBDLAddr64Disp12Len4() const { return isMemDisp12Len4(GR64Reg); }
376   bool isBDLAddr64Disp12Len8() const { return isMemDisp12Len8(GR64Reg); }
377   bool isBDRAddr64Disp12() const { return isMemDisp12(BDRMem, GR64Reg); }
378   bool isBDVAddr64Disp12() const { return isMemDisp12(BDVMem, GR64Reg); }
379   bool isU1Imm() const { return isImm(0, 1); }
380   bool isU2Imm() const { return isImm(0, 3); }
381   bool isU3Imm() const { return isImm(0, 7); }
382   bool isU4Imm() const { return isImm(0, 15); }
383   bool isU8Imm() const { return isImm(0, 255); }
384   bool isS8Imm() const { return isImm(-128, 127); }
385   bool isU12Imm() const { return isImm(0, 4095); }
386   bool isU16Imm() const { return isImm(0, 65535); }
387   bool isS16Imm() const { return isImm(-32768, 32767); }
388   bool isU32Imm() const { return isImm(0, (1LL << 32) - 1); }
389   bool isS32Imm() const { return isImm(-(1LL << 31), (1LL << 31) - 1); }
390   bool isU48Imm() const { return isImm(0, (1LL << 48) - 1); }
391 };
392 
393 class SystemZAsmParser : public MCTargetAsmParser {
394 #define GET_ASSEMBLER_HEADER
395 #include "SystemZGenAsmMatcher.inc"
396 
397 private:
398   MCAsmParser &Parser;
399   enum RegisterGroup {
400     RegGR,
401     RegFP,
402     RegV,
403     RegAR,
404     RegCR
405   };
406   struct Register {
407     RegisterGroup Group;
408     unsigned Num;
409     SMLoc StartLoc, EndLoc;
410   };
411 
412   SystemZTargetStreamer &getTargetStreamer() {
413     assert(getParser().getStreamer().getTargetStreamer() &&
414            "do not have a target streamer");
415     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
416     return static_cast<SystemZTargetStreamer &>(TS);
417   }
418 
419   bool parseRegister(Register &Reg, bool RequirePercent,
420                      bool RestoreOnFailure = false);
421 
422   bool parseIntegerRegister(Register &Reg, RegisterGroup Group);
423 
424   ParseStatus parseRegister(OperandVector &Operands, RegisterKind Kind);
425 
426   ParseStatus parseAnyRegister(OperandVector &Operands);
427 
428   bool parseAddress(bool &HaveReg1, Register &Reg1, bool &HaveReg2,
429                     Register &Reg2, const MCExpr *&Disp, const MCExpr *&Length,
430                     bool HasLength = false, bool HasVectorIndex = false);
431   bool parseAddressRegister(Register &Reg);
432 
433   bool ParseDirectiveInsn(SMLoc L);
434   bool ParseDirectiveMachine(SMLoc L);
435   bool ParseGNUAttribute(SMLoc L);
436 
437   ParseStatus parseAddress(OperandVector &Operands, MemoryKind MemKind,
438                            RegisterKind RegKind);
439 
440   ParseStatus parsePCRel(OperandVector &Operands, int64_t MinVal,
441                          int64_t MaxVal, bool AllowTLS);
442 
443   bool parseOperand(OperandVector &Operands, StringRef Mnemonic);
444 
445   // Both the hlasm and gnu variants still rely on the basic gnu asm
446   // format with respect to inputs, clobbers, outputs etc.
447   //
448   // However, calling the overriden getAssemblerDialect() method in
449   // AsmParser is problematic. It either returns the AssemblerDialect field
450   // in the MCAsmInfo instance if the AssemblerDialect field in AsmParser is
451   // unset, otherwise it returns the private AssemblerDialect field in
452   // AsmParser.
453   //
454   // The problematic part is because, we forcibly set the inline asm dialect
455   // in the AsmParser instance in AsmPrinterInlineAsm.cpp. Soo any query
456   // to the overriden getAssemblerDialect function in AsmParser.cpp, will
457   // not return the assembler dialect set in the respective MCAsmInfo instance.
458   //
459   // For this purpose, we explicitly query the SystemZMCAsmInfo instance
460   // here, to get the "correct" assembler dialect, and use it in various
461   // functions.
462   unsigned getMAIAssemblerDialect() {
463     return Parser.getContext().getAsmInfo()->getAssemblerDialect();
464   }
465 
466   // An alphabetic character in HLASM is a letter from 'A' through 'Z',
467   // or from 'a' through 'z', or '$', '_','#', or '@'.
468   inline bool isHLASMAlpha(char C) {
469     return isAlpha(C) || llvm::is_contained("_@#$", C);
470   }
471 
472   // A digit in HLASM is a number from 0 to 9.
473   inline bool isHLASMAlnum(char C) { return isHLASMAlpha(C) || isDigit(C); }
474 
475   // Are we parsing using the AD_HLASM dialect?
476   inline bool isParsingHLASM() { return getMAIAssemblerDialect() == AD_HLASM; }
477 
478   // Are we parsing using the AD_GNU dialect?
479   inline bool isParsingGNU() { return getMAIAssemblerDialect() == AD_GNU; }
480 
481 public:
482   SystemZAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser,
483                    const MCInstrInfo &MII,
484                    const MCTargetOptions &Options)
485     : MCTargetAsmParser(Options, sti, MII), Parser(parser) {
486     MCAsmParserExtension::Initialize(Parser);
487 
488     // Alias the .word directive to .short.
489     parser.addAliasForDirective(".word", ".short");
490 
491     // Initialize the set of available features.
492     setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
493   }
494 
495   // Override MCTargetAsmParser.
496   ParseStatus parseDirective(AsmToken DirectiveID) override;
497   bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
498   bool ParseRegister(MCRegister &RegNo, SMLoc &StartLoc, SMLoc &EndLoc,
499                      bool RequirePercent, bool RestoreOnFailure);
500   ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
501                                SMLoc &EndLoc) override;
502   bool parseInstruction(ParseInstructionInfo &Info, StringRef Name,
503                         SMLoc NameLoc, OperandVector &Operands) override;
504   bool matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
505                                OperandVector &Operands, MCStreamer &Out,
506                                uint64_t &ErrorInfo,
507                                bool MatchingInlineAsm) override;
508   bool isLabel(AsmToken &Token) override;
509 
510   // Used by the TableGen code to parse particular operand types.
511   ParseStatus parseGR32(OperandVector &Operands) {
512     return parseRegister(Operands, GR32Reg);
513   }
514   ParseStatus parseGRH32(OperandVector &Operands) {
515     return parseRegister(Operands, GRH32Reg);
516   }
517   ParseStatus parseGRX32(OperandVector &Operands) {
518     llvm_unreachable("GRX32 should only be used for pseudo instructions");
519   }
520   ParseStatus parseGR64(OperandVector &Operands) {
521     return parseRegister(Operands, GR64Reg);
522   }
523   ParseStatus parseGR128(OperandVector &Operands) {
524     return parseRegister(Operands, GR128Reg);
525   }
526   ParseStatus parseADDR32(OperandVector &Operands) {
527     // For the AsmParser, we will accept %r0 for ADDR32 as well.
528     return parseRegister(Operands, GR32Reg);
529   }
530   ParseStatus parseADDR64(OperandVector &Operands) {
531     // For the AsmParser, we will accept %r0 for ADDR64 as well.
532     return parseRegister(Operands, GR64Reg);
533   }
534   ParseStatus parseADDR128(OperandVector &Operands) {
535     llvm_unreachable("Shouldn't be used as an operand");
536   }
537   ParseStatus parseFP32(OperandVector &Operands) {
538     return parseRegister(Operands, FP32Reg);
539   }
540   ParseStatus parseFP64(OperandVector &Operands) {
541     return parseRegister(Operands, FP64Reg);
542   }
543   ParseStatus parseFP128(OperandVector &Operands) {
544     return parseRegister(Operands, FP128Reg);
545   }
546   ParseStatus parseVR32(OperandVector &Operands) {
547     return parseRegister(Operands, VR32Reg);
548   }
549   ParseStatus parseVR64(OperandVector &Operands) {
550     return parseRegister(Operands, VR64Reg);
551   }
552   ParseStatus parseVF128(OperandVector &Operands) {
553     llvm_unreachable("Shouldn't be used as an operand");
554   }
555   ParseStatus parseVR128(OperandVector &Operands) {
556     return parseRegister(Operands, VR128Reg);
557   }
558   ParseStatus parseAR32(OperandVector &Operands) {
559     return parseRegister(Operands, AR32Reg);
560   }
561   ParseStatus parseCR64(OperandVector &Operands) {
562     return parseRegister(Operands, CR64Reg);
563   }
564   ParseStatus parseAnyReg(OperandVector &Operands) {
565     return parseAnyRegister(Operands);
566   }
567   ParseStatus parseBDAddr32(OperandVector &Operands) {
568     return parseAddress(Operands, BDMem, GR32Reg);
569   }
570   ParseStatus parseBDAddr64(OperandVector &Operands) {
571     return parseAddress(Operands, BDMem, GR64Reg);
572   }
573   ParseStatus parseBDXAddr64(OperandVector &Operands) {
574     return parseAddress(Operands, BDXMem, GR64Reg);
575   }
576   ParseStatus parseBDLAddr64(OperandVector &Operands) {
577     return parseAddress(Operands, BDLMem, GR64Reg);
578   }
579   ParseStatus parseBDRAddr64(OperandVector &Operands) {
580     return parseAddress(Operands, BDRMem, GR64Reg);
581   }
582   ParseStatus parseBDVAddr64(OperandVector &Operands) {
583     return parseAddress(Operands, BDVMem, GR64Reg);
584   }
585   ParseStatus parsePCRel12(OperandVector &Operands) {
586     return parsePCRel(Operands, -(1LL << 12), (1LL << 12) - 1, false);
587   }
588   ParseStatus parsePCRel16(OperandVector &Operands) {
589     return parsePCRel(Operands, -(1LL << 16), (1LL << 16) - 1, false);
590   }
591   ParseStatus parsePCRel24(OperandVector &Operands) {
592     return parsePCRel(Operands, -(1LL << 24), (1LL << 24) - 1, false);
593   }
594   ParseStatus parsePCRel32(OperandVector &Operands) {
595     return parsePCRel(Operands, -(1LL << 32), (1LL << 32) - 1, false);
596   }
597   ParseStatus parsePCRelTLS16(OperandVector &Operands) {
598     return parsePCRel(Operands, -(1LL << 16), (1LL << 16) - 1, true);
599   }
600   ParseStatus parsePCRelTLS32(OperandVector &Operands) {
601     return parsePCRel(Operands, -(1LL << 32), (1LL << 32) - 1, true);
602   }
603 };
604 
605 } // end anonymous namespace
606 
607 #define GET_REGISTER_MATCHER
608 #define GET_SUBTARGET_FEATURE_NAME
609 #define GET_MATCHER_IMPLEMENTATION
610 #define GET_MNEMONIC_SPELL_CHECKER
611 #include "SystemZGenAsmMatcher.inc"
612 
613 // Used for the .insn directives; contains information needed to parse the
614 // operands in the directive.
615 struct InsnMatchEntry {
616   StringRef Format;
617   uint64_t Opcode;
618   int32_t NumOperands;
619   MatchClassKind OperandKinds[7];
620 };
621 
622 // For equal_range comparison.
623 struct CompareInsn {
624   bool operator() (const InsnMatchEntry &LHS, StringRef RHS) {
625     return LHS.Format < RHS;
626   }
627   bool operator() (StringRef LHS, const InsnMatchEntry &RHS) {
628     return LHS < RHS.Format;
629   }
630   bool operator() (const InsnMatchEntry &LHS, const InsnMatchEntry &RHS) {
631     return LHS.Format < RHS.Format;
632   }
633 };
634 
635 // Table initializing information for parsing the .insn directive.
636 static struct InsnMatchEntry InsnMatchTable[] = {
637   /* Format, Opcode, NumOperands, OperandKinds */
638   { "e", SystemZ::InsnE, 1,
639     { MCK_U16Imm } },
640   { "ri", SystemZ::InsnRI, 3,
641     { MCK_U32Imm, MCK_AnyReg, MCK_S16Imm } },
642   { "rie", SystemZ::InsnRIE, 4,
643     { MCK_U48Imm, MCK_AnyReg, MCK_AnyReg, MCK_PCRel16 } },
644   { "ril", SystemZ::InsnRIL, 3,
645     { MCK_U48Imm, MCK_AnyReg, MCK_PCRel32 } },
646   { "rilu", SystemZ::InsnRILU, 3,
647     { MCK_U48Imm, MCK_AnyReg, MCK_U32Imm } },
648   { "ris", SystemZ::InsnRIS, 5,
649     { MCK_U48Imm, MCK_AnyReg, MCK_S8Imm, MCK_U4Imm, MCK_BDAddr64Disp12 } },
650   { "rr", SystemZ::InsnRR, 3,
651     { MCK_U16Imm, MCK_AnyReg, MCK_AnyReg } },
652   { "rre", SystemZ::InsnRRE, 3,
653     { MCK_U32Imm, MCK_AnyReg, MCK_AnyReg } },
654   { "rrf", SystemZ::InsnRRF, 5,
655     { MCK_U32Imm, MCK_AnyReg, MCK_AnyReg, MCK_AnyReg, MCK_U4Imm } },
656   { "rrs", SystemZ::InsnRRS, 5,
657     { MCK_U48Imm, MCK_AnyReg, MCK_AnyReg, MCK_U4Imm, MCK_BDAddr64Disp12 } },
658   { "rs", SystemZ::InsnRS, 4,
659     { MCK_U32Imm, MCK_AnyReg, MCK_AnyReg, MCK_BDAddr64Disp12 } },
660   { "rse", SystemZ::InsnRSE, 4,
661     { MCK_U48Imm, MCK_AnyReg, MCK_AnyReg, MCK_BDAddr64Disp12 } },
662   { "rsi", SystemZ::InsnRSI, 4,
663     { MCK_U48Imm, MCK_AnyReg, MCK_AnyReg, MCK_PCRel16 } },
664   { "rsy", SystemZ::InsnRSY, 4,
665     { MCK_U48Imm, MCK_AnyReg, MCK_AnyReg, MCK_BDAddr64Disp20 } },
666   { "rx", SystemZ::InsnRX, 3,
667     { MCK_U32Imm, MCK_AnyReg, MCK_BDXAddr64Disp12 } },
668   { "rxe", SystemZ::InsnRXE, 3,
669     { MCK_U48Imm, MCK_AnyReg, MCK_BDXAddr64Disp12 } },
670   { "rxf", SystemZ::InsnRXF, 4,
671     { MCK_U48Imm, MCK_AnyReg, MCK_AnyReg, MCK_BDXAddr64Disp12 } },
672   { "rxy", SystemZ::InsnRXY, 3,
673     { MCK_U48Imm, MCK_AnyReg, MCK_BDXAddr64Disp20 } },
674   { "s", SystemZ::InsnS, 2,
675     { MCK_U32Imm, MCK_BDAddr64Disp12 } },
676   { "si", SystemZ::InsnSI, 3,
677     { MCK_U32Imm, MCK_BDAddr64Disp12, MCK_S8Imm } },
678   { "sil", SystemZ::InsnSIL, 3,
679     { MCK_U48Imm, MCK_BDAddr64Disp12, MCK_U16Imm } },
680   { "siy", SystemZ::InsnSIY, 3,
681     { MCK_U48Imm, MCK_BDAddr64Disp20, MCK_U8Imm } },
682   { "ss", SystemZ::InsnSS, 4,
683     { MCK_U48Imm, MCK_BDXAddr64Disp12, MCK_BDAddr64Disp12, MCK_AnyReg } },
684   { "sse", SystemZ::InsnSSE, 3,
685     { MCK_U48Imm, MCK_BDAddr64Disp12, MCK_BDAddr64Disp12 } },
686   { "ssf", SystemZ::InsnSSF, 4,
687     { MCK_U48Imm, MCK_BDAddr64Disp12, MCK_BDAddr64Disp12, MCK_AnyReg } },
688   { "vri", SystemZ::InsnVRI, 6,
689     { MCK_U48Imm, MCK_VR128, MCK_VR128, MCK_U12Imm, MCK_U4Imm, MCK_U4Imm } },
690   { "vrr", SystemZ::InsnVRR, 7,
691     { MCK_U48Imm, MCK_VR128, MCK_VR128, MCK_VR128, MCK_U4Imm, MCK_U4Imm,
692       MCK_U4Imm } },
693   { "vrs", SystemZ::InsnVRS, 5,
694     { MCK_U48Imm, MCK_AnyReg, MCK_VR128, MCK_BDAddr64Disp12, MCK_U4Imm } },
695   { "vrv", SystemZ::InsnVRV, 4,
696     { MCK_U48Imm, MCK_VR128, MCK_BDVAddr64Disp12, MCK_U4Imm } },
697   { "vrx", SystemZ::InsnVRX, 4,
698     { MCK_U48Imm, MCK_VR128, MCK_BDXAddr64Disp12, MCK_U4Imm } },
699   { "vsi", SystemZ::InsnVSI, 4,
700     { MCK_U48Imm, MCK_VR128, MCK_BDAddr64Disp12, MCK_U8Imm } }
701 };
702 
703 static void printMCExpr(const MCExpr *E, raw_ostream &OS) {
704   if (!E)
705     return;
706   if (auto *CE = dyn_cast<MCConstantExpr>(E))
707     OS << *CE;
708   else if (auto *UE = dyn_cast<MCUnaryExpr>(E))
709     OS << *UE;
710   else if (auto *BE = dyn_cast<MCBinaryExpr>(E))
711     OS << *BE;
712   else if (auto *SRE = dyn_cast<MCSymbolRefExpr>(E))
713     OS << *SRE;
714   else
715     OS << *E;
716 }
717 
718 void SystemZOperand::print(raw_ostream &OS) const {
719   switch (Kind) {
720   case KindToken:
721     OS << "Token:" << getToken();
722     break;
723   case KindReg:
724     OS << "Reg:" << SystemZGNUInstPrinter::getRegisterName(getReg());
725     break;
726   case KindImm:
727     OS << "Imm:";
728     printMCExpr(getImm(), OS);
729     break;
730   case KindImmTLS:
731     OS << "ImmTLS:";
732     printMCExpr(getImmTLS().Imm, OS);
733     if (getImmTLS().Sym) {
734       OS << ", ";
735       printMCExpr(getImmTLS().Sym, OS);
736     }
737     break;
738   case KindMem: {
739     const MemOp &Op = getMem();
740     OS << "Mem:" << *cast<MCConstantExpr>(Op.Disp);
741     if (Op.Base) {
742       OS << "(";
743       if (Op.MemKind == BDLMem)
744         OS << *cast<MCConstantExpr>(Op.Length.Imm) << ",";
745       else if (Op.MemKind == BDRMem)
746         OS << SystemZGNUInstPrinter::getRegisterName(Op.Length.Reg) << ",";
747       if (Op.Index)
748         OS << SystemZGNUInstPrinter::getRegisterName(Op.Index) << ",";
749       OS << SystemZGNUInstPrinter::getRegisterName(Op.Base);
750       OS << ")";
751     }
752     break;
753   }
754   case KindInvalid:
755     break;
756   }
757 }
758 
759 // Parse one register of the form %<prefix><number>.
760 bool SystemZAsmParser::parseRegister(Register &Reg, bool RequirePercent,
761                                      bool RestoreOnFailure) {
762   const AsmToken &PercentTok = Parser.getTok();
763   bool HasPercent = PercentTok.is(AsmToken::Percent);
764 
765   Reg.StartLoc = PercentTok.getLoc();
766 
767   if (RequirePercent && PercentTok.isNot(AsmToken::Percent))
768     return Error(PercentTok.getLoc(), "register expected");
769 
770   if (HasPercent) {
771     Parser.Lex(); // Eat percent token.
772   }
773 
774   // Expect a register name.
775   if (Parser.getTok().isNot(AsmToken::Identifier)) {
776     if (RestoreOnFailure && HasPercent)
777       getLexer().UnLex(PercentTok);
778     return Error(Reg.StartLoc,
779                  HasPercent ? "invalid register" : "register expected");
780   }
781 
782   // Check that there's a prefix.
783   StringRef Name = Parser.getTok().getString();
784   if (Name.size() < 2) {
785     if (RestoreOnFailure && HasPercent)
786       getLexer().UnLex(PercentTok);
787     return Error(Reg.StartLoc, "invalid register");
788   }
789   char Prefix = Name[0];
790 
791   // Treat the rest of the register name as a register number.
792   if (Name.substr(1).getAsInteger(10, Reg.Num)) {
793     if (RestoreOnFailure && HasPercent)
794       getLexer().UnLex(PercentTok);
795     return Error(Reg.StartLoc, "invalid register");
796   }
797 
798   // Look for valid combinations of prefix and number.
799   if (Prefix == 'r' && Reg.Num < 16)
800     Reg.Group = RegGR;
801   else if (Prefix == 'f' && Reg.Num < 16)
802     Reg.Group = RegFP;
803   else if (Prefix == 'v' && Reg.Num < 32)
804     Reg.Group = RegV;
805   else if (Prefix == 'a' && Reg.Num < 16)
806     Reg.Group = RegAR;
807   else if (Prefix == 'c' && Reg.Num < 16)
808     Reg.Group = RegCR;
809   else {
810     if (RestoreOnFailure && HasPercent)
811       getLexer().UnLex(PercentTok);
812     return Error(Reg.StartLoc, "invalid register");
813   }
814 
815   Reg.EndLoc = Parser.getTok().getLoc();
816   Parser.Lex();
817   return false;
818 }
819 
820 // Parse a register of kind Kind and add it to Operands.
821 ParseStatus SystemZAsmParser::parseRegister(OperandVector &Operands,
822                                             RegisterKind Kind) {
823   Register Reg;
824   RegisterGroup Group;
825   switch (Kind) {
826   case GR32Reg:
827   case GRH32Reg:
828   case GR64Reg:
829   case GR128Reg:
830     Group = RegGR;
831     break;
832   case FP32Reg:
833   case FP64Reg:
834   case FP128Reg:
835     Group = RegFP;
836     break;
837   case VR32Reg:
838   case VR64Reg:
839   case VR128Reg:
840     Group = RegV;
841     break;
842   case AR32Reg:
843     Group = RegAR;
844     break;
845   case CR64Reg:
846     Group = RegCR;
847     break;
848   }
849 
850   // Handle register names of the form %<prefix><number>
851   if (isParsingGNU() && Parser.getTok().is(AsmToken::Percent)) {
852     if (parseRegister(Reg, /*RequirePercent=*/true))
853       return ParseStatus::Failure;
854 
855     // Check the parsed register group "Reg.Group" with the expected "Group"
856     // Have to error out if user specified wrong prefix.
857     switch (Group) {
858     case RegGR:
859     case RegFP:
860     case RegAR:
861     case RegCR:
862       if (Group != Reg.Group)
863         return Error(Reg.StartLoc, "invalid operand for instruction");
864       break;
865     case RegV:
866       if (Reg.Group != RegV && Reg.Group != RegFP)
867         return Error(Reg.StartLoc, "invalid operand for instruction");
868       break;
869     }
870   } else if (Parser.getTok().is(AsmToken::Integer)) {
871     if (parseIntegerRegister(Reg, Group))
872       return ParseStatus::Failure;
873   }
874   // Otherwise we didn't match a register operand.
875   else
876     return ParseStatus::NoMatch;
877 
878   // Determine the LLVM register number according to Kind.
879   const unsigned *Regs;
880   switch (Kind) {
881   case GR32Reg:  Regs = SystemZMC::GR32Regs;  break;
882   case GRH32Reg: Regs = SystemZMC::GRH32Regs; break;
883   case GR64Reg:  Regs = SystemZMC::GR64Regs;  break;
884   case GR128Reg: Regs = SystemZMC::GR128Regs; break;
885   case FP32Reg:  Regs = SystemZMC::FP32Regs;  break;
886   case FP64Reg:  Regs = SystemZMC::FP64Regs;  break;
887   case FP128Reg: Regs = SystemZMC::FP128Regs; break;
888   case VR32Reg:  Regs = SystemZMC::VR32Regs;  break;
889   case VR64Reg:  Regs = SystemZMC::VR64Regs;  break;
890   case VR128Reg: Regs = SystemZMC::VR128Regs; break;
891   case AR32Reg:  Regs = SystemZMC::AR32Regs;  break;
892   case CR64Reg:  Regs = SystemZMC::CR64Regs;  break;
893   }
894   if (Regs[Reg.Num] == 0)
895     return Error(Reg.StartLoc, "invalid register pair");
896 
897   Operands.push_back(
898       SystemZOperand::createReg(Kind, Regs[Reg.Num], Reg.StartLoc, Reg.EndLoc));
899   return ParseStatus::Success;
900 }
901 
902 // Parse any type of register (including integers) and add it to Operands.
903 ParseStatus SystemZAsmParser::parseAnyRegister(OperandVector &Operands) {
904   SMLoc StartLoc = Parser.getTok().getLoc();
905 
906   // Handle integer values.
907   if (Parser.getTok().is(AsmToken::Integer)) {
908     const MCExpr *Register;
909     if (Parser.parseExpression(Register))
910       return ParseStatus::Failure;
911 
912     if (auto *CE = dyn_cast<MCConstantExpr>(Register)) {
913       int64_t Value = CE->getValue();
914       if (Value < 0 || Value > 15)
915         return Error(StartLoc, "invalid register");
916     }
917 
918     SMLoc EndLoc =
919       SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
920 
921     Operands.push_back(SystemZOperand::createImm(Register, StartLoc, EndLoc));
922   }
923   else {
924     if (isParsingHLASM())
925       return ParseStatus::NoMatch;
926 
927     Register Reg;
928     if (parseRegister(Reg, /*RequirePercent=*/true))
929       return ParseStatus::Failure;
930 
931     if (Reg.Num > 15)
932       return Error(StartLoc, "invalid register");
933 
934     // Map to the correct register kind.
935     RegisterKind Kind;
936     unsigned RegNo;
937     if (Reg.Group == RegGR) {
938       Kind = GR64Reg;
939       RegNo = SystemZMC::GR64Regs[Reg.Num];
940     }
941     else if (Reg.Group == RegFP) {
942       Kind = FP64Reg;
943       RegNo = SystemZMC::FP64Regs[Reg.Num];
944     }
945     else if (Reg.Group == RegV) {
946       Kind = VR128Reg;
947       RegNo = SystemZMC::VR128Regs[Reg.Num];
948     }
949     else if (Reg.Group == RegAR) {
950       Kind = AR32Reg;
951       RegNo = SystemZMC::AR32Regs[Reg.Num];
952     }
953     else if (Reg.Group == RegCR) {
954       Kind = CR64Reg;
955       RegNo = SystemZMC::CR64Regs[Reg.Num];
956     }
957     else {
958       return ParseStatus::Failure;
959     }
960 
961     Operands.push_back(SystemZOperand::createReg(Kind, RegNo,
962                                                  Reg.StartLoc, Reg.EndLoc));
963   }
964   return ParseStatus::Success;
965 }
966 
967 bool SystemZAsmParser::parseIntegerRegister(Register &Reg,
968                                             RegisterGroup Group) {
969   Reg.StartLoc = Parser.getTok().getLoc();
970   // We have an integer token
971   const MCExpr *Register;
972   if (Parser.parseExpression(Register))
973     return true;
974 
975   const auto *CE = dyn_cast<MCConstantExpr>(Register);
976   if (!CE)
977     return true;
978 
979   int64_t MaxRegNum = (Group == RegV) ? 31 : 15;
980   int64_t Value = CE->getValue();
981   if (Value < 0 || Value > MaxRegNum) {
982     Error(Parser.getTok().getLoc(), "invalid register");
983     return true;
984   }
985 
986   // Assign the Register Number
987   Reg.Num = (unsigned)Value;
988   Reg.Group = Group;
989   Reg.EndLoc = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
990 
991   // At this point, successfully parsed an integer register.
992   return false;
993 }
994 
995 // Parse a memory operand into Reg1, Reg2, Disp, and Length.
996 bool SystemZAsmParser::parseAddress(bool &HaveReg1, Register &Reg1,
997                                     bool &HaveReg2, Register &Reg2,
998                                     const MCExpr *&Disp, const MCExpr *&Length,
999                                     bool HasLength, bool HasVectorIndex) {
1000   // Parse the displacement, which must always be present.
1001   if (getParser().parseExpression(Disp))
1002     return true;
1003 
1004   // Parse the optional base and index.
1005   HaveReg1 = false;
1006   HaveReg2 = false;
1007   Length = nullptr;
1008 
1009   // If we have a scenario as below:
1010   //   vgef %v0, 0(0), 0
1011   // This is an example of a "BDVMem" instruction type.
1012   //
1013   // So when we parse this as an integer register, the register group
1014   // needs to be tied to "RegV". Usually when the prefix is passed in
1015   // as %<prefix><reg-number> its easy to check which group it should belong to
1016   // However, if we're passing in just the integer there's no real way to
1017   // "check" what register group it should belong to.
1018   //
1019   // When the user passes in the register as an integer, the user assumes that
1020   // the compiler is responsible for substituting it as the right kind of
1021   // register. Whereas, when the user specifies a "prefix", the onus is on
1022   // the user to make sure they pass in the right kind of register.
1023   //
1024   // The restriction only applies to the first Register (i.e. Reg1). Reg2 is
1025   // always a general register. Reg1 should be of group RegV if "HasVectorIndex"
1026   // (i.e. insn is of type BDVMem) is true.
1027   RegisterGroup RegGroup = HasVectorIndex ? RegV : RegGR;
1028 
1029   if (getLexer().is(AsmToken::LParen)) {
1030     Parser.Lex();
1031 
1032     if (isParsingGNU() && getLexer().is(AsmToken::Percent)) {
1033       // Parse the first register.
1034       HaveReg1 = true;
1035       if (parseRegister(Reg1, /*RequirePercent=*/true))
1036         return true;
1037     }
1038     // So if we have an integer as the first token in ([tok1], ..), it could:
1039     // 1. Refer to a "Register" (i.e X,R,V fields in BD[X|R|V]Mem type of
1040     // instructions)
1041     // 2. Refer to a "Length" field (i.e L field in BDLMem type of instructions)
1042     else if (getLexer().is(AsmToken::Integer)) {
1043       if (HasLength) {
1044         // Instruction has a "Length" field, safe to parse the first token as
1045         // the "Length" field
1046         if (getParser().parseExpression(Length))
1047           return true;
1048       } else {
1049         // Otherwise, if the instruction has no "Length" field, parse the
1050         // token as a "Register". We don't have to worry about whether the
1051         // instruction is invalid here, because the caller will take care of
1052         // error reporting.
1053         HaveReg1 = true;
1054         if (parseIntegerRegister(Reg1, RegGroup))
1055           return true;
1056       }
1057     } else {
1058       // If its not an integer or a percent token, then if the instruction
1059       // is reported to have a "Length" then, parse it as "Length".
1060       if (HasLength) {
1061         if (getParser().parseExpression(Length))
1062           return true;
1063       }
1064     }
1065 
1066     // Check whether there's a second register.
1067     if (getLexer().is(AsmToken::Comma)) {
1068       Parser.Lex();
1069       HaveReg2 = true;
1070 
1071       if (getLexer().is(AsmToken::Integer)) {
1072         if (parseIntegerRegister(Reg2, RegGR))
1073           return true;
1074       } else if (isParsingGNU()) {
1075         if (Parser.getTok().is(AsmToken::Percent)) {
1076           if (parseRegister(Reg2, /*RequirePercent=*/true))
1077             return true;
1078         } else {
1079           // GAS allows ",)" to indicate a missing base register.
1080           Reg2.Num = 0;
1081           Reg2.Group = RegGR;
1082           Reg2.StartLoc = Reg2.EndLoc = Parser.getTok().getLoc();
1083         }
1084       }
1085     }
1086 
1087     // Consume the closing bracket.
1088     if (getLexer().isNot(AsmToken::RParen))
1089       return Error(Parser.getTok().getLoc(), "unexpected token in address");
1090     Parser.Lex();
1091   }
1092   return false;
1093 }
1094 
1095 // Verify that Reg is a valid address register (base or index).
1096 bool
1097 SystemZAsmParser::parseAddressRegister(Register &Reg) {
1098   if (Reg.Group == RegV) {
1099     Error(Reg.StartLoc, "invalid use of vector addressing");
1100     return true;
1101   }
1102   if (Reg.Group != RegGR) {
1103     Error(Reg.StartLoc, "invalid address register");
1104     return true;
1105   }
1106   return false;
1107 }
1108 
1109 // Parse a memory operand and add it to Operands.  The other arguments
1110 // are as above.
1111 ParseStatus SystemZAsmParser::parseAddress(OperandVector &Operands,
1112                                            MemoryKind MemKind,
1113                                            RegisterKind RegKind) {
1114   SMLoc StartLoc = Parser.getTok().getLoc();
1115   unsigned Base = 0, Index = 0, LengthReg = 0;
1116   Register Reg1, Reg2;
1117   bool HaveReg1, HaveReg2;
1118   const MCExpr *Disp;
1119   const MCExpr *Length;
1120 
1121   bool HasLength = (MemKind == BDLMem) ? true : false;
1122   bool HasVectorIndex = (MemKind == BDVMem) ? true : false;
1123   if (parseAddress(HaveReg1, Reg1, HaveReg2, Reg2, Disp, Length, HasLength,
1124                    HasVectorIndex))
1125     return ParseStatus::Failure;
1126 
1127   const unsigned *Regs;
1128   switch (RegKind) {
1129   case GR32Reg: Regs = SystemZMC::GR32Regs; break;
1130   case GR64Reg: Regs = SystemZMC::GR64Regs; break;
1131   default: llvm_unreachable("invalid RegKind");
1132   }
1133 
1134   switch (MemKind) {
1135   case BDMem:
1136     // If we have Reg1, it must be an address register.
1137     if (HaveReg1) {
1138       if (parseAddressRegister(Reg1))
1139         return ParseStatus::Failure;
1140       Base = Reg1.Num == 0 ? 0 : Regs[Reg1.Num];
1141     }
1142     // There must be no Reg2.
1143     if (HaveReg2)
1144       return Error(StartLoc, "invalid use of indexed addressing");
1145     break;
1146   case BDXMem:
1147     // If we have Reg1, it must be an address register.
1148     if (HaveReg1) {
1149       if (parseAddressRegister(Reg1))
1150         return ParseStatus::Failure;
1151       // If there are two registers, the first one is the index and the
1152       // second is the base.  If there is only a single register, it is
1153       // used as base with GAS and as index with HLASM.
1154       if (HaveReg2 || isParsingHLASM())
1155         Index = Reg1.Num == 0 ? 0 : Regs[Reg1.Num];
1156       else
1157         Base = Reg1.Num == 0 ? 0 : Regs[Reg1.Num];
1158     }
1159     // If we have Reg2, it must be an address register.
1160     if (HaveReg2) {
1161       if (parseAddressRegister(Reg2))
1162         return ParseStatus::Failure;
1163       Base = Reg2.Num == 0 ? 0 : Regs[Reg2.Num];
1164     }
1165     break;
1166   case BDLMem:
1167     // If we have Reg2, it must be an address register.
1168     if (HaveReg2) {
1169       if (parseAddressRegister(Reg2))
1170         return ParseStatus::Failure;
1171       Base = Reg2.Num == 0 ? 0 : Regs[Reg2.Num];
1172     }
1173     // We cannot support base+index addressing.
1174     if (HaveReg1 && HaveReg2)
1175       return Error(StartLoc, "invalid use of indexed addressing");
1176     // We must have a length.
1177     if (!Length)
1178       return Error(StartLoc, "missing length in address");
1179     break;
1180   case BDRMem:
1181     // We must have Reg1, and it must be a GPR.
1182     if (!HaveReg1 || Reg1.Group != RegGR)
1183       return Error(StartLoc, "invalid operand for instruction");
1184     LengthReg = SystemZMC::GR64Regs[Reg1.Num];
1185     // If we have Reg2, it must be an address register.
1186     if (HaveReg2) {
1187       if (parseAddressRegister(Reg2))
1188         return ParseStatus::Failure;
1189       Base = Reg2.Num == 0 ? 0 : Regs[Reg2.Num];
1190     }
1191     break;
1192   case BDVMem:
1193     // We must have Reg1, and it must be a vector register.
1194     if (!HaveReg1 || Reg1.Group != RegV)
1195       return Error(StartLoc, "vector index required in address");
1196     Index = SystemZMC::VR128Regs[Reg1.Num];
1197     // In GAS mode, we must have Reg2, since a single register would be
1198     // interpreted as base register, which cannot be a vector register.
1199     if (isParsingGNU() && !HaveReg2)
1200       return Error(Reg1.StartLoc, "invalid use of vector addressing");
1201     // If we have Reg2, it must be an address register.
1202     if (HaveReg2) {
1203       if (parseAddressRegister(Reg2))
1204         return ParseStatus::Failure;
1205       Base = Reg2.Num == 0 ? 0 : Regs[Reg2.Num];
1206     }
1207     break;
1208   }
1209 
1210   SMLoc EndLoc =
1211       SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1212   Operands.push_back(SystemZOperand::createMem(MemKind, RegKind, Base, Disp,
1213                                                Index, Length, LengthReg,
1214                                                StartLoc, EndLoc));
1215   return ParseStatus::Success;
1216 }
1217 
1218 ParseStatus SystemZAsmParser::parseDirective(AsmToken DirectiveID) {
1219   StringRef IDVal = DirectiveID.getIdentifier();
1220 
1221   if (IDVal == ".insn")
1222     return ParseDirectiveInsn(DirectiveID.getLoc());
1223   if (IDVal == ".machine")
1224     return ParseDirectiveMachine(DirectiveID.getLoc());
1225   if (IDVal.starts_with(".gnu_attribute"))
1226     return ParseGNUAttribute(DirectiveID.getLoc());
1227 
1228   return ParseStatus::NoMatch;
1229 }
1230 
1231 /// ParseDirectiveInsn
1232 /// ::= .insn [ format, encoding, (operands (, operands)*) ]
1233 bool SystemZAsmParser::ParseDirectiveInsn(SMLoc L) {
1234   MCAsmParser &Parser = getParser();
1235 
1236   // Expect instruction format as identifier.
1237   StringRef Format;
1238   SMLoc ErrorLoc = Parser.getTok().getLoc();
1239   if (Parser.parseIdentifier(Format))
1240     return Error(ErrorLoc, "expected instruction format");
1241 
1242   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> Operands;
1243 
1244   // Find entry for this format in InsnMatchTable.
1245   auto EntryRange =
1246     std::equal_range(std::begin(InsnMatchTable), std::end(InsnMatchTable),
1247                      Format, CompareInsn());
1248 
1249   // If first == second, couldn't find a match in the table.
1250   if (EntryRange.first == EntryRange.second)
1251     return Error(ErrorLoc, "unrecognized format");
1252 
1253   struct InsnMatchEntry *Entry = EntryRange.first;
1254 
1255   // Format should match from equal_range.
1256   assert(Entry->Format == Format);
1257 
1258   // Parse the following operands using the table's information.
1259   for (int I = 0; I < Entry->NumOperands; I++) {
1260     MatchClassKind Kind = Entry->OperandKinds[I];
1261 
1262     SMLoc StartLoc = Parser.getTok().getLoc();
1263 
1264     // Always expect commas as separators for operands.
1265     if (getLexer().isNot(AsmToken::Comma))
1266       return Error(StartLoc, "unexpected token in directive");
1267     Lex();
1268 
1269     // Parse operands.
1270     ParseStatus ResTy;
1271     if (Kind == MCK_AnyReg)
1272       ResTy = parseAnyReg(Operands);
1273     else if (Kind == MCK_VR128)
1274       ResTy = parseVR128(Operands);
1275     else if (Kind == MCK_BDXAddr64Disp12 || Kind == MCK_BDXAddr64Disp20)
1276       ResTy = parseBDXAddr64(Operands);
1277     else if (Kind == MCK_BDAddr64Disp12 || Kind == MCK_BDAddr64Disp20)
1278       ResTy = parseBDAddr64(Operands);
1279     else if (Kind == MCK_BDVAddr64Disp12)
1280       ResTy = parseBDVAddr64(Operands);
1281     else if (Kind == MCK_PCRel32)
1282       ResTy = parsePCRel32(Operands);
1283     else if (Kind == MCK_PCRel16)
1284       ResTy = parsePCRel16(Operands);
1285     else {
1286       // Only remaining operand kind is an immediate.
1287       const MCExpr *Expr;
1288       SMLoc StartLoc = Parser.getTok().getLoc();
1289 
1290       // Expect immediate expression.
1291       if (Parser.parseExpression(Expr))
1292         return Error(StartLoc, "unexpected token in directive");
1293 
1294       SMLoc EndLoc =
1295         SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1296 
1297       Operands.push_back(SystemZOperand::createImm(Expr, StartLoc, EndLoc));
1298       ResTy = ParseStatus::Success;
1299     }
1300 
1301     if (!ResTy.isSuccess())
1302       return true;
1303   }
1304 
1305   // Build the instruction with the parsed operands.
1306   MCInst Inst = MCInstBuilder(Entry->Opcode);
1307 
1308   for (size_t I = 0; I < Operands.size(); I++) {
1309     MCParsedAsmOperand &Operand = *Operands[I];
1310     MatchClassKind Kind = Entry->OperandKinds[I];
1311 
1312     // Verify operand.
1313     unsigned Res = validateOperandClass(Operand, Kind);
1314     if (Res != Match_Success)
1315       return Error(Operand.getStartLoc(), "unexpected operand type");
1316 
1317     // Add operands to instruction.
1318     SystemZOperand &ZOperand = static_cast<SystemZOperand &>(Operand);
1319     if (ZOperand.isReg())
1320       ZOperand.addRegOperands(Inst, 1);
1321     else if (ZOperand.isMem(BDMem))
1322       ZOperand.addBDAddrOperands(Inst, 2);
1323     else if (ZOperand.isMem(BDXMem))
1324       ZOperand.addBDXAddrOperands(Inst, 3);
1325     else if (ZOperand.isMem(BDVMem))
1326       ZOperand.addBDVAddrOperands(Inst, 3);
1327     else if (ZOperand.isImm())
1328       ZOperand.addImmOperands(Inst, 1);
1329     else
1330       llvm_unreachable("unexpected operand type");
1331   }
1332 
1333   // Emit as a regular instruction.
1334   Parser.getStreamer().emitInstruction(Inst, getSTI());
1335 
1336   return false;
1337 }
1338 
1339 /// ParseDirectiveMachine
1340 /// ::= .machine [ mcpu ]
1341 bool SystemZAsmParser::ParseDirectiveMachine(SMLoc L) {
1342   MCAsmParser &Parser = getParser();
1343   if (Parser.getTok().isNot(AsmToken::Identifier) &&
1344       Parser.getTok().isNot(AsmToken::String))
1345     return TokError("unexpected token in '.machine' directive");
1346 
1347   StringRef CPU = Parser.getTok().getIdentifier();
1348   Parser.Lex();
1349   if (parseEOL())
1350     return true;
1351 
1352   MCSubtargetInfo &STI = copySTI();
1353   STI.setDefaultFeatures(CPU, /*TuneCPU*/ CPU, "");
1354   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
1355 
1356   getTargetStreamer().emitMachine(CPU);
1357 
1358   return false;
1359 }
1360 
1361 bool SystemZAsmParser::ParseGNUAttribute(SMLoc L) {
1362   int64_t Tag;
1363   int64_t IntegerValue;
1364   if (!Parser.parseGNUAttribute(L, Tag, IntegerValue))
1365     return Error(L, "malformed .gnu_attribute directive");
1366 
1367   // Tag_GNU_S390_ABI_Vector tag is '8' and can be 0, 1, or 2.
1368   if (Tag != 8 || (IntegerValue < 0 || IntegerValue > 2))
1369     return Error(L, "unrecognized .gnu_attribute tag/value pair.");
1370 
1371   Parser.getStreamer().emitGNUAttribute(Tag, IntegerValue);
1372 
1373   return parseEOL();
1374 }
1375 
1376 bool SystemZAsmParser::ParseRegister(MCRegister &RegNo, SMLoc &StartLoc,
1377                                      SMLoc &EndLoc, bool RequirePercent,
1378                                      bool RestoreOnFailure) {
1379   Register Reg;
1380   if (parseRegister(Reg, RequirePercent, RestoreOnFailure))
1381     return true;
1382   if (Reg.Group == RegGR)
1383     RegNo = SystemZMC::GR64Regs[Reg.Num];
1384   else if (Reg.Group == RegFP)
1385     RegNo = SystemZMC::FP64Regs[Reg.Num];
1386   else if (Reg.Group == RegV)
1387     RegNo = SystemZMC::VR128Regs[Reg.Num];
1388   else if (Reg.Group == RegAR)
1389     RegNo = SystemZMC::AR32Regs[Reg.Num];
1390   else if (Reg.Group == RegCR)
1391     RegNo = SystemZMC::CR64Regs[Reg.Num];
1392   StartLoc = Reg.StartLoc;
1393   EndLoc = Reg.EndLoc;
1394   return false;
1395 }
1396 
1397 bool SystemZAsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
1398                                      SMLoc &EndLoc) {
1399   return ParseRegister(Reg, StartLoc, EndLoc, /*RequirePercent=*/false,
1400                        /*RestoreOnFailure=*/false);
1401 }
1402 
1403 ParseStatus SystemZAsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
1404                                                SMLoc &EndLoc) {
1405   bool Result = ParseRegister(Reg, StartLoc, EndLoc, /*RequirePercent=*/false,
1406                               /*RestoreOnFailure=*/true);
1407   bool PendingErrors = getParser().hasPendingError();
1408   getParser().clearPendingErrors();
1409   if (PendingErrors)
1410     return ParseStatus::Failure;
1411   if (Result)
1412     return ParseStatus::NoMatch;
1413   return ParseStatus::Success;
1414 }
1415 
1416 bool SystemZAsmParser::parseInstruction(ParseInstructionInfo &Info,
1417                                         StringRef Name, SMLoc NameLoc,
1418                                         OperandVector &Operands) {
1419 
1420   // Apply mnemonic aliases first, before doing anything else, in
1421   // case the target uses it.
1422   applyMnemonicAliases(Name, getAvailableFeatures(), getMAIAssemblerDialect());
1423 
1424   Operands.push_back(SystemZOperand::createToken(Name, NameLoc));
1425 
1426   // Read the remaining operands.
1427   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1428     // Read the first operand.
1429     if (parseOperand(Operands, Name)) {
1430       return true;
1431     }
1432 
1433     // Read any subsequent operands.
1434     while (getLexer().is(AsmToken::Comma)) {
1435       Parser.Lex();
1436 
1437       if (isParsingHLASM() && getLexer().is(AsmToken::Space))
1438         return Error(
1439             Parser.getTok().getLoc(),
1440             "No space allowed between comma that separates operand entries");
1441 
1442       if (parseOperand(Operands, Name)) {
1443         return true;
1444       }
1445     }
1446 
1447     // Under the HLASM variant, we could have the remark field
1448     // The remark field occurs after the operation entries
1449     // There is a space that separates the operation entries and the
1450     // remark field.
1451     if (isParsingHLASM() && getTok().is(AsmToken::Space)) {
1452       // We've confirmed that there is a Remark field.
1453       StringRef Remark(getLexer().LexUntilEndOfStatement());
1454       Parser.Lex();
1455 
1456       // If there is nothing after the space, then there is nothing to emit
1457       // We could have a situation as this:
1458       // "  \n"
1459       // After lexing above, we will have
1460       // "\n"
1461       // This isn't an explicit remark field, so we don't have to output
1462       // this as a comment.
1463       if (Remark.size())
1464         // Output the entire Remarks Field as a comment
1465         getStreamer().AddComment(Remark);
1466     }
1467 
1468     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1469       SMLoc Loc = getLexer().getLoc();
1470       return Error(Loc, "unexpected token in argument list");
1471     }
1472   }
1473 
1474   // Consume the EndOfStatement.
1475   Parser.Lex();
1476   return false;
1477 }
1478 
1479 bool SystemZAsmParser::parseOperand(OperandVector &Operands,
1480                                     StringRef Mnemonic) {
1481   // Check if the current operand has a custom associated parser, if so, try to
1482   // custom parse the operand, or fallback to the general approach.  Force all
1483   // features to be available during the operand check, or else we will fail to
1484   // find the custom parser, and then we will later get an InvalidOperand error
1485   // instead of a MissingFeature errror.
1486   FeatureBitset AvailableFeatures = getAvailableFeatures();
1487   FeatureBitset All;
1488   All.set();
1489   setAvailableFeatures(All);
1490   ParseStatus Res = MatchOperandParserImpl(Operands, Mnemonic);
1491   setAvailableFeatures(AvailableFeatures);
1492   if (Res.isSuccess())
1493     return false;
1494 
1495   // If there wasn't a custom match, try the generic matcher below. Otherwise,
1496   // there was a match, but an error occurred, in which case, just return that
1497   // the operand parsing failed.
1498   if (Res.isFailure())
1499     return true;
1500 
1501   // Check for a register.  All real register operands should have used
1502   // a context-dependent parse routine, which gives the required register
1503   // class.  The code is here to mop up other cases, like those where
1504   // the instruction isn't recognized.
1505   if (isParsingGNU() && Parser.getTok().is(AsmToken::Percent)) {
1506     Register Reg;
1507     if (parseRegister(Reg, /*RequirePercent=*/true))
1508       return true;
1509     Operands.push_back(SystemZOperand::createInvalid(Reg.StartLoc, Reg.EndLoc));
1510     return false;
1511   }
1512 
1513   // The only other type of operand is an immediate or address.  As above,
1514   // real address operands should have used a context-dependent parse routine,
1515   // so we treat any plain expression as an immediate.
1516   SMLoc StartLoc = Parser.getTok().getLoc();
1517   Register Reg1, Reg2;
1518   bool HaveReg1, HaveReg2;
1519   const MCExpr *Expr;
1520   const MCExpr *Length;
1521   if (parseAddress(HaveReg1, Reg1, HaveReg2, Reg2, Expr, Length,
1522                    /*HasLength*/ true, /*HasVectorIndex*/ true))
1523     return true;
1524   // If the register combination is not valid for any instruction, reject it.
1525   // Otherwise, fall back to reporting an unrecognized instruction.
1526   if (HaveReg1 && Reg1.Group != RegGR && Reg1.Group != RegV
1527       && parseAddressRegister(Reg1))
1528     return true;
1529   if (HaveReg2 && parseAddressRegister(Reg2))
1530     return true;
1531 
1532   SMLoc EndLoc =
1533     SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1534   if (HaveReg1 || HaveReg2 || Length)
1535     Operands.push_back(SystemZOperand::createInvalid(StartLoc, EndLoc));
1536   else
1537     Operands.push_back(SystemZOperand::createImm(Expr, StartLoc, EndLoc));
1538   return false;
1539 }
1540 
1541 bool SystemZAsmParser::matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1542                                                OperandVector &Operands,
1543                                                MCStreamer &Out,
1544                                                uint64_t &ErrorInfo,
1545                                                bool MatchingInlineAsm) {
1546   MCInst Inst;
1547   unsigned MatchResult;
1548 
1549   unsigned Dialect = getMAIAssemblerDialect();
1550 
1551   FeatureBitset MissingFeatures;
1552   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,
1553                                      MatchingInlineAsm, Dialect);
1554   switch (MatchResult) {
1555   case Match_Success:
1556     Inst.setLoc(IDLoc);
1557     Out.emitInstruction(Inst, getSTI());
1558     return false;
1559 
1560   case Match_MissingFeature: {
1561     assert(MissingFeatures.any() && "Unknown missing feature!");
1562     // Special case the error message for the very common case where only
1563     // a single subtarget feature is missing
1564     std::string Msg = "instruction requires:";
1565     for (unsigned I = 0, E = MissingFeatures.size(); I != E; ++I) {
1566       if (MissingFeatures[I]) {
1567         Msg += " ";
1568         Msg += getSubtargetFeatureName(I);
1569       }
1570     }
1571     return Error(IDLoc, Msg);
1572   }
1573 
1574   case Match_InvalidOperand: {
1575     SMLoc ErrorLoc = IDLoc;
1576     if (ErrorInfo != ~0ULL) {
1577       if (ErrorInfo >= Operands.size())
1578         return Error(IDLoc, "too few operands for instruction");
1579 
1580       ErrorLoc = ((SystemZOperand &)*Operands[ErrorInfo]).getStartLoc();
1581       if (ErrorLoc == SMLoc())
1582         ErrorLoc = IDLoc;
1583     }
1584     return Error(ErrorLoc, "invalid operand for instruction");
1585   }
1586 
1587   case Match_MnemonicFail: {
1588     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
1589     std::string Suggestion = SystemZMnemonicSpellCheck(
1590         ((SystemZOperand &)*Operands[0]).getToken(), FBS, Dialect);
1591     return Error(IDLoc, "invalid instruction" + Suggestion,
1592                  ((SystemZOperand &)*Operands[0]).getLocRange());
1593   }
1594   }
1595 
1596   llvm_unreachable("Unexpected match type");
1597 }
1598 
1599 ParseStatus SystemZAsmParser::parsePCRel(OperandVector &Operands,
1600                                          int64_t MinVal, int64_t MaxVal,
1601                                          bool AllowTLS) {
1602   MCContext &Ctx = getContext();
1603   MCStreamer &Out = getStreamer();
1604   const MCExpr *Expr;
1605   SMLoc StartLoc = Parser.getTok().getLoc();
1606   if (getParser().parseExpression(Expr))
1607     return ParseStatus::NoMatch;
1608 
1609   auto IsOutOfRangeConstant = [&](const MCExpr *E, bool Negate) -> bool {
1610     if (auto *CE = dyn_cast<MCConstantExpr>(E)) {
1611       int64_t Value = CE->getValue();
1612       if (Negate)
1613         Value = -Value;
1614       if ((Value & 1) || Value < MinVal || Value > MaxVal)
1615         return true;
1616     }
1617     return false;
1618   };
1619 
1620   // For consistency with the GNU assembler, treat immediates as offsets
1621   // from ".".
1622   if (auto *CE = dyn_cast<MCConstantExpr>(Expr)) {
1623     if (isParsingHLASM())
1624       return Error(StartLoc, "Expected PC-relative expression");
1625     if (IsOutOfRangeConstant(CE, false))
1626       return Error(StartLoc, "offset out of range");
1627     int64_t Value = CE->getValue();
1628     MCSymbol *Sym = Ctx.createTempSymbol();
1629     Out.emitLabel(Sym);
1630     const MCExpr *Base = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
1631                                                  Ctx);
1632     Expr = Value == 0 ? Base : MCBinaryExpr::createAdd(Base, Expr, Ctx);
1633   }
1634 
1635   // For consistency with the GNU assembler, conservatively assume that a
1636   // constant offset must by itself be within the given size range.
1637   if (const auto *BE = dyn_cast<MCBinaryExpr>(Expr))
1638     if (IsOutOfRangeConstant(BE->getLHS(), false) ||
1639         IsOutOfRangeConstant(BE->getRHS(),
1640                              BE->getOpcode() == MCBinaryExpr::Sub))
1641       return Error(StartLoc, "offset out of range");
1642 
1643   // Optionally match :tls_gdcall: or :tls_ldcall: followed by a TLS symbol.
1644   const MCExpr *Sym = nullptr;
1645   if (AllowTLS && getLexer().is(AsmToken::Colon)) {
1646     Parser.Lex();
1647 
1648     if (Parser.getTok().isNot(AsmToken::Identifier))
1649       return Error(Parser.getTok().getLoc(), "unexpected token");
1650 
1651     MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
1652     StringRef Name = Parser.getTok().getString();
1653     if (Name == "tls_gdcall")
1654       Kind = MCSymbolRefExpr::VK_TLSGD;
1655     else if (Name == "tls_ldcall")
1656       Kind = MCSymbolRefExpr::VK_TLSLDM;
1657     else
1658       return Error(Parser.getTok().getLoc(), "unknown TLS tag");
1659     Parser.Lex();
1660 
1661     if (Parser.getTok().isNot(AsmToken::Colon))
1662       return Error(Parser.getTok().getLoc(), "unexpected token");
1663     Parser.Lex();
1664 
1665     if (Parser.getTok().isNot(AsmToken::Identifier))
1666       return Error(Parser.getTok().getLoc(), "unexpected token");
1667 
1668     StringRef Identifier = Parser.getTok().getString();
1669     Sym = MCSymbolRefExpr::create(Ctx.getOrCreateSymbol(Identifier),
1670                                   Kind, Ctx);
1671     Parser.Lex();
1672   }
1673 
1674   SMLoc EndLoc =
1675     SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1676 
1677   if (AllowTLS)
1678     Operands.push_back(SystemZOperand::createImmTLS(Expr, Sym,
1679                                                     StartLoc, EndLoc));
1680   else
1681     Operands.push_back(SystemZOperand::createImm(Expr, StartLoc, EndLoc));
1682 
1683   return ParseStatus::Success;
1684 }
1685 
1686 bool SystemZAsmParser::isLabel(AsmToken &Token) {
1687   if (isParsingGNU())
1688     return true;
1689 
1690   // HLASM labels are ordinary symbols.
1691   // An HLASM label always starts at column 1.
1692   // An ordinary symbol syntax is laid out as follows:
1693   // Rules:
1694   // 1. Has to start with an "alphabetic character". Can be followed by up to
1695   //    62 alphanumeric characters. An "alphabetic character", in this scenario,
1696   //    is a letter from 'A' through 'Z', or from 'a' through 'z',
1697   //    or '$', '_', '#', or '@'
1698   // 2. Labels are case-insensitive. E.g. "lab123", "LAB123", "lAb123", etc.
1699   //    are all treated as the same symbol. However, the processing for the case
1700   //    folding will not be done in this function.
1701   StringRef RawLabel = Token.getString();
1702   SMLoc Loc = Token.getLoc();
1703 
1704   // An HLASM label cannot be empty.
1705   if (!RawLabel.size())
1706     return !Error(Loc, "HLASM Label cannot be empty");
1707 
1708   // An HLASM label cannot exceed greater than 63 characters.
1709   if (RawLabel.size() > 63)
1710     return !Error(Loc, "Maximum length for HLASM Label is 63 characters");
1711 
1712   // A label must start with an "alphabetic character".
1713   if (!isHLASMAlpha(RawLabel[0]))
1714     return !Error(Loc, "HLASM Label has to start with an alphabetic "
1715                        "character or the underscore character");
1716 
1717   // Now, we've established that the length is valid
1718   // and the first character is alphabetic.
1719   // Check whether remaining string is alphanumeric.
1720   for (unsigned I = 1; I < RawLabel.size(); ++I)
1721     if (!isHLASMAlnum(RawLabel[I]))
1722       return !Error(Loc, "HLASM Label has to be alphanumeric");
1723 
1724   return true;
1725 }
1726 
1727 // Force static initialization.
1728 // NOLINTNEXTLINE(readability-identifier-naming)
1729 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSystemZAsmParser() {
1730   RegisterMCAsmParser<SystemZAsmParser> X(getTheSystemZTarget());
1731 }
1732