1 //===-- SystemZAsmParser.cpp - Parse SystemZ assembly instructions --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "MCTargetDesc/SystemZMCTargetDesc.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCInstBuilder.h"
18 #include "llvm/MC/MCParser/MCAsmLexer.h"
19 #include "llvm/MC/MCParser/MCAsmParser.h"
20 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
21 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
22 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/SMLoc.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstddef>
32 #include <cstdint>
33 #include <iterator>
34 #include <memory>
35 #include <string>
36 
37 using namespace llvm;
38 
39 // Return true if Expr is in the range [MinValue, MaxValue].
40 static bool inRange(const MCExpr *Expr, int64_t MinValue, int64_t MaxValue) {
41   if (auto *CE = dyn_cast<MCConstantExpr>(Expr)) {
42     int64_t Value = CE->getValue();
43     return Value >= MinValue && Value <= MaxValue;
44   }
45   return false;
46 }
47 
48 namespace {
49 
50 enum RegisterKind {
51   GR32Reg,
52   GRH32Reg,
53   GR64Reg,
54   GR128Reg,
55   ADDR32Reg,
56   ADDR64Reg,
57   FP32Reg,
58   FP64Reg,
59   FP128Reg,
60   VR32Reg,
61   VR64Reg,
62   VR128Reg,
63   AR32Reg,
64   CR64Reg,
65 };
66 
67 enum MemoryKind {
68   BDMem,
69   BDXMem,
70   BDLMem,
71   BDRMem,
72   BDVMem
73 };
74 
75 class SystemZOperand : public MCParsedAsmOperand {
76 private:
77   enum OperandKind {
78     KindInvalid,
79     KindToken,
80     KindReg,
81     KindImm,
82     KindImmTLS,
83     KindMem
84   };
85 
86   OperandKind Kind;
87   SMLoc StartLoc, EndLoc;
88 
89   // A string of length Length, starting at Data.
90   struct TokenOp {
91     const char *Data;
92     unsigned Length;
93   };
94 
95   // LLVM register Num, which has kind Kind.  In some ways it might be
96   // easier for this class to have a register bank (general, floating-point
97   // or access) and a raw register number (0-15).  This would postpone the
98   // interpretation of the operand to the add*() methods and avoid the need
99   // for context-dependent parsing.  However, we do things the current way
100   // because of the virtual getReg() method, which needs to distinguish
101   // between (say) %r0 used as a single register and %r0 used as a pair.
102   // Context-dependent parsing can also give us slightly better error
103   // messages when invalid pairs like %r1 are used.
104   struct RegOp {
105     RegisterKind Kind;
106     unsigned Num;
107   };
108 
109   // Base + Disp + Index, where Base and Index are LLVM registers or 0.
110   // MemKind says what type of memory this is and RegKind says what type
111   // the base register has (ADDR32Reg or ADDR64Reg).  Length is the operand
112   // length for D(L,B)-style operands, otherwise it is null.
113   struct MemOp {
114     unsigned Base : 12;
115     unsigned Index : 12;
116     unsigned MemKind : 4;
117     unsigned RegKind : 4;
118     const MCExpr *Disp;
119     union {
120       const MCExpr *Imm;
121       unsigned Reg;
122     } Length;
123   };
124 
125   // Imm is an immediate operand, and Sym is an optional TLS symbol
126   // for use with a __tls_get_offset marker relocation.
127   struct ImmTLSOp {
128     const MCExpr *Imm;
129     const MCExpr *Sym;
130   };
131 
132   union {
133     TokenOp Token;
134     RegOp Reg;
135     const MCExpr *Imm;
136     ImmTLSOp ImmTLS;
137     MemOp Mem;
138   };
139 
140   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
141     // Add as immediates when possible.  Null MCExpr = 0.
142     if (!Expr)
143       Inst.addOperand(MCOperand::createImm(0));
144     else if (auto *CE = dyn_cast<MCConstantExpr>(Expr))
145       Inst.addOperand(MCOperand::createImm(CE->getValue()));
146     else
147       Inst.addOperand(MCOperand::createExpr(Expr));
148   }
149 
150 public:
151   SystemZOperand(OperandKind kind, SMLoc startLoc, SMLoc endLoc)
152       : Kind(kind), StartLoc(startLoc), EndLoc(endLoc) {}
153 
154   // Create particular kinds of operand.
155   static std::unique_ptr<SystemZOperand> createInvalid(SMLoc StartLoc,
156                                                        SMLoc EndLoc) {
157     return make_unique<SystemZOperand>(KindInvalid, StartLoc, EndLoc);
158   }
159 
160   static std::unique_ptr<SystemZOperand> createToken(StringRef Str, SMLoc Loc) {
161     auto Op = make_unique<SystemZOperand>(KindToken, Loc, Loc);
162     Op->Token.Data = Str.data();
163     Op->Token.Length = Str.size();
164     return Op;
165   }
166 
167   static std::unique_ptr<SystemZOperand>
168   createReg(RegisterKind Kind, unsigned Num, SMLoc StartLoc, SMLoc EndLoc) {
169     auto Op = make_unique<SystemZOperand>(KindReg, StartLoc, EndLoc);
170     Op->Reg.Kind = Kind;
171     Op->Reg.Num = Num;
172     return Op;
173   }
174 
175   static std::unique_ptr<SystemZOperand>
176   createImm(const MCExpr *Expr, SMLoc StartLoc, SMLoc EndLoc) {
177     auto Op = make_unique<SystemZOperand>(KindImm, StartLoc, EndLoc);
178     Op->Imm = Expr;
179     return Op;
180   }
181 
182   static std::unique_ptr<SystemZOperand>
183   createMem(MemoryKind MemKind, RegisterKind RegKind, unsigned Base,
184             const MCExpr *Disp, unsigned Index, const MCExpr *LengthImm,
185             unsigned LengthReg, SMLoc StartLoc, SMLoc EndLoc) {
186     auto Op = make_unique<SystemZOperand>(KindMem, StartLoc, EndLoc);
187     Op->Mem.MemKind = MemKind;
188     Op->Mem.RegKind = RegKind;
189     Op->Mem.Base = Base;
190     Op->Mem.Index = Index;
191     Op->Mem.Disp = Disp;
192     if (MemKind == BDLMem)
193       Op->Mem.Length.Imm = LengthImm;
194     if (MemKind == BDRMem)
195       Op->Mem.Length.Reg = LengthReg;
196     return Op;
197   }
198 
199   static std::unique_ptr<SystemZOperand>
200   createImmTLS(const MCExpr *Imm, const MCExpr *Sym,
201                SMLoc StartLoc, SMLoc EndLoc) {
202     auto Op = make_unique<SystemZOperand>(KindImmTLS, StartLoc, EndLoc);
203     Op->ImmTLS.Imm = Imm;
204     Op->ImmTLS.Sym = Sym;
205     return Op;
206   }
207 
208   // Token operands
209   bool isToken() const override {
210     return Kind == KindToken;
211   }
212   StringRef getToken() const {
213     assert(Kind == KindToken && "Not a token");
214     return StringRef(Token.Data, Token.Length);
215   }
216 
217   // Register operands.
218   bool isReg() const override {
219     return Kind == KindReg;
220   }
221   bool isReg(RegisterKind RegKind) const {
222     return Kind == KindReg && Reg.Kind == RegKind;
223   }
224   unsigned getReg() const override {
225     assert(Kind == KindReg && "Not a register");
226     return Reg.Num;
227   }
228 
229   // Immediate operands.
230   bool isImm() const override {
231     return Kind == KindImm;
232   }
233   bool isImm(int64_t MinValue, int64_t MaxValue) const {
234     return Kind == KindImm && inRange(Imm, MinValue, MaxValue);
235   }
236   const MCExpr *getImm() const {
237     assert(Kind == KindImm && "Not an immediate");
238     return Imm;
239   }
240 
241   // Immediate operands with optional TLS symbol.
242   bool isImmTLS() const {
243     return Kind == KindImmTLS;
244   }
245 
246   // Memory operands.
247   bool isMem() const override {
248     return Kind == KindMem;
249   }
250   bool isMem(MemoryKind MemKind) const {
251     return (Kind == KindMem &&
252             (Mem.MemKind == MemKind ||
253              // A BDMem can be treated as a BDXMem in which the index
254              // register field is 0.
255              (Mem.MemKind == BDMem && MemKind == BDXMem)));
256   }
257   bool isMem(MemoryKind MemKind, RegisterKind RegKind) const {
258     return isMem(MemKind) && Mem.RegKind == RegKind;
259   }
260   bool isMemDisp12(MemoryKind MemKind, RegisterKind RegKind) const {
261     return isMem(MemKind, RegKind) && inRange(Mem.Disp, 0, 0xfff);
262   }
263   bool isMemDisp20(MemoryKind MemKind, RegisterKind RegKind) const {
264     return isMem(MemKind, RegKind) && inRange(Mem.Disp, -524288, 524287);
265   }
266   bool isMemDisp12Len4(RegisterKind RegKind) const {
267     return isMemDisp12(BDLMem, RegKind) && inRange(Mem.Length.Imm, 1, 0x10);
268   }
269   bool isMemDisp12Len8(RegisterKind RegKind) const {
270     return isMemDisp12(BDLMem, RegKind) && inRange(Mem.Length.Imm, 1, 0x100);
271   }
272 
273   // Override MCParsedAsmOperand.
274   SMLoc getStartLoc() const override { return StartLoc; }
275   SMLoc getEndLoc() const override { return EndLoc; }
276   void print(raw_ostream &OS) const override;
277 
278   /// getLocRange - Get the range between the first and last token of this
279   /// operand.
280   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
281 
282   // Used by the TableGen code to add particular types of operand
283   // to an instruction.
284   void addRegOperands(MCInst &Inst, unsigned N) const {
285     assert(N == 1 && "Invalid number of operands");
286     Inst.addOperand(MCOperand::createReg(getReg()));
287   }
288   void addImmOperands(MCInst &Inst, unsigned N) const {
289     assert(N == 1 && "Invalid number of operands");
290     addExpr(Inst, getImm());
291   }
292   void addBDAddrOperands(MCInst &Inst, unsigned N) const {
293     assert(N == 2 && "Invalid number of operands");
294     assert(isMem(BDMem) && "Invalid operand type");
295     Inst.addOperand(MCOperand::createReg(Mem.Base));
296     addExpr(Inst, Mem.Disp);
297   }
298   void addBDXAddrOperands(MCInst &Inst, unsigned N) const {
299     assert(N == 3 && "Invalid number of operands");
300     assert(isMem(BDXMem) && "Invalid operand type");
301     Inst.addOperand(MCOperand::createReg(Mem.Base));
302     addExpr(Inst, Mem.Disp);
303     Inst.addOperand(MCOperand::createReg(Mem.Index));
304   }
305   void addBDLAddrOperands(MCInst &Inst, unsigned N) const {
306     assert(N == 3 && "Invalid number of operands");
307     assert(isMem(BDLMem) && "Invalid operand type");
308     Inst.addOperand(MCOperand::createReg(Mem.Base));
309     addExpr(Inst, Mem.Disp);
310     addExpr(Inst, Mem.Length.Imm);
311   }
312   void addBDRAddrOperands(MCInst &Inst, unsigned N) const {
313     assert(N == 3 && "Invalid number of operands");
314     assert(isMem(BDRMem) && "Invalid operand type");
315     Inst.addOperand(MCOperand::createReg(Mem.Base));
316     addExpr(Inst, Mem.Disp);
317     Inst.addOperand(MCOperand::createReg(Mem.Length.Reg));
318   }
319   void addBDVAddrOperands(MCInst &Inst, unsigned N) const {
320     assert(N == 3 && "Invalid number of operands");
321     assert(isMem(BDVMem) && "Invalid operand type");
322     Inst.addOperand(MCOperand::createReg(Mem.Base));
323     addExpr(Inst, Mem.Disp);
324     Inst.addOperand(MCOperand::createReg(Mem.Index));
325   }
326   void addImmTLSOperands(MCInst &Inst, unsigned N) const {
327     assert(N == 2 && "Invalid number of operands");
328     assert(Kind == KindImmTLS && "Invalid operand type");
329     addExpr(Inst, ImmTLS.Imm);
330     if (ImmTLS.Sym)
331       addExpr(Inst, ImmTLS.Sym);
332   }
333 
334   // Used by the TableGen code to check for particular operand types.
335   bool isGR32() const { return isReg(GR32Reg); }
336   bool isGRH32() const { return isReg(GRH32Reg); }
337   bool isGRX32() const { return false; }
338   bool isGR64() const { return isReg(GR64Reg); }
339   bool isGR128() const { return isReg(GR128Reg); }
340   bool isADDR32() const { return isReg(ADDR32Reg); }
341   bool isADDR64() const { return isReg(ADDR64Reg); }
342   bool isADDR128() const { return false; }
343   bool isFP32() const { return isReg(FP32Reg); }
344   bool isFP64() const { return isReg(FP64Reg); }
345   bool isFP128() const { return isReg(FP128Reg); }
346   bool isVR32() const { return isReg(VR32Reg); }
347   bool isVR64() const { return isReg(VR64Reg); }
348   bool isVF128() const { return false; }
349   bool isVR128() const { return isReg(VR128Reg); }
350   bool isAR32() const { return isReg(AR32Reg); }
351   bool isCR64() const { return isReg(CR64Reg); }
352   bool isAnyReg() const { return (isReg() || isImm(0, 15)); }
353   bool isBDAddr32Disp12() const { return isMemDisp12(BDMem, ADDR32Reg); }
354   bool isBDAddr32Disp20() const { return isMemDisp20(BDMem, ADDR32Reg); }
355   bool isBDAddr64Disp12() const { return isMemDisp12(BDMem, ADDR64Reg); }
356   bool isBDAddr64Disp20() const { return isMemDisp20(BDMem, ADDR64Reg); }
357   bool isBDXAddr64Disp12() const { return isMemDisp12(BDXMem, ADDR64Reg); }
358   bool isBDXAddr64Disp20() const { return isMemDisp20(BDXMem, ADDR64Reg); }
359   bool isBDLAddr64Disp12Len4() const { return isMemDisp12Len4(ADDR64Reg); }
360   bool isBDLAddr64Disp12Len8() const { return isMemDisp12Len8(ADDR64Reg); }
361   bool isBDRAddr64Disp12() const { return isMemDisp12(BDRMem, ADDR64Reg); }
362   bool isBDVAddr64Disp12() const { return isMemDisp12(BDVMem, ADDR64Reg); }
363   bool isU1Imm() const { return isImm(0, 1); }
364   bool isU2Imm() const { return isImm(0, 3); }
365   bool isU3Imm() const { return isImm(0, 7); }
366   bool isU4Imm() const { return isImm(0, 15); }
367   bool isU6Imm() const { return isImm(0, 63); }
368   bool isU8Imm() const { return isImm(0, 255); }
369   bool isS8Imm() const { return isImm(-128, 127); }
370   bool isU12Imm() const { return isImm(0, 4095); }
371   bool isU16Imm() const { return isImm(0, 65535); }
372   bool isS16Imm() const { return isImm(-32768, 32767); }
373   bool isU32Imm() const { return isImm(0, (1LL << 32) - 1); }
374   bool isS32Imm() const { return isImm(-(1LL << 31), (1LL << 31) - 1); }
375   bool isU48Imm() const { return isImm(0, (1LL << 48) - 1); }
376 };
377 
378 class SystemZAsmParser : public MCTargetAsmParser {
379 #define GET_ASSEMBLER_HEADER
380 #include "SystemZGenAsmMatcher.inc"
381 
382 private:
383   MCAsmParser &Parser;
384   enum RegisterGroup {
385     RegGR,
386     RegFP,
387     RegV,
388     RegAR,
389     RegCR
390   };
391   struct Register {
392     RegisterGroup Group;
393     unsigned Num;
394     SMLoc StartLoc, EndLoc;
395   };
396 
397   bool parseRegister(Register &Reg);
398 
399   bool parseRegister(Register &Reg, RegisterGroup Group, const unsigned *Regs,
400                      bool IsAddress = false);
401 
402   OperandMatchResultTy parseRegister(OperandVector &Operands,
403                                      RegisterGroup Group, const unsigned *Regs,
404                                      RegisterKind Kind);
405 
406   OperandMatchResultTy parseAnyRegister(OperandVector &Operands);
407 
408   bool parseAddress(bool &HaveReg1, Register &Reg1,
409                     bool &HaveReg2, Register &Reg2,
410                     const MCExpr *&Disp, const MCExpr *&Length);
411   bool parseAddressRegister(Register &Reg);
412 
413   bool ParseDirectiveInsn(SMLoc L);
414 
415   OperandMatchResultTy parseAddress(OperandVector &Operands,
416                                     MemoryKind MemKind, const unsigned *Regs,
417                                     RegisterKind RegKind);
418 
419   OperandMatchResultTy parsePCRel(OperandVector &Operands, int64_t MinVal,
420                                   int64_t MaxVal, bool AllowTLS);
421 
422   bool parseOperand(OperandVector &Operands, StringRef Mnemonic);
423 
424 public:
425   SystemZAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser,
426                    const MCInstrInfo &MII,
427                    const MCTargetOptions &Options)
428     : MCTargetAsmParser(Options, sti, MII), Parser(parser) {
429     MCAsmParserExtension::Initialize(Parser);
430 
431     // Alias the .word directive to .short.
432     parser.addAliasForDirective(".word", ".short");
433 
434     // Initialize the set of available features.
435     setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
436   }
437 
438   // Override MCTargetAsmParser.
439   bool ParseDirective(AsmToken DirectiveID) override;
440   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
441   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
442                         SMLoc NameLoc, OperandVector &Operands) override;
443   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
444                                OperandVector &Operands, MCStreamer &Out,
445                                uint64_t &ErrorInfo,
446                                bool MatchingInlineAsm) override;
447 
448   // Used by the TableGen code to parse particular operand types.
449   OperandMatchResultTy parseGR32(OperandVector &Operands) {
450     return parseRegister(Operands, RegGR, SystemZMC::GR32Regs, GR32Reg);
451   }
452   OperandMatchResultTy parseGRH32(OperandVector &Operands) {
453     return parseRegister(Operands, RegGR, SystemZMC::GRH32Regs, GRH32Reg);
454   }
455   OperandMatchResultTy parseGRX32(OperandVector &Operands) {
456     llvm_unreachable("GRX32 should only be used for pseudo instructions");
457   }
458   OperandMatchResultTy parseGR64(OperandVector &Operands) {
459     return parseRegister(Operands, RegGR, SystemZMC::GR64Regs, GR64Reg);
460   }
461   OperandMatchResultTy parseGR128(OperandVector &Operands) {
462     return parseRegister(Operands, RegGR, SystemZMC::GR128Regs, GR128Reg);
463   }
464   OperandMatchResultTy parseADDR32(OperandVector &Operands) {
465     return parseRegister(Operands, RegGR, SystemZMC::GR32Regs, ADDR32Reg);
466   }
467   OperandMatchResultTy parseADDR64(OperandVector &Operands) {
468     return parseRegister(Operands, RegGR, SystemZMC::GR64Regs, ADDR64Reg);
469   }
470   OperandMatchResultTy parseADDR128(OperandVector &Operands) {
471     llvm_unreachable("Shouldn't be used as an operand");
472   }
473   OperandMatchResultTy parseFP32(OperandVector &Operands) {
474     return parseRegister(Operands, RegFP, SystemZMC::FP32Regs, FP32Reg);
475   }
476   OperandMatchResultTy parseFP64(OperandVector &Operands) {
477     return parseRegister(Operands, RegFP, SystemZMC::FP64Regs, FP64Reg);
478   }
479   OperandMatchResultTy parseFP128(OperandVector &Operands) {
480     return parseRegister(Operands, RegFP, SystemZMC::FP128Regs, FP128Reg);
481   }
482   OperandMatchResultTy parseVR32(OperandVector &Operands) {
483     return parseRegister(Operands, RegV, SystemZMC::VR32Regs, VR32Reg);
484   }
485   OperandMatchResultTy parseVR64(OperandVector &Operands) {
486     return parseRegister(Operands, RegV, SystemZMC::VR64Regs, VR64Reg);
487   }
488   OperandMatchResultTy parseVF128(OperandVector &Operands) {
489     llvm_unreachable("Shouldn't be used as an operand");
490   }
491   OperandMatchResultTy parseVR128(OperandVector &Operands) {
492     return parseRegister(Operands, RegV, SystemZMC::VR128Regs, VR128Reg);
493   }
494   OperandMatchResultTy parseAR32(OperandVector &Operands) {
495     return parseRegister(Operands, RegAR, SystemZMC::AR32Regs, AR32Reg);
496   }
497   OperandMatchResultTy parseCR64(OperandVector &Operands) {
498     return parseRegister(Operands, RegCR, SystemZMC::CR64Regs, CR64Reg);
499   }
500   OperandMatchResultTy parseAnyReg(OperandVector &Operands) {
501     return parseAnyRegister(Operands);
502   }
503   OperandMatchResultTy parseBDAddr32(OperandVector &Operands) {
504     return parseAddress(Operands, BDMem, SystemZMC::GR32Regs, ADDR32Reg);
505   }
506   OperandMatchResultTy parseBDAddr64(OperandVector &Operands) {
507     return parseAddress(Operands, BDMem, SystemZMC::GR64Regs, ADDR64Reg);
508   }
509   OperandMatchResultTy parseBDXAddr64(OperandVector &Operands) {
510     return parseAddress(Operands, BDXMem, SystemZMC::GR64Regs, ADDR64Reg);
511   }
512   OperandMatchResultTy parseBDLAddr64(OperandVector &Operands) {
513     return parseAddress(Operands, BDLMem, SystemZMC::GR64Regs, ADDR64Reg);
514   }
515   OperandMatchResultTy parseBDRAddr64(OperandVector &Operands) {
516     return parseAddress(Operands, BDRMem, SystemZMC::GR64Regs, ADDR64Reg);
517   }
518   OperandMatchResultTy parseBDVAddr64(OperandVector &Operands) {
519     return parseAddress(Operands, BDVMem, SystemZMC::GR64Regs, ADDR64Reg);
520   }
521   OperandMatchResultTy parsePCRel12(OperandVector &Operands) {
522     return parsePCRel(Operands, -(1LL << 12), (1LL << 12) - 1, false);
523   }
524   OperandMatchResultTy parsePCRel16(OperandVector &Operands) {
525     return parsePCRel(Operands, -(1LL << 16), (1LL << 16) - 1, false);
526   }
527   OperandMatchResultTy parsePCRel24(OperandVector &Operands) {
528     return parsePCRel(Operands, -(1LL << 24), (1LL << 24) - 1, false);
529   }
530   OperandMatchResultTy parsePCRel32(OperandVector &Operands) {
531     return parsePCRel(Operands, -(1LL << 32), (1LL << 32) - 1, false);
532   }
533   OperandMatchResultTy parsePCRelTLS16(OperandVector &Operands) {
534     return parsePCRel(Operands, -(1LL << 16), (1LL << 16) - 1, true);
535   }
536   OperandMatchResultTy parsePCRelTLS32(OperandVector &Operands) {
537     return parsePCRel(Operands, -(1LL << 32), (1LL << 32) - 1, true);
538   }
539 };
540 
541 } // end anonymous namespace
542 
543 #define GET_REGISTER_MATCHER
544 #define GET_SUBTARGET_FEATURE_NAME
545 #define GET_MATCHER_IMPLEMENTATION
546 #include "SystemZGenAsmMatcher.inc"
547 
548 // Used for the .insn directives; contains information needed to parse the
549 // operands in the directive.
550 struct InsnMatchEntry {
551   StringRef Format;
552   uint64_t Opcode;
553   int32_t NumOperands;
554   MatchClassKind OperandKinds[5];
555 };
556 
557 // For equal_range comparison.
558 struct CompareInsn {
559   bool operator() (const InsnMatchEntry &LHS, StringRef RHS) {
560     return LHS.Format < RHS;
561   }
562   bool operator() (StringRef LHS, const InsnMatchEntry &RHS) {
563     return LHS < RHS.Format;
564   }
565   bool operator() (const InsnMatchEntry &LHS, const InsnMatchEntry &RHS) {
566     return LHS.Format < RHS.Format;
567   }
568 };
569 
570 // Table initializing information for parsing the .insn directive.
571 static struct InsnMatchEntry InsnMatchTable[] = {
572   /* Format, Opcode, NumOperands, OperandKinds */
573   { "e", SystemZ::InsnE, 1,
574     { MCK_U16Imm } },
575   { "ri", SystemZ::InsnRI, 3,
576     { MCK_U32Imm, MCK_AnyReg, MCK_S16Imm } },
577   { "rie", SystemZ::InsnRIE, 4,
578     { MCK_U48Imm, MCK_AnyReg, MCK_AnyReg, MCK_PCRel16 } },
579   { "ril", SystemZ::InsnRIL, 3,
580     { MCK_U48Imm, MCK_AnyReg, MCK_PCRel32 } },
581   { "rilu", SystemZ::InsnRILU, 3,
582     { MCK_U48Imm, MCK_AnyReg, MCK_U32Imm } },
583   { "ris", SystemZ::InsnRIS, 5,
584     { MCK_U48Imm, MCK_AnyReg, MCK_S8Imm, MCK_U4Imm, MCK_BDAddr64Disp12 } },
585   { "rr", SystemZ::InsnRR, 3,
586     { MCK_U16Imm, MCK_AnyReg, MCK_AnyReg } },
587   { "rre", SystemZ::InsnRRE, 3,
588     { MCK_U32Imm, MCK_AnyReg, MCK_AnyReg } },
589   { "rrf", SystemZ::InsnRRF, 5,
590     { MCK_U32Imm, MCK_AnyReg, MCK_AnyReg, MCK_AnyReg, MCK_U4Imm } },
591   { "rrs", SystemZ::InsnRRS, 5,
592     { MCK_U48Imm, MCK_AnyReg, MCK_AnyReg, MCK_U4Imm, MCK_BDAddr64Disp12 } },
593   { "rs", SystemZ::InsnRS, 4,
594     { MCK_U32Imm, MCK_AnyReg, MCK_AnyReg, MCK_BDAddr64Disp12 } },
595   { "rse", SystemZ::InsnRSE, 4,
596     { MCK_U48Imm, MCK_AnyReg, MCK_AnyReg, MCK_BDAddr64Disp12 } },
597   { "rsi", SystemZ::InsnRSI, 4,
598     { MCK_U48Imm, MCK_AnyReg, MCK_AnyReg, MCK_PCRel16 } },
599   { "rsy", SystemZ::InsnRSY, 4,
600     { MCK_U48Imm, MCK_AnyReg, MCK_AnyReg, MCK_BDAddr64Disp20 } },
601   { "rx", SystemZ::InsnRX, 3,
602     { MCK_U32Imm, MCK_AnyReg, MCK_BDXAddr64Disp12 } },
603   { "rxe", SystemZ::InsnRXE, 3,
604     { MCK_U48Imm, MCK_AnyReg, MCK_BDXAddr64Disp12 } },
605   { "rxf", SystemZ::InsnRXF, 4,
606     { MCK_U48Imm, MCK_AnyReg, MCK_AnyReg, MCK_BDXAddr64Disp12 } },
607   { "rxy", SystemZ::InsnRXY, 3,
608     { MCK_U48Imm, MCK_AnyReg, MCK_BDXAddr64Disp20 } },
609   { "s", SystemZ::InsnS, 2,
610     { MCK_U32Imm, MCK_BDAddr64Disp12 } },
611   { "si", SystemZ::InsnSI, 3,
612     { MCK_U32Imm, MCK_BDAddr64Disp12, MCK_S8Imm } },
613   { "sil", SystemZ::InsnSIL, 3,
614     { MCK_U48Imm, MCK_BDAddr64Disp12, MCK_U16Imm } },
615   { "siy", SystemZ::InsnSIY, 3,
616     { MCK_U48Imm, MCK_BDAddr64Disp20, MCK_U8Imm } },
617   { "ss", SystemZ::InsnSS, 4,
618     { MCK_U48Imm, MCK_BDXAddr64Disp12, MCK_BDAddr64Disp12, MCK_AnyReg } },
619   { "sse", SystemZ::InsnSSE, 3,
620     { MCK_U48Imm, MCK_BDAddr64Disp12, MCK_BDAddr64Disp12 } },
621   { "ssf", SystemZ::InsnSSF, 4,
622     { MCK_U48Imm, MCK_BDAddr64Disp12, MCK_BDAddr64Disp12, MCK_AnyReg } }
623 };
624 
625 void SystemZOperand::print(raw_ostream &OS) const {
626   llvm_unreachable("Not implemented");
627 }
628 
629 // Parse one register of the form %<prefix><number>.
630 bool SystemZAsmParser::parseRegister(Register &Reg) {
631   Reg.StartLoc = Parser.getTok().getLoc();
632 
633   // Eat the % prefix.
634   if (Parser.getTok().isNot(AsmToken::Percent))
635     return Error(Parser.getTok().getLoc(), "register expected");
636   Parser.Lex();
637 
638   // Expect a register name.
639   if (Parser.getTok().isNot(AsmToken::Identifier))
640     return Error(Reg.StartLoc, "invalid register");
641 
642   // Check that there's a prefix.
643   StringRef Name = Parser.getTok().getString();
644   if (Name.size() < 2)
645     return Error(Reg.StartLoc, "invalid register");
646   char Prefix = Name[0];
647 
648   // Treat the rest of the register name as a register number.
649   if (Name.substr(1).getAsInteger(10, Reg.Num))
650     return Error(Reg.StartLoc, "invalid register");
651 
652   // Look for valid combinations of prefix and number.
653   if (Prefix == 'r' && Reg.Num < 16)
654     Reg.Group = RegGR;
655   else if (Prefix == 'f' && Reg.Num < 16)
656     Reg.Group = RegFP;
657   else if (Prefix == 'v' && Reg.Num < 32)
658     Reg.Group = RegV;
659   else if (Prefix == 'a' && Reg.Num < 16)
660     Reg.Group = RegAR;
661   else if (Prefix == 'c' && Reg.Num < 16)
662     Reg.Group = RegCR;
663   else
664     return Error(Reg.StartLoc, "invalid register");
665 
666   Reg.EndLoc = Parser.getTok().getLoc();
667   Parser.Lex();
668   return false;
669 }
670 
671 // Parse a register of group Group.  If Regs is nonnull, use it to map
672 // the raw register number to LLVM numbering, with zero entries
673 // indicating an invalid register.  IsAddress says whether the
674 // register appears in an address context. Allow FP Group if expecting
675 // RegV Group, since the f-prefix yields the FP group even while used
676 // with vector instructions.
677 bool SystemZAsmParser::parseRegister(Register &Reg, RegisterGroup Group,
678                                      const unsigned *Regs, bool IsAddress) {
679   if (parseRegister(Reg))
680     return true;
681   if (Reg.Group != Group && !(Reg.Group == RegFP && Group == RegV))
682     return Error(Reg.StartLoc, "invalid operand for instruction");
683   if (Regs && Regs[Reg.Num] == 0)
684     return Error(Reg.StartLoc, "invalid register pair");
685   if (Reg.Num == 0 && IsAddress)
686     return Error(Reg.StartLoc, "%r0 used in an address");
687   if (Regs)
688     Reg.Num = Regs[Reg.Num];
689   return false;
690 }
691 
692 // Parse a register and add it to Operands.  The other arguments are as above.
693 OperandMatchResultTy
694 SystemZAsmParser::parseRegister(OperandVector &Operands, RegisterGroup Group,
695                                 const unsigned *Regs, RegisterKind Kind) {
696   if (Parser.getTok().isNot(AsmToken::Percent))
697     return MatchOperand_NoMatch;
698 
699   Register Reg;
700   bool IsAddress = (Kind == ADDR32Reg || Kind == ADDR64Reg);
701   if (parseRegister(Reg, Group, Regs, IsAddress))
702     return MatchOperand_ParseFail;
703 
704   Operands.push_back(SystemZOperand::createReg(Kind, Reg.Num,
705                                                Reg.StartLoc, Reg.EndLoc));
706   return MatchOperand_Success;
707 }
708 
709 // Parse any type of register (including integers) and add it to Operands.
710 OperandMatchResultTy
711 SystemZAsmParser::parseAnyRegister(OperandVector &Operands) {
712   // Handle integer values.
713   if (Parser.getTok().is(AsmToken::Integer)) {
714     const MCExpr *Register;
715     SMLoc StartLoc = Parser.getTok().getLoc();
716     if (Parser.parseExpression(Register))
717       return MatchOperand_ParseFail;
718 
719     if (auto *CE = dyn_cast<MCConstantExpr>(Register)) {
720       int64_t Value = CE->getValue();
721       if (Value < 0 || Value > 15) {
722         Error(StartLoc, "invalid register");
723         return MatchOperand_ParseFail;
724       }
725     }
726 
727     SMLoc EndLoc =
728       SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
729 
730     Operands.push_back(SystemZOperand::createImm(Register, StartLoc, EndLoc));
731   }
732   else {
733     Register Reg;
734     if (parseRegister(Reg))
735       return MatchOperand_ParseFail;
736 
737     // Map to the correct register kind.
738     RegisterKind Kind;
739     unsigned RegNo;
740     if (Reg.Group == RegGR) {
741       Kind = GR64Reg;
742       RegNo = SystemZMC::GR64Regs[Reg.Num];
743     }
744     else if (Reg.Group == RegFP) {
745       Kind = FP64Reg;
746       RegNo = SystemZMC::FP64Regs[Reg.Num];
747     }
748     else if (Reg.Group == RegV) {
749       Kind = VR128Reg;
750       RegNo = SystemZMC::VR128Regs[Reg.Num];
751     }
752     else if (Reg.Group == RegAR) {
753       Kind = AR32Reg;
754       RegNo = SystemZMC::AR32Regs[Reg.Num];
755     }
756     else if (Reg.Group == RegCR) {
757       Kind = CR64Reg;
758       RegNo = SystemZMC::CR64Regs[Reg.Num];
759     }
760     else {
761       return MatchOperand_ParseFail;
762     }
763 
764     Operands.push_back(SystemZOperand::createReg(Kind, RegNo,
765                                                  Reg.StartLoc, Reg.EndLoc));
766   }
767   return MatchOperand_Success;
768 }
769 
770 // Parse a memory operand into Reg1, Reg2, Disp, and Length.
771 bool SystemZAsmParser::parseAddress(bool &HaveReg1, Register &Reg1,
772                                     bool &HaveReg2, Register &Reg2,
773                                     const MCExpr *&Disp,
774                                     const MCExpr *&Length) {
775   // Parse the displacement, which must always be present.
776   if (getParser().parseExpression(Disp))
777     return true;
778 
779   // Parse the optional base and index.
780   HaveReg1 = false;
781   HaveReg2 = false;
782   Length = nullptr;
783   if (getLexer().is(AsmToken::LParen)) {
784     Parser.Lex();
785 
786     if (getLexer().is(AsmToken::Percent)) {
787       // Parse the first register.
788       HaveReg1 = true;
789       if (parseRegister(Reg1))
790         return true;
791     } else {
792       // Parse the length.
793       if (getParser().parseExpression(Length))
794         return true;
795     }
796 
797     // Check whether there's a second register.
798     if (getLexer().is(AsmToken::Comma)) {
799       Parser.Lex();
800       HaveReg2 = true;
801       if (parseRegister(Reg2))
802         return true;
803     }
804 
805     // Consume the closing bracket.
806     if (getLexer().isNot(AsmToken::RParen))
807       return Error(Parser.getTok().getLoc(), "unexpected token in address");
808     Parser.Lex();
809   }
810   return false;
811 }
812 
813 // Verify that Reg is a valid address register (base or index).
814 bool
815 SystemZAsmParser::parseAddressRegister(Register &Reg) {
816   if (Reg.Group == RegV) {
817     Error(Reg.StartLoc, "invalid use of vector addressing");
818     return true;
819   } else if (Reg.Group != RegGR) {
820     Error(Reg.StartLoc, "invalid address register");
821     return true;
822   } else if (Reg.Num == 0) {
823     Error(Reg.StartLoc, "%r0 used in an address");
824     return true;
825   }
826   return false;
827 }
828 
829 // Parse a memory operand and add it to Operands.  The other arguments
830 // are as above.
831 OperandMatchResultTy
832 SystemZAsmParser::parseAddress(OperandVector &Operands, MemoryKind MemKind,
833                                const unsigned *Regs, RegisterKind RegKind) {
834   SMLoc StartLoc = Parser.getTok().getLoc();
835   unsigned Base = 0, Index = 0, LengthReg = 0;
836   Register Reg1, Reg2;
837   bool HaveReg1, HaveReg2;
838   const MCExpr *Disp;
839   const MCExpr *Length;
840   if (parseAddress(HaveReg1, Reg1, HaveReg2, Reg2, Disp, Length))
841     return MatchOperand_ParseFail;
842 
843   switch (MemKind) {
844   case BDMem:
845     // If we have Reg1, it must be an address register.
846     if (HaveReg1) {
847       if (parseAddressRegister(Reg1))
848         return MatchOperand_ParseFail;
849       Base = Regs[Reg1.Num];
850     }
851     // There must be no Reg2 or length.
852     if (Length) {
853       Error(StartLoc, "invalid use of length addressing");
854       return MatchOperand_ParseFail;
855     }
856     if (HaveReg2) {
857       Error(StartLoc, "invalid use of indexed addressing");
858       return MatchOperand_ParseFail;
859     }
860     break;
861   case BDXMem:
862     // If we have Reg1, it must be an address register.
863     if (HaveReg1) {
864       if (parseAddressRegister(Reg1))
865         return MatchOperand_ParseFail;
866       // If the are two registers, the first one is the index and the
867       // second is the base.
868       if (HaveReg2)
869         Index = Regs[Reg1.Num];
870       else
871         Base = Regs[Reg1.Num];
872     }
873     // If we have Reg2, it must be an address register.
874     if (HaveReg2) {
875       if (parseAddressRegister(Reg2))
876         return MatchOperand_ParseFail;
877       Base = Regs[Reg2.Num];
878     }
879     // There must be no length.
880     if (Length) {
881       Error(StartLoc, "invalid use of length addressing");
882       return MatchOperand_ParseFail;
883     }
884     break;
885   case BDLMem:
886     // If we have Reg2, it must be an address register.
887     if (HaveReg2) {
888       if (parseAddressRegister(Reg2))
889         return MatchOperand_ParseFail;
890       Base = Regs[Reg2.Num];
891     }
892     // We cannot support base+index addressing.
893     if (HaveReg1 && HaveReg2) {
894       Error(StartLoc, "invalid use of indexed addressing");
895       return MatchOperand_ParseFail;
896     }
897     // We must have a length.
898     if (!Length) {
899       Error(StartLoc, "missing length in address");
900       return MatchOperand_ParseFail;
901     }
902     break;
903   case BDRMem:
904     // We must have Reg1, and it must be a GPR.
905     if (!HaveReg1 || Reg1.Group != RegGR) {
906       Error(StartLoc, "invalid operand for instruction");
907       return MatchOperand_ParseFail;
908     }
909     LengthReg = SystemZMC::GR64Regs[Reg1.Num];
910     // If we have Reg2, it must be an address register.
911     if (HaveReg2) {
912       if (parseAddressRegister(Reg2))
913         return MatchOperand_ParseFail;
914       Base = Regs[Reg2.Num];
915     }
916     // There must be no length.
917     if (Length) {
918       Error(StartLoc, "invalid use of length addressing");
919       return MatchOperand_ParseFail;
920     }
921     break;
922   case BDVMem:
923     // We must have Reg1, and it must be a vector register.
924     if (!HaveReg1 || Reg1.Group != RegV) {
925       Error(StartLoc, "vector index required in address");
926       return MatchOperand_ParseFail;
927     }
928     Index = SystemZMC::VR128Regs[Reg1.Num];
929     // If we have Reg2, it must be an address register.
930     if (HaveReg2) {
931       if (parseAddressRegister(Reg2))
932         return MatchOperand_ParseFail;
933       Base = Regs[Reg2.Num];
934     }
935     // There must be no length.
936     if (Length) {
937       Error(StartLoc, "invalid use of length addressing");
938       return MatchOperand_ParseFail;
939     }
940     break;
941   }
942 
943   SMLoc EndLoc =
944     SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
945   Operands.push_back(SystemZOperand::createMem(MemKind, RegKind, Base, Disp,
946                                                Index, Length, LengthReg,
947                                                StartLoc, EndLoc));
948   return MatchOperand_Success;
949 }
950 
951 bool SystemZAsmParser::ParseDirective(AsmToken DirectiveID) {
952   StringRef IDVal = DirectiveID.getIdentifier();
953 
954   if (IDVal == ".insn")
955     return ParseDirectiveInsn(DirectiveID.getLoc());
956 
957   return true;
958 }
959 
960 /// ParseDirectiveInsn
961 /// ::= .insn [ format, encoding, (operands (, operands)*) ]
962 bool SystemZAsmParser::ParseDirectiveInsn(SMLoc L) {
963   MCAsmParser &Parser = getParser();
964 
965   // Expect instruction format as identifier.
966   StringRef Format;
967   SMLoc ErrorLoc = Parser.getTok().getLoc();
968   if (Parser.parseIdentifier(Format))
969     return Error(ErrorLoc, "expected instruction format");
970 
971   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> Operands;
972 
973   // Find entry for this format in InsnMatchTable.
974   auto EntryRange =
975     std::equal_range(std::begin(InsnMatchTable), std::end(InsnMatchTable),
976                      Format, CompareInsn());
977 
978   // If first == second, couldn't find a match in the table.
979   if (EntryRange.first == EntryRange.second)
980     return Error(ErrorLoc, "unrecognized format");
981 
982   struct InsnMatchEntry *Entry = EntryRange.first;
983 
984   // Format should match from equal_range.
985   assert(Entry->Format == Format);
986 
987   // Parse the following operands using the table's information.
988   for (int i = 0; i < Entry->NumOperands; i++) {
989     MatchClassKind Kind = Entry->OperandKinds[i];
990 
991     SMLoc StartLoc = Parser.getTok().getLoc();
992 
993     // Always expect commas as separators for operands.
994     if (getLexer().isNot(AsmToken::Comma))
995       return Error(StartLoc, "unexpected token in directive");
996     Lex();
997 
998     // Parse operands.
999     OperandMatchResultTy ResTy;
1000     if (Kind == MCK_AnyReg)
1001       ResTy = parseAnyReg(Operands);
1002     else if (Kind == MCK_BDXAddr64Disp12 || Kind == MCK_BDXAddr64Disp20)
1003       ResTy = parseBDXAddr64(Operands);
1004     else if (Kind == MCK_BDAddr64Disp12 || Kind == MCK_BDAddr64Disp20)
1005       ResTy = parseBDAddr64(Operands);
1006     else if (Kind == MCK_PCRel32)
1007       ResTy = parsePCRel32(Operands);
1008     else if (Kind == MCK_PCRel16)
1009       ResTy = parsePCRel16(Operands);
1010     else {
1011       // Only remaining operand kind is an immediate.
1012       const MCExpr *Expr;
1013       SMLoc StartLoc = Parser.getTok().getLoc();
1014 
1015       // Expect immediate expression.
1016       if (Parser.parseExpression(Expr))
1017         return Error(StartLoc, "unexpected token in directive");
1018 
1019       SMLoc EndLoc =
1020         SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1021 
1022       Operands.push_back(SystemZOperand::createImm(Expr, StartLoc, EndLoc));
1023       ResTy = MatchOperand_Success;
1024     }
1025 
1026     if (ResTy != MatchOperand_Success)
1027       return true;
1028   }
1029 
1030   // Build the instruction with the parsed operands.
1031   MCInst Inst = MCInstBuilder(Entry->Opcode);
1032 
1033   for (size_t i = 0; i < Operands.size(); i++) {
1034     MCParsedAsmOperand &Operand = *Operands[i];
1035     MatchClassKind Kind = Entry->OperandKinds[i];
1036 
1037     // Verify operand.
1038     unsigned Res = validateOperandClass(Operand, Kind);
1039     if (Res != Match_Success)
1040       return Error(Operand.getStartLoc(), "unexpected operand type");
1041 
1042     // Add operands to instruction.
1043     SystemZOperand &ZOperand = static_cast<SystemZOperand &>(Operand);
1044     if (ZOperand.isReg())
1045       ZOperand.addRegOperands(Inst, 1);
1046     else if (ZOperand.isMem(BDMem))
1047       ZOperand.addBDAddrOperands(Inst, 2);
1048     else if (ZOperand.isMem(BDXMem))
1049       ZOperand.addBDXAddrOperands(Inst, 3);
1050     else if (ZOperand.isImm())
1051       ZOperand.addImmOperands(Inst, 1);
1052     else
1053       llvm_unreachable("unexpected operand type");
1054   }
1055 
1056   // Emit as a regular instruction.
1057   Parser.getStreamer().EmitInstruction(Inst, getSTI());
1058 
1059   return false;
1060 }
1061 
1062 bool SystemZAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1063                                      SMLoc &EndLoc) {
1064   Register Reg;
1065   if (parseRegister(Reg))
1066     return true;
1067   if (Reg.Group == RegGR)
1068     RegNo = SystemZMC::GR64Regs[Reg.Num];
1069   else if (Reg.Group == RegFP)
1070     RegNo = SystemZMC::FP64Regs[Reg.Num];
1071   else if (Reg.Group == RegV)
1072     RegNo = SystemZMC::VR128Regs[Reg.Num];
1073   else if (Reg.Group == RegAR)
1074     RegNo = SystemZMC::AR32Regs[Reg.Num];
1075   else if (Reg.Group == RegCR)
1076     RegNo = SystemZMC::CR64Regs[Reg.Num];
1077   StartLoc = Reg.StartLoc;
1078   EndLoc = Reg.EndLoc;
1079   return false;
1080 }
1081 
1082 bool SystemZAsmParser::ParseInstruction(ParseInstructionInfo &Info,
1083                                         StringRef Name, SMLoc NameLoc,
1084                                         OperandVector &Operands) {
1085   Operands.push_back(SystemZOperand::createToken(Name, NameLoc));
1086 
1087   // Read the remaining operands.
1088   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1089     // Read the first operand.
1090     if (parseOperand(Operands, Name)) {
1091       return true;
1092     }
1093 
1094     // Read any subsequent operands.
1095     while (getLexer().is(AsmToken::Comma)) {
1096       Parser.Lex();
1097       if (parseOperand(Operands, Name)) {
1098         return true;
1099       }
1100     }
1101     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1102       SMLoc Loc = getLexer().getLoc();
1103       return Error(Loc, "unexpected token in argument list");
1104     }
1105   }
1106 
1107   // Consume the EndOfStatement.
1108   Parser.Lex();
1109   return false;
1110 }
1111 
1112 bool SystemZAsmParser::parseOperand(OperandVector &Operands,
1113                                     StringRef Mnemonic) {
1114   // Check if the current operand has a custom associated parser, if so, try to
1115   // custom parse the operand, or fallback to the general approach.  Force all
1116   // features to be available during the operand check, or else we will fail to
1117   // find the custom parser, and then we will later get an InvalidOperand error
1118   // instead of a MissingFeature errror.
1119   uint64_t AvailableFeatures = getAvailableFeatures();
1120   setAvailableFeatures(~(uint64_t)0);
1121   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1122   setAvailableFeatures(AvailableFeatures);
1123   if (ResTy == MatchOperand_Success)
1124     return false;
1125 
1126   // If there wasn't a custom match, try the generic matcher below. Otherwise,
1127   // there was a match, but an error occurred, in which case, just return that
1128   // the operand parsing failed.
1129   if (ResTy == MatchOperand_ParseFail)
1130     return true;
1131 
1132   // Check for a register.  All real register operands should have used
1133   // a context-dependent parse routine, which gives the required register
1134   // class.  The code is here to mop up other cases, like those where
1135   // the instruction isn't recognized.
1136   if (Parser.getTok().is(AsmToken::Percent)) {
1137     Register Reg;
1138     if (parseRegister(Reg))
1139       return true;
1140     Operands.push_back(SystemZOperand::createInvalid(Reg.StartLoc, Reg.EndLoc));
1141     return false;
1142   }
1143 
1144   // The only other type of operand is an immediate or address.  As above,
1145   // real address operands should have used a context-dependent parse routine,
1146   // so we treat any plain expression as an immediate.
1147   SMLoc StartLoc = Parser.getTok().getLoc();
1148   Register Reg1, Reg2;
1149   bool HaveReg1, HaveReg2;
1150   const MCExpr *Expr;
1151   const MCExpr *Length;
1152   if (parseAddress(HaveReg1, Reg1, HaveReg2, Reg2, Expr, Length))
1153     return true;
1154   // If the register combination is not valid for any instruction, reject it.
1155   // Otherwise, fall back to reporting an unrecognized instruction.
1156   if (HaveReg1 && Reg1.Group != RegGR && Reg1.Group != RegV
1157       && parseAddressRegister(Reg1))
1158     return true;
1159   if (HaveReg2 && parseAddressRegister(Reg2))
1160     return true;
1161 
1162   SMLoc EndLoc =
1163     SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1164   if (HaveReg1 || HaveReg2 || Length)
1165     Operands.push_back(SystemZOperand::createInvalid(StartLoc, EndLoc));
1166   else
1167     Operands.push_back(SystemZOperand::createImm(Expr, StartLoc, EndLoc));
1168   return false;
1169 }
1170 
1171 std::string SystemZMnemonicSpellCheck(StringRef S, uint64_t FBS);
1172 
1173 bool SystemZAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1174                                                OperandVector &Operands,
1175                                                MCStreamer &Out,
1176                                                uint64_t &ErrorInfo,
1177                                                bool MatchingInlineAsm) {
1178   MCInst Inst;
1179   unsigned MatchResult;
1180 
1181   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
1182                                      MatchingInlineAsm);
1183   switch (MatchResult) {
1184   case Match_Success:
1185     Inst.setLoc(IDLoc);
1186     Out.EmitInstruction(Inst, getSTI());
1187     return false;
1188 
1189   case Match_MissingFeature: {
1190     assert(ErrorInfo && "Unknown missing feature!");
1191     // Special case the error message for the very common case where only
1192     // a single subtarget feature is missing
1193     std::string Msg = "instruction requires:";
1194     uint64_t Mask = 1;
1195     for (unsigned I = 0; I < sizeof(ErrorInfo) * 8 - 1; ++I) {
1196       if (ErrorInfo & Mask) {
1197         Msg += " ";
1198         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
1199       }
1200       Mask <<= 1;
1201     }
1202     return Error(IDLoc, Msg);
1203   }
1204 
1205   case Match_InvalidOperand: {
1206     SMLoc ErrorLoc = IDLoc;
1207     if (ErrorInfo != ~0ULL) {
1208       if (ErrorInfo >= Operands.size())
1209         return Error(IDLoc, "too few operands for instruction");
1210 
1211       ErrorLoc = ((SystemZOperand &)*Operands[ErrorInfo]).getStartLoc();
1212       if (ErrorLoc == SMLoc())
1213         ErrorLoc = IDLoc;
1214     }
1215     return Error(ErrorLoc, "invalid operand for instruction");
1216   }
1217 
1218   case Match_MnemonicFail: {
1219     uint64_t FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
1220     std::string Suggestion = SystemZMnemonicSpellCheck(
1221       ((SystemZOperand &)*Operands[0]).getToken(), FBS);
1222     return Error(IDLoc, "invalid instruction" + Suggestion,
1223                  ((SystemZOperand &)*Operands[0]).getLocRange());
1224   }
1225   }
1226 
1227   llvm_unreachable("Unexpected match type");
1228 }
1229 
1230 OperandMatchResultTy
1231 SystemZAsmParser::parsePCRel(OperandVector &Operands, int64_t MinVal,
1232                              int64_t MaxVal, bool AllowTLS) {
1233   MCContext &Ctx = getContext();
1234   MCStreamer &Out = getStreamer();
1235   const MCExpr *Expr;
1236   SMLoc StartLoc = Parser.getTok().getLoc();
1237   if (getParser().parseExpression(Expr))
1238     return MatchOperand_NoMatch;
1239 
1240   // For consistency with the GNU assembler, treat immediates as offsets
1241   // from ".".
1242   if (auto *CE = dyn_cast<MCConstantExpr>(Expr)) {
1243     int64_t Value = CE->getValue();
1244     if ((Value & 1) || Value < MinVal || Value > MaxVal) {
1245       Error(StartLoc, "offset out of range");
1246       return MatchOperand_ParseFail;
1247     }
1248     MCSymbol *Sym = Ctx.createTempSymbol();
1249     Out.EmitLabel(Sym);
1250     const MCExpr *Base = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
1251                                                  Ctx);
1252     Expr = Value == 0 ? Base : MCBinaryExpr::createAdd(Base, Expr, Ctx);
1253   }
1254 
1255   // Optionally match :tls_gdcall: or :tls_ldcall: followed by a TLS symbol.
1256   const MCExpr *Sym = nullptr;
1257   if (AllowTLS && getLexer().is(AsmToken::Colon)) {
1258     Parser.Lex();
1259 
1260     if (Parser.getTok().isNot(AsmToken::Identifier)) {
1261       Error(Parser.getTok().getLoc(), "unexpected token");
1262       return MatchOperand_ParseFail;
1263     }
1264 
1265     MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
1266     StringRef Name = Parser.getTok().getString();
1267     if (Name == "tls_gdcall")
1268       Kind = MCSymbolRefExpr::VK_TLSGD;
1269     else if (Name == "tls_ldcall")
1270       Kind = MCSymbolRefExpr::VK_TLSLDM;
1271     else {
1272       Error(Parser.getTok().getLoc(), "unknown TLS tag");
1273       return MatchOperand_ParseFail;
1274     }
1275     Parser.Lex();
1276 
1277     if (Parser.getTok().isNot(AsmToken::Colon)) {
1278       Error(Parser.getTok().getLoc(), "unexpected token");
1279       return MatchOperand_ParseFail;
1280     }
1281     Parser.Lex();
1282 
1283     if (Parser.getTok().isNot(AsmToken::Identifier)) {
1284       Error(Parser.getTok().getLoc(), "unexpected token");
1285       return MatchOperand_ParseFail;
1286     }
1287 
1288     StringRef Identifier = Parser.getTok().getString();
1289     Sym = MCSymbolRefExpr::create(Ctx.getOrCreateSymbol(Identifier),
1290                                   Kind, Ctx);
1291     Parser.Lex();
1292   }
1293 
1294   SMLoc EndLoc =
1295     SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1296 
1297   if (AllowTLS)
1298     Operands.push_back(SystemZOperand::createImmTLS(Expr, Sym,
1299                                                     StartLoc, EndLoc));
1300   else
1301     Operands.push_back(SystemZOperand::createImm(Expr, StartLoc, EndLoc));
1302 
1303   return MatchOperand_Success;
1304 }
1305 
1306 // Force static initialization.
1307 extern "C" void LLVMInitializeSystemZAsmParser() {
1308   RegisterMCAsmParser<SystemZAsmParser> X(getTheSystemZTarget());
1309 }
1310