1 //===-- SparcAsmParser.cpp - Parse Sparc assembly to MCInst instructions --===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "MCTargetDesc/SparcMCExpr.h"
10 #include "MCTargetDesc/SparcMCTargetDesc.h"
11 #include "TargetInfo/SparcTargetInfo.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/MC/MCContext.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCInst.h"
18 #include "llvm/MC/MCInstrInfo.h"
19 #include "llvm/MC/MCObjectFileInfo.h"
20 #include "llvm/MC/MCParser/MCAsmLexer.h"
21 #include "llvm/MC/MCParser/MCAsmParser.h"
22 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
23 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/TargetRegistry.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/SMLoc.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/TargetParser/Triple.h"
34 #include <algorithm>
35 #include <cassert>
36 #include <cstdint>
37 #include <memory>
38 
39 using namespace llvm;
40 
41 // The generated AsmMatcher SparcGenAsmMatcher uses "Sparc" as the target
42 // namespace. But SPARC backend uses "SP" as its namespace.
43 namespace llvm {
44 namespace Sparc {
45 
46     using namespace SP;
47 
48 } // end namespace Sparc
49 } // end namespace llvm
50 
51 namespace {
52 
53 class SparcOperand;
54 
55 class SparcAsmParser : public MCTargetAsmParser {
56   MCAsmParser &Parser;
57 
58   enum class TailRelocKind { Load_GOT, Add_TLS, Load_TLS, Call_TLS };
59 
60   /// @name Auto-generated Match Functions
61   /// {
62 
63 #define GET_ASSEMBLER_HEADER
64 #include "SparcGenAsmMatcher.inc"
65 
66   /// }
67 
68   // public interface of the MCTargetAsmParser.
69   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
70                                OperandVector &Operands, MCStreamer &Out,
71                                uint64_t &ErrorInfo,
72                                bool MatchingInlineAsm) override;
73   bool parseRegister(MCRegister &RegNo, SMLoc &StartLoc,
74                      SMLoc &EndLoc) override;
75   OperandMatchResultTy tryParseRegister(MCRegister &RegNo, SMLoc &StartLoc,
76                                         SMLoc &EndLoc) override;
77   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
78                         SMLoc NameLoc, OperandVector &Operands) override;
79   ParseStatus parseDirective(AsmToken DirectiveID) override;
80 
81   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
82                                       unsigned Kind) override;
83 
84   // Custom parse functions for Sparc specific operands.
85   OperandMatchResultTy parseMEMOperand(OperandVector &Operands);
86 
87   OperandMatchResultTy parseMembarTag(OperandVector &Operands);
88 
89   template <TailRelocKind Kind>
90   OperandMatchResultTy parseTailRelocSym(OperandVector &Operands);
91 
92   template <unsigned N>
93   OperandMatchResultTy parseShiftAmtImm(OperandVector &Operands);
94 
95   OperandMatchResultTy parseCallTarget(OperandVector &Operands);
96 
97   OperandMatchResultTy parseOperand(OperandVector &Operands, StringRef Name);
98 
99   OperandMatchResultTy
100   parseSparcAsmOperand(std::unique_ptr<SparcOperand> &Operand,
101                        bool isCall = false);
102 
103   OperandMatchResultTy parseBranchModifiers(OperandVector &Operands);
104 
105   // Helper function for dealing with %lo / %hi in PIC mode.
106   const SparcMCExpr *adjustPICRelocation(SparcMCExpr::VariantKind VK,
107                                          const MCExpr *subExpr);
108 
109   // returns true if Tok is matched to a register and returns register in RegNo.
110   bool matchRegisterName(const AsmToken &Tok, MCRegister &RegNo,
111                          unsigned &RegKind);
112 
113   bool matchSparcAsmModifiers(const MCExpr *&EVal, SMLoc &EndLoc);
114 
115   bool is64Bit() const {
116     return getSTI().getTargetTriple().getArch() == Triple::sparcv9;
117   }
118 
119   bool expandSET(MCInst &Inst, SMLoc IDLoc,
120                  SmallVectorImpl<MCInst> &Instructions);
121 
122   SMLoc getLoc() const { return getParser().getTok().getLoc(); }
123 
124 public:
125   SparcAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser,
126                 const MCInstrInfo &MII,
127                 const MCTargetOptions &Options)
128       : MCTargetAsmParser(Options, sti, MII), Parser(parser) {
129     Parser.addAliasForDirective(".half", ".2byte");
130     Parser.addAliasForDirective(".uahalf", ".2byte");
131     Parser.addAliasForDirective(".word", ".4byte");
132     Parser.addAliasForDirective(".uaword", ".4byte");
133     Parser.addAliasForDirective(".nword", is64Bit() ? ".8byte" : ".4byte");
134     if (is64Bit())
135       Parser.addAliasForDirective(".xword", ".8byte");
136 
137     // Initialize the set of available features.
138     setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
139   }
140 };
141 
142 } // end anonymous namespace
143 
144   static const MCPhysReg IntRegs[32] = {
145     Sparc::G0, Sparc::G1, Sparc::G2, Sparc::G3,
146     Sparc::G4, Sparc::G5, Sparc::G6, Sparc::G7,
147     Sparc::O0, Sparc::O1, Sparc::O2, Sparc::O3,
148     Sparc::O4, Sparc::O5, Sparc::O6, Sparc::O7,
149     Sparc::L0, Sparc::L1, Sparc::L2, Sparc::L3,
150     Sparc::L4, Sparc::L5, Sparc::L6, Sparc::L7,
151     Sparc::I0, Sparc::I1, Sparc::I2, Sparc::I3,
152     Sparc::I4, Sparc::I5, Sparc::I6, Sparc::I7 };
153 
154   static const MCPhysReg FloatRegs[32] = {
155     Sparc::F0,  Sparc::F1,  Sparc::F2,  Sparc::F3,
156     Sparc::F4,  Sparc::F5,  Sparc::F6,  Sparc::F7,
157     Sparc::F8,  Sparc::F9,  Sparc::F10, Sparc::F11,
158     Sparc::F12, Sparc::F13, Sparc::F14, Sparc::F15,
159     Sparc::F16, Sparc::F17, Sparc::F18, Sparc::F19,
160     Sparc::F20, Sparc::F21, Sparc::F22, Sparc::F23,
161     Sparc::F24, Sparc::F25, Sparc::F26, Sparc::F27,
162     Sparc::F28, Sparc::F29, Sparc::F30, Sparc::F31 };
163 
164   static const MCPhysReg DoubleRegs[32] = {
165     Sparc::D0,  Sparc::D1,  Sparc::D2,  Sparc::D3,
166     Sparc::D4,  Sparc::D5,  Sparc::D6,  Sparc::D7,
167     Sparc::D8,  Sparc::D9,  Sparc::D10, Sparc::D11,
168     Sparc::D12, Sparc::D13, Sparc::D14, Sparc::D15,
169     Sparc::D16, Sparc::D17, Sparc::D18, Sparc::D19,
170     Sparc::D20, Sparc::D21, Sparc::D22, Sparc::D23,
171     Sparc::D24, Sparc::D25, Sparc::D26, Sparc::D27,
172     Sparc::D28, Sparc::D29, Sparc::D30, Sparc::D31 };
173 
174   static const MCPhysReg QuadFPRegs[32] = {
175     Sparc::Q0,  Sparc::Q1,  Sparc::Q2,  Sparc::Q3,
176     Sparc::Q4,  Sparc::Q5,  Sparc::Q6,  Sparc::Q7,
177     Sparc::Q8,  Sparc::Q9,  Sparc::Q10, Sparc::Q11,
178     Sparc::Q12, Sparc::Q13, Sparc::Q14, Sparc::Q15 };
179 
180   static const MCPhysReg ASRRegs[32] = {
181     SP::Y,     SP::ASR1,  SP::ASR2,  SP::ASR3,
182     SP::ASR4,  SP::ASR5,  SP::ASR6, SP::ASR7,
183     SP::ASR8,  SP::ASR9,  SP::ASR10, SP::ASR11,
184     SP::ASR12, SP::ASR13, SP::ASR14, SP::ASR15,
185     SP::ASR16, SP::ASR17, SP::ASR18, SP::ASR19,
186     SP::ASR20, SP::ASR21, SP::ASR22, SP::ASR23,
187     SP::ASR24, SP::ASR25, SP::ASR26, SP::ASR27,
188     SP::ASR28, SP::ASR29, SP::ASR30, SP::ASR31};
189 
190   static const MCPhysReg IntPairRegs[] = {
191     Sparc::G0_G1, Sparc::G2_G3, Sparc::G4_G5, Sparc::G6_G7,
192     Sparc::O0_O1, Sparc::O2_O3, Sparc::O4_O5, Sparc::O6_O7,
193     Sparc::L0_L1, Sparc::L2_L3, Sparc::L4_L5, Sparc::L6_L7,
194     Sparc::I0_I1, Sparc::I2_I3, Sparc::I4_I5, Sparc::I6_I7};
195 
196   static const MCPhysReg CoprocRegs[32] = {
197     Sparc::C0,  Sparc::C1,  Sparc::C2,  Sparc::C3,
198     Sparc::C4,  Sparc::C5,  Sparc::C6,  Sparc::C7,
199     Sparc::C8,  Sparc::C9,  Sparc::C10, Sparc::C11,
200     Sparc::C12, Sparc::C13, Sparc::C14, Sparc::C15,
201     Sparc::C16, Sparc::C17, Sparc::C18, Sparc::C19,
202     Sparc::C20, Sparc::C21, Sparc::C22, Sparc::C23,
203     Sparc::C24, Sparc::C25, Sparc::C26, Sparc::C27,
204     Sparc::C28, Sparc::C29, Sparc::C30, Sparc::C31 };
205 
206   static const MCPhysReg CoprocPairRegs[] = {
207     Sparc::C0_C1,   Sparc::C2_C3,   Sparc::C4_C5,   Sparc::C6_C7,
208     Sparc::C8_C9,   Sparc::C10_C11, Sparc::C12_C13, Sparc::C14_C15,
209     Sparc::C16_C17, Sparc::C18_C19, Sparc::C20_C21, Sparc::C22_C23,
210     Sparc::C24_C25, Sparc::C26_C27, Sparc::C28_C29, Sparc::C30_C31};
211 
212 namespace {
213 
214 /// SparcOperand - Instances of this class represent a parsed Sparc machine
215 /// instruction.
216 class SparcOperand : public MCParsedAsmOperand {
217 public:
218   enum RegisterKind {
219     rk_None,
220     rk_IntReg,
221     rk_IntPairReg,
222     rk_FloatReg,
223     rk_DoubleReg,
224     rk_QuadReg,
225     rk_CoprocReg,
226     rk_CoprocPairReg,
227     rk_Special,
228   };
229 
230 private:
231   enum KindTy {
232     k_Token,
233     k_Register,
234     k_Immediate,
235     k_MemoryReg,
236     k_MemoryImm
237   } Kind;
238 
239   SMLoc StartLoc, EndLoc;
240 
241   struct Token {
242     const char *Data;
243     unsigned Length;
244   };
245 
246   struct RegOp {
247     unsigned RegNum;
248     RegisterKind Kind;
249   };
250 
251   struct ImmOp {
252     const MCExpr *Val;
253   };
254 
255   struct MemOp {
256     unsigned Base;
257     unsigned OffsetReg;
258     const MCExpr *Off;
259   };
260 
261   union {
262     struct Token Tok;
263     struct RegOp Reg;
264     struct ImmOp Imm;
265     struct MemOp Mem;
266   };
267 
268 public:
269   SparcOperand(KindTy K) : Kind(K) {}
270 
271   bool isToken() const override { return Kind == k_Token; }
272   bool isReg() const override { return Kind == k_Register; }
273   bool isImm() const override { return Kind == k_Immediate; }
274   bool isMem() const override { return isMEMrr() || isMEMri(); }
275   bool isMEMrr() const { return Kind == k_MemoryReg; }
276   bool isMEMri() const { return Kind == k_MemoryImm; }
277   bool isMembarTag() const { return Kind == k_Immediate; }
278   bool isTailRelocSym() const { return Kind == k_Immediate; }
279 
280   bool isCallTarget() const {
281     if (!isImm())
282       return false;
283 
284     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val))
285       return CE->getValue() % 4 == 0;
286 
287     return true;
288   }
289 
290   bool isShiftAmtImm5() const {
291     if (!isImm())
292       return false;
293 
294     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val))
295       return isUInt<5>(CE->getValue());
296 
297     return false;
298   }
299 
300   bool isShiftAmtImm6() const {
301     if (!isImm())
302       return false;
303 
304     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val))
305       return isUInt<6>(CE->getValue());
306 
307     return false;
308   }
309 
310   bool isIntReg() const {
311     return (Kind == k_Register && Reg.Kind == rk_IntReg);
312   }
313 
314   bool isFloatReg() const {
315     return (Kind == k_Register && Reg.Kind == rk_FloatReg);
316   }
317 
318   bool isFloatOrDoubleReg() const {
319     return (Kind == k_Register && (Reg.Kind == rk_FloatReg
320                                    || Reg.Kind == rk_DoubleReg));
321   }
322 
323   bool isCoprocReg() const {
324     return (Kind == k_Register && Reg.Kind == rk_CoprocReg);
325   }
326 
327   StringRef getToken() const {
328     assert(Kind == k_Token && "Invalid access!");
329     return StringRef(Tok.Data, Tok.Length);
330   }
331 
332   unsigned getReg() const override {
333     assert((Kind == k_Register) && "Invalid access!");
334     return Reg.RegNum;
335   }
336 
337   const MCExpr *getImm() const {
338     assert((Kind == k_Immediate) && "Invalid access!");
339     return Imm.Val;
340   }
341 
342   unsigned getMemBase() const {
343     assert((Kind == k_MemoryReg || Kind == k_MemoryImm) && "Invalid access!");
344     return Mem.Base;
345   }
346 
347   unsigned getMemOffsetReg() const {
348     assert((Kind == k_MemoryReg) && "Invalid access!");
349     return Mem.OffsetReg;
350   }
351 
352   const MCExpr *getMemOff() const {
353     assert((Kind == k_MemoryImm) && "Invalid access!");
354     return Mem.Off;
355   }
356 
357   /// getStartLoc - Get the location of the first token of this operand.
358   SMLoc getStartLoc() const override {
359     return StartLoc;
360   }
361   /// getEndLoc - Get the location of the last token of this operand.
362   SMLoc getEndLoc() const override {
363     return EndLoc;
364   }
365 
366   void print(raw_ostream &OS) const override {
367     switch (Kind) {
368     case k_Token:     OS << "Token: " << getToken() << "\n"; break;
369     case k_Register:  OS << "Reg: #" << getReg() << "\n"; break;
370     case k_Immediate: OS << "Imm: " << getImm() << "\n"; break;
371     case k_MemoryReg: OS << "Mem: " << getMemBase() << "+"
372                          << getMemOffsetReg() << "\n"; break;
373     case k_MemoryImm: assert(getMemOff() != nullptr);
374       OS << "Mem: " << getMemBase()
375          << "+" << *getMemOff()
376          << "\n"; break;
377     }
378   }
379 
380   void addRegOperands(MCInst &Inst, unsigned N) const {
381     assert(N == 1 && "Invalid number of operands!");
382     Inst.addOperand(MCOperand::createReg(getReg()));
383   }
384 
385   void addImmOperands(MCInst &Inst, unsigned N) const {
386     assert(N == 1 && "Invalid number of operands!");
387     const MCExpr *Expr = getImm();
388     addExpr(Inst, Expr);
389   }
390 
391   void addShiftAmtImm5Operands(MCInst &Inst, unsigned N) const {
392     assert(N == 1 && "Invalid number of operands!");
393     addExpr(Inst, getImm());
394   }
395   void addShiftAmtImm6Operands(MCInst &Inst, unsigned N) const {
396     assert(N == 1 && "Invalid number of operands!");
397     addExpr(Inst, getImm());
398   }
399 
400   void addExpr(MCInst &Inst, const MCExpr *Expr) const{
401     // Add as immediate when possible.  Null MCExpr = 0.
402     if (!Expr)
403       Inst.addOperand(MCOperand::createImm(0));
404     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
405       Inst.addOperand(MCOperand::createImm(CE->getValue()));
406     else
407       Inst.addOperand(MCOperand::createExpr(Expr));
408   }
409 
410   void addMEMrrOperands(MCInst &Inst, unsigned N) const {
411     assert(N == 2 && "Invalid number of operands!");
412 
413     Inst.addOperand(MCOperand::createReg(getMemBase()));
414 
415     assert(getMemOffsetReg() != 0 && "Invalid offset");
416     Inst.addOperand(MCOperand::createReg(getMemOffsetReg()));
417   }
418 
419   void addMEMriOperands(MCInst &Inst, unsigned N) const {
420     assert(N == 2 && "Invalid number of operands!");
421 
422     Inst.addOperand(MCOperand::createReg(getMemBase()));
423 
424     const MCExpr *Expr = getMemOff();
425     addExpr(Inst, Expr);
426   }
427 
428   void addMembarTagOperands(MCInst &Inst, unsigned N) const {
429     assert(N == 1 && "Invalid number of operands!");
430     const MCExpr *Expr = getImm();
431     addExpr(Inst, Expr);
432   }
433 
434   void addCallTargetOperands(MCInst &Inst, unsigned N) const {
435     assert(N == 1 && "Invalid number of operands!");
436     addExpr(Inst, getImm());
437   }
438 
439   void addTailRelocSymOperands(MCInst &Inst, unsigned N) const {
440     assert(N == 1 && "Invalid number of operands!");
441     addExpr(Inst, getImm());
442   }
443 
444   static std::unique_ptr<SparcOperand> CreateToken(StringRef Str, SMLoc S) {
445     auto Op = std::make_unique<SparcOperand>(k_Token);
446     Op->Tok.Data = Str.data();
447     Op->Tok.Length = Str.size();
448     Op->StartLoc = S;
449     Op->EndLoc = S;
450     return Op;
451   }
452 
453   static std::unique_ptr<SparcOperand> CreateReg(unsigned RegNum, unsigned Kind,
454                                                  SMLoc S, SMLoc E) {
455     auto Op = std::make_unique<SparcOperand>(k_Register);
456     Op->Reg.RegNum = RegNum;
457     Op->Reg.Kind   = (SparcOperand::RegisterKind)Kind;
458     Op->StartLoc = S;
459     Op->EndLoc = E;
460     return Op;
461   }
462 
463   static std::unique_ptr<SparcOperand> CreateImm(const MCExpr *Val, SMLoc S,
464                                                  SMLoc E) {
465     auto Op = std::make_unique<SparcOperand>(k_Immediate);
466     Op->Imm.Val = Val;
467     Op->StartLoc = S;
468     Op->EndLoc = E;
469     return Op;
470   }
471 
472   static bool MorphToIntPairReg(SparcOperand &Op) {
473     unsigned Reg = Op.getReg();
474     assert(Op.Reg.Kind == rk_IntReg);
475     unsigned regIdx = 32;
476     if (Reg >= Sparc::G0 && Reg <= Sparc::G7)
477       regIdx = Reg - Sparc::G0;
478     else if (Reg >= Sparc::O0 && Reg <= Sparc::O7)
479       regIdx = Reg - Sparc::O0 + 8;
480     else if (Reg >= Sparc::L0 && Reg <= Sparc::L7)
481       regIdx = Reg - Sparc::L0 + 16;
482     else if (Reg >= Sparc::I0 && Reg <= Sparc::I7)
483       regIdx = Reg - Sparc::I0 + 24;
484     if (regIdx % 2 || regIdx > 31)
485       return false;
486     Op.Reg.RegNum = IntPairRegs[regIdx / 2];
487     Op.Reg.Kind = rk_IntPairReg;
488     return true;
489   }
490 
491   static bool MorphToDoubleReg(SparcOperand &Op) {
492     unsigned Reg = Op.getReg();
493     assert(Op.Reg.Kind == rk_FloatReg);
494     unsigned regIdx = Reg - Sparc::F0;
495     if (regIdx % 2 || regIdx > 31)
496       return false;
497     Op.Reg.RegNum = DoubleRegs[regIdx / 2];
498     Op.Reg.Kind = rk_DoubleReg;
499     return true;
500   }
501 
502   static bool MorphToQuadReg(SparcOperand &Op) {
503     unsigned Reg = Op.getReg();
504     unsigned regIdx = 0;
505     switch (Op.Reg.Kind) {
506     default: llvm_unreachable("Unexpected register kind!");
507     case rk_FloatReg:
508       regIdx = Reg - Sparc::F0;
509       if (regIdx % 4 || regIdx > 31)
510         return false;
511       Reg = QuadFPRegs[regIdx / 4];
512       break;
513     case rk_DoubleReg:
514       regIdx =  Reg - Sparc::D0;
515       if (regIdx % 2 || regIdx > 31)
516         return false;
517       Reg = QuadFPRegs[regIdx / 2];
518       break;
519     }
520     Op.Reg.RegNum = Reg;
521     Op.Reg.Kind = rk_QuadReg;
522     return true;
523   }
524 
525   static bool MorphToCoprocPairReg(SparcOperand &Op) {
526     unsigned Reg = Op.getReg();
527     assert(Op.Reg.Kind == rk_CoprocReg);
528     unsigned regIdx = 32;
529     if (Reg >= Sparc::C0 && Reg <= Sparc::C31)
530       regIdx = Reg - Sparc::C0;
531     if (regIdx % 2 || regIdx > 31)
532       return false;
533     Op.Reg.RegNum = CoprocPairRegs[regIdx / 2];
534     Op.Reg.Kind = rk_CoprocPairReg;
535     return true;
536   }
537 
538   static std::unique_ptr<SparcOperand>
539   MorphToMEMrr(unsigned Base, std::unique_ptr<SparcOperand> Op) {
540     unsigned offsetReg = Op->getReg();
541     Op->Kind = k_MemoryReg;
542     Op->Mem.Base = Base;
543     Op->Mem.OffsetReg = offsetReg;
544     Op->Mem.Off = nullptr;
545     return Op;
546   }
547 
548   static std::unique_ptr<SparcOperand>
549   CreateMEMr(unsigned Base, SMLoc S, SMLoc E) {
550     auto Op = std::make_unique<SparcOperand>(k_MemoryReg);
551     Op->Mem.Base = Base;
552     Op->Mem.OffsetReg = Sparc::G0;  // always 0
553     Op->Mem.Off = nullptr;
554     Op->StartLoc = S;
555     Op->EndLoc = E;
556     return Op;
557   }
558 
559   static std::unique_ptr<SparcOperand>
560   MorphToMEMri(unsigned Base, std::unique_ptr<SparcOperand> Op) {
561     const MCExpr *Imm  = Op->getImm();
562     Op->Kind = k_MemoryImm;
563     Op->Mem.Base = Base;
564     Op->Mem.OffsetReg = 0;
565     Op->Mem.Off = Imm;
566     return Op;
567   }
568 };
569 
570 } // end anonymous namespace
571 
572 bool SparcAsmParser::expandSET(MCInst &Inst, SMLoc IDLoc,
573                                SmallVectorImpl<MCInst> &Instructions) {
574   MCOperand MCRegOp = Inst.getOperand(0);
575   MCOperand MCValOp = Inst.getOperand(1);
576   assert(MCRegOp.isReg());
577   assert(MCValOp.isImm() || MCValOp.isExpr());
578 
579   // the imm operand can be either an expression or an immediate.
580   bool IsImm = Inst.getOperand(1).isImm();
581   int64_t RawImmValue = IsImm ? MCValOp.getImm() : 0;
582 
583   // Allow either a signed or unsigned 32-bit immediate.
584   if (RawImmValue < -2147483648LL || RawImmValue > 4294967295LL) {
585     return Error(IDLoc,
586                  "set: argument must be between -2147483648 and 4294967295");
587   }
588 
589   // If the value was expressed as a large unsigned number, that's ok.
590   // We want to see if it "looks like" a small signed number.
591   int32_t ImmValue = RawImmValue;
592   // For 'set' you can't use 'or' with a negative operand on V9 because
593   // that would splat the sign bit across the upper half of the destination
594   // register, whereas 'set' is defined to zero the high 32 bits.
595   bool IsEffectivelyImm13 =
596       IsImm && ((is64Bit() ? 0 : -4096) <= ImmValue && ImmValue < 4096);
597   const MCExpr *ValExpr;
598   if (IsImm)
599     ValExpr = MCConstantExpr::create(ImmValue, getContext());
600   else
601     ValExpr = MCValOp.getExpr();
602 
603   MCOperand PrevReg = MCOperand::createReg(Sparc::G0);
604 
605   // If not just a signed imm13 value, then either we use a 'sethi' with a
606   // following 'or', or a 'sethi' by itself if there are no more 1 bits.
607   // In either case, start with the 'sethi'.
608   if (!IsEffectivelyImm13) {
609     MCInst TmpInst;
610     const MCExpr *Expr = adjustPICRelocation(SparcMCExpr::VK_Sparc_HI, ValExpr);
611     TmpInst.setLoc(IDLoc);
612     TmpInst.setOpcode(SP::SETHIi);
613     TmpInst.addOperand(MCRegOp);
614     TmpInst.addOperand(MCOperand::createExpr(Expr));
615     Instructions.push_back(TmpInst);
616     PrevReg = MCRegOp;
617   }
618 
619   // The low bits require touching in 3 cases:
620   // * A non-immediate value will always require both instructions.
621   // * An effectively imm13 value needs only an 'or' instruction.
622   // * Otherwise, an immediate that is not effectively imm13 requires the
623   //   'or' only if bits remain after clearing the 22 bits that 'sethi' set.
624   // If the low bits are known zeros, there's nothing to do.
625   // In the second case, and only in that case, must we NOT clear
626   // bits of the immediate value via the %lo() assembler function.
627   // Note also, the 'or' instruction doesn't mind a large value in the case
628   // where the operand to 'set' was 0xFFFFFzzz - it does exactly what you mean.
629   if (!IsImm || IsEffectivelyImm13 || (ImmValue & 0x3ff)) {
630     MCInst TmpInst;
631     const MCExpr *Expr;
632     if (IsEffectivelyImm13)
633       Expr = ValExpr;
634     else
635       Expr = adjustPICRelocation(SparcMCExpr::VK_Sparc_LO, ValExpr);
636     TmpInst.setLoc(IDLoc);
637     TmpInst.setOpcode(SP::ORri);
638     TmpInst.addOperand(MCRegOp);
639     TmpInst.addOperand(PrevReg);
640     TmpInst.addOperand(MCOperand::createExpr(Expr));
641     Instructions.push_back(TmpInst);
642   }
643   return false;
644 }
645 
646 bool SparcAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
647                                              OperandVector &Operands,
648                                              MCStreamer &Out,
649                                              uint64_t &ErrorInfo,
650                                              bool MatchingInlineAsm) {
651   MCInst Inst;
652   SmallVector<MCInst, 8> Instructions;
653   unsigned MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
654                                               MatchingInlineAsm);
655   switch (MatchResult) {
656   case Match_Success: {
657     switch (Inst.getOpcode()) {
658     default:
659       Inst.setLoc(IDLoc);
660       Instructions.push_back(Inst);
661       break;
662     case SP::SET:
663       if (expandSET(Inst, IDLoc, Instructions))
664         return true;
665       break;
666     }
667 
668     for (const MCInst &I : Instructions) {
669       Out.emitInstruction(I, getSTI());
670     }
671     return false;
672   }
673 
674   case Match_MissingFeature:
675     return Error(IDLoc,
676                  "instruction requires a CPU feature not currently enabled");
677 
678   case Match_InvalidOperand: {
679     SMLoc ErrorLoc = IDLoc;
680     if (ErrorInfo != ~0ULL) {
681       if (ErrorInfo >= Operands.size())
682         return Error(IDLoc, "too few operands for instruction");
683 
684       ErrorLoc = ((SparcOperand &)*Operands[ErrorInfo]).getStartLoc();
685       if (ErrorLoc == SMLoc())
686         ErrorLoc = IDLoc;
687     }
688 
689     return Error(ErrorLoc, "invalid operand for instruction");
690   }
691   case Match_MnemonicFail:
692     return Error(IDLoc, "invalid instruction mnemonic");
693   }
694   llvm_unreachable("Implement any new match types added!");
695 }
696 
697 bool SparcAsmParser::parseRegister(MCRegister &RegNo, SMLoc &StartLoc,
698                                    SMLoc &EndLoc) {
699   if (tryParseRegister(RegNo, StartLoc, EndLoc) != MatchOperand_Success)
700     return Error(StartLoc, "invalid register name");
701   return false;
702 }
703 
704 OperandMatchResultTy SparcAsmParser::tryParseRegister(MCRegister &RegNo,
705                                                       SMLoc &StartLoc,
706                                                       SMLoc &EndLoc) {
707   const AsmToken &Tok = Parser.getTok();
708   StartLoc = Tok.getLoc();
709   EndLoc = Tok.getEndLoc();
710   RegNo = 0;
711   if (getLexer().getKind() != AsmToken::Percent)
712     return MatchOperand_NoMatch;
713   Parser.Lex();
714   unsigned regKind = SparcOperand::rk_None;
715   if (matchRegisterName(Tok, RegNo, regKind)) {
716     Parser.Lex();
717     return MatchOperand_Success;
718   }
719 
720   getLexer().UnLex(Tok);
721   return MatchOperand_NoMatch;
722 }
723 
724 static void applyMnemonicAliases(StringRef &Mnemonic,
725                                  const FeatureBitset &Features,
726                                  unsigned VariantID);
727 
728 bool SparcAsmParser::ParseInstruction(ParseInstructionInfo &Info,
729                                       StringRef Name, SMLoc NameLoc,
730                                       OperandVector &Operands) {
731 
732   // First operand in MCInst is instruction mnemonic.
733   Operands.push_back(SparcOperand::CreateToken(Name, NameLoc));
734 
735   // apply mnemonic aliases, if any, so that we can parse operands correctly.
736   applyMnemonicAliases(Name, getAvailableFeatures(), 0);
737 
738   if (getLexer().isNot(AsmToken::EndOfStatement)) {
739     // Read the first operand.
740     if (getLexer().is(AsmToken::Comma)) {
741       if (parseBranchModifiers(Operands) != MatchOperand_Success) {
742         SMLoc Loc = getLexer().getLoc();
743         return Error(Loc, "unexpected token");
744       }
745     }
746     if (parseOperand(Operands, Name) != MatchOperand_Success) {
747       SMLoc Loc = getLexer().getLoc();
748       return Error(Loc, "unexpected token");
749     }
750 
751     while (getLexer().is(AsmToken::Comma) || getLexer().is(AsmToken::Plus)) {
752       if (getLexer().is(AsmToken::Plus)) {
753       // Plus tokens are significant in software_traps (p83, sparcv8.pdf). We must capture them.
754         Operands.push_back(SparcOperand::CreateToken("+", Parser.getTok().getLoc()));
755       }
756       Parser.Lex(); // Eat the comma or plus.
757       // Parse and remember the operand.
758       if (parseOperand(Operands, Name) != MatchOperand_Success) {
759         SMLoc Loc = getLexer().getLoc();
760         return Error(Loc, "unexpected token");
761       }
762     }
763   }
764   if (getLexer().isNot(AsmToken::EndOfStatement)) {
765     SMLoc Loc = getLexer().getLoc();
766     return Error(Loc, "unexpected token");
767   }
768   Parser.Lex(); // Consume the EndOfStatement.
769   return false;
770 }
771 
772 ParseStatus SparcAsmParser::parseDirective(AsmToken DirectiveID) {
773   StringRef IDVal = DirectiveID.getString();
774 
775   if (IDVal == ".register") {
776     // For now, ignore .register directive.
777     Parser.eatToEndOfStatement();
778     return ParseStatus::Success;
779   }
780   if (IDVal == ".proc") {
781     // For compatibility, ignore this directive.
782     // (It's supposed to be an "optimization" in the Sun assembler)
783     Parser.eatToEndOfStatement();
784     return ParseStatus::Success;
785   }
786 
787   // Let the MC layer to handle other directives.
788   return ParseStatus::NoMatch;
789 }
790 
791 OperandMatchResultTy
792 SparcAsmParser::parseMEMOperand(OperandVector &Operands) {
793   SMLoc S, E;
794 
795   std::unique_ptr<SparcOperand> LHS;
796   if (parseSparcAsmOperand(LHS) != MatchOperand_Success)
797     return MatchOperand_NoMatch;
798 
799   // Single immediate operand
800   if (LHS->isImm()) {
801     Operands.push_back(SparcOperand::MorphToMEMri(Sparc::G0, std::move(LHS)));
802     return MatchOperand_Success;
803   }
804 
805   if (!LHS->isIntReg()) {
806     Error(LHS->getStartLoc(), "invalid register kind for this operand");
807     return MatchOperand_ParseFail;
808   }
809 
810   AsmToken Tok = getLexer().getTok();
811   // The plus token may be followed by a register or an immediate value, the
812   // minus one is always interpreted as sign for the immediate value
813   if (Tok.is(AsmToken::Plus) || Tok.is(AsmToken::Minus)) {
814     (void)Parser.parseOptionalToken(AsmToken::Plus);
815 
816     std::unique_ptr<SparcOperand> RHS;
817     if (parseSparcAsmOperand(RHS) != MatchOperand_Success)
818       return MatchOperand_NoMatch;
819 
820     if (RHS->isReg() && !RHS->isIntReg()) {
821       Error(RHS->getStartLoc(), "invalid register kind for this operand");
822       return MatchOperand_ParseFail;
823     }
824 
825     Operands.push_back(
826         RHS->isImm()
827             ? SparcOperand::MorphToMEMri(LHS->getReg(), std::move(RHS))
828             : SparcOperand::MorphToMEMrr(LHS->getReg(), std::move(RHS)));
829 
830     return MatchOperand_Success;
831   }
832 
833   Operands.push_back(SparcOperand::CreateMEMr(LHS->getReg(), S, E));
834   return MatchOperand_Success;
835 }
836 
837 template <unsigned N>
838 OperandMatchResultTy SparcAsmParser::parseShiftAmtImm(OperandVector &Operands) {
839   SMLoc S = Parser.getTok().getLoc();
840   SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
841 
842   // This is a register, not an immediate
843   if (getLexer().getKind() == AsmToken::Percent)
844     return MatchOperand_NoMatch;
845 
846   const MCExpr *Expr;
847   if (getParser().parseExpression(Expr))
848     return MatchOperand_ParseFail;
849 
850   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
851   if (!CE) {
852     Error(S, "constant expression expected");
853     return MatchOperand_ParseFail;
854   }
855 
856   if (!isUInt<N>(CE->getValue())) {
857     Error(S, "immediate shift value out of range");
858     return MatchOperand_ParseFail;
859   }
860 
861   Operands.push_back(SparcOperand::CreateImm(Expr, S, E));
862   return MatchOperand_Success;
863 }
864 
865 template <SparcAsmParser::TailRelocKind Kind>
866 OperandMatchResultTy
867 SparcAsmParser::parseTailRelocSym(OperandVector &Operands) {
868   SMLoc S = getLoc();
869   SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
870 
871   auto MatchesKind = [](SparcMCExpr::VariantKind VK) -> bool {
872     switch (Kind) {
873     case TailRelocKind::Load_GOT:
874       // Non-TLS relocations on ld (or ldx).
875       // ld [%rr + %rr], %rr, %rel(sym)
876       return VK == SparcMCExpr::VK_Sparc_GOTDATA_OP;
877     case TailRelocKind::Add_TLS:
878       // TLS relocations on add.
879       // add %rr, %rr, %rr, %rel(sym)
880       switch (VK) {
881       case SparcMCExpr::VK_Sparc_TLS_GD_ADD:
882       case SparcMCExpr::VK_Sparc_TLS_IE_ADD:
883       case SparcMCExpr::VK_Sparc_TLS_LDM_ADD:
884       case SparcMCExpr::VK_Sparc_TLS_LDO_ADD:
885         return true;
886       default:
887         return false;
888       }
889     case TailRelocKind::Load_TLS:
890       // TLS relocations on ld (or ldx).
891       // ld[x] %addr, %rr, %rel(sym)
892       switch (VK) {
893       case SparcMCExpr::VK_Sparc_TLS_IE_LD:
894       case SparcMCExpr::VK_Sparc_TLS_IE_LDX:
895         return true;
896       default:
897         return false;
898       }
899     case TailRelocKind::Call_TLS:
900       // TLS relocations on call.
901       // call sym, %rel(sym)
902       switch (VK) {
903       case SparcMCExpr::VK_Sparc_TLS_GD_CALL:
904       case SparcMCExpr::VK_Sparc_TLS_LDM_CALL:
905         return true;
906       default:
907         return false;
908       }
909     }
910     llvm_unreachable("Unhandled SparcAsmParser::TailRelocKind enum");
911   };
912 
913   if (getLexer().getKind() != AsmToken::Percent) {
914     Error(getLoc(), "expected '%' for operand modifier");
915     return MatchOperand_ParseFail;
916   }
917 
918   const AsmToken Tok = Parser.getTok();
919   getParser().Lex(); // Eat '%'
920 
921   if (getLexer().getKind() != AsmToken::Identifier) {
922     Error(getLoc(), "expected valid identifier for operand modifier");
923     return MatchOperand_ParseFail;
924   }
925 
926   StringRef Name = getParser().getTok().getIdentifier();
927   SparcMCExpr::VariantKind VK = SparcMCExpr::parseVariantKind(Name);
928   if (VK == SparcMCExpr::VK_Sparc_None) {
929     Error(getLoc(), "invalid operand modifier");
930     return MatchOperand_ParseFail;
931   }
932 
933   if (!MatchesKind(VK)) {
934     // Did not match the specified set of relocation types, put '%' back.
935     getLexer().UnLex(Tok);
936     return MatchOperand_NoMatch;
937   }
938 
939   Parser.Lex(); // Eat the identifier.
940   if (getLexer().getKind() != AsmToken::LParen) {
941     Error(getLoc(), "expected '('");
942     return MatchOperand_ParseFail;
943   }
944 
945   getParser().Lex(); // Eat '('
946   const MCExpr *SubExpr;
947   if (getParser().parseParenExpression(SubExpr, E)) {
948     return MatchOperand_ParseFail;
949   }
950 
951   const MCExpr *Val = adjustPICRelocation(VK, SubExpr);
952   Operands.push_back(SparcOperand::CreateImm(Val, S, E));
953   return MatchOperand_Success;
954 }
955 
956 OperandMatchResultTy SparcAsmParser::parseMembarTag(OperandVector &Operands) {
957   SMLoc S = Parser.getTok().getLoc();
958   const MCExpr *EVal;
959   int64_t ImmVal = 0;
960 
961   std::unique_ptr<SparcOperand> Mask;
962   if (parseSparcAsmOperand(Mask) == MatchOperand_Success) {
963     if (!Mask->isImm() || !Mask->getImm()->evaluateAsAbsolute(ImmVal) ||
964         ImmVal < 0 || ImmVal > 127) {
965       Error(S, "invalid membar mask number");
966       return MatchOperand_ParseFail;
967     }
968   }
969 
970   while (getLexer().getKind() == AsmToken::Hash) {
971     SMLoc TagStart = getLexer().getLoc();
972     Parser.Lex(); // Eat the '#'.
973     unsigned MaskVal = StringSwitch<unsigned>(Parser.getTok().getString())
974       .Case("LoadLoad", 0x1)
975       .Case("StoreLoad", 0x2)
976       .Case("LoadStore", 0x4)
977       .Case("StoreStore", 0x8)
978       .Case("Lookaside", 0x10)
979       .Case("MemIssue", 0x20)
980       .Case("Sync", 0x40)
981       .Default(0);
982 
983     Parser.Lex(); // Eat the identifier token.
984 
985     if (!MaskVal) {
986       Error(TagStart, "unknown membar tag");
987       return MatchOperand_ParseFail;
988     }
989 
990     ImmVal |= MaskVal;
991 
992     if (getLexer().getKind() == AsmToken::Pipe)
993       Parser.Lex(); // Eat the '|'.
994   }
995 
996   EVal = MCConstantExpr::create(ImmVal, getContext());
997   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
998   Operands.push_back(SparcOperand::CreateImm(EVal, S, E));
999   return MatchOperand_Success;
1000 }
1001 
1002 OperandMatchResultTy SparcAsmParser::parseCallTarget(OperandVector &Operands) {
1003   SMLoc S = Parser.getTok().getLoc();
1004   SMLoc E = SMLoc::getFromPointer(S.getPointer() - 1);
1005 
1006   switch (getLexer().getKind()) {
1007   default:
1008     return MatchOperand_NoMatch;
1009   case AsmToken::LParen:
1010   case AsmToken::Integer:
1011   case AsmToken::Identifier:
1012   case AsmToken::Dot:
1013     break;
1014   }
1015 
1016   const MCExpr *DestValue;
1017   if (getParser().parseExpression(DestValue))
1018     return MatchOperand_NoMatch;
1019 
1020   bool IsPic = getContext().getObjectFileInfo()->isPositionIndependent();
1021   SparcMCExpr::VariantKind Kind =
1022       IsPic ? SparcMCExpr::VK_Sparc_WPLT30 : SparcMCExpr::VK_Sparc_WDISP30;
1023 
1024   const MCExpr *DestExpr = SparcMCExpr::create(Kind, DestValue, getContext());
1025   Operands.push_back(SparcOperand::CreateImm(DestExpr, S, E));
1026   return MatchOperand_Success;
1027 }
1028 
1029 OperandMatchResultTy
1030 SparcAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
1031 
1032   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1033 
1034   // If there wasn't a custom match, try the generic matcher below. Otherwise,
1035   // there was a match, but an error occurred, in which case, just return that
1036   // the operand parsing failed.
1037   if (ResTy == MatchOperand_Success || ResTy == MatchOperand_ParseFail)
1038     return ResTy;
1039 
1040   if (getLexer().is(AsmToken::LBrac)) {
1041     // Memory operand
1042     Operands.push_back(SparcOperand::CreateToken("[",
1043                                                  Parser.getTok().getLoc()));
1044     Parser.Lex(); // Eat the [
1045 
1046     if (Mnemonic == "cas" || Mnemonic == "casx" || Mnemonic == "casa") {
1047       SMLoc S = Parser.getTok().getLoc();
1048       if (getLexer().getKind() != AsmToken::Percent)
1049         return MatchOperand_NoMatch;
1050       Parser.Lex(); // eat %
1051 
1052       MCRegister RegNo;
1053       unsigned RegKind;
1054       if (!matchRegisterName(Parser.getTok(), RegNo, RegKind))
1055         return MatchOperand_NoMatch;
1056 
1057       Parser.Lex(); // Eat the identifier token.
1058       SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer()-1);
1059       Operands.push_back(SparcOperand::CreateReg(RegNo, RegKind, S, E));
1060       ResTy = MatchOperand_Success;
1061     } else {
1062       ResTy = parseMEMOperand(Operands);
1063     }
1064 
1065     if (ResTy != MatchOperand_Success)
1066       return ResTy;
1067 
1068     if (!getLexer().is(AsmToken::RBrac))
1069       return MatchOperand_ParseFail;
1070 
1071     Operands.push_back(SparcOperand::CreateToken("]",
1072                                                  Parser.getTok().getLoc()));
1073     Parser.Lex(); // Eat the ]
1074 
1075     // Parse an optional address-space identifier after the address.
1076     if (getLexer().is(AsmToken::Integer)) {
1077       std::unique_ptr<SparcOperand> Op;
1078       ResTy = parseSparcAsmOperand(Op, false);
1079       if (ResTy != MatchOperand_Success || !Op)
1080         return MatchOperand_ParseFail;
1081       Operands.push_back(std::move(Op));
1082     }
1083     return MatchOperand_Success;
1084   }
1085 
1086   std::unique_ptr<SparcOperand> Op;
1087 
1088   ResTy = parseSparcAsmOperand(Op, (Mnemonic == "call"));
1089   if (ResTy != MatchOperand_Success || !Op)
1090     return MatchOperand_ParseFail;
1091 
1092   // Push the parsed operand into the list of operands
1093   Operands.push_back(std::move(Op));
1094 
1095   return MatchOperand_Success;
1096 }
1097 
1098 OperandMatchResultTy
1099 SparcAsmParser::parseSparcAsmOperand(std::unique_ptr<SparcOperand> &Op,
1100                                      bool isCall) {
1101   SMLoc S = Parser.getTok().getLoc();
1102   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1103   const MCExpr *EVal;
1104 
1105   Op = nullptr;
1106   switch (getLexer().getKind()) {
1107   default:  break;
1108 
1109   case AsmToken::Percent: {
1110     Parser.Lex(); // Eat the '%'.
1111     MCRegister RegNo;
1112     unsigned RegKind;
1113     if (matchRegisterName(Parser.getTok(), RegNo, RegKind)) {
1114       StringRef name = Parser.getTok().getString();
1115       Parser.Lex(); // Eat the identifier token.
1116       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1117       switch (RegNo) {
1118       default:
1119         Op = SparcOperand::CreateReg(RegNo, RegKind, S, E);
1120         break;
1121       case Sparc::PSR:
1122         Op = SparcOperand::CreateToken("%psr", S);
1123         break;
1124       case Sparc::FSR:
1125         Op = SparcOperand::CreateToken("%fsr", S);
1126         break;
1127       case Sparc::FQ:
1128         Op = SparcOperand::CreateToken("%fq", S);
1129         break;
1130       case Sparc::CPSR:
1131         Op = SparcOperand::CreateToken("%csr", S);
1132         break;
1133       case Sparc::CPQ:
1134         Op = SparcOperand::CreateToken("%cq", S);
1135         break;
1136       case Sparc::WIM:
1137         Op = SparcOperand::CreateToken("%wim", S);
1138         break;
1139       case Sparc::TBR:
1140         Op = SparcOperand::CreateToken("%tbr", S);
1141         break;
1142       case Sparc::PC:
1143         Op = SparcOperand::CreateToken("%pc", S);
1144         break;
1145       case Sparc::ICC:
1146         if (name == "xcc")
1147           Op = SparcOperand::CreateToken("%xcc", S);
1148         else
1149           Op = SparcOperand::CreateToken("%icc", S);
1150         break;
1151       }
1152       break;
1153     }
1154     if (matchSparcAsmModifiers(EVal, E)) {
1155       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1156       Op = SparcOperand::CreateImm(EVal, S, E);
1157     }
1158     break;
1159   }
1160 
1161   case AsmToken::Plus:
1162   case AsmToken::Minus:
1163   case AsmToken::Integer:
1164   case AsmToken::LParen:
1165   case AsmToken::Dot:
1166   case AsmToken::Identifier:
1167     if (getParser().parseExpression(EVal, E))
1168       break;
1169 
1170     int64_t Res;
1171     if (!EVal->evaluateAsAbsolute(Res)) {
1172       SparcMCExpr::VariantKind Kind = SparcMCExpr::VK_Sparc_13;
1173 
1174       if (getContext().getObjectFileInfo()->isPositionIndependent()) {
1175         if (isCall)
1176           Kind = SparcMCExpr::VK_Sparc_WPLT30;
1177         else
1178           Kind = SparcMCExpr::VK_Sparc_GOT13;
1179       }
1180       EVal = SparcMCExpr::create(Kind, EVal, getContext());
1181     }
1182     Op = SparcOperand::CreateImm(EVal, S, E);
1183     break;
1184   }
1185   return (Op) ? MatchOperand_Success : MatchOperand_ParseFail;
1186 }
1187 
1188 OperandMatchResultTy
1189 SparcAsmParser::parseBranchModifiers(OperandVector &Operands) {
1190   // parse (,a|,pn|,pt)+
1191 
1192   while (getLexer().is(AsmToken::Comma)) {
1193     Parser.Lex(); // Eat the comma
1194 
1195     if (!getLexer().is(AsmToken::Identifier))
1196       return MatchOperand_ParseFail;
1197     StringRef modName = Parser.getTok().getString();
1198     if (modName == "a" || modName == "pn" || modName == "pt") {
1199       Operands.push_back(SparcOperand::CreateToken(modName,
1200                                                    Parser.getTok().getLoc()));
1201       Parser.Lex(); // eat the identifier.
1202     }
1203   }
1204   return MatchOperand_Success;
1205 }
1206 
1207 bool SparcAsmParser::matchRegisterName(const AsmToken &Tok, MCRegister &RegNo,
1208                                        unsigned &RegKind) {
1209   int64_t intVal = 0;
1210   RegNo = 0;
1211   RegKind = SparcOperand::rk_None;
1212   if (Tok.is(AsmToken::Identifier)) {
1213     StringRef name = Tok.getString();
1214 
1215     // %fp
1216     if (name.equals("fp")) {
1217       RegNo = Sparc::I6;
1218       RegKind = SparcOperand::rk_IntReg;
1219       return true;
1220     }
1221     // %sp
1222     if (name.equals("sp")) {
1223       RegNo = Sparc::O6;
1224       RegKind = SparcOperand::rk_IntReg;
1225       return true;
1226     }
1227 
1228     if (name.equals("y")) {
1229       RegNo = Sparc::Y;
1230       RegKind = SparcOperand::rk_Special;
1231       return true;
1232     }
1233 
1234     if (name.substr(0, 3).equals_insensitive("asr") &&
1235         !name.substr(3).getAsInteger(10, intVal) && intVal > 0 && intVal < 32) {
1236       RegNo = ASRRegs[intVal];
1237       RegKind = SparcOperand::rk_Special;
1238       return true;
1239     }
1240 
1241     // %fprs is an alias of %asr6.
1242     if (name.equals("fprs")) {
1243       RegNo = ASRRegs[6];
1244       RegKind = SparcOperand::rk_Special;
1245       return true;
1246     }
1247 
1248     if (name.equals("icc")) {
1249       RegNo = Sparc::ICC;
1250       RegKind = SparcOperand::rk_Special;
1251       return true;
1252     }
1253 
1254     if (name.equals("psr")) {
1255       RegNo = Sparc::PSR;
1256       RegKind = SparcOperand::rk_Special;
1257       return true;
1258     }
1259 
1260     if (name.equals("fsr")) {
1261       RegNo = Sparc::FSR;
1262       RegKind = SparcOperand::rk_Special;
1263       return true;
1264     }
1265 
1266     if (name.equals("fq")) {
1267       RegNo = Sparc::FQ;
1268       RegKind = SparcOperand::rk_Special;
1269       return true;
1270     }
1271 
1272     if (name.equals("csr")) {
1273       RegNo = Sparc::CPSR;
1274       RegKind = SparcOperand::rk_Special;
1275       return true;
1276     }
1277 
1278     if (name.equals("cq")) {
1279       RegNo = Sparc::CPQ;
1280       RegKind = SparcOperand::rk_Special;
1281       return true;
1282     }
1283 
1284     if (name.equals("wim")) {
1285       RegNo = Sparc::WIM;
1286       RegKind = SparcOperand::rk_Special;
1287       return true;
1288     }
1289 
1290     if (name.equals("tbr")) {
1291       RegNo = Sparc::TBR;
1292       RegKind = SparcOperand::rk_Special;
1293       return true;
1294     }
1295 
1296     if (name.equals("xcc")) {
1297       // FIXME:: check 64bit.
1298       RegNo = Sparc::ICC;
1299       RegKind = SparcOperand::rk_Special;
1300       return true;
1301     }
1302 
1303     // %fcc0 - %fcc3
1304     if (name.substr(0, 3).equals_insensitive("fcc") &&
1305         !name.substr(3).getAsInteger(10, intVal) && intVal < 4) {
1306       // FIXME: check 64bit and  handle %fcc1 - %fcc3
1307       RegNo = Sparc::FCC0 + intVal;
1308       RegKind = SparcOperand::rk_Special;
1309       return true;
1310     }
1311 
1312     // %g0 - %g7
1313     if (name.substr(0, 1).equals_insensitive("g") &&
1314         !name.substr(1).getAsInteger(10, intVal) && intVal < 8) {
1315       RegNo = IntRegs[intVal];
1316       RegKind = SparcOperand::rk_IntReg;
1317       return true;
1318     }
1319     // %o0 - %o7
1320     if (name.substr(0, 1).equals_insensitive("o") &&
1321         !name.substr(1).getAsInteger(10, intVal) && intVal < 8) {
1322       RegNo = IntRegs[8 + intVal];
1323       RegKind = SparcOperand::rk_IntReg;
1324       return true;
1325     }
1326     if (name.substr(0, 1).equals_insensitive("l") &&
1327         !name.substr(1).getAsInteger(10, intVal) && intVal < 8) {
1328       RegNo = IntRegs[16 + intVal];
1329       RegKind = SparcOperand::rk_IntReg;
1330       return true;
1331     }
1332     if (name.substr(0, 1).equals_insensitive("i") &&
1333         !name.substr(1).getAsInteger(10, intVal) && intVal < 8) {
1334       RegNo = IntRegs[24 + intVal];
1335       RegKind = SparcOperand::rk_IntReg;
1336       return true;
1337     }
1338     // %f0 - %f31
1339     if (name.substr(0, 1).equals_insensitive("f") &&
1340         !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 32) {
1341       RegNo = FloatRegs[intVal];
1342       RegKind = SparcOperand::rk_FloatReg;
1343       return true;
1344     }
1345     // %f32 - %f62
1346     if (name.substr(0, 1).equals_insensitive("f") &&
1347         !name.substr(1, 2).getAsInteger(10, intVal) && intVal >= 32 &&
1348         intVal <= 62 && (intVal % 2 == 0)) {
1349       // FIXME: Check V9
1350       RegNo = DoubleRegs[intVal/2];
1351       RegKind = SparcOperand::rk_DoubleReg;
1352       return true;
1353     }
1354 
1355     // %r0 - %r31
1356     if (name.substr(0, 1).equals_insensitive("r") &&
1357         !name.substr(1, 2).getAsInteger(10, intVal) && intVal < 31) {
1358       RegNo = IntRegs[intVal];
1359       RegKind = SparcOperand::rk_IntReg;
1360       return true;
1361     }
1362 
1363     // %c0 - %c31
1364     if (name.substr(0, 1).equals_insensitive("c") &&
1365         !name.substr(1).getAsInteger(10, intVal) && intVal < 32) {
1366       RegNo = CoprocRegs[intVal];
1367       RegKind = SparcOperand::rk_CoprocReg;
1368       return true;
1369     }
1370 
1371     if (name.equals("tpc")) {
1372       RegNo = Sparc::TPC;
1373       RegKind = SparcOperand::rk_Special;
1374       return true;
1375     }
1376     if (name.equals("tnpc")) {
1377       RegNo = Sparc::TNPC;
1378       RegKind = SparcOperand::rk_Special;
1379       return true;
1380     }
1381     if (name.equals("tstate")) {
1382       RegNo = Sparc::TSTATE;
1383       RegKind = SparcOperand::rk_Special;
1384       return true;
1385     }
1386     if (name.equals("tt")) {
1387       RegNo = Sparc::TT;
1388       RegKind = SparcOperand::rk_Special;
1389       return true;
1390     }
1391     if (name.equals("tick")) {
1392       RegNo = Sparc::TICK;
1393       RegKind = SparcOperand::rk_Special;
1394       return true;
1395     }
1396     if (name.equals("tba")) {
1397       RegNo = Sparc::TBA;
1398       RegKind = SparcOperand::rk_Special;
1399       return true;
1400     }
1401     if (name.equals("pstate")) {
1402       RegNo = Sparc::PSTATE;
1403       RegKind = SparcOperand::rk_Special;
1404       return true;
1405     }
1406     if (name.equals("tl")) {
1407       RegNo = Sparc::TL;
1408       RegKind = SparcOperand::rk_Special;
1409       return true;
1410     }
1411     if (name.equals("pil")) {
1412       RegNo = Sparc::PIL;
1413       RegKind = SparcOperand::rk_Special;
1414       return true;
1415     }
1416     if (name.equals("cwp")) {
1417       RegNo = Sparc::CWP;
1418       RegKind = SparcOperand::rk_Special;
1419       return true;
1420     }
1421     if (name.equals("cansave")) {
1422       RegNo = Sparc::CANSAVE;
1423       RegKind = SparcOperand::rk_Special;
1424       return true;
1425     }
1426     if (name.equals("canrestore")) {
1427       RegNo = Sparc::CANRESTORE;
1428       RegKind = SparcOperand::rk_Special;
1429       return true;
1430     }
1431     if (name.equals("cleanwin")) {
1432       RegNo = Sparc::CLEANWIN;
1433       RegKind = SparcOperand::rk_Special;
1434       return true;
1435     }
1436     if (name.equals("otherwin")) {
1437       RegNo = Sparc::OTHERWIN;
1438       RegKind = SparcOperand::rk_Special;
1439       return true;
1440     }
1441     if (name.equals("wstate")) {
1442       RegNo = Sparc::WSTATE;
1443       RegKind = SparcOperand::rk_Special;
1444       return true;
1445     }
1446     if (name.equals("pc")) {
1447       RegNo = Sparc::PC;
1448       RegKind = SparcOperand::rk_Special;
1449       return true;
1450     }
1451   }
1452   return false;
1453 }
1454 
1455 // Determine if an expression contains a reference to the symbol
1456 // "_GLOBAL_OFFSET_TABLE_".
1457 static bool hasGOTReference(const MCExpr *Expr) {
1458   switch (Expr->getKind()) {
1459   case MCExpr::Target:
1460     if (const SparcMCExpr *SE = dyn_cast<SparcMCExpr>(Expr))
1461       return hasGOTReference(SE->getSubExpr());
1462     break;
1463 
1464   case MCExpr::Constant:
1465     break;
1466 
1467   case MCExpr::Binary: {
1468     const MCBinaryExpr *BE = cast<MCBinaryExpr>(Expr);
1469     return hasGOTReference(BE->getLHS()) || hasGOTReference(BE->getRHS());
1470   }
1471 
1472   case MCExpr::SymbolRef: {
1473     const MCSymbolRefExpr &SymRef = *cast<MCSymbolRefExpr>(Expr);
1474     return (SymRef.getSymbol().getName() == "_GLOBAL_OFFSET_TABLE_");
1475   }
1476 
1477   case MCExpr::Unary:
1478     return hasGOTReference(cast<MCUnaryExpr>(Expr)->getSubExpr());
1479   }
1480   return false;
1481 }
1482 
1483 const SparcMCExpr *
1484 SparcAsmParser::adjustPICRelocation(SparcMCExpr::VariantKind VK,
1485                                     const MCExpr *subExpr) {
1486   // When in PIC mode, "%lo(...)" and "%hi(...)" behave differently.
1487   // If the expression refers contains _GLOBAL_OFFSET_TABLE, it is
1488   // actually a %pc10 or %pc22 relocation. Otherwise, they are interpreted
1489   // as %got10 or %got22 relocation.
1490 
1491   if (getContext().getObjectFileInfo()->isPositionIndependent()) {
1492     switch(VK) {
1493     default: break;
1494     case SparcMCExpr::VK_Sparc_LO:
1495       VK = (hasGOTReference(subExpr) ? SparcMCExpr::VK_Sparc_PC10
1496                                      : SparcMCExpr::VK_Sparc_GOT10);
1497       break;
1498     case SparcMCExpr::VK_Sparc_HI:
1499       VK = (hasGOTReference(subExpr) ? SparcMCExpr::VK_Sparc_PC22
1500                                      : SparcMCExpr::VK_Sparc_GOT22);
1501       break;
1502     }
1503   }
1504 
1505   return SparcMCExpr::create(VK, subExpr, getContext());
1506 }
1507 
1508 bool SparcAsmParser::matchSparcAsmModifiers(const MCExpr *&EVal,
1509                                             SMLoc &EndLoc) {
1510   AsmToken Tok = Parser.getTok();
1511   if (!Tok.is(AsmToken::Identifier))
1512     return false;
1513 
1514   StringRef name = Tok.getString();
1515 
1516   SparcMCExpr::VariantKind VK = SparcMCExpr::parseVariantKind(name);
1517   switch (VK) {
1518   case SparcMCExpr::VK_Sparc_None:
1519     Error(getLoc(), "invalid operand modifier");
1520     return false;
1521 
1522   case SparcMCExpr::VK_Sparc_GOTDATA_OP:
1523   case SparcMCExpr::VK_Sparc_TLS_GD_ADD:
1524   case SparcMCExpr::VK_Sparc_TLS_GD_CALL:
1525   case SparcMCExpr::VK_Sparc_TLS_IE_ADD:
1526   case SparcMCExpr::VK_Sparc_TLS_IE_LD:
1527   case SparcMCExpr::VK_Sparc_TLS_IE_LDX:
1528   case SparcMCExpr::VK_Sparc_TLS_LDM_ADD:
1529   case SparcMCExpr::VK_Sparc_TLS_LDM_CALL:
1530   case SparcMCExpr::VK_Sparc_TLS_LDO_ADD:
1531     // These are special-cased at tablegen level.
1532     return false;
1533 
1534   default:
1535     break;
1536   }
1537 
1538   Parser.Lex(); // Eat the identifier.
1539   if (Parser.getTok().getKind() != AsmToken::LParen)
1540     return false;
1541 
1542   Parser.Lex(); // Eat the LParen token.
1543   const MCExpr *subExpr;
1544   if (Parser.parseParenExpression(subExpr, EndLoc))
1545     return false;
1546 
1547   EVal = adjustPICRelocation(VK, subExpr);
1548   return true;
1549 }
1550 
1551 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeSparcAsmParser() {
1552   RegisterMCAsmParser<SparcAsmParser> A(getTheSparcTarget());
1553   RegisterMCAsmParser<SparcAsmParser> B(getTheSparcV9Target());
1554   RegisterMCAsmParser<SparcAsmParser> C(getTheSparcelTarget());
1555 }
1556 
1557 #define GET_REGISTER_MATCHER
1558 #define GET_MATCHER_IMPLEMENTATION
1559 #include "SparcGenAsmMatcher.inc"
1560 
1561 unsigned SparcAsmParser::validateTargetOperandClass(MCParsedAsmOperand &GOp,
1562                                                     unsigned Kind) {
1563   SparcOperand &Op = (SparcOperand &)GOp;
1564   if (Op.isFloatOrDoubleReg()) {
1565     switch (Kind) {
1566     default: break;
1567     case MCK_DFPRegs:
1568       if (!Op.isFloatReg() || SparcOperand::MorphToDoubleReg(Op))
1569         return MCTargetAsmParser::Match_Success;
1570       break;
1571     case MCK_QFPRegs:
1572       if (SparcOperand::MorphToQuadReg(Op))
1573         return MCTargetAsmParser::Match_Success;
1574       break;
1575     }
1576   }
1577   if (Op.isIntReg() && Kind == MCK_IntPair) {
1578     if (SparcOperand::MorphToIntPairReg(Op))
1579       return MCTargetAsmParser::Match_Success;
1580   }
1581   if (Op.isCoprocReg() && Kind == MCK_CoprocPair) {
1582      if (SparcOperand::MorphToCoprocPairReg(Op))
1583        return MCTargetAsmParser::Match_Success;
1584    }
1585   return Match_InvalidOperand;
1586 }
1587