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