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