[Sparc] Add register class for floating point conditional flags (%fcc0 - %fcc3).
[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   ResTy = parseSparcAsmOperand(Op, (Mnemonic == "call"));
635   if (ResTy != MatchOperand_Success || !Op)
636     return MatchOperand_ParseFail;
637
638   // Push the parsed operand into the list of operands
639   Operands.push_back(Op);
640
641   return MatchOperand_Success;
642 }
643
644 SparcAsmParser::OperandMatchResultTy
645 SparcAsmParser::parseSparcAsmOperand(SparcOperand *&Op, bool isCall)
646 {
647
648   SMLoc S = Parser.getTok().getLoc();
649   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
650   const MCExpr *EVal;
651
652   Op = 0;
653   switch (getLexer().getKind()) {
654   default:  break;
655
656   case AsmToken::Percent:
657     Parser.Lex(); // Eat the '%'.
658     unsigned RegNo;
659     unsigned RegKind;
660     if (matchRegisterName(Parser.getTok(), RegNo, RegKind)) {
661       StringRef name = Parser.getTok().getString();
662       Parser.Lex(); // Eat the identifier token.
663       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
664       switch (RegNo) {
665       default:
666         Op = SparcOperand::CreateReg(RegNo, RegKind, S, E);
667         break;
668       case Sparc::Y:
669         Op = SparcOperand::CreateToken("%y", S);
670         break;
671
672       case Sparc::ICC:
673         if (name == "xcc")
674           Op = SparcOperand::CreateToken("%xcc", S);
675         else
676           Op = SparcOperand::CreateToken("%icc", S);
677         break;
678
679       case Sparc::FCC0:
680         assert(name == "fcc0" && "Cannot handle %fcc other than %fcc0 yet");
681         Op = SparcOperand::CreateToken("%fcc0", S);
682         break;
683       }
684       break;
685     }
686     if (matchSparcAsmModifiers(EVal, E)) {
687       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
688       Op = SparcOperand::CreateImm(EVal, S, E);
689     }
690     break;
691
692   case AsmToken::Minus:
693   case AsmToken::Integer:
694     if (!getParser().parseExpression(EVal, E))
695       Op = SparcOperand::CreateImm(EVal, S, E);
696     break;
697
698   case AsmToken::Identifier: {
699     StringRef Identifier;
700     if (!getParser().parseIdentifier(Identifier)) {
701       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
702       MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
703
704       const MCExpr *Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
705                                                   getContext());
706       if (isCall &&
707           getContext().getObjectFileInfo()->getRelocM() == Reloc::PIC_)
708         Res = SparcMCExpr::Create(SparcMCExpr::VK_Sparc_WPLT30, Res,
709                                   getContext());
710       Op = SparcOperand::CreateImm(Res, S, E);
711     }
712     break;
713   }
714   }
715   return (Op) ? MatchOperand_Success : MatchOperand_ParseFail;
716 }
717
718 SparcAsmParser::OperandMatchResultTy SparcAsmParser::
719 parseBranchModifiers(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
720
721   // parse (,a|,pn|,pt)+
722
723   while (getLexer().is(AsmToken::Comma)) {
724
725     Parser.Lex(); // Eat the comma
726
727     if (!getLexer().is(AsmToken::Identifier))
728       return MatchOperand_ParseFail;
729     StringRef modName = Parser.getTok().getString();
730     if (modName == "a" || modName == "pn" || modName == "pt") {
731       Operands.push_back(SparcOperand::CreateToken(modName,
732                                                    Parser.getTok().getLoc()));
733       Parser.Lex(); // eat the identifier.
734     }
735   }
736   return MatchOperand_Success;
737 }
738
739 bool SparcAsmParser::matchRegisterName(const AsmToken &Tok,
740                                        unsigned &RegNo,
741                                        unsigned &RegKind)
742 {
743   int64_t intVal = 0;
744   RegNo = 0;
745   RegKind = SparcOperand::rk_None;
746   if (Tok.is(AsmToken::Identifier)) {
747     StringRef name = Tok.getString();
748
749     // %fp
750     if (name.equals("fp")) {
751       RegNo = Sparc::I6;
752       RegKind = SparcOperand::rk_IntReg;
753       return true;
754     }
755     // %sp
756     if (name.equals("sp")) {
757       RegNo = Sparc::O6;
758       RegKind = SparcOperand::rk_IntReg;
759       return true;
760     }
761
762     if (name.equals("y")) {
763       RegNo = Sparc::Y;
764       RegKind = SparcOperand::rk_Y;
765       return true;
766     }
767
768     if (name.equals("icc")) {
769       RegNo = Sparc::ICC;
770       RegKind = SparcOperand::rk_CCReg;
771       return true;
772     }
773
774     if (name.equals("xcc")) {
775       // FIXME:: check 64bit.
776       RegNo = Sparc::ICC;
777       RegKind = SparcOperand::rk_CCReg;
778       return true;
779     }
780
781     // %fcc0 - %fcc3
782     if (name.substr(0, 3).equals_lower("fcc")
783         && !name.substr(3).getAsInteger(10, intVal)
784         && intVal < 4) {
785       // FIXME: check 64bit and  handle %fcc1 - %fcc3
786       RegNo = Sparc::FCC0;
787       RegKind = SparcOperand::rk_CCReg;
788       return true;
789     }
790
791     // %g0 - %g7
792     if (name.substr(0, 1).equals_lower("g")
793         && !name.substr(1).getAsInteger(10, intVal)
794         && intVal < 8) {
795       RegNo = IntRegs[intVal];
796       RegKind = SparcOperand::rk_IntReg;
797       return true;
798     }
799     // %o0 - %o7
800     if (name.substr(0, 1).equals_lower("o")
801         && !name.substr(1).getAsInteger(10, intVal)
802         && intVal < 8) {
803       RegNo = IntRegs[8 + intVal];
804       RegKind = SparcOperand::rk_IntReg;
805       return true;
806     }
807     if (name.substr(0, 1).equals_lower("l")
808         && !name.substr(1).getAsInteger(10, intVal)
809         && intVal < 8) {
810       RegNo = IntRegs[16 + intVal];
811       RegKind = SparcOperand::rk_IntReg;
812       return true;
813     }
814     if (name.substr(0, 1).equals_lower("i")
815         && !name.substr(1).getAsInteger(10, intVal)
816         && intVal < 8) {
817       RegNo = IntRegs[24 + intVal];
818       RegKind = SparcOperand::rk_IntReg;
819       return true;
820     }
821     // %f0 - %f31
822     if (name.substr(0, 1).equals_lower("f")
823         && !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 32) {
824       RegNo = FloatRegs[intVal];
825       RegKind = SparcOperand::rk_FloatReg;
826       return true;
827     }
828     // %f32 - %f62
829     if (name.substr(0, 1).equals_lower("f")
830         && !name.substr(1, 2).getAsInteger(10, intVal)
831         && intVal >= 32 && intVal <= 62 && (intVal % 2 == 0)) {
832       // FIXME: Check V9
833       RegNo = DoubleRegs[intVal/2];
834       RegKind = SparcOperand::rk_DoubleReg;
835       return true;
836     }
837
838     // %r0 - %r31
839     if (name.substr(0, 1).equals_lower("r")
840         && !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 31) {
841       RegNo = IntRegs[intVal];
842       RegKind = SparcOperand::rk_IntReg;
843       return true;
844     }
845   }
846   return false;
847 }
848
849 static bool hasGOTReference(const MCExpr *Expr) {
850   switch (Expr->getKind()) {
851   case MCExpr::Target:
852     if (const SparcMCExpr *SE = dyn_cast<SparcMCExpr>(Expr))
853       return hasGOTReference(SE->getSubExpr());
854     break;
855
856   case MCExpr::Constant:
857     break;
858
859   case MCExpr::Binary: {
860     const MCBinaryExpr *BE = cast<MCBinaryExpr>(Expr);
861     return hasGOTReference(BE->getLHS()) || hasGOTReference(BE->getRHS());
862   }
863
864   case MCExpr::SymbolRef: {
865     const MCSymbolRefExpr &SymRef = *cast<MCSymbolRefExpr>(Expr);
866     return (SymRef.getSymbol().getName() == "_GLOBAL_OFFSET_TABLE_");
867   }
868
869   case MCExpr::Unary:
870     return hasGOTReference(cast<MCUnaryExpr>(Expr)->getSubExpr());
871   }
872   return false;
873 }
874
875 bool SparcAsmParser::matchSparcAsmModifiers(const MCExpr *&EVal,
876                                             SMLoc &EndLoc)
877 {
878   AsmToken Tok = Parser.getTok();
879   if (!Tok.is(AsmToken::Identifier))
880     return false;
881
882   StringRef name = Tok.getString();
883
884   SparcMCExpr::VariantKind VK = SparcMCExpr::parseVariantKind(name);
885
886   if (VK == SparcMCExpr::VK_Sparc_None)
887     return false;
888
889   Parser.Lex(); // Eat the identifier.
890   if (Parser.getTok().getKind() != AsmToken::LParen)
891     return false;
892
893   Parser.Lex(); // Eat the LParen token.
894   const MCExpr *subExpr;
895   if (Parser.parseParenExpression(subExpr, EndLoc))
896     return false;
897
898   bool isPIC = getContext().getObjectFileInfo()->getRelocM() == Reloc::PIC_;
899
900   switch(VK) {
901   default: break;
902   case SparcMCExpr::VK_Sparc_LO:
903     VK =  (hasGOTReference(subExpr)
904            ? SparcMCExpr::VK_Sparc_PC10
905            : (isPIC ? SparcMCExpr::VK_Sparc_GOT10 : VK));
906     break;
907   case SparcMCExpr::VK_Sparc_HI:
908     VK =  (hasGOTReference(subExpr)
909            ? SparcMCExpr::VK_Sparc_PC22
910            : (isPIC ? SparcMCExpr::VK_Sparc_GOT22 : VK));
911     break;
912   }
913
914   EVal = SparcMCExpr::Create(VK, subExpr, getContext());
915   return true;
916 }
917
918
919 extern "C" void LLVMInitializeSparcAsmParser() {
920   RegisterMCAsmParser<SparcAsmParser> A(TheSparcTarget);
921   RegisterMCAsmParser<SparcAsmParser> B(TheSparcV9Target);
922 }
923
924 #define GET_REGISTER_MATCHER
925 #define GET_MATCHER_IMPLEMENTATION
926 #include "SparcGenAsmMatcher.inc"
927
928
929
930 unsigned SparcAsmParser::
931 validateTargetOperandClass(MCParsedAsmOperand *GOp,
932                            unsigned Kind)
933 {
934   SparcOperand *Op = (SparcOperand*)GOp;
935   if (Op->isFloatOrDoubleReg()) {
936     switch (Kind) {
937     default: break;
938     case MCK_DFPRegs:
939       if (!Op->isFloatReg() || SparcOperand::MorphToDoubleReg(Op))
940         return MCTargetAsmParser::Match_Success;
941       break;
942     case MCK_QFPRegs:
943       if (SparcOperand::MorphToQuadReg(Op))
944         return MCTargetAsmParser::Match_Success;
945       break;
946     }
947   }
948   return Match_InvalidOperand;
949 }