There are a few places where subtarget features are still
[oota-llvm.git] / lib / Target / AMDGPU / AsmParser / AMDGPUAsmParser.cpp
1 //===-- AMDGPUAsmParser.cpp - Parse SI asm to MCInst instructions ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
11 #include "MCTargetDesc/AMDGPUTargetStreamer.h"
12 #include "Utils/AMDGPUBaseInfo.h"
13 #include "AMDKernelCodeT.h"
14 #include "SIDefines.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCParser/MCAsmLexer.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/MC/MCTargetAsmParser.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/Debug.h"
36
37 using namespace llvm;
38
39 namespace {
40
41 struct OptionalOperand;
42
43 class AMDGPUOperand : public MCParsedAsmOperand {
44   enum KindTy {
45     Token,
46     Immediate,
47     Register,
48     Expression
49   } Kind;
50
51   SMLoc StartLoc, EndLoc;
52
53 public:
54   AMDGPUOperand(enum KindTy K) : MCParsedAsmOperand(), Kind(K) {}
55
56   MCContext *Ctx;
57
58   enum ImmTy {
59     ImmTyNone,
60     ImmTyDSOffset0,
61     ImmTyDSOffset1,
62     ImmTyGDS,
63     ImmTyOffset,
64     ImmTyGLC,
65     ImmTySLC,
66     ImmTyTFE,
67     ImmTyClamp,
68     ImmTyOMod
69   };
70
71   struct TokOp {
72     const char *Data;
73     unsigned Length;
74   };
75
76   struct ImmOp {
77     bool IsFPImm;
78     ImmTy Type;
79     int64_t Val;
80   };
81
82   struct RegOp {
83     unsigned RegNo;
84     int Modifiers;
85     const MCRegisterInfo *TRI;
86     bool IsForcedVOP3;
87   };
88
89   union {
90     TokOp Tok;
91     ImmOp Imm;
92     RegOp Reg;
93     const MCExpr *Expr;
94   };
95
96   void addImmOperands(MCInst &Inst, unsigned N) const {
97     Inst.addOperand(MCOperand::createImm(getImm()));
98   }
99
100   StringRef getToken() const {
101     return StringRef(Tok.Data, Tok.Length);
102   }
103
104   void addRegOperands(MCInst &Inst, unsigned N) const {
105     Inst.addOperand(MCOperand::createReg(getReg()));
106   }
107
108   void addRegOrImmOperands(MCInst &Inst, unsigned N) const {
109     if (isReg())
110       addRegOperands(Inst, N);
111     else
112       addImmOperands(Inst, N);
113   }
114
115   void addRegWithInputModsOperands(MCInst &Inst, unsigned N) const {
116     Inst.addOperand(MCOperand::createImm(
117         Reg.Modifiers == -1 ? 0 : Reg.Modifiers));
118     addRegOperands(Inst, N);
119   }
120
121   void addSoppBrTargetOperands(MCInst &Inst, unsigned N) const {
122     if (isImm())
123       addImmOperands(Inst, N);
124     else {
125       assert(isExpr());
126       Inst.addOperand(MCOperand::createExpr(Expr));
127     }
128   }
129
130   bool defaultTokenHasSuffix() const {
131     StringRef Token(Tok.Data, Tok.Length);
132
133     return Token.endswith("_e32") || Token.endswith("_e64");
134   }
135
136   bool isToken() const override {
137     return Kind == Token;
138   }
139
140   bool isImm() const override {
141     return Kind == Immediate;
142   }
143
144   bool isInlineImm() const {
145     float F = BitsToFloat(Imm.Val);
146     // TODO: Add 0.5pi for VI
147     return isImm() && ((Imm.Val <= 64 && Imm.Val >= -16) ||
148            (F == 0.0 || F == 0.5 || F == -0.5 || F == 1.0 || F == -1.0 ||
149            F == 2.0 || F == -2.0 || F == 4.0 || F == -4.0));
150   }
151
152   bool isDSOffset0() const {
153     assert(isImm());
154     return Imm.Type == ImmTyDSOffset0;
155   }
156
157   bool isDSOffset1() const {
158     assert(isImm());
159     return Imm.Type == ImmTyDSOffset1;
160   }
161
162   int64_t getImm() const {
163     return Imm.Val;
164   }
165
166   enum ImmTy getImmTy() const {
167     assert(isImm());
168     return Imm.Type;
169   }
170
171   bool isRegKind() const {
172     return Kind == Register;
173   }
174
175   bool isReg() const override {
176     return Kind == Register && Reg.Modifiers == -1;
177   }
178
179   bool isRegWithInputMods() const {
180     return Kind == Register && (Reg.IsForcedVOP3 || Reg.Modifiers != -1);
181   }
182
183   void setModifiers(unsigned Mods) {
184     assert(isReg());
185     Reg.Modifiers = Mods;
186   }
187
188   bool hasModifiers() const {
189     assert(isRegKind());
190     return Reg.Modifiers != -1;
191   }
192
193   unsigned getReg() const override {
194     return Reg.RegNo;
195   }
196
197   bool isRegOrImm() const {
198     return isReg() || isImm();
199   }
200
201   bool isRegClass(unsigned RCID) const {
202     return Reg.TRI->getRegClass(RCID).contains(getReg());
203   }
204
205   bool isSCSrc32() const {
206     return isInlineImm() || (isReg() && isRegClass(AMDGPU::SReg_32RegClassID));
207   }
208
209   bool isSSrc32() const {
210     return isImm() || (isReg() && isRegClass(AMDGPU::SReg_32RegClassID));
211   }
212
213   bool isSSrc64() const {
214     return isImm() || isInlineImm() ||
215            (isReg() && isRegClass(AMDGPU::SReg_64RegClassID));
216   }
217
218   bool isVCSrc32() const {
219     return isInlineImm() || (isReg() && isRegClass(AMDGPU::VS_32RegClassID));
220   }
221
222   bool isVCSrc64() const {
223     return isInlineImm() || (isReg() && isRegClass(AMDGPU::VS_64RegClassID));
224   }
225
226   bool isVSrc32() const {
227     return isImm() || (isReg() && isRegClass(AMDGPU::VS_32RegClassID));
228   }
229
230   bool isVSrc64() const {
231     return isImm() || (isReg() && isRegClass(AMDGPU::VS_64RegClassID));
232   }
233
234   bool isMem() const override {
235     return false;
236   }
237
238   bool isExpr() const {
239     return Kind == Expression;
240   }
241
242   bool isSoppBrTarget() const {
243     return isExpr() || isImm();
244   }
245
246   SMLoc getStartLoc() const override {
247     return StartLoc;
248   }
249
250   SMLoc getEndLoc() const override {
251     return EndLoc;
252   }
253
254   void print(raw_ostream &OS) const override { }
255
256   static std::unique_ptr<AMDGPUOperand> CreateImm(int64_t Val, SMLoc Loc,
257                                                   enum ImmTy Type = ImmTyNone,
258                                                   bool IsFPImm = false) {
259     auto Op = llvm::make_unique<AMDGPUOperand>(Immediate);
260     Op->Imm.Val = Val;
261     Op->Imm.IsFPImm = IsFPImm;
262     Op->Imm.Type = Type;
263     Op->StartLoc = Loc;
264     Op->EndLoc = Loc;
265     return Op;
266   }
267
268   static std::unique_ptr<AMDGPUOperand> CreateToken(StringRef Str, SMLoc Loc,
269                                            bool HasExplicitEncodingSize = true) {
270     auto Res = llvm::make_unique<AMDGPUOperand>(Token);
271     Res->Tok.Data = Str.data();
272     Res->Tok.Length = Str.size();
273     Res->StartLoc = Loc;
274     Res->EndLoc = Loc;
275     return Res;
276   }
277
278   static std::unique_ptr<AMDGPUOperand> CreateReg(unsigned RegNo, SMLoc S,
279                                                   SMLoc E,
280                                                   const MCRegisterInfo *TRI,
281                                                   bool ForceVOP3) {
282     auto Op = llvm::make_unique<AMDGPUOperand>(Register);
283     Op->Reg.RegNo = RegNo;
284     Op->Reg.TRI = TRI;
285     Op->Reg.Modifiers = -1;
286     Op->Reg.IsForcedVOP3 = ForceVOP3;
287     Op->StartLoc = S;
288     Op->EndLoc = E;
289     return Op;
290   }
291
292   static std::unique_ptr<AMDGPUOperand> CreateExpr(const class MCExpr *Expr, SMLoc S) {
293     auto Op = llvm::make_unique<AMDGPUOperand>(Expression);
294     Op->Expr = Expr;
295     Op->StartLoc = S;
296     Op->EndLoc = S;
297     return Op;
298   }
299
300   bool isDSOffset() const;
301   bool isDSOffset01() const;
302   bool isSWaitCnt() const;
303   bool isMubufOffset() const;
304 };
305
306 class AMDGPUAsmParser : public MCTargetAsmParser {
307   MCSubtargetInfo &STI;
308   const MCInstrInfo &MII;
309   MCAsmParser &Parser;
310
311   unsigned ForcedEncodingSize;
312   /// @name Auto-generated Match Functions
313   /// {
314
315 #define GET_ASSEMBLER_HEADER
316 #include "AMDGPUGenAsmMatcher.inc"
317
318   /// }
319
320 private:
321   bool ParseDirectiveMajorMinor(uint32_t &Major, uint32_t &Minor);
322   bool ParseDirectiveHSACodeObjectVersion();
323   bool ParseDirectiveHSACodeObjectISA();
324   bool ParseAMDKernelCodeTValue(StringRef ID, amd_kernel_code_t &Header);
325   bool ParseDirectiveAMDKernelCodeT();
326
327 public:
328   AMDGPUAsmParser(MCSubtargetInfo &STI, MCAsmParser &_Parser,
329                const MCInstrInfo &MII,
330                const MCTargetOptions &Options)
331       : MCTargetAsmParser(), STI(STI), MII(MII), Parser(_Parser),
332         ForcedEncodingSize(0){
333
334     if (STI.getFeatureBits().none()) {
335       // Set default features.
336       STI.ToggleFeature("SOUTHERN_ISLANDS");
337     }
338
339     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
340   }
341
342   AMDGPUTargetStreamer &getTargetStreamer() {
343     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
344     return static_cast<AMDGPUTargetStreamer &>(TS);
345   }
346
347   unsigned getForcedEncodingSize() const {
348     return ForcedEncodingSize;
349   }
350
351   void setForcedEncodingSize(unsigned Size) {
352     ForcedEncodingSize = Size;
353   }
354
355   bool isForcedVOP3() const {
356     return ForcedEncodingSize == 64;
357   }
358
359   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
360   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
361   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
362                                OperandVector &Operands, MCStreamer &Out,
363                                uint64_t &ErrorInfo,
364                                FeatureBitset &ErrorMissingFeature,
365                                bool MatchingInlineAsm) override;
366   bool ParseDirective(AsmToken DirectiveID) override;
367   OperandMatchResultTy parseOperand(OperandVector &Operands, StringRef Mnemonic);
368   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
369                         SMLoc NameLoc, OperandVector &Operands) override;
370
371   OperandMatchResultTy parseIntWithPrefix(const char *Prefix, int64_t &Int,
372                                           int64_t Default = 0);
373   OperandMatchResultTy parseIntWithPrefix(const char *Prefix,
374                                           OperandVector &Operands,
375                                           enum AMDGPUOperand::ImmTy ImmTy =
376                                                       AMDGPUOperand::ImmTyNone);
377   OperandMatchResultTy parseNamedBit(const char *Name, OperandVector &Operands,
378                                      enum AMDGPUOperand::ImmTy ImmTy =
379                                                       AMDGPUOperand::ImmTyNone);
380   OperandMatchResultTy parseOptionalOps(
381                                    const ArrayRef<OptionalOperand> &OptionalOps,
382                                    OperandVector &Operands);
383
384
385   void cvtDSOffset01(MCInst &Inst, const OperandVector &Operands);
386   void cvtDS(MCInst &Inst, const OperandVector &Operands);
387   OperandMatchResultTy parseDSOptionalOps(OperandVector &Operands);
388   OperandMatchResultTy parseDSOff01OptionalOps(OperandVector &Operands);
389   OperandMatchResultTy parseDSOffsetOptional(OperandVector &Operands);
390
391   bool parseCnt(int64_t &IntVal);
392   OperandMatchResultTy parseSWaitCntOps(OperandVector &Operands);
393   OperandMatchResultTy parseSOppBrTarget(OperandVector &Operands);
394
395   OperandMatchResultTy parseFlatOptionalOps(OperandVector &Operands);
396   OperandMatchResultTy parseFlatAtomicOptionalOps(OperandVector &Operands);
397   void cvtFlat(MCInst &Inst, const OperandVector &Operands);
398
399   void cvtMubuf(MCInst &Inst, const OperandVector &Operands);
400   OperandMatchResultTy parseOffset(OperandVector &Operands);
401   OperandMatchResultTy parseMubufOptionalOps(OperandVector &Operands);
402   OperandMatchResultTy parseGLC(OperandVector &Operands);
403   OperandMatchResultTy parseSLC(OperandVector &Operands);
404   OperandMatchResultTy parseTFE(OperandVector &Operands);
405
406   OperandMatchResultTy parseDMask(OperandVector &Operands);
407   OperandMatchResultTy parseUNorm(OperandVector &Operands);
408   OperandMatchResultTy parseR128(OperandVector &Operands);
409
410   void cvtVOP3(MCInst &Inst, const OperandVector &Operands);
411   OperandMatchResultTy parseVOP3OptionalOps(OperandVector &Operands);
412 };
413
414 struct OptionalOperand {
415   const char *Name;
416   AMDGPUOperand::ImmTy Type;
417   bool IsBit;
418   int64_t Default;
419   bool (*ConvertResult)(int64_t&);
420 };
421
422 }
423
424 static unsigned getRegClass(bool IsVgpr, unsigned RegWidth) {
425   if (IsVgpr) {
426     switch (RegWidth) {
427       default: llvm_unreachable("Unknown register width");
428       case 1: return AMDGPU::VGPR_32RegClassID;
429       case 2: return AMDGPU::VReg_64RegClassID;
430       case 3: return AMDGPU::VReg_96RegClassID;
431       case 4: return AMDGPU::VReg_128RegClassID;
432       case 8: return AMDGPU::VReg_256RegClassID;
433       case 16: return AMDGPU::VReg_512RegClassID;
434     }
435   }
436
437   switch (RegWidth) {
438     default: llvm_unreachable("Unknown register width");
439     case 1: return AMDGPU::SGPR_32RegClassID;
440     case 2: return AMDGPU::SGPR_64RegClassID;
441     case 4: return AMDGPU::SReg_128RegClassID;
442     case 8: return AMDGPU::SReg_256RegClassID;
443     case 16: return AMDGPU::SReg_512RegClassID;
444   }
445 }
446
447 static unsigned getRegForName(const StringRef &RegName) {
448
449   return StringSwitch<unsigned>(RegName)
450     .Case("exec", AMDGPU::EXEC)
451     .Case("vcc", AMDGPU::VCC)
452     .Case("flat_scr", AMDGPU::FLAT_SCR)
453     .Case("m0", AMDGPU::M0)
454     .Case("scc", AMDGPU::SCC)
455     .Case("flat_scr_lo", AMDGPU::FLAT_SCR_LO)
456     .Case("flat_scr_hi", AMDGPU::FLAT_SCR_HI)
457     .Case("vcc_lo", AMDGPU::VCC_LO)
458     .Case("vcc_hi", AMDGPU::VCC_HI)
459     .Case("exec_lo", AMDGPU::EXEC_LO)
460     .Case("exec_hi", AMDGPU::EXEC_HI)
461     .Default(0);
462 }
463
464 bool AMDGPUAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) {
465   const AsmToken Tok = Parser.getTok();
466   StartLoc = Tok.getLoc();
467   EndLoc = Tok.getEndLoc();
468   const StringRef &RegName = Tok.getString();
469   RegNo = getRegForName(RegName);
470
471   if (RegNo) {
472     Parser.Lex();
473     return false;
474   }
475
476   // Match vgprs and sgprs
477   if (RegName[0] != 's' && RegName[0] != 'v')
478     return true;
479
480   bool IsVgpr = RegName[0] == 'v';
481   unsigned RegWidth;
482   unsigned RegIndexInClass;
483   if (RegName.size() > 1) {
484     // We have a 32-bit register
485     RegWidth = 1;
486     if (RegName.substr(1).getAsInteger(10, RegIndexInClass))
487       return true;
488     Parser.Lex();
489   } else {
490     // We have a register greater than 32-bits.
491
492     int64_t RegLo, RegHi;
493     Parser.Lex();
494     if (getLexer().isNot(AsmToken::LBrac))
495       return true;
496
497     Parser.Lex();
498     if (getParser().parseAbsoluteExpression(RegLo))
499       return true;
500
501     if (getLexer().isNot(AsmToken::Colon))
502       return true;
503
504     Parser.Lex();
505     if (getParser().parseAbsoluteExpression(RegHi))
506       return true;
507
508     if (getLexer().isNot(AsmToken::RBrac))
509       return true;
510
511     Parser.Lex();
512     RegWidth = (RegHi - RegLo) + 1;
513     if (IsVgpr) {
514       // VGPR registers aren't aligned.
515       RegIndexInClass = RegLo;
516     } else {
517       // SGPR registers are aligned.  Max alignment is 4 dwords.
518       RegIndexInClass = RegLo / std::min(RegWidth, 4u);
519     }
520   }
521
522   const MCRegisterInfo *TRC = getContext().getRegisterInfo();
523   unsigned RC = getRegClass(IsVgpr, RegWidth);
524   if (RegIndexInClass > TRC->getRegClass(RC).getNumRegs())
525     return true;
526   RegNo = TRC->getRegClass(RC).getRegister(RegIndexInClass);
527   return false;
528 }
529
530 unsigned AMDGPUAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
531
532   uint64_t TSFlags = MII.get(Inst.getOpcode()).TSFlags;
533
534   if ((getForcedEncodingSize() == 32 && (TSFlags & SIInstrFlags::VOP3)) ||
535       (getForcedEncodingSize() == 64 && !(TSFlags & SIInstrFlags::VOP3)))
536     return Match_InvalidOperand;
537
538   return Match_Success;
539 }
540
541
542 bool AMDGPUAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
543                                               OperandVector &Operands,
544                                               MCStreamer &Out,
545                                               uint64_t &ErrorInfo,
546                                               FeatureBitset &ErrorMissingFeature,
547                                               bool MatchingInlineAsm) {
548   MCInst Inst;
549
550   switch (MatchInstructionImpl(Operands, Inst, ErrorInfo, ErrorMissingFeature, MatchingInlineAsm)) {
551     default: break;
552     case Match_Success:
553       Inst.setLoc(IDLoc);
554       Out.EmitInstruction(Inst, STI);
555       return false;
556     case Match_MissingFeature:
557       return Error(IDLoc, "instruction not supported on this GPU");
558
559     case Match_MnemonicFail:
560       return Error(IDLoc, "unrecognized instruction mnemonic");
561
562     case Match_InvalidOperand: {
563       SMLoc ErrorLoc = IDLoc;
564       if (ErrorInfo != ~0ULL) {
565         if (ErrorInfo >= Operands.size()) {
566           if (isForcedVOP3()) {
567             // If 64-bit encoding has been forced we can end up with no
568             // clamp or omod operands if none of the registers have modifiers,
569             // so we need to add these to the operand list.
570             AMDGPUOperand &LastOp =
571                 ((AMDGPUOperand &)*Operands[Operands.size() - 1]);
572             if (LastOp.isRegKind() ||
573                (LastOp.isImm() &&
574                 LastOp.getImmTy() != AMDGPUOperand::ImmTyNone)) {
575               SMLoc S = Parser.getTok().getLoc();
576               Operands.push_back(AMDGPUOperand::CreateImm(0, S,
577                                  AMDGPUOperand::ImmTyClamp));
578               Operands.push_back(AMDGPUOperand::CreateImm(0, S,
579                                  AMDGPUOperand::ImmTyOMod));
580               bool Res = MatchAndEmitInstruction(IDLoc, Opcode, Operands,
581                                                  Out, ErrorInfo,
582                                                  ErrorMissingFeature,
583                                                  MatchingInlineAsm);
584               if (!Res)
585                 return Res;
586             }
587
588           }
589           return Error(IDLoc, "too few operands for instruction");
590         }
591
592         ErrorLoc = ((AMDGPUOperand &)*Operands[ErrorInfo]).getStartLoc();
593         if (ErrorLoc == SMLoc())
594           ErrorLoc = IDLoc;
595       }
596       return Error(ErrorLoc, "invalid operand for instruction");
597     }
598   }
599   llvm_unreachable("Implement any new match types added!");
600 }
601
602 bool AMDGPUAsmParser::ParseDirectiveMajorMinor(uint32_t &Major,
603                                                uint32_t &Minor) {
604   if (getLexer().isNot(AsmToken::Integer))
605     return TokError("invalid major version");
606
607   Major = getLexer().getTok().getIntVal();
608   Lex();
609
610   if (getLexer().isNot(AsmToken::Comma))
611     return TokError("minor version number required, comma expected");
612   Lex();
613
614   if (getLexer().isNot(AsmToken::Integer))
615     return TokError("invalid minor version");
616
617   Minor = getLexer().getTok().getIntVal();
618   Lex();
619
620   return false;
621 }
622
623 bool AMDGPUAsmParser::ParseDirectiveHSACodeObjectVersion() {
624
625   uint32_t Major;
626   uint32_t Minor;
627
628   if (ParseDirectiveMajorMinor(Major, Minor))
629     return true;
630
631   getTargetStreamer().EmitDirectiveHSACodeObjectVersion(Major, Minor);
632   return false;
633 }
634
635 bool AMDGPUAsmParser::ParseDirectiveHSACodeObjectISA() {
636
637   uint32_t Major;
638   uint32_t Minor;
639   uint32_t Stepping;
640   StringRef VendorName;
641   StringRef ArchName;
642
643   // If this directive has no arguments, then use the ISA version for the
644   // targeted GPU.
645   if (getLexer().is(AsmToken::EndOfStatement)) {
646     AMDGPU::IsaVersion Isa = AMDGPU::getIsaVersion(STI.getFeatureBits());
647     getTargetStreamer().EmitDirectiveHSACodeObjectISA(Isa.Major, Isa.Minor,
648                                                       Isa.Stepping,
649                                                       "AMD", "AMDGPU");
650     return false;
651   }
652
653
654   if (ParseDirectiveMajorMinor(Major, Minor))
655     return true;
656
657   if (getLexer().isNot(AsmToken::Comma))
658     return TokError("stepping version number required, comma expected");
659   Lex();
660
661   if (getLexer().isNot(AsmToken::Integer))
662     return TokError("invalid stepping version");
663
664   Stepping = getLexer().getTok().getIntVal();
665   Lex();
666
667   if (getLexer().isNot(AsmToken::Comma))
668     return TokError("vendor name required, comma expected");
669   Lex();
670
671   if (getLexer().isNot(AsmToken::String))
672     return TokError("invalid vendor name");
673
674   VendorName = getLexer().getTok().getStringContents();
675   Lex();
676
677   if (getLexer().isNot(AsmToken::Comma))
678     return TokError("arch name required, comma expected");
679   Lex();
680
681   if (getLexer().isNot(AsmToken::String))
682     return TokError("invalid arch name");
683
684   ArchName = getLexer().getTok().getStringContents();
685   Lex();
686
687   getTargetStreamer().EmitDirectiveHSACodeObjectISA(Major, Minor, Stepping,
688                                                     VendorName, ArchName);
689   return false;
690 }
691
692 bool AMDGPUAsmParser::ParseAMDKernelCodeTValue(StringRef ID,
693                                                amd_kernel_code_t &Header) {
694
695   if (getLexer().isNot(AsmToken::Equal))
696     return TokError("expected '='");
697   Lex();
698
699   if (getLexer().isNot(AsmToken::Integer))
700     return TokError("amd_kernel_code_t values must be integers");
701
702   uint64_t Value = getLexer().getTok().getIntVal();
703   Lex();
704
705   if (ID == "kernel_code_version_major")
706     Header.amd_kernel_code_version_major = Value;
707   else if (ID == "kernel_code_version_minor")
708     Header.amd_kernel_code_version_minor = Value;
709   else if (ID == "machine_kind")
710     Header.amd_machine_kind = Value;
711   else if (ID == "machine_version_major")
712     Header.amd_machine_version_major = Value;
713   else if (ID == "machine_version_minor")
714     Header.amd_machine_version_minor = Value;
715   else if (ID == "machine_version_stepping")
716     Header.amd_machine_version_stepping = Value;
717   else if (ID == "kernel_code_entry_byte_offset")
718     Header.kernel_code_entry_byte_offset = Value;
719   else if (ID == "kernel_code_prefetch_byte_size")
720     Header.kernel_code_prefetch_byte_size = Value;
721   else if (ID == "max_scratch_backing_memory_byte_size")
722     Header.max_scratch_backing_memory_byte_size = Value;
723   else if (ID == "compute_pgm_rsrc1_vgprs")
724     Header.compute_pgm_resource_registers |= S_00B848_VGPRS(Value);
725   else if (ID == "compute_pgm_rsrc1_sgprs")
726     Header.compute_pgm_resource_registers |= S_00B848_SGPRS(Value);
727   else if (ID == "compute_pgm_rsrc1_priority")
728     Header.compute_pgm_resource_registers |= S_00B848_PRIORITY(Value);
729   else if (ID == "compute_pgm_rsrc1_float_mode")
730     Header.compute_pgm_resource_registers |= S_00B848_FLOAT_MODE(Value);
731   else if (ID == "compute_pgm_rsrc1_priv")
732     Header.compute_pgm_resource_registers |= S_00B848_PRIV(Value);
733   else if (ID == "compute_pgm_rsrc1_dx10_clamp")
734     Header.compute_pgm_resource_registers |= S_00B848_DX10_CLAMP(Value);
735   else if (ID == "compute_pgm_rsrc1_debug_mode")
736     Header.compute_pgm_resource_registers |= S_00B848_DEBUG_MODE(Value);
737   else if (ID == "compute_pgm_rsrc1_ieee_mode")
738     Header.compute_pgm_resource_registers |= S_00B848_IEEE_MODE(Value);
739   else if (ID == "compute_pgm_rsrc2_scratch_en")
740     Header.compute_pgm_resource_registers |= (S_00B84C_SCRATCH_EN(Value) << 32);
741   else if (ID == "compute_pgm_rsrc2_user_sgpr")
742     Header.compute_pgm_resource_registers |= (S_00B84C_USER_SGPR(Value) << 32);
743   else if (ID == "compute_pgm_rsrc2_tgid_x_en")
744     Header.compute_pgm_resource_registers |= (S_00B84C_TGID_X_EN(Value) << 32);
745   else if (ID == "compute_pgm_rsrc2_tgid_y_en")
746     Header.compute_pgm_resource_registers |= (S_00B84C_TGID_Y_EN(Value) << 32);
747   else if (ID == "compute_pgm_rsrc2_tgid_z_en")
748     Header.compute_pgm_resource_registers |= (S_00B84C_TGID_Z_EN(Value) << 32);
749   else if (ID == "compute_pgm_rsrc2_tg_size_en")
750     Header.compute_pgm_resource_registers |= (S_00B84C_TG_SIZE_EN(Value) << 32);
751   else if (ID == "compute_pgm_rsrc2_tidig_comp_cnt")
752     Header.compute_pgm_resource_registers |=
753         (S_00B84C_TIDIG_COMP_CNT(Value) << 32);
754   else if (ID == "compute_pgm_rsrc2_excp_en_msb")
755     Header.compute_pgm_resource_registers |=
756         (S_00B84C_EXCP_EN_MSB(Value) << 32);
757   else if (ID == "compute_pgm_rsrc2_lds_size")
758     Header.compute_pgm_resource_registers |= (S_00B84C_LDS_SIZE(Value) << 32);
759   else if (ID == "compute_pgm_rsrc2_excp_en")
760     Header.compute_pgm_resource_registers |= (S_00B84C_EXCP_EN(Value) << 32);
761   else if (ID == "compute_pgm_resource_registers")
762     Header.compute_pgm_resource_registers = Value;
763   else if (ID == "enable_sgpr_private_segment_buffer")
764     Header.code_properties |=
765         (Value << AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER_SHIFT);
766   else if (ID == "enable_sgpr_dispatch_ptr")
767     Header.code_properties |=
768         (Value << AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR_SHIFT);
769   else if (ID == "enable_sgpr_queue_ptr")
770     Header.code_properties |=
771         (Value << AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR_SHIFT);
772   else if (ID == "enable_sgpr_kernarg_segment_ptr")
773     Header.code_properties |=
774         (Value << AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR_SHIFT);
775   else if (ID == "enable_sgpr_dispatch_id")
776     Header.code_properties |=
777         (Value << AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID_SHIFT);
778   else if (ID == "enable_sgpr_flat_scratch_init")
779     Header.code_properties |=
780         (Value << AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT_SHIFT);
781   else if (ID == "enable_sgpr_private_segment_size")
782     Header.code_properties |=
783         (Value << AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_SIZE_SHIFT);
784   else if (ID == "enable_sgpr_grid_workgroup_count_x")
785     Header.code_properties |=
786         (Value << AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_X_SHIFT);
787   else if (ID == "enable_sgpr_grid_workgroup_count_y")
788     Header.code_properties |=
789         (Value << AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Y_SHIFT);
790   else if (ID == "enable_sgpr_grid_workgroup_count_z")
791     Header.code_properties |=
792         (Value << AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Z_SHIFT);
793   else if (ID == "enable_ordered_append_gds")
794     Header.code_properties |=
795         (Value << AMD_CODE_PROPERTY_ENABLE_ORDERED_APPEND_GDS_SHIFT);
796   else if (ID == "private_element_size")
797     Header.code_properties |=
798         (Value << AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE_SHIFT);
799   else if (ID == "is_ptr64")
800     Header.code_properties |=
801         (Value << AMD_CODE_PROPERTY_IS_PTR64_SHIFT);
802   else if (ID == "is_dynamic_callstack")
803     Header.code_properties |=
804         (Value << AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK_SHIFT);
805   else if (ID == "is_debug_enabled")
806     Header.code_properties |=
807         (Value << AMD_CODE_PROPERTY_IS_DEBUG_SUPPORTED_SHIFT);
808   else if (ID == "is_xnack_enabled")
809     Header.code_properties |=
810         (Value << AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED_SHIFT);
811   else if (ID == "workitem_private_segment_byte_size")
812     Header.workitem_private_segment_byte_size = Value;
813   else if (ID == "workgroup_group_segment_byte_size")
814     Header.workgroup_group_segment_byte_size = Value;
815   else if (ID == "gds_segment_byte_size")
816     Header.gds_segment_byte_size = Value;
817   else if (ID == "kernarg_segment_byte_size")
818     Header.kernarg_segment_byte_size = Value;
819   else if (ID == "workgroup_fbarrier_count")
820     Header.workgroup_fbarrier_count = Value;
821   else if (ID == "wavefront_sgpr_count")
822     Header.wavefront_sgpr_count = Value;
823   else if (ID == "workitem_vgpr_count")
824     Header.workitem_vgpr_count = Value;
825   else if (ID == "reserved_vgpr_first")
826     Header.reserved_vgpr_first = Value;
827   else if (ID == "reserved_vgpr_count")
828     Header.reserved_vgpr_count = Value;
829   else if (ID == "reserved_sgpr_first")
830     Header.reserved_sgpr_first = Value;
831   else if (ID == "reserved_sgpr_count")
832     Header.reserved_sgpr_count = Value;
833   else if (ID == "debug_wavefront_private_segment_offset_sgpr")
834     Header.debug_wavefront_private_segment_offset_sgpr = Value;
835   else if (ID == "debug_private_segment_buffer_sgpr")
836     Header.debug_private_segment_buffer_sgpr = Value;
837   else if (ID == "kernarg_segment_alignment")
838     Header.kernarg_segment_alignment = Value;
839   else if (ID == "group_segment_alignment")
840     Header.group_segment_alignment = Value;
841   else if (ID == "private_segment_alignment")
842     Header.private_segment_alignment = Value;
843   else if (ID == "wavefront_size")
844     Header.wavefront_size = Value;
845   else if (ID == "call_convention")
846     Header.call_convention = Value;
847   else if (ID == "runtime_loader_kernel_symbol")
848     Header.runtime_loader_kernel_symbol = Value;
849   else
850     return TokError("amd_kernel_code_t value not recognized.");
851
852   return false;
853 }
854
855 bool AMDGPUAsmParser::ParseDirectiveAMDKernelCodeT() {
856
857   amd_kernel_code_t Header;
858   AMDGPU::initDefaultAMDKernelCodeT(Header, STI.getFeatureBits());
859
860   while (true) {
861
862     if (getLexer().isNot(AsmToken::EndOfStatement))
863       return TokError("amd_kernel_code_t values must begin on a new line");
864
865     // Lex EndOfStatement.  This is in a while loop, because lexing a comment
866     // will set the current token to EndOfStatement.
867     while(getLexer().is(AsmToken::EndOfStatement))
868       Lex();
869
870     if (getLexer().isNot(AsmToken::Identifier))
871       return TokError("expected value identifier or .end_amd_kernel_code_t");
872
873     StringRef ID = getLexer().getTok().getIdentifier();
874     Lex();
875
876     if (ID == ".end_amd_kernel_code_t")
877       break;
878
879     if (ParseAMDKernelCodeTValue(ID, Header))
880       return true;
881   }
882
883   getTargetStreamer().EmitAMDKernelCodeT(Header);
884
885   return false;
886 }
887
888 bool AMDGPUAsmParser::ParseDirective(AsmToken DirectiveID) {
889   StringRef IDVal = DirectiveID.getString();
890
891   if (IDVal == ".hsa_code_object_version")
892     return ParseDirectiveHSACodeObjectVersion();
893
894   if (IDVal == ".hsa_code_object_isa")
895     return ParseDirectiveHSACodeObjectISA();
896
897   if (IDVal == ".amd_kernel_code_t")
898     return ParseDirectiveAMDKernelCodeT();
899
900   return true;
901 }
902
903 static bool operandsHaveModifiers(const OperandVector &Operands) {
904
905   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
906     const AMDGPUOperand &Op = ((AMDGPUOperand&)*Operands[i]);
907     if (Op.isRegKind() && Op.hasModifiers())
908       return true;
909     if (Op.isImm() && (Op.getImmTy() == AMDGPUOperand::ImmTyOMod ||
910                        Op.getImmTy() == AMDGPUOperand::ImmTyClamp))
911       return true;
912   }
913   return false;
914 }
915
916 AMDGPUAsmParser::OperandMatchResultTy
917 AMDGPUAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
918
919   // Try to parse with a custom parser
920   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
921
922   // If we successfully parsed the operand or if there as an error parsing,
923   // we are done.
924   //
925   // If we are parsing after we reach EndOfStatement then this means we
926   // are appending default values to the Operands list.  This is only done
927   // by custom parser, so we shouldn't continue on to the generic parsing.
928   if (ResTy == MatchOperand_Success || ResTy == MatchOperand_ParseFail ||
929       getLexer().is(AsmToken::EndOfStatement))
930     return ResTy;
931
932   bool Negate = false, Abs = false;
933   if (getLexer().getKind()== AsmToken::Minus) {
934     Parser.Lex();
935     Negate = true;
936   }
937
938   if (getLexer().getKind() == AsmToken::Pipe) {
939     Parser.Lex();
940     Abs = true;
941   }
942
943   switch(getLexer().getKind()) {
944     case AsmToken::Integer: {
945       SMLoc S = Parser.getTok().getLoc();
946       int64_t IntVal;
947       if (getParser().parseAbsoluteExpression(IntVal))
948         return MatchOperand_ParseFail;
949       APInt IntVal32(32, IntVal);
950       if (IntVal32.getSExtValue() != IntVal) {
951         Error(S, "invalid immediate: only 32-bit values are legal");
952         return MatchOperand_ParseFail;
953       }
954
955       IntVal = IntVal32.getSExtValue();
956       if (Negate)
957         IntVal *= -1;
958       Operands.push_back(AMDGPUOperand::CreateImm(IntVal, S));
959       return MatchOperand_Success;
960     }
961     case AsmToken::Real: {
962       // FIXME: We should emit an error if a double precisions floating-point
963       // value is used.  I'm not sure the best way to detect this.
964       SMLoc S = Parser.getTok().getLoc();
965       int64_t IntVal;
966       if (getParser().parseAbsoluteExpression(IntVal))
967         return MatchOperand_ParseFail;
968
969       APFloat F((float)BitsToDouble(IntVal));
970       if (Negate)
971         F.changeSign();
972       Operands.push_back(
973           AMDGPUOperand::CreateImm(F.bitcastToAPInt().getZExtValue(), S));
974       return MatchOperand_Success;
975     }
976     case AsmToken::Identifier: {
977       SMLoc S, E;
978       unsigned RegNo;
979       if (!ParseRegister(RegNo, S, E)) {
980
981         bool HasModifiers = operandsHaveModifiers(Operands);
982         unsigned Modifiers = 0;
983
984         if (Negate)
985           Modifiers |= 0x1;
986
987         if (Abs) {
988           if (getLexer().getKind() != AsmToken::Pipe)
989             return MatchOperand_ParseFail;
990           Parser.Lex();
991           Modifiers |= 0x2;
992         }
993
994         if (Modifiers && !HasModifiers) {
995           // We are adding a modifier to src1 or src2 and previous sources
996           // don't have modifiers, so we need to go back and empty modifers
997           // for each previous source.
998           for (unsigned PrevRegIdx = Operands.size() - 1; PrevRegIdx > 1;
999                --PrevRegIdx) {
1000
1001             AMDGPUOperand &RegOp = ((AMDGPUOperand&)*Operands[PrevRegIdx]);
1002             RegOp.setModifiers(0);
1003           }
1004         }
1005
1006
1007         Operands.push_back(AMDGPUOperand::CreateReg(
1008             RegNo, S, E, getContext().getRegisterInfo(),
1009             isForcedVOP3()));
1010
1011         if (HasModifiers || Modifiers) {
1012           AMDGPUOperand &RegOp = ((AMDGPUOperand&)*Operands[Operands.size() - 1]);
1013           RegOp.setModifiers(Modifiers);
1014
1015         }
1016      }  else {
1017       Operands.push_back(AMDGPUOperand::CreateToken(Parser.getTok().getString(),
1018                                                     S));
1019       Parser.Lex();
1020      }
1021      return MatchOperand_Success;
1022     }
1023     default:
1024       return MatchOperand_NoMatch;
1025   }
1026 }
1027
1028 bool AMDGPUAsmParser::ParseInstruction(ParseInstructionInfo &Info,
1029                                        StringRef Name,
1030                                        SMLoc NameLoc, OperandVector &Operands) {
1031
1032   // Clear any forced encodings from the previous instruction.
1033   setForcedEncodingSize(0);
1034
1035   if (Name.endswith("_e64"))
1036     setForcedEncodingSize(64);
1037   else if (Name.endswith("_e32"))
1038     setForcedEncodingSize(32);
1039
1040   // Add the instruction mnemonic
1041   Operands.push_back(AMDGPUOperand::CreateToken(Name, NameLoc));
1042
1043   while (!getLexer().is(AsmToken::EndOfStatement)) {
1044     AMDGPUAsmParser::OperandMatchResultTy Res = parseOperand(Operands, Name);
1045
1046     // Eat the comma or space if there is one.
1047     if (getLexer().is(AsmToken::Comma))
1048       Parser.Lex();
1049
1050     switch (Res) {
1051       case MatchOperand_Success: break;
1052       case MatchOperand_ParseFail: return Error(getLexer().getLoc(),
1053                                                 "failed parsing operand.");
1054       case MatchOperand_NoMatch: return Error(getLexer().getLoc(),
1055                                               "not a valid operand.");
1056     }
1057   }
1058
1059   // Once we reach end of statement, continue parsing so we can add default
1060   // values for optional arguments.
1061   AMDGPUAsmParser::OperandMatchResultTy Res;
1062   while ((Res = parseOperand(Operands, Name)) != MatchOperand_NoMatch) {
1063     if (Res != MatchOperand_Success)
1064       return Error(getLexer().getLoc(), "failed parsing operand.");
1065   }
1066   return false;
1067 }
1068
1069 //===----------------------------------------------------------------------===//
1070 // Utility functions
1071 //===----------------------------------------------------------------------===//
1072
1073 AMDGPUAsmParser::OperandMatchResultTy
1074 AMDGPUAsmParser::parseIntWithPrefix(const char *Prefix, int64_t &Int,
1075                                     int64_t Default) {
1076
1077   // We are at the end of the statement, and this is a default argument, so
1078   // use a default value.
1079   if (getLexer().is(AsmToken::EndOfStatement)) {
1080     Int = Default;
1081     return MatchOperand_Success;
1082   }
1083
1084   switch(getLexer().getKind()) {
1085     default: return MatchOperand_NoMatch;
1086     case AsmToken::Identifier: {
1087       StringRef OffsetName = Parser.getTok().getString();
1088       if (!OffsetName.equals(Prefix))
1089         return MatchOperand_NoMatch;
1090
1091       Parser.Lex();
1092       if (getLexer().isNot(AsmToken::Colon))
1093         return MatchOperand_ParseFail;
1094
1095       Parser.Lex();
1096       if (getLexer().isNot(AsmToken::Integer))
1097         return MatchOperand_ParseFail;
1098
1099       if (getParser().parseAbsoluteExpression(Int))
1100         return MatchOperand_ParseFail;
1101       break;
1102     }
1103   }
1104   return MatchOperand_Success;
1105 }
1106
1107 AMDGPUAsmParser::OperandMatchResultTy
1108 AMDGPUAsmParser::parseIntWithPrefix(const char *Prefix, OperandVector &Operands,
1109                                     enum AMDGPUOperand::ImmTy ImmTy) {
1110
1111   SMLoc S = Parser.getTok().getLoc();
1112   int64_t Offset = 0;
1113
1114   AMDGPUAsmParser::OperandMatchResultTy Res = parseIntWithPrefix(Prefix, Offset);
1115   if (Res != MatchOperand_Success)
1116     return Res;
1117
1118   Operands.push_back(AMDGPUOperand::CreateImm(Offset, S, ImmTy));
1119   return MatchOperand_Success;
1120 }
1121
1122 AMDGPUAsmParser::OperandMatchResultTy
1123 AMDGPUAsmParser::parseNamedBit(const char *Name, OperandVector &Operands,
1124                                enum AMDGPUOperand::ImmTy ImmTy) {
1125   int64_t Bit = 0;
1126   SMLoc S = Parser.getTok().getLoc();
1127
1128   // We are at the end of the statement, and this is a default argument, so
1129   // use a default value.
1130   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1131     switch(getLexer().getKind()) {
1132       case AsmToken::Identifier: {
1133         StringRef Tok = Parser.getTok().getString();
1134         if (Tok == Name) {
1135           Bit = 1;
1136           Parser.Lex();
1137         } else if (Tok.startswith("no") && Tok.endswith(Name)) {
1138           Bit = 0;
1139           Parser.Lex();
1140         } else {
1141           return MatchOperand_NoMatch;
1142         }
1143         break;
1144       }
1145       default:
1146         return MatchOperand_NoMatch;
1147     }
1148   }
1149
1150   Operands.push_back(AMDGPUOperand::CreateImm(Bit, S, ImmTy));
1151   return MatchOperand_Success;
1152 }
1153
1154 static bool operandsHasOptionalOp(const OperandVector &Operands,
1155                                   const OptionalOperand &OOp) {
1156   for (unsigned i = 0; i < Operands.size(); i++) {
1157     const AMDGPUOperand &ParsedOp = ((const AMDGPUOperand &)*Operands[i]);
1158     if ((ParsedOp.isImm() && ParsedOp.getImmTy() == OOp.Type) ||
1159         (ParsedOp.isToken() && ParsedOp.getToken() == OOp.Name))
1160       return true;
1161
1162   }
1163   return false;
1164 }
1165
1166 AMDGPUAsmParser::OperandMatchResultTy
1167 AMDGPUAsmParser::parseOptionalOps(const ArrayRef<OptionalOperand> &OptionalOps,
1168                                    OperandVector &Operands) {
1169   SMLoc S = Parser.getTok().getLoc();
1170   for (const OptionalOperand &Op : OptionalOps) {
1171     if (operandsHasOptionalOp(Operands, Op))
1172       continue;
1173     AMDGPUAsmParser::OperandMatchResultTy Res;
1174     int64_t Value;
1175     if (Op.IsBit) {
1176       Res = parseNamedBit(Op.Name, Operands, Op.Type);
1177       if (Res == MatchOperand_NoMatch)
1178         continue;
1179       return Res;
1180     }
1181
1182     Res = parseIntWithPrefix(Op.Name, Value, Op.Default);
1183
1184     if (Res == MatchOperand_NoMatch)
1185       continue;
1186
1187     if (Res != MatchOperand_Success)
1188       return Res;
1189
1190     if (Op.ConvertResult && !Op.ConvertResult(Value)) {
1191       return MatchOperand_ParseFail;
1192     }
1193
1194     Operands.push_back(AMDGPUOperand::CreateImm(Value, S, Op.Type));
1195     return MatchOperand_Success;
1196   }
1197   return MatchOperand_NoMatch;
1198 }
1199
1200 //===----------------------------------------------------------------------===//
1201 // ds
1202 //===----------------------------------------------------------------------===//
1203
1204 static const OptionalOperand DSOptionalOps [] = {
1205   {"offset",  AMDGPUOperand::ImmTyOffset, false, 0, nullptr},
1206   {"gds",     AMDGPUOperand::ImmTyGDS, true, 0, nullptr}
1207 };
1208
1209 static const OptionalOperand DSOptionalOpsOff01 [] = {
1210   {"offset0", AMDGPUOperand::ImmTyDSOffset0, false, 0, nullptr},
1211   {"offset1", AMDGPUOperand::ImmTyDSOffset1, false, 0, nullptr},
1212   {"gds",     AMDGPUOperand::ImmTyGDS, true, 0, nullptr}
1213 };
1214
1215 AMDGPUAsmParser::OperandMatchResultTy
1216 AMDGPUAsmParser::parseDSOptionalOps(OperandVector &Operands) {
1217   return parseOptionalOps(DSOptionalOps, Operands);
1218 }
1219 AMDGPUAsmParser::OperandMatchResultTy
1220 AMDGPUAsmParser::parseDSOff01OptionalOps(OperandVector &Operands) {
1221   return parseOptionalOps(DSOptionalOpsOff01, Operands);
1222 }
1223
1224 AMDGPUAsmParser::OperandMatchResultTy
1225 AMDGPUAsmParser::parseDSOffsetOptional(OperandVector &Operands) {
1226   SMLoc S = Parser.getTok().getLoc();
1227   AMDGPUAsmParser::OperandMatchResultTy Res =
1228     parseIntWithPrefix("offset", Operands, AMDGPUOperand::ImmTyOffset);
1229   if (Res == MatchOperand_NoMatch) {
1230     Operands.push_back(AMDGPUOperand::CreateImm(0, S,
1231                        AMDGPUOperand::ImmTyOffset));
1232     Res = MatchOperand_Success;
1233   }
1234   return Res;
1235 }
1236
1237 bool AMDGPUOperand::isDSOffset() const {
1238   return isImm() && isUInt<16>(getImm());
1239 }
1240
1241 bool AMDGPUOperand::isDSOffset01() const {
1242   return isImm() && isUInt<8>(getImm());
1243 }
1244
1245 void AMDGPUAsmParser::cvtDSOffset01(MCInst &Inst,
1246                                     const OperandVector &Operands) {
1247
1248   std::map<enum AMDGPUOperand::ImmTy, unsigned> OptionalIdx;
1249
1250   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1251     AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
1252
1253     // Add the register arguments
1254     if (Op.isReg()) {
1255       Op.addRegOperands(Inst, 1);
1256       continue;
1257     }
1258
1259     // Handle optional arguments
1260     OptionalIdx[Op.getImmTy()] = i;
1261   }
1262
1263   unsigned Offset0Idx = OptionalIdx[AMDGPUOperand::ImmTyDSOffset0];
1264   unsigned Offset1Idx = OptionalIdx[AMDGPUOperand::ImmTyDSOffset1];
1265   unsigned GDSIdx = OptionalIdx[AMDGPUOperand::ImmTyGDS];
1266
1267   ((AMDGPUOperand &)*Operands[Offset0Idx]).addImmOperands(Inst, 1); // offset0
1268   ((AMDGPUOperand &)*Operands[Offset1Idx]).addImmOperands(Inst, 1); // offset1
1269   ((AMDGPUOperand &)*Operands[GDSIdx]).addImmOperands(Inst, 1); // gds
1270   Inst.addOperand(MCOperand::createReg(AMDGPU::M0)); // m0
1271 }
1272
1273 void AMDGPUAsmParser::cvtDS(MCInst &Inst, const OperandVector &Operands) {
1274
1275   std::map<enum AMDGPUOperand::ImmTy, unsigned> OptionalIdx;
1276   bool GDSOnly = false;
1277
1278   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1279     AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
1280
1281     // Add the register arguments
1282     if (Op.isReg()) {
1283       Op.addRegOperands(Inst, 1);
1284       continue;
1285     }
1286
1287     if (Op.isToken() && Op.getToken() == "gds") {
1288       GDSOnly = true;
1289       continue;
1290     }
1291
1292     // Handle optional arguments
1293     OptionalIdx[Op.getImmTy()] = i;
1294   }
1295
1296   unsigned OffsetIdx = OptionalIdx[AMDGPUOperand::ImmTyOffset];
1297   ((AMDGPUOperand &)*Operands[OffsetIdx]).addImmOperands(Inst, 1); // offset
1298
1299   if (!GDSOnly) {
1300     unsigned GDSIdx = OptionalIdx[AMDGPUOperand::ImmTyGDS];
1301     ((AMDGPUOperand &)*Operands[GDSIdx]).addImmOperands(Inst, 1); // gds
1302   }
1303   Inst.addOperand(MCOperand::createReg(AMDGPU::M0)); // m0
1304 }
1305
1306
1307 //===----------------------------------------------------------------------===//
1308 // s_waitcnt
1309 //===----------------------------------------------------------------------===//
1310
1311 bool AMDGPUAsmParser::parseCnt(int64_t &IntVal) {
1312   StringRef CntName = Parser.getTok().getString();
1313   int64_t CntVal;
1314
1315   Parser.Lex();
1316   if (getLexer().isNot(AsmToken::LParen))
1317     return true;
1318
1319   Parser.Lex();
1320   if (getLexer().isNot(AsmToken::Integer))
1321     return true;
1322
1323   if (getParser().parseAbsoluteExpression(CntVal))
1324     return true;
1325
1326   if (getLexer().isNot(AsmToken::RParen))
1327     return true;
1328
1329   Parser.Lex();
1330   if (getLexer().is(AsmToken::Amp) || getLexer().is(AsmToken::Comma))
1331     Parser.Lex();
1332
1333   int CntShift;
1334   int CntMask;
1335
1336   if (CntName == "vmcnt") {
1337     CntMask = 0xf;
1338     CntShift = 0;
1339   } else if (CntName == "expcnt") {
1340     CntMask = 0x7;
1341     CntShift = 4;
1342   } else if (CntName == "lgkmcnt") {
1343     CntMask = 0x7;
1344     CntShift = 8;
1345   } else {
1346     return true;
1347   }
1348
1349   IntVal &= ~(CntMask << CntShift);
1350   IntVal |= (CntVal << CntShift);
1351   return false;
1352 }
1353
1354 AMDGPUAsmParser::OperandMatchResultTy
1355 AMDGPUAsmParser::parseSWaitCntOps(OperandVector &Operands) {
1356   // Disable all counters by default.
1357   // vmcnt   [3:0]
1358   // expcnt  [6:4]
1359   // lgkmcnt [10:8]
1360   int64_t CntVal = 0x77f;
1361   SMLoc S = Parser.getTok().getLoc();
1362
1363   switch(getLexer().getKind()) {
1364     default: return MatchOperand_ParseFail;
1365     case AsmToken::Integer:
1366       // The operand can be an integer value.
1367       if (getParser().parseAbsoluteExpression(CntVal))
1368         return MatchOperand_ParseFail;
1369       break;
1370
1371     case AsmToken::Identifier:
1372       do {
1373         if (parseCnt(CntVal))
1374           return MatchOperand_ParseFail;
1375       } while(getLexer().isNot(AsmToken::EndOfStatement));
1376       break;
1377   }
1378   Operands.push_back(AMDGPUOperand::CreateImm(CntVal, S));
1379   return MatchOperand_Success;
1380 }
1381
1382 bool AMDGPUOperand::isSWaitCnt() const {
1383   return isImm();
1384 }
1385
1386 //===----------------------------------------------------------------------===//
1387 // sopp branch targets
1388 //===----------------------------------------------------------------------===//
1389
1390 AMDGPUAsmParser::OperandMatchResultTy
1391 AMDGPUAsmParser::parseSOppBrTarget(OperandVector &Operands) {
1392   SMLoc S = Parser.getTok().getLoc();
1393
1394   switch (getLexer().getKind()) {
1395     default: return MatchOperand_ParseFail;
1396     case AsmToken::Integer: {
1397       int64_t Imm;
1398       if (getParser().parseAbsoluteExpression(Imm))
1399         return MatchOperand_ParseFail;
1400       Operands.push_back(AMDGPUOperand::CreateImm(Imm, S));
1401       return MatchOperand_Success;
1402     }
1403
1404     case AsmToken::Identifier:
1405       Operands.push_back(AMDGPUOperand::CreateExpr(
1406           MCSymbolRefExpr::create(getContext().getOrCreateSymbol(
1407                                   Parser.getTok().getString()), getContext()), S));
1408       Parser.Lex();
1409       return MatchOperand_Success;
1410   }
1411 }
1412
1413 //===----------------------------------------------------------------------===//
1414 // flat
1415 //===----------------------------------------------------------------------===//
1416
1417 static const OptionalOperand FlatOptionalOps [] = {
1418   {"glc",    AMDGPUOperand::ImmTyGLC, true, 0, nullptr},
1419   {"slc",    AMDGPUOperand::ImmTySLC, true, 0, nullptr},
1420   {"tfe",    AMDGPUOperand::ImmTyTFE, true, 0, nullptr}
1421 };
1422
1423 static const OptionalOperand FlatAtomicOptionalOps [] = {
1424   {"slc",    AMDGPUOperand::ImmTySLC, true, 0, nullptr},
1425   {"tfe",    AMDGPUOperand::ImmTyTFE, true, 0, nullptr}
1426 };
1427
1428 AMDGPUAsmParser::OperandMatchResultTy
1429 AMDGPUAsmParser::parseFlatOptionalOps(OperandVector &Operands) {
1430   return parseOptionalOps(FlatOptionalOps, Operands);
1431 }
1432
1433 AMDGPUAsmParser::OperandMatchResultTy
1434 AMDGPUAsmParser::parseFlatAtomicOptionalOps(OperandVector &Operands) {
1435   return parseOptionalOps(FlatAtomicOptionalOps, Operands);
1436 }
1437
1438 void AMDGPUAsmParser::cvtFlat(MCInst &Inst,
1439                                const OperandVector &Operands) {
1440   std::map<AMDGPUOperand::ImmTy, unsigned> OptionalIdx;
1441
1442   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1443     AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
1444
1445     // Add the register arguments
1446     if (Op.isReg()) {
1447       Op.addRegOperands(Inst, 1);
1448       continue;
1449     }
1450
1451     // Handle 'glc' token which is sometimes hard-coded into the
1452     // asm string.  There are no MCInst operands for these.
1453     if (Op.isToken())
1454       continue;
1455
1456     // Handle optional arguments
1457     OptionalIdx[Op.getImmTy()] = i;
1458
1459   }
1460
1461   // flat atomic instructions don't have a glc argument.
1462   if (OptionalIdx.count(AMDGPUOperand::ImmTyGLC)) {
1463     unsigned GLCIdx = OptionalIdx[AMDGPUOperand::ImmTyGLC];
1464     ((AMDGPUOperand &)*Operands[GLCIdx]).addImmOperands(Inst, 1);
1465   }
1466
1467   unsigned SLCIdx = OptionalIdx[AMDGPUOperand::ImmTySLC];
1468   unsigned TFEIdx = OptionalIdx[AMDGPUOperand::ImmTyTFE];
1469
1470   ((AMDGPUOperand &)*Operands[SLCIdx]).addImmOperands(Inst, 1);
1471   ((AMDGPUOperand &)*Operands[TFEIdx]).addImmOperands(Inst, 1);
1472 }
1473
1474 //===----------------------------------------------------------------------===//
1475 // mubuf
1476 //===----------------------------------------------------------------------===//
1477
1478 static const OptionalOperand MubufOptionalOps [] = {
1479   {"offset", AMDGPUOperand::ImmTyOffset, false, 0, nullptr},
1480   {"glc",    AMDGPUOperand::ImmTyGLC, true, 0, nullptr},
1481   {"slc",    AMDGPUOperand::ImmTySLC, true, 0, nullptr},
1482   {"tfe",    AMDGPUOperand::ImmTyTFE, true, 0, nullptr}
1483 };
1484
1485 AMDGPUAsmParser::OperandMatchResultTy
1486 AMDGPUAsmParser::parseMubufOptionalOps(OperandVector &Operands) {
1487   return parseOptionalOps(MubufOptionalOps, Operands);
1488 }
1489
1490 AMDGPUAsmParser::OperandMatchResultTy
1491 AMDGPUAsmParser::parseOffset(OperandVector &Operands) {
1492   return parseIntWithPrefix("offset", Operands);
1493 }
1494
1495 AMDGPUAsmParser::OperandMatchResultTy
1496 AMDGPUAsmParser::parseGLC(OperandVector &Operands) {
1497   return parseNamedBit("glc", Operands);
1498 }
1499
1500 AMDGPUAsmParser::OperandMatchResultTy
1501 AMDGPUAsmParser::parseSLC(OperandVector &Operands) {
1502   return parseNamedBit("slc", Operands);
1503 }
1504
1505 AMDGPUAsmParser::OperandMatchResultTy
1506 AMDGPUAsmParser::parseTFE(OperandVector &Operands) {
1507   return parseNamedBit("tfe", Operands);
1508 }
1509
1510 bool AMDGPUOperand::isMubufOffset() const {
1511   return isImm() && isUInt<12>(getImm());
1512 }
1513
1514 void AMDGPUAsmParser::cvtMubuf(MCInst &Inst,
1515                                const OperandVector &Operands) {
1516   std::map<enum AMDGPUOperand::ImmTy, unsigned> OptionalIdx;
1517
1518   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1519     AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
1520
1521     // Add the register arguments
1522     if (Op.isReg()) {
1523       Op.addRegOperands(Inst, 1);
1524       continue;
1525     }
1526
1527     // Handle the case where soffset is an immediate
1528     if (Op.isImm() && Op.getImmTy() == AMDGPUOperand::ImmTyNone) {
1529       Op.addImmOperands(Inst, 1);
1530       continue;
1531     }
1532
1533     // Handle tokens like 'offen' which are sometimes hard-coded into the
1534     // asm string.  There are no MCInst operands for these.
1535     if (Op.isToken()) {
1536       continue;
1537     }
1538     assert(Op.isImm());
1539
1540     // Handle optional arguments
1541     OptionalIdx[Op.getImmTy()] = i;
1542   }
1543
1544   assert(OptionalIdx.size() == 4);
1545
1546   unsigned OffsetIdx = OptionalIdx[AMDGPUOperand::ImmTyOffset];
1547   unsigned GLCIdx = OptionalIdx[AMDGPUOperand::ImmTyGLC];
1548   unsigned SLCIdx = OptionalIdx[AMDGPUOperand::ImmTySLC];
1549   unsigned TFEIdx = OptionalIdx[AMDGPUOperand::ImmTyTFE];
1550
1551   ((AMDGPUOperand &)*Operands[OffsetIdx]).addImmOperands(Inst, 1);
1552   ((AMDGPUOperand &)*Operands[GLCIdx]).addImmOperands(Inst, 1);
1553   ((AMDGPUOperand &)*Operands[SLCIdx]).addImmOperands(Inst, 1);
1554   ((AMDGPUOperand &)*Operands[TFEIdx]).addImmOperands(Inst, 1);
1555 }
1556
1557 //===----------------------------------------------------------------------===//
1558 // mimg
1559 //===----------------------------------------------------------------------===//
1560
1561 AMDGPUAsmParser::OperandMatchResultTy
1562 AMDGPUAsmParser::parseDMask(OperandVector &Operands) {
1563   return parseIntWithPrefix("dmask", Operands);
1564 }
1565
1566 AMDGPUAsmParser::OperandMatchResultTy
1567 AMDGPUAsmParser::parseUNorm(OperandVector &Operands) {
1568   return parseNamedBit("unorm", Operands);
1569 }
1570
1571 AMDGPUAsmParser::OperandMatchResultTy
1572 AMDGPUAsmParser::parseR128(OperandVector &Operands) {
1573   return parseNamedBit("r128", Operands);
1574 }
1575
1576 //===----------------------------------------------------------------------===//
1577 // vop3
1578 //===----------------------------------------------------------------------===//
1579
1580 static bool ConvertOmodMul(int64_t &Mul) {
1581   if (Mul != 1 && Mul != 2 && Mul != 4)
1582     return false;
1583
1584   Mul >>= 1;
1585   return true;
1586 }
1587
1588 static bool ConvertOmodDiv(int64_t &Div) {
1589   if (Div == 1) {
1590     Div = 0;
1591     return true;
1592   }
1593
1594   if (Div == 2) {
1595     Div = 3;
1596     return true;
1597   }
1598
1599   return false;
1600 }
1601
1602 static const OptionalOperand VOP3OptionalOps [] = {
1603   {"clamp", AMDGPUOperand::ImmTyClamp, true, 0, nullptr},
1604   {"mul",   AMDGPUOperand::ImmTyOMod, false, 1, ConvertOmodMul},
1605   {"div",   AMDGPUOperand::ImmTyOMod, false, 1, ConvertOmodDiv},
1606 };
1607
1608 static bool isVOP3(OperandVector &Operands) {
1609   if (operandsHaveModifiers(Operands))
1610     return true;
1611
1612   AMDGPUOperand &DstOp = ((AMDGPUOperand&)*Operands[1]);
1613
1614   if (DstOp.isReg() && DstOp.isRegClass(AMDGPU::SGPR_64RegClassID))
1615     return true;
1616
1617   if (Operands.size() >= 5)
1618     return true;
1619
1620   if (Operands.size() > 3) {
1621     AMDGPUOperand &Src1Op = ((AMDGPUOperand&)*Operands[3]);
1622     if (Src1Op.getReg() && (Src1Op.isRegClass(AMDGPU::SReg_32RegClassID) ||
1623                             Src1Op.isRegClass(AMDGPU::SReg_64RegClassID)))
1624       return true;
1625   }
1626   return false;
1627 }
1628
1629 AMDGPUAsmParser::OperandMatchResultTy
1630 AMDGPUAsmParser::parseVOP3OptionalOps(OperandVector &Operands) {
1631
1632   // The value returned by this function may change after parsing
1633   // an operand so store the original value here.
1634   bool HasModifiers = operandsHaveModifiers(Operands);
1635
1636   bool IsVOP3 = isVOP3(Operands);
1637   if (HasModifiers || IsVOP3 ||
1638       getLexer().isNot(AsmToken::EndOfStatement) ||
1639       getForcedEncodingSize() == 64) {
1640
1641     AMDGPUAsmParser::OperandMatchResultTy Res =
1642         parseOptionalOps(VOP3OptionalOps, Operands);
1643
1644     if (!HasModifiers && Res == MatchOperand_Success) {
1645       // We have added a modifier operation, so we need to make sure all
1646       // previous register operands have modifiers
1647       for (unsigned i = 2, e = Operands.size(); i != e; ++i) {
1648         AMDGPUOperand &Op = ((AMDGPUOperand&)*Operands[i]);
1649         if (Op.isReg())
1650           Op.setModifiers(0);
1651       }
1652     }
1653     return Res;
1654   }
1655   return MatchOperand_NoMatch;
1656 }
1657
1658 void AMDGPUAsmParser::cvtVOP3(MCInst &Inst, const OperandVector &Operands) {
1659   ((AMDGPUOperand &)*Operands[1]).addRegOperands(Inst, 1);
1660   unsigned i = 2;
1661
1662   std::map<enum AMDGPUOperand::ImmTy, unsigned> OptionalIdx;
1663
1664   if (operandsHaveModifiers(Operands)) {
1665     for (unsigned e = Operands.size(); i != e; ++i) {
1666       AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
1667
1668       if (Op.isRegWithInputMods()) {
1669         ((AMDGPUOperand &)*Operands[i]).addRegWithInputModsOperands(Inst, 2);
1670         continue;
1671       }
1672       OptionalIdx[Op.getImmTy()] = i;
1673     }
1674
1675     unsigned ClampIdx = OptionalIdx[AMDGPUOperand::ImmTyClamp];
1676     unsigned OModIdx = OptionalIdx[AMDGPUOperand::ImmTyOMod];
1677
1678     ((AMDGPUOperand &)*Operands[ClampIdx]).addImmOperands(Inst, 1);
1679     ((AMDGPUOperand &)*Operands[OModIdx]).addImmOperands(Inst, 1);
1680   } else {
1681     for (unsigned e = Operands.size(); i != e; ++i)
1682       ((AMDGPUOperand &)*Operands[i]).addRegOrImmOperands(Inst, 1);
1683   }
1684 }
1685
1686 /// Force static initialization.
1687 extern "C" void LLVMInitializeAMDGPUAsmParser() {
1688   RegisterMCAsmParser<AMDGPUAsmParser> A(TheAMDGPUTarget);
1689   RegisterMCAsmParser<AMDGPUAsmParser> B(TheGCNTarget);
1690 }
1691
1692 #define GET_REGISTER_MATCHER
1693 #define GET_MATCHER_IMPLEMENTATION
1694 #include "AMDGPUGenAsmMatcher.inc"
1695