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