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