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