Make Sparc assembler accept parenthesized constant expressions.
[oota-llvm.git] / lib / Target / Sparc / AsmParser / SparcAsmParser.cpp
1 //===-- SparcAsmParser.cpp - Parse Sparc assembly to MCInst instructions --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "MCTargetDesc/SparcMCTargetDesc.h"
11 #include "MCTargetDesc/SparcMCExpr.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCObjectFileInfo.h"
16 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
17 #include "llvm/MC/MCStreamer.h"
18 #include "llvm/MC/MCSubtargetInfo.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/MC/MCTargetAsmParser.h"
21 #include "llvm/Support/TargetRegistry.h"
22
23 using namespace llvm;
24
25 // The generated AsmMatcher SparcGenAsmMatcher uses "Sparc" as the target
26 // namespace. But SPARC backend uses "SP" as its namespace.
27 namespace llvm {
28   namespace Sparc {
29     using namespace SP;
30   }
31 }
32
33 namespace {
34 class SparcOperand;
35 class SparcAsmParser : public MCTargetAsmParser {
36
37   MCSubtargetInfo &STI;
38   MCAsmParser &Parser;
39
40   /// @name Auto-generated Match Functions
41   /// {
42
43 #define GET_ASSEMBLER_HEADER
44 #include "SparcGenAsmMatcher.inc"
45
46   /// }
47
48   // public interface of the MCTargetAsmParser.
49   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
50                                OperandVector &Operands, MCStreamer &Out,
51                                uint64_t &ErrorInfo,
52                                bool MatchingInlineAsm) override;
53   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
54   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
55                         SMLoc NameLoc, OperandVector &Operands) override;
56   bool ParseDirective(AsmToken DirectiveID) override;
57
58   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
59                                       unsigned Kind) override;
60
61   // Custom parse functions for Sparc specific operands.
62   OperandMatchResultTy parseMEMOperand(OperandVector &Operands);
63
64   OperandMatchResultTy parseOperand(OperandVector &Operands, StringRef Name);
65
66   OperandMatchResultTy
67   parseSparcAsmOperand(std::unique_ptr<SparcOperand> &Operand,
68                        bool isCall = false);
69
70   OperandMatchResultTy parseBranchModifiers(OperandVector &Operands);
71
72   // returns true if Tok is matched to a register and returns register in RegNo.
73   bool matchRegisterName(const AsmToken &Tok, unsigned &RegNo,
74                          unsigned &RegKind);
75
76   bool matchSparcAsmModifiers(const MCExpr *&EVal, SMLoc &EndLoc);
77   bool parseDirectiveWord(unsigned Size, SMLoc L);
78
79   bool is64Bit() const { return STI.getTargetTriple().startswith("sparcv9"); }
80 public:
81   SparcAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
82                 const MCInstrInfo &MII,
83                 const MCTargetOptions &Options)
84       : MCTargetAsmParser(), STI(sti), Parser(parser) {
85     // Initialize the set of available features.
86     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
87   }
88
89 };
90
91   static unsigned IntRegs[32] = {
92     Sparc::G0, Sparc::G1, Sparc::G2, Sparc::G3,
93     Sparc::G4, Sparc::G5, Sparc::G6, Sparc::G7,
94     Sparc::O0, Sparc::O1, Sparc::O2, Sparc::O3,
95     Sparc::O4, Sparc::O5, Sparc::O6, Sparc::O7,
96     Sparc::L0, Sparc::L1, Sparc::L2, Sparc::L3,
97     Sparc::L4, Sparc::L5, Sparc::L6, Sparc::L7,
98     Sparc::I0, Sparc::I1, Sparc::I2, Sparc::I3,
99     Sparc::I4, Sparc::I5, Sparc::I6, Sparc::I7 };
100
101   static unsigned FloatRegs[32] = {
102     Sparc::F0,  Sparc::F1,  Sparc::F2,  Sparc::F3,
103     Sparc::F4,  Sparc::F5,  Sparc::F6,  Sparc::F7,
104     Sparc::F8,  Sparc::F9,  Sparc::F10, Sparc::F11,
105     Sparc::F12, Sparc::F13, Sparc::F14, Sparc::F15,
106     Sparc::F16, Sparc::F17, Sparc::F18, Sparc::F19,
107     Sparc::F20, Sparc::F21, Sparc::F22, Sparc::F23,
108     Sparc::F24, Sparc::F25, Sparc::F26, Sparc::F27,
109     Sparc::F28, Sparc::F29, Sparc::F30, Sparc::F31 };
110
111   static unsigned DoubleRegs[32] = {
112     Sparc::D0,  Sparc::D1,  Sparc::D2,  Sparc::D3,
113     Sparc::D4,  Sparc::D5,  Sparc::D6,  Sparc::D7,
114     Sparc::D8,  Sparc::D7,  Sparc::D8,  Sparc::D9,
115     Sparc::D12, Sparc::D13, Sparc::D14, Sparc::D15,
116     Sparc::D16, Sparc::D17, Sparc::D18, Sparc::D19,
117     Sparc::D20, Sparc::D21, Sparc::D22, Sparc::D23,
118     Sparc::D24, Sparc::D25, Sparc::D26, Sparc::D27,
119     Sparc::D28, Sparc::D29, Sparc::D30, Sparc::D31 };
120
121   static unsigned QuadFPRegs[32] = {
122     Sparc::Q0,  Sparc::Q1,  Sparc::Q2,  Sparc::Q3,
123     Sparc::Q4,  Sparc::Q5,  Sparc::Q6,  Sparc::Q7,
124     Sparc::Q8,  Sparc::Q9,  Sparc::Q10, Sparc::Q11,
125     Sparc::Q12, Sparc::Q13, Sparc::Q14, Sparc::Q15 };
126
127
128 /// SparcOperand - Instances of this class represent a parsed Sparc machine
129 /// instruction.
130 class SparcOperand : public MCParsedAsmOperand {
131 public:
132   enum RegisterKind {
133     rk_None,
134     rk_IntReg,
135     rk_FloatReg,
136     rk_DoubleReg,
137     rk_QuadReg,
138     rk_CCReg,
139     rk_Y
140   };
141 private:
142   enum KindTy {
143     k_Token,
144     k_Register,
145     k_Immediate,
146     k_MemoryReg,
147     k_MemoryImm
148   } Kind;
149
150   SMLoc StartLoc, EndLoc;
151
152   struct Token {
153     const char *Data;
154     unsigned Length;
155   };
156
157   struct RegOp {
158     unsigned RegNum;
159     RegisterKind Kind;
160   };
161
162   struct ImmOp {
163     const MCExpr *Val;
164   };
165
166   struct MemOp {
167     unsigned Base;
168     unsigned OffsetReg;
169     const MCExpr *Off;
170   };
171
172   union {
173     struct Token Tok;
174     struct RegOp Reg;
175     struct ImmOp Imm;
176     struct MemOp Mem;
177   };
178 public:
179   SparcOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
180
181   bool isToken() const override { return Kind == k_Token; }
182   bool isReg() const override { return Kind == k_Register; }
183   bool isImm() const override { return Kind == k_Immediate; }
184   bool isMem() const override { return isMEMrr() || isMEMri(); }
185   bool isMEMrr() const { return Kind == k_MemoryReg; }
186   bool isMEMri() const { return Kind == k_MemoryImm; }
187
188   bool isFloatReg() const {
189     return (Kind == k_Register && Reg.Kind == rk_FloatReg);
190   }
191
192   bool isFloatOrDoubleReg() const {
193     return (Kind == k_Register && (Reg.Kind == rk_FloatReg
194                                    || Reg.Kind == rk_DoubleReg));
195   }
196
197
198   StringRef getToken() const {
199     assert(Kind == k_Token && "Invalid access!");
200     return StringRef(Tok.Data, Tok.Length);
201   }
202
203   unsigned getReg() const override {
204     assert((Kind == k_Register) && "Invalid access!");
205     return Reg.RegNum;
206   }
207
208   const MCExpr *getImm() const {
209     assert((Kind == k_Immediate) && "Invalid access!");
210     return Imm.Val;
211   }
212
213   unsigned getMemBase() const {
214     assert((Kind == k_MemoryReg || Kind == k_MemoryImm) && "Invalid access!");
215     return Mem.Base;
216   }
217
218   unsigned getMemOffsetReg() const {
219     assert((Kind == k_MemoryReg) && "Invalid access!");
220     return Mem.OffsetReg;
221   }
222
223   const MCExpr *getMemOff() const {
224     assert((Kind == k_MemoryImm) && "Invalid access!");
225     return Mem.Off;
226   }
227
228   /// getStartLoc - Get the location of the first token of this operand.
229   SMLoc getStartLoc() const override {
230     return StartLoc;
231   }
232   /// getEndLoc - Get the location of the last token of this operand.
233   SMLoc getEndLoc() const override {
234     return EndLoc;
235   }
236
237   void print(raw_ostream &OS) const override {
238     switch (Kind) {
239     case k_Token:     OS << "Token: " << getToken() << "\n"; break;
240     case k_Register:  OS << "Reg: #" << getReg() << "\n"; break;
241     case k_Immediate: OS << "Imm: " << getImm() << "\n"; break;
242     case k_MemoryReg: OS << "Mem: " << getMemBase() << "+"
243                          << getMemOffsetReg() << "\n"; break;
244     case k_MemoryImm: assert(getMemOff() != nullptr);
245       OS << "Mem: " << getMemBase()
246          << "+" << *getMemOff()
247          << "\n"; break;
248     }
249   }
250
251   void addRegOperands(MCInst &Inst, unsigned N) const {
252     assert(N == 1 && "Invalid number of operands!");
253     Inst.addOperand(MCOperand::CreateReg(getReg()));
254   }
255
256   void addImmOperands(MCInst &Inst, unsigned N) const {
257     assert(N == 1 && "Invalid number of operands!");
258     const MCExpr *Expr = getImm();
259     addExpr(Inst, Expr);
260   }
261
262   void addExpr(MCInst &Inst, const MCExpr *Expr) const{
263     // Add as immediate when possible.  Null MCExpr = 0.
264     if (!Expr)
265       Inst.addOperand(MCOperand::CreateImm(0));
266     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
267       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
268     else
269       Inst.addOperand(MCOperand::CreateExpr(Expr));
270   }
271
272   void addMEMrrOperands(MCInst &Inst, unsigned N) const {
273     assert(N == 2 && "Invalid number of operands!");
274
275     Inst.addOperand(MCOperand::CreateReg(getMemBase()));
276
277     assert(getMemOffsetReg() != 0 && "Invalid offset");
278     Inst.addOperand(MCOperand::CreateReg(getMemOffsetReg()));
279   }
280
281   void addMEMriOperands(MCInst &Inst, unsigned N) const {
282     assert(N == 2 && "Invalid number of operands!");
283
284     Inst.addOperand(MCOperand::CreateReg(getMemBase()));
285
286     const MCExpr *Expr = getMemOff();
287     addExpr(Inst, Expr);
288   }
289
290   static std::unique_ptr<SparcOperand> CreateToken(StringRef Str, SMLoc S) {
291     auto Op = make_unique<SparcOperand>(k_Token);
292     Op->Tok.Data = Str.data();
293     Op->Tok.Length = Str.size();
294     Op->StartLoc = S;
295     Op->EndLoc = S;
296     return Op;
297   }
298
299   static std::unique_ptr<SparcOperand> CreateReg(unsigned RegNum, unsigned Kind,
300                                                  SMLoc S, SMLoc E) {
301     auto Op = make_unique<SparcOperand>(k_Register);
302     Op->Reg.RegNum = RegNum;
303     Op->Reg.Kind   = (SparcOperand::RegisterKind)Kind;
304     Op->StartLoc = S;
305     Op->EndLoc = E;
306     return Op;
307   }
308
309   static std::unique_ptr<SparcOperand> CreateImm(const MCExpr *Val, SMLoc S,
310                                                  SMLoc E) {
311     auto Op = make_unique<SparcOperand>(k_Immediate);
312     Op->Imm.Val = Val;
313     Op->StartLoc = S;
314     Op->EndLoc = E;
315     return Op;
316   }
317
318   static bool MorphToDoubleReg(SparcOperand &Op) {
319     unsigned Reg = Op.getReg();
320     assert(Op.Reg.Kind == rk_FloatReg);
321     unsigned regIdx = Reg - Sparc::F0;
322     if (regIdx % 2 || regIdx > 31)
323       return false;
324     Op.Reg.RegNum = DoubleRegs[regIdx / 2];
325     Op.Reg.Kind = rk_DoubleReg;
326     return true;
327   }
328
329   static bool MorphToQuadReg(SparcOperand &Op) {
330     unsigned Reg = Op.getReg();
331     unsigned regIdx = 0;
332     switch (Op.Reg.Kind) {
333     default: llvm_unreachable("Unexpected register kind!");
334     case rk_FloatReg:
335       regIdx = Reg - Sparc::F0;
336       if (regIdx % 4 || regIdx > 31)
337         return false;
338       Reg = QuadFPRegs[regIdx / 4];
339       break;
340     case rk_DoubleReg:
341       regIdx =  Reg - Sparc::D0;
342       if (regIdx % 2 || regIdx > 31)
343         return false;
344       Reg = QuadFPRegs[regIdx / 2];
345       break;
346     }
347     Op.Reg.RegNum = Reg;
348     Op.Reg.Kind = rk_QuadReg;
349     return true;
350   }
351
352   static std::unique_ptr<SparcOperand>
353   MorphToMEMrr(unsigned Base, std::unique_ptr<SparcOperand> Op) {
354     unsigned offsetReg = Op->getReg();
355     Op->Kind = k_MemoryReg;
356     Op->Mem.Base = Base;
357     Op->Mem.OffsetReg = offsetReg;
358     Op->Mem.Off = nullptr;
359     return Op;
360   }
361
362   static std::unique_ptr<SparcOperand>
363   CreateMEMr(unsigned Base, SMLoc S, SMLoc E) {
364     auto Op = make_unique<SparcOperand>(k_MemoryReg);
365     Op->Mem.Base = Base;
366     Op->Mem.OffsetReg = Sparc::G0;  // always 0
367     Op->Mem.Off = nullptr;
368     Op->StartLoc = S;
369     Op->EndLoc = E;
370     return Op;
371   }
372
373   static std::unique_ptr<SparcOperand>
374   MorphToMEMri(unsigned Base, std::unique_ptr<SparcOperand> Op) {
375     const MCExpr *Imm  = Op->getImm();
376     Op->Kind = k_MemoryImm;
377     Op->Mem.Base = Base;
378     Op->Mem.OffsetReg = 0;
379     Op->Mem.Off = Imm;
380     return Op;
381   }
382 };
383
384 } // end namespace
385
386 bool SparcAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
387                                              OperandVector &Operands,
388                                              MCStreamer &Out,
389                                              uint64_t &ErrorInfo,
390                                              bool MatchingInlineAsm) {
391   MCInst Inst;
392   SmallVector<MCInst, 8> Instructions;
393   unsigned MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
394                                               MatchingInlineAsm);
395   switch (MatchResult) {
396   case Match_Success: {
397     Inst.setLoc(IDLoc);
398     Out.EmitInstruction(Inst, STI);
399     return false;
400   }
401
402   case Match_MissingFeature:
403     return Error(IDLoc,
404                  "instruction requires a CPU feature not currently enabled");
405
406   case Match_InvalidOperand: {
407     SMLoc ErrorLoc = IDLoc;
408     if (ErrorInfo != ~0ULL) {
409       if (ErrorInfo >= Operands.size())
410         return Error(IDLoc, "too few operands for instruction");
411
412       ErrorLoc = ((SparcOperand &)*Operands[ErrorInfo]).getStartLoc();
413       if (ErrorLoc == SMLoc())
414         ErrorLoc = IDLoc;
415     }
416
417     return Error(ErrorLoc, "invalid operand for instruction");
418   }
419   case Match_MnemonicFail:
420     return Error(IDLoc, "invalid instruction mnemonic");
421   }
422   llvm_unreachable("Implement any new match types added!");
423 }
424
425 bool SparcAsmParser::
426 ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc)
427 {
428   const AsmToken &Tok = Parser.getTok();
429   StartLoc = Tok.getLoc();
430   EndLoc = Tok.getEndLoc();
431   RegNo = 0;
432   if (getLexer().getKind() != AsmToken::Percent)
433     return false;
434   Parser.Lex();
435   unsigned regKind = SparcOperand::rk_None;
436   if (matchRegisterName(Tok, RegNo, regKind)) {
437     Parser.Lex();
438     return false;
439   }
440
441   return Error(StartLoc, "invalid register name");
442 }
443
444 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
445                                  unsigned VariantID);
446
447 bool SparcAsmParser::ParseInstruction(ParseInstructionInfo &Info,
448                                       StringRef Name, SMLoc NameLoc,
449                                       OperandVector &Operands) {
450
451   // First operand in MCInst is instruction mnemonic.
452   Operands.push_back(SparcOperand::CreateToken(Name, NameLoc));
453
454   // apply mnemonic aliases, if any, so that we can parse operands correctly.
455   applyMnemonicAliases(Name, getAvailableFeatures(), 0);
456
457   if (getLexer().isNot(AsmToken::EndOfStatement)) {
458     // Read the first operand.
459     if (getLexer().is(AsmToken::Comma)) {
460       if (parseBranchModifiers(Operands) != MatchOperand_Success) {
461         SMLoc Loc = getLexer().getLoc();
462         Parser.eatToEndOfStatement();
463         return Error(Loc, "unexpected token");
464       }
465     }
466     if (parseOperand(Operands, Name) != MatchOperand_Success) {
467       SMLoc Loc = getLexer().getLoc();
468       Parser.eatToEndOfStatement();
469       return Error(Loc, "unexpected token");
470     }
471
472     while (getLexer().is(AsmToken::Comma)) {
473       Parser.Lex(); // Eat the comma.
474       // Parse and remember the operand.
475       if (parseOperand(Operands, Name) != MatchOperand_Success) {
476         SMLoc Loc = getLexer().getLoc();
477         Parser.eatToEndOfStatement();
478         return Error(Loc, "unexpected token");
479       }
480     }
481   }
482   if (getLexer().isNot(AsmToken::EndOfStatement)) {
483     SMLoc Loc = getLexer().getLoc();
484     Parser.eatToEndOfStatement();
485     return Error(Loc, "unexpected token");
486   }
487   Parser.Lex(); // Consume the EndOfStatement.
488   return false;
489 }
490
491 bool SparcAsmParser::
492 ParseDirective(AsmToken DirectiveID)
493 {
494   StringRef IDVal = DirectiveID.getString();
495
496   if (IDVal == ".byte")
497     return parseDirectiveWord(1, DirectiveID.getLoc());
498
499   if (IDVal == ".half")
500     return parseDirectiveWord(2, DirectiveID.getLoc());
501
502   if (IDVal == ".word")
503     return parseDirectiveWord(4, DirectiveID.getLoc());
504
505   if (IDVal == ".nword")
506     return parseDirectiveWord(is64Bit() ? 8 : 4, DirectiveID.getLoc());
507
508   if (is64Bit() && IDVal == ".xword")
509     return parseDirectiveWord(8, DirectiveID.getLoc());
510
511   if (IDVal == ".register") {
512     // For now, ignore .register directive.
513     Parser.eatToEndOfStatement();
514     return false;
515   }
516
517   // Let the MC layer to handle other directives.
518   return true;
519 }
520
521 bool SparcAsmParser:: parseDirectiveWord(unsigned Size, SMLoc L) {
522   if (getLexer().isNot(AsmToken::EndOfStatement)) {
523     for (;;) {
524       const MCExpr *Value;
525       if (getParser().parseExpression(Value))
526         return true;
527
528       getParser().getStreamer().EmitValue(Value, Size);
529
530       if (getLexer().is(AsmToken::EndOfStatement))
531         break;
532
533       // FIXME: Improve diagnostic.
534       if (getLexer().isNot(AsmToken::Comma))
535         return Error(L, "unexpected token in directive");
536       Parser.Lex();
537     }
538   }
539   Parser.Lex();
540   return false;
541 }
542
543 SparcAsmParser::OperandMatchResultTy
544 SparcAsmParser::parseMEMOperand(OperandVector &Operands) {
545
546   SMLoc S, E;
547   unsigned BaseReg = 0;
548
549   if (ParseRegister(BaseReg, S, E)) {
550     return MatchOperand_NoMatch;
551   }
552
553   switch (getLexer().getKind()) {
554   default: return MatchOperand_NoMatch;
555
556   case AsmToken::Comma:
557   case AsmToken::RBrac:
558   case AsmToken::EndOfStatement:
559     Operands.push_back(SparcOperand::CreateMEMr(BaseReg, S, E));
560     return MatchOperand_Success;
561
562   case AsmToken:: Plus:
563     Parser.Lex(); // Eat the '+'
564     break;
565   case AsmToken::Minus:
566     break;
567   }
568
569   std::unique_ptr<SparcOperand> Offset;
570   OperandMatchResultTy ResTy = parseSparcAsmOperand(Offset);
571   if (ResTy != MatchOperand_Success || !Offset)
572     return MatchOperand_NoMatch;
573
574   Operands.push_back(
575       Offset->isImm() ? SparcOperand::MorphToMEMri(BaseReg, std::move(Offset))
576                       : SparcOperand::MorphToMEMrr(BaseReg, std::move(Offset)));
577
578   return MatchOperand_Success;
579 }
580
581 SparcAsmParser::OperandMatchResultTy
582 SparcAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
583
584   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
585
586   // If there wasn't a custom match, try the generic matcher below. Otherwise,
587   // there was a match, but an error occurred, in which case, just return that
588   // the operand parsing failed.
589   if (ResTy == MatchOperand_Success || ResTy == MatchOperand_ParseFail)
590     return ResTy;
591
592   if (getLexer().is(AsmToken::LBrac)) {
593     // Memory operand
594     Operands.push_back(SparcOperand::CreateToken("[",
595                                                  Parser.getTok().getLoc()));
596     Parser.Lex(); // Eat the [
597
598     if (Mnemonic == "cas" || Mnemonic == "casx") {
599       SMLoc S = Parser.getTok().getLoc();
600       if (getLexer().getKind() != AsmToken::Percent)
601         return MatchOperand_NoMatch;
602       Parser.Lex(); // eat %
603
604       unsigned RegNo, RegKind;
605       if (!matchRegisterName(Parser.getTok(), RegNo, RegKind))
606         return MatchOperand_NoMatch;
607
608       Parser.Lex(); // Eat the identifier token.
609       SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer()-1);
610       Operands.push_back(SparcOperand::CreateReg(RegNo, RegKind, S, E));
611       ResTy = MatchOperand_Success;
612     } else {
613       ResTy = parseMEMOperand(Operands);
614     }
615
616     if (ResTy != MatchOperand_Success)
617       return ResTy;
618
619     if (!getLexer().is(AsmToken::RBrac))
620       return MatchOperand_ParseFail;
621
622     Operands.push_back(SparcOperand::CreateToken("]",
623                                                  Parser.getTok().getLoc()));
624     Parser.Lex(); // Eat the ]
625     return MatchOperand_Success;
626   }
627
628   std::unique_ptr<SparcOperand> Op;
629
630   ResTy = parseSparcAsmOperand(Op, (Mnemonic == "call"));
631   if (ResTy != MatchOperand_Success || !Op)
632     return MatchOperand_ParseFail;
633
634   // Push the parsed operand into the list of operands
635   Operands.push_back(std::move(Op));
636
637   return MatchOperand_Success;
638 }
639
640 SparcAsmParser::OperandMatchResultTy
641 SparcAsmParser::parseSparcAsmOperand(std::unique_ptr<SparcOperand> &Op,
642                                      bool isCall) {
643
644   SMLoc S = Parser.getTok().getLoc();
645   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
646   const MCExpr *EVal;
647
648   Op = nullptr;
649   switch (getLexer().getKind()) {
650   default:  break;
651
652   case AsmToken::Percent:
653     Parser.Lex(); // Eat the '%'.
654     unsigned RegNo;
655     unsigned RegKind;
656     if (matchRegisterName(Parser.getTok(), RegNo, RegKind)) {
657       StringRef name = Parser.getTok().getString();
658       Parser.Lex(); // Eat the identifier token.
659       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
660       switch (RegNo) {
661       default:
662         Op = SparcOperand::CreateReg(RegNo, RegKind, S, E);
663         break;
664       case Sparc::Y:
665         Op = SparcOperand::CreateToken("%y", S);
666         break;
667
668       case Sparc::ICC:
669         if (name == "xcc")
670           Op = SparcOperand::CreateToken("%xcc", S);
671         else
672           Op = SparcOperand::CreateToken("%icc", S);
673         break;
674       }
675       break;
676     }
677     if (matchSparcAsmModifiers(EVal, E)) {
678       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
679       Op = SparcOperand::CreateImm(EVal, S, E);
680     }
681     break;
682
683   case AsmToken::Minus:
684   case AsmToken::Integer:
685   case AsmToken::LParen:
686     if (!getParser().parseExpression(EVal, E))
687       Op = SparcOperand::CreateImm(EVal, S, E);
688     break;
689
690   case AsmToken::Identifier: {
691     StringRef Identifier;
692     if (!getParser().parseIdentifier(Identifier)) {
693       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
694       MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
695
696       const MCExpr *Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
697                                                   getContext());
698       if (isCall &&
699           getContext().getObjectFileInfo()->getRelocM() == Reloc::PIC_)
700         Res = SparcMCExpr::Create(SparcMCExpr::VK_Sparc_WPLT30, Res,
701                                   getContext());
702       Op = SparcOperand::CreateImm(Res, S, E);
703     }
704     break;
705   }
706   }
707   return (Op) ? MatchOperand_Success : MatchOperand_ParseFail;
708 }
709
710 SparcAsmParser::OperandMatchResultTy
711 SparcAsmParser::parseBranchModifiers(OperandVector &Operands) {
712
713   // parse (,a|,pn|,pt)+
714
715   while (getLexer().is(AsmToken::Comma)) {
716
717     Parser.Lex(); // Eat the comma
718
719     if (!getLexer().is(AsmToken::Identifier))
720       return MatchOperand_ParseFail;
721     StringRef modName = Parser.getTok().getString();
722     if (modName == "a" || modName == "pn" || modName == "pt") {
723       Operands.push_back(SparcOperand::CreateToken(modName,
724                                                    Parser.getTok().getLoc()));
725       Parser.Lex(); // eat the identifier.
726     }
727   }
728   return MatchOperand_Success;
729 }
730
731 bool SparcAsmParser::matchRegisterName(const AsmToken &Tok,
732                                        unsigned &RegNo,
733                                        unsigned &RegKind)
734 {
735   int64_t intVal = 0;
736   RegNo = 0;
737   RegKind = SparcOperand::rk_None;
738   if (Tok.is(AsmToken::Identifier)) {
739     StringRef name = Tok.getString();
740
741     // %fp
742     if (name.equals("fp")) {
743       RegNo = Sparc::I6;
744       RegKind = SparcOperand::rk_IntReg;
745       return true;
746     }
747     // %sp
748     if (name.equals("sp")) {
749       RegNo = Sparc::O6;
750       RegKind = SparcOperand::rk_IntReg;
751       return true;
752     }
753
754     if (name.equals("y")) {
755       RegNo = Sparc::Y;
756       RegKind = SparcOperand::rk_Y;
757       return true;
758     }
759
760     if (name.equals("icc")) {
761       RegNo = Sparc::ICC;
762       RegKind = SparcOperand::rk_CCReg;
763       return true;
764     }
765
766     if (name.equals("xcc")) {
767       // FIXME:: check 64bit.
768       RegNo = Sparc::ICC;
769       RegKind = SparcOperand::rk_CCReg;
770       return true;
771     }
772
773     // %fcc0 - %fcc3
774     if (name.substr(0, 3).equals_lower("fcc")
775         && !name.substr(3).getAsInteger(10, intVal)
776         && intVal < 4) {
777       // FIXME: check 64bit and  handle %fcc1 - %fcc3
778       RegNo = Sparc::FCC0 + intVal;
779       RegKind = SparcOperand::rk_CCReg;
780       return true;
781     }
782
783     // %g0 - %g7
784     if (name.substr(0, 1).equals_lower("g")
785         && !name.substr(1).getAsInteger(10, intVal)
786         && intVal < 8) {
787       RegNo = IntRegs[intVal];
788       RegKind = SparcOperand::rk_IntReg;
789       return true;
790     }
791     // %o0 - %o7
792     if (name.substr(0, 1).equals_lower("o")
793         && !name.substr(1).getAsInteger(10, intVal)
794         && intVal < 8) {
795       RegNo = IntRegs[8 + intVal];
796       RegKind = SparcOperand::rk_IntReg;
797       return true;
798     }
799     if (name.substr(0, 1).equals_lower("l")
800         && !name.substr(1).getAsInteger(10, intVal)
801         && intVal < 8) {
802       RegNo = IntRegs[16 + intVal];
803       RegKind = SparcOperand::rk_IntReg;
804       return true;
805     }
806     if (name.substr(0, 1).equals_lower("i")
807         && !name.substr(1).getAsInteger(10, intVal)
808         && intVal < 8) {
809       RegNo = IntRegs[24 + intVal];
810       RegKind = SparcOperand::rk_IntReg;
811       return true;
812     }
813     // %f0 - %f31
814     if (name.substr(0, 1).equals_lower("f")
815         && !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 32) {
816       RegNo = FloatRegs[intVal];
817       RegKind = SparcOperand::rk_FloatReg;
818       return true;
819     }
820     // %f32 - %f62
821     if (name.substr(0, 1).equals_lower("f")
822         && !name.substr(1, 2).getAsInteger(10, intVal)
823         && intVal >= 32 && intVal <= 62 && (intVal % 2 == 0)) {
824       // FIXME: Check V9
825       RegNo = DoubleRegs[intVal/2];
826       RegKind = SparcOperand::rk_DoubleReg;
827       return true;
828     }
829
830     // %r0 - %r31
831     if (name.substr(0, 1).equals_lower("r")
832         && !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 31) {
833       RegNo = IntRegs[intVal];
834       RegKind = SparcOperand::rk_IntReg;
835       return true;
836     }
837   }
838   return false;
839 }
840
841 static bool hasGOTReference(const MCExpr *Expr) {
842   switch (Expr->getKind()) {
843   case MCExpr::Target:
844     if (const SparcMCExpr *SE = dyn_cast<SparcMCExpr>(Expr))
845       return hasGOTReference(SE->getSubExpr());
846     break;
847
848   case MCExpr::Constant:
849     break;
850
851   case MCExpr::Binary: {
852     const MCBinaryExpr *BE = cast<MCBinaryExpr>(Expr);
853     return hasGOTReference(BE->getLHS()) || hasGOTReference(BE->getRHS());
854   }
855
856   case MCExpr::SymbolRef: {
857     const MCSymbolRefExpr &SymRef = *cast<MCSymbolRefExpr>(Expr);
858     return (SymRef.getSymbol().getName() == "_GLOBAL_OFFSET_TABLE_");
859   }
860
861   case MCExpr::Unary:
862     return hasGOTReference(cast<MCUnaryExpr>(Expr)->getSubExpr());
863   }
864   return false;
865 }
866
867 bool SparcAsmParser::matchSparcAsmModifiers(const MCExpr *&EVal,
868                                             SMLoc &EndLoc)
869 {
870   AsmToken Tok = Parser.getTok();
871   if (!Tok.is(AsmToken::Identifier))
872     return false;
873
874   StringRef name = Tok.getString();
875
876   SparcMCExpr::VariantKind VK = SparcMCExpr::parseVariantKind(name);
877
878   if (VK == SparcMCExpr::VK_Sparc_None)
879     return false;
880
881   Parser.Lex(); // Eat the identifier.
882   if (Parser.getTok().getKind() != AsmToken::LParen)
883     return false;
884
885   Parser.Lex(); // Eat the LParen token.
886   const MCExpr *subExpr;
887   if (Parser.parseParenExpression(subExpr, EndLoc))
888     return false;
889
890   bool isPIC = getContext().getObjectFileInfo()->getRelocM() == Reloc::PIC_;
891
892   switch(VK) {
893   default: break;
894   case SparcMCExpr::VK_Sparc_LO:
895     VK =  (hasGOTReference(subExpr)
896            ? SparcMCExpr::VK_Sparc_PC10
897            : (isPIC ? SparcMCExpr::VK_Sparc_GOT10 : VK));
898     break;
899   case SparcMCExpr::VK_Sparc_HI:
900     VK =  (hasGOTReference(subExpr)
901            ? SparcMCExpr::VK_Sparc_PC22
902            : (isPIC ? SparcMCExpr::VK_Sparc_GOT22 : VK));
903     break;
904   }
905
906   EVal = SparcMCExpr::Create(VK, subExpr, getContext());
907   return true;
908 }
909
910
911 extern "C" void LLVMInitializeSparcAsmParser() {
912   RegisterMCAsmParser<SparcAsmParser> A(TheSparcTarget);
913   RegisterMCAsmParser<SparcAsmParser> B(TheSparcV9Target);
914 }
915
916 #define GET_REGISTER_MATCHER
917 #define GET_MATCHER_IMPLEMENTATION
918 #include "SparcGenAsmMatcher.inc"
919
920 unsigned SparcAsmParser::validateTargetOperandClass(MCParsedAsmOperand &GOp,
921                                                     unsigned Kind) {
922   SparcOperand &Op = (SparcOperand &)GOp;
923   if (Op.isFloatOrDoubleReg()) {
924     switch (Kind) {
925     default: break;
926     case MCK_DFPRegs:
927       if (!Op.isFloatReg() || SparcOperand::MorphToDoubleReg(Op))
928         return MCTargetAsmParser::Match_Success;
929       break;
930     case MCK_QFPRegs:
931       if (SparcOperand::MorphToQuadReg(Op))
932         return MCTargetAsmParser::Match_Success;
933       break;
934     }
935   }
936   return Match_InvalidOperand;
937 }