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