Unify duplicated functions.
[oota-llvm.git] / lib / Target / Mips / AsmParser / MipsAsmParser.cpp
1 //===-- MipsAsmParser.cpp - Parse Mips 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/MipsMCTargetDesc.h"
11 #include "MipsRegisterInfo.h"
12 #include "MipsTargetStreamer.h"
13 #include "llvm/ADT/APInt.h"
14 #include "llvm/ADT/StringSwitch.h"
15 #include "llvm/MC/MCContext.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCInst.h"
18 #include "llvm/MC/MCParser/MCAsmLexer.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCSubtargetInfo.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/MC/MCTargetAsmParser.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/TargetRegistry.h"
26
27 using namespace llvm;
28
29 namespace llvm {
30 class MCInstrInfo;
31 }
32
33 namespace {
34 class MipsAssemblerOptions {
35 public:
36   MipsAssemblerOptions() : aTReg(1), reorder(true), macro(true) {}
37
38   unsigned getATRegNum() { return aTReg; }
39   bool setATReg(unsigned Reg);
40
41   bool isReorder() { return reorder; }
42   void setReorder() { reorder = true; }
43   void setNoreorder() { reorder = false; }
44
45   bool isMacro() { return macro; }
46   void setMacro() { macro = true; }
47   void setNomacro() { macro = false; }
48
49 private:
50   unsigned aTReg;
51   bool reorder;
52   bool macro;
53 };
54 }
55
56 namespace {
57 class MipsAsmParser : public MCTargetAsmParser {
58
59   MipsTargetStreamer &getTargetStreamer() {
60     MCTargetStreamer &TS = *Parser.getStreamer().getTargetStreamer();
61     return static_cast<MipsTargetStreamer &>(TS);
62   }
63
64   MCSubtargetInfo &STI;
65   MCAsmParser &Parser;
66   MipsAssemblerOptions Options;
67   bool hasConsumedDollar;
68
69 #define GET_ASSEMBLER_HEADER
70 #include "MipsGenAsmMatcher.inc"
71
72   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
73                                SmallVectorImpl<MCParsedAsmOperand *> &Operands,
74                                MCStreamer &Out, unsigned &ErrorInfo,
75                                bool MatchingInlineAsm);
76
77   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
78
79   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
80                         SMLoc NameLoc,
81                         SmallVectorImpl<MCParsedAsmOperand *> &Operands);
82
83   bool ParseDirective(AsmToken DirectiveID);
84
85   MipsAsmParser::OperandMatchResultTy
86   parseRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands, int RegKind);
87
88   MipsAsmParser::OperandMatchResultTy
89   parseMSARegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands, int RegKind);
90
91   MipsAsmParser::OperandMatchResultTy
92   parseMSACtrlRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
93                    int RegKind);
94
95   MipsAsmParser::OperandMatchResultTy
96   parseMemOperand(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
97
98   bool parsePtrReg(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
99                    int RegKind);
100
101   MipsAsmParser::OperandMatchResultTy
102   parsePtrReg(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
103
104   MipsAsmParser::OperandMatchResultTy
105   parseGPR32(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
106
107   MipsAsmParser::OperandMatchResultTy
108   parseGPR64(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
109
110   MipsAsmParser::OperandMatchResultTy
111   parseHWRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
112
113   MipsAsmParser::OperandMatchResultTy
114   parseCCRRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
115
116   MipsAsmParser::OperandMatchResultTy
117   parseAFGR64Regs(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
118
119   MipsAsmParser::OperandMatchResultTy
120   parseFGR64Regs(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
121
122   MipsAsmParser::OperandMatchResultTy
123   parseFGR32Regs(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
124
125   MipsAsmParser::OperandMatchResultTy
126   parseFGRH32Regs(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
127
128   MipsAsmParser::OperandMatchResultTy
129   parseFCCRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
130
131   MipsAsmParser::OperandMatchResultTy
132   parseACC64DSP(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
133
134   MipsAsmParser::OperandMatchResultTy
135   parseLO32DSP(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
136
137   MipsAsmParser::OperandMatchResultTy
138   parseHI32DSP(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
139
140   MipsAsmParser::OperandMatchResultTy
141   parseCOP2(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
142
143   MipsAsmParser::OperandMatchResultTy
144   parseMSA128BRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
145
146   MipsAsmParser::OperandMatchResultTy
147   parseMSA128HRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
148
149   MipsAsmParser::OperandMatchResultTy
150   parseMSA128WRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
151
152   MipsAsmParser::OperandMatchResultTy
153   parseMSA128DRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
154
155   MipsAsmParser::OperandMatchResultTy
156   parseMSA128CtrlRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
157
158   MipsAsmParser::OperandMatchResultTy
159   parseInvNum(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
160
161   MipsAsmParser::OperandMatchResultTy
162   parseLSAImm(SmallVectorImpl<MCParsedAsmOperand *> &Operands);
163
164   bool searchSymbolAlias(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
165                          unsigned RegKind);
166
167   bool ParseOperand(SmallVectorImpl<MCParsedAsmOperand *> &,
168                     StringRef Mnemonic);
169
170   int tryParseRegister(bool is64BitReg);
171
172   bool tryParseRegisterOperand(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
173                                bool is64BitReg);
174
175   bool needsExpansion(MCInst &Inst);
176
177   void expandInstruction(MCInst &Inst, SMLoc IDLoc,
178                          SmallVectorImpl<MCInst> &Instructions);
179   void expandLoadImm(MCInst &Inst, SMLoc IDLoc,
180                      SmallVectorImpl<MCInst> &Instructions);
181   void expandLoadAddressImm(MCInst &Inst, SMLoc IDLoc,
182                             SmallVectorImpl<MCInst> &Instructions);
183   void expandLoadAddressReg(MCInst &Inst, SMLoc IDLoc,
184                             SmallVectorImpl<MCInst> &Instructions);
185   void expandMemInst(MCInst &Inst, SMLoc IDLoc,
186                      SmallVectorImpl<MCInst> &Instructions, bool isLoad,
187                      bool isImmOpnd);
188   bool reportParseError(StringRef ErrorMsg);
189
190   bool parseMemOffset(const MCExpr *&Res, bool isParenExpr);
191   bool parseRelocOperand(const MCExpr *&Res);
192
193   const MCExpr *evaluateRelocExpr(const MCExpr *Expr, StringRef RelocStr);
194
195   bool isEvaluated(const MCExpr *Expr);
196   bool parseDirectiveSet();
197   bool parseDirectiveMipsHackELFFlags();
198   bool parseDirectiveOption();
199
200   bool parseSetAtDirective();
201   bool parseSetNoAtDirective();
202   bool parseSetMacroDirective();
203   bool parseSetNoMacroDirective();
204   bool parseSetReorderDirective();
205   bool parseSetNoReorderDirective();
206   bool parseSetMips16Directive();
207   bool parseSetNoMips16Directive();
208
209   bool parseSetAssignment();
210
211   bool parseDirectiveWord(unsigned Size, SMLoc L);
212   bool parseDirectiveGpWord();
213
214   MCSymbolRefExpr::VariantKind getVariantKind(StringRef Symbol);
215
216   bool isMips64() const {
217     return (STI.getFeatureBits() & Mips::FeatureMips64) != 0;
218   }
219
220   bool isFP64() const {
221     return (STI.getFeatureBits() & Mips::FeatureFP64Bit) != 0;
222   }
223
224   bool isN64() const { return STI.getFeatureBits() & Mips::FeatureN64; }
225
226   bool isMicroMips() const {
227     return STI.getFeatureBits() & Mips::FeatureMicroMips;
228   }
229
230   int matchRegisterName(StringRef Symbol, bool is64BitReg);
231
232   int matchCPURegisterName(StringRef Symbol);
233
234   int matchRegisterByNumber(unsigned RegNum, unsigned RegClass);
235
236   int matchFPURegisterName(StringRef Name);
237
238   int matchFCCRegisterName(StringRef Name);
239
240   int matchACRegisterName(StringRef Name);
241
242   int matchMSA128RegisterName(StringRef Name);
243
244   int matchMSA128CtrlRegisterName(StringRef Name);
245
246   int regKindToRegClass(int RegKind);
247
248   unsigned getReg(int RC, int RegNo);
249
250   int getATReg();
251
252   bool processInstruction(MCInst &Inst, SMLoc IDLoc,
253                           SmallVectorImpl<MCInst> &Instructions);
254
255   // Helper function that checks if the value of a vector index is within the
256   // boundaries of accepted values for each RegisterKind
257   // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
258   bool validateMSAIndex(int Val, int RegKind);
259
260 public:
261   MipsAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
262                 const MCInstrInfo &MII)
263       : MCTargetAsmParser(), STI(sti), Parser(parser),
264         hasConsumedDollar(false) {
265     // Initialize the set of available features.
266     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
267   }
268
269   MCAsmParser &getParser() const { return Parser; }
270   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
271 };
272 }
273
274 namespace {
275
276 /// MipsOperand - Instances of this class represent a parsed Mips machine
277 /// instruction.
278 class MipsOperand : public MCParsedAsmOperand {
279
280 public:
281   enum RegisterKind {
282     Kind_None,
283     Kind_GPR32,
284     Kind_GPR64,
285     Kind_HWRegs,
286     Kind_FGR32Regs,
287     Kind_FGRH32Regs,
288     Kind_FGR64Regs,
289     Kind_AFGR64Regs,
290     Kind_CCRRegs,
291     Kind_FCCRegs,
292     Kind_ACC64DSP,
293     Kind_LO32DSP,
294     Kind_HI32DSP,
295     Kind_COP2,
296     Kind_MSA128BRegs,
297     Kind_MSA128HRegs,
298     Kind_MSA128WRegs,
299     Kind_MSA128DRegs,
300     Kind_MSA128CtrlRegs
301   };
302
303 private:
304   enum KindTy {
305     k_CondCode,
306     k_CoprocNum,
307     k_Immediate,
308     k_Memory,
309     k_PostIndexRegister,
310     k_Register,
311     k_PtrReg,
312     k_Token,
313     k_LSAImm
314   } Kind;
315
316   MipsOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
317
318   struct Token {
319     const char *Data;
320     unsigned Length;
321   };
322
323   struct RegOp {
324     unsigned RegNum;
325     RegisterKind Kind;
326   };
327
328   struct ImmOp {
329     const MCExpr *Val;
330   };
331
332   struct MemOp {
333     unsigned Base;
334     const MCExpr *Off;
335   };
336
337   union {
338     struct Token Tok;
339     struct RegOp Reg;
340     struct ImmOp Imm;
341     struct MemOp Mem;
342   };
343
344   SMLoc StartLoc, EndLoc;
345
346 public:
347   void addRegOperands(MCInst &Inst, unsigned N) const {
348     assert(N == 1 && "Invalid number of operands!");
349     Inst.addOperand(MCOperand::CreateReg(getReg()));
350   }
351
352   void addPtrRegOperands(MCInst &Inst, unsigned N) const {
353     assert(N == 1 && "Invalid number of operands!");
354     Inst.addOperand(MCOperand::CreateReg(getPtrReg()));
355   }
356
357   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
358     // Add as immediate when possible.  Null MCExpr = 0.
359     if (Expr == 0)
360       Inst.addOperand(MCOperand::CreateImm(0));
361     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
362       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
363     else
364       Inst.addOperand(MCOperand::CreateExpr(Expr));
365   }
366
367   void addImmOperands(MCInst &Inst, unsigned N) const {
368     assert(N == 1 && "Invalid number of operands!");
369     const MCExpr *Expr = getImm();
370     addExpr(Inst, Expr);
371   }
372
373   void addMemOperands(MCInst &Inst, unsigned N) const {
374     assert(N == 2 && "Invalid number of operands!");
375
376     Inst.addOperand(MCOperand::CreateReg(getMemBase()));
377
378     const MCExpr *Expr = getMemOff();
379     addExpr(Inst, Expr);
380   }
381
382   bool isReg() const { return Kind == k_Register; }
383   bool isImm() const { return Kind == k_Immediate; }
384   bool isToken() const { return Kind == k_Token; }
385   bool isMem() const { return Kind == k_Memory; }
386   bool isPtrReg() const { return Kind == k_PtrReg; }
387   bool isInvNum() const { return Kind == k_Immediate; }
388   bool isLSAImm() const { return Kind == k_LSAImm; }
389
390   StringRef getToken() const {
391     assert(Kind == k_Token && "Invalid access!");
392     return StringRef(Tok.Data, Tok.Length);
393   }
394
395   unsigned getReg() const {
396     assert((Kind == k_Register) && "Invalid access!");
397     return Reg.RegNum;
398   }
399
400   unsigned getPtrReg() const {
401     assert((Kind == k_PtrReg) && "Invalid access!");
402     return Reg.RegNum;
403   }
404
405   void setRegKind(RegisterKind RegKind) {
406     assert((Kind == k_Register || Kind == k_PtrReg) && "Invalid access!");
407     Reg.Kind = RegKind;
408   }
409
410   const MCExpr *getImm() const {
411     assert((Kind == k_Immediate || Kind == k_LSAImm) && "Invalid access!");
412     return Imm.Val;
413   }
414
415   unsigned getMemBase() const {
416     assert((Kind == k_Memory) && "Invalid access!");
417     return Mem.Base;
418   }
419
420   const MCExpr *getMemOff() const {
421     assert((Kind == k_Memory) && "Invalid access!");
422     return Mem.Off;
423   }
424
425   static MipsOperand *CreateToken(StringRef Str, SMLoc S) {
426     MipsOperand *Op = new MipsOperand(k_Token);
427     Op->Tok.Data = Str.data();
428     Op->Tok.Length = Str.size();
429     Op->StartLoc = S;
430     Op->EndLoc = S;
431     return Op;
432   }
433
434   static MipsOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
435     MipsOperand *Op = new MipsOperand(k_Register);
436     Op->Reg.RegNum = RegNum;
437     Op->StartLoc = S;
438     Op->EndLoc = E;
439     return Op;
440   }
441
442   static MipsOperand *CreatePtrReg(unsigned RegNum, SMLoc S, SMLoc E) {
443     MipsOperand *Op = new MipsOperand(k_PtrReg);
444     Op->Reg.RegNum = RegNum;
445     Op->StartLoc = S;
446     Op->EndLoc = E;
447     return Op;
448   }
449
450   static MipsOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
451     MipsOperand *Op = new MipsOperand(k_Immediate);
452     Op->Imm.Val = Val;
453     Op->StartLoc = S;
454     Op->EndLoc = E;
455     return Op;
456   }
457
458   static MipsOperand *CreateLSAImm(const MCExpr *Val, SMLoc S, SMLoc E) {
459     MipsOperand *Op = new MipsOperand(k_LSAImm);
460     Op->Imm.Val = Val;
461     Op->StartLoc = S;
462     Op->EndLoc = E;
463     return Op;
464   }
465
466   static MipsOperand *CreateMem(unsigned Base, const MCExpr *Off, SMLoc S,
467                                 SMLoc E) {
468     MipsOperand *Op = new MipsOperand(k_Memory);
469     Op->Mem.Base = Base;
470     Op->Mem.Off = Off;
471     Op->StartLoc = S;
472     Op->EndLoc = E;
473     return Op;
474   }
475
476   bool isGPR32Asm() const {
477     return Kind == k_Register && Reg.Kind == Kind_GPR32;
478   }
479   void addRegAsmOperands(MCInst &Inst, unsigned N) const {
480     Inst.addOperand(MCOperand::CreateReg(Reg.RegNum));
481   }
482
483   bool isGPR64Asm() const {
484     return Kind == k_Register && Reg.Kind == Kind_GPR64;
485   }
486
487   bool isHWRegsAsm() const {
488     assert((Kind == k_Register) && "Invalid access!");
489     return Reg.Kind == Kind_HWRegs;
490   }
491
492   bool isCCRAsm() const {
493     assert((Kind == k_Register) && "Invalid access!");
494     return Reg.Kind == Kind_CCRRegs;
495   }
496
497   bool isAFGR64Asm() const {
498     return Kind == k_Register && Reg.Kind == Kind_AFGR64Regs;
499   }
500
501   bool isFGR64Asm() const {
502     return Kind == k_Register && Reg.Kind == Kind_FGR64Regs;
503   }
504
505   bool isFGR32Asm() const {
506     return (Kind == k_Register) && Reg.Kind == Kind_FGR32Regs;
507   }
508
509   bool isFGRH32Asm() const {
510     return (Kind == k_Register) && Reg.Kind == Kind_FGRH32Regs;
511   }
512
513   bool isFCCRegsAsm() const {
514     return (Kind == k_Register) && Reg.Kind == Kind_FCCRegs;
515   }
516
517   bool isACC64DSPAsm() const {
518     return Kind == k_Register && Reg.Kind == Kind_ACC64DSP;
519   }
520
521   bool isLO32DSPAsm() const {
522     return Kind == k_Register && Reg.Kind == Kind_LO32DSP;
523   }
524
525   bool isHI32DSPAsm() const {
526     return Kind == k_Register && Reg.Kind == Kind_HI32DSP;
527   }
528
529   bool isCOP2Asm() const { return Kind == k_Register && Reg.Kind == Kind_COP2; }
530
531   bool isMSA128BAsm() const {
532     return Kind == k_Register && Reg.Kind == Kind_MSA128BRegs;
533   }
534
535   bool isMSA128HAsm() const {
536     return Kind == k_Register && Reg.Kind == Kind_MSA128HRegs;
537   }
538
539   bool isMSA128WAsm() const {
540     return Kind == k_Register && Reg.Kind == Kind_MSA128WRegs;
541   }
542
543   bool isMSA128DAsm() const {
544     return Kind == k_Register && Reg.Kind == Kind_MSA128DRegs;
545   }
546
547   bool isMSA128CRAsm() const {
548     return Kind == k_Register && Reg.Kind == Kind_MSA128CtrlRegs;
549   }
550
551   /// getStartLoc - Get the location of the first token of this operand.
552   SMLoc getStartLoc() const { return StartLoc; }
553   /// getEndLoc - Get the location of the last token of this operand.
554   SMLoc getEndLoc() const { return EndLoc; }
555
556   virtual void print(raw_ostream &OS) const {
557     llvm_unreachable("unimplemented!");
558   }
559 }; // class MipsOperand
560 } // namespace
561
562 namespace llvm {
563 extern const MCInstrDesc MipsInsts[];
564 }
565 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
566   return MipsInsts[Opcode];
567 }
568
569 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
570                                        SmallVectorImpl<MCInst> &Instructions) {
571   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
572   Inst.setLoc(IDLoc);
573
574   if (MCID.isBranch() || MCID.isCall()) {
575     const unsigned Opcode = Inst.getOpcode();
576     MCOperand Offset;
577
578     switch (Opcode) {
579     default:
580       break;
581     case Mips::BEQ:
582     case Mips::BNE:
583       assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
584       Offset = Inst.getOperand(2);
585       if (!Offset.isImm())
586         break; // We'll deal with this situation later on when applying fixups.
587       if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
588         return Error(IDLoc, "branch target out of range");
589       if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
590         return Error(IDLoc, "branch to misaligned address");
591       break;
592     case Mips::BGEZ:
593     case Mips::BGTZ:
594     case Mips::BLEZ:
595     case Mips::BLTZ:
596     case Mips::BGEZAL:
597     case Mips::BLTZAL:
598     case Mips::BC1F:
599     case Mips::BC1T:
600       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
601       Offset = Inst.getOperand(1);
602       if (!Offset.isImm())
603         break; // We'll deal with this situation later on when applying fixups.
604       if (!isIntN(isMicroMips() ? 17 : 18, Offset.getImm()))
605         return Error(IDLoc, "branch target out of range");
606       if (OffsetToAlignment(Offset.getImm(), 1LL << (isMicroMips() ? 1 : 2)))
607         return Error(IDLoc, "branch to misaligned address");
608       break;
609     }
610   }
611
612   if (MCID.hasDelaySlot() && Options.isReorder()) {
613     // If this instruction has a delay slot and .set reorder is active,
614     // emit a NOP after it.
615     Instructions.push_back(Inst);
616     MCInst NopInst;
617     NopInst.setOpcode(Mips::SLL);
618     NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
619     NopInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
620     NopInst.addOperand(MCOperand::CreateImm(0));
621     Instructions.push_back(NopInst);
622     return false;
623   }
624
625   if (MCID.mayLoad() || MCID.mayStore()) {
626     // Check the offset of memory operand, if it is a symbol
627     // reference or immediate we may have to expand instructions.
628     for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
629       const MCOperandInfo &OpInfo = MCID.OpInfo[i];
630       if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
631           (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
632         MCOperand &Op = Inst.getOperand(i);
633         if (Op.isImm()) {
634           int MemOffset = Op.getImm();
635           if (MemOffset < -32768 || MemOffset > 32767) {
636             // Offset can't exceed 16bit value.
637             expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), true);
638             return false;
639           }
640         } else if (Op.isExpr()) {
641           const MCExpr *Expr = Op.getExpr();
642           if (Expr->getKind() == MCExpr::SymbolRef) {
643             const MCSymbolRefExpr *SR =
644                 static_cast<const MCSymbolRefExpr *>(Expr);
645             if (SR->getKind() == MCSymbolRefExpr::VK_None) {
646               // Expand symbol.
647               expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
648               return false;
649             }
650           } else if (!isEvaluated(Expr)) {
651             expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
652             return false;
653           }
654         }
655       }
656     } // for
657   }   // if load/store
658
659   if (needsExpansion(Inst))
660     expandInstruction(Inst, IDLoc, Instructions);
661   else
662     Instructions.push_back(Inst);
663
664   return false;
665 }
666
667 bool MipsAsmParser::needsExpansion(MCInst &Inst) {
668
669   switch (Inst.getOpcode()) {
670   case Mips::LoadImm32Reg:
671   case Mips::LoadAddr32Imm:
672   case Mips::LoadAddr32Reg:
673     return true;
674   default:
675     return false;
676   }
677 }
678
679 void MipsAsmParser::expandInstruction(MCInst &Inst, SMLoc IDLoc,
680                                       SmallVectorImpl<MCInst> &Instructions) {
681   switch (Inst.getOpcode()) {
682   case Mips::LoadImm32Reg:
683     return expandLoadImm(Inst, IDLoc, Instructions);
684   case Mips::LoadAddr32Imm:
685     return expandLoadAddressImm(Inst, IDLoc, Instructions);
686   case Mips::LoadAddr32Reg:
687     return expandLoadAddressReg(Inst, IDLoc, Instructions);
688   }
689 }
690
691 void MipsAsmParser::expandLoadImm(MCInst &Inst, SMLoc IDLoc,
692                                   SmallVectorImpl<MCInst> &Instructions) {
693   MCInst tmpInst;
694   const MCOperand &ImmOp = Inst.getOperand(1);
695   assert(ImmOp.isImm() && "expected immediate operand kind");
696   const MCOperand &RegOp = Inst.getOperand(0);
697   assert(RegOp.isReg() && "expected register operand kind");
698
699   int ImmValue = ImmOp.getImm();
700   tmpInst.setLoc(IDLoc);
701   if (0 <= ImmValue && ImmValue <= 65535) {
702     // For 0 <= j <= 65535.
703     // li d,j => ori d,$zero,j
704     tmpInst.setOpcode(Mips::ORi);
705     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
706     tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
707     tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
708     Instructions.push_back(tmpInst);
709   } else if (ImmValue < 0 && ImmValue >= -32768) {
710     // For -32768 <= j < 0.
711     // li d,j => addiu d,$zero,j
712     tmpInst.setOpcode(Mips::ADDiu);
713     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
714     tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
715     tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
716     Instructions.push_back(tmpInst);
717   } else {
718     // For any other value of j that is representable as a 32-bit integer.
719     // li d,j => lui d,hi16(j)
720     //           ori d,d,lo16(j)
721     tmpInst.setOpcode(Mips::LUi);
722     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
723     tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
724     Instructions.push_back(tmpInst);
725     tmpInst.clear();
726     tmpInst.setOpcode(Mips::ORi);
727     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
728     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
729     tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
730     tmpInst.setLoc(IDLoc);
731     Instructions.push_back(tmpInst);
732   }
733 }
734
735 void
736 MipsAsmParser::expandLoadAddressReg(MCInst &Inst, SMLoc IDLoc,
737                                     SmallVectorImpl<MCInst> &Instructions) {
738   MCInst tmpInst;
739   const MCOperand &ImmOp = Inst.getOperand(2);
740   assert(ImmOp.isImm() && "expected immediate operand kind");
741   const MCOperand &SrcRegOp = Inst.getOperand(1);
742   assert(SrcRegOp.isReg() && "expected register operand kind");
743   const MCOperand &DstRegOp = Inst.getOperand(0);
744   assert(DstRegOp.isReg() && "expected register operand kind");
745   int ImmValue = ImmOp.getImm();
746   if (-32768 <= ImmValue && ImmValue <= 65535) {
747     // For -32768 <= j <= 65535.
748     // la d,j(s) => addiu d,s,j
749     tmpInst.setOpcode(Mips::ADDiu);
750     tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
751     tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
752     tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
753     Instructions.push_back(tmpInst);
754   } else {
755     // For any other value of j that is representable as a 32-bit integer.
756     // la d,j(s) => lui d,hi16(j)
757     //              ori d,d,lo16(j)
758     //              addu d,d,s
759     tmpInst.setOpcode(Mips::LUi);
760     tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
761     tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
762     Instructions.push_back(tmpInst);
763     tmpInst.clear();
764     tmpInst.setOpcode(Mips::ORi);
765     tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
766     tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
767     tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
768     Instructions.push_back(tmpInst);
769     tmpInst.clear();
770     tmpInst.setOpcode(Mips::ADDu);
771     tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
772     tmpInst.addOperand(MCOperand::CreateReg(DstRegOp.getReg()));
773     tmpInst.addOperand(MCOperand::CreateReg(SrcRegOp.getReg()));
774     Instructions.push_back(tmpInst);
775   }
776 }
777
778 void
779 MipsAsmParser::expandLoadAddressImm(MCInst &Inst, SMLoc IDLoc,
780                                     SmallVectorImpl<MCInst> &Instructions) {
781   MCInst tmpInst;
782   const MCOperand &ImmOp = Inst.getOperand(1);
783   assert(ImmOp.isImm() && "expected immediate operand kind");
784   const MCOperand &RegOp = Inst.getOperand(0);
785   assert(RegOp.isReg() && "expected register operand kind");
786   int ImmValue = ImmOp.getImm();
787   if (-32768 <= ImmValue && ImmValue <= 65535) {
788     // For -32768 <= j <= 65535.
789     // la d,j => addiu d,$zero,j
790     tmpInst.setOpcode(Mips::ADDiu);
791     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
792     tmpInst.addOperand(MCOperand::CreateReg(Mips::ZERO));
793     tmpInst.addOperand(MCOperand::CreateImm(ImmValue));
794     Instructions.push_back(tmpInst);
795   } else {
796     // For any other value of j that is representable as a 32-bit integer.
797     // la d,j => lui d,hi16(j)
798     //           ori d,d,lo16(j)
799     tmpInst.setOpcode(Mips::LUi);
800     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
801     tmpInst.addOperand(MCOperand::CreateImm((ImmValue & 0xffff0000) >> 16));
802     Instructions.push_back(tmpInst);
803     tmpInst.clear();
804     tmpInst.setOpcode(Mips::ORi);
805     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
806     tmpInst.addOperand(MCOperand::CreateReg(RegOp.getReg()));
807     tmpInst.addOperand(MCOperand::CreateImm(ImmValue & 0xffff));
808     Instructions.push_back(tmpInst);
809   }
810 }
811
812 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc,
813                                   SmallVectorImpl<MCInst> &Instructions,
814                                   bool isLoad, bool isImmOpnd) {
815   const MCSymbolRefExpr *SR;
816   MCInst TempInst;
817   unsigned ImmOffset, HiOffset, LoOffset;
818   const MCExpr *ExprOffset;
819   unsigned TmpRegNum;
820   unsigned AtRegNum = getReg(
821       (isMips64()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, getATReg());
822   // 1st operand is either the source or destination register.
823   assert(Inst.getOperand(0).isReg() && "expected register operand kind");
824   unsigned RegOpNum = Inst.getOperand(0).getReg();
825   // 2nd operand is the base register.
826   assert(Inst.getOperand(1).isReg() && "expected register operand kind");
827   unsigned BaseRegNum = Inst.getOperand(1).getReg();
828   // 3rd operand is either an immediate or expression.
829   if (isImmOpnd) {
830     assert(Inst.getOperand(2).isImm() && "expected immediate operand kind");
831     ImmOffset = Inst.getOperand(2).getImm();
832     LoOffset = ImmOffset & 0x0000ffff;
833     HiOffset = (ImmOffset & 0xffff0000) >> 16;
834     // If msb of LoOffset is 1(negative number) we must increment HiOffset.
835     if (LoOffset & 0x8000)
836       HiOffset++;
837   } else
838     ExprOffset = Inst.getOperand(2).getExpr();
839   // All instructions will have the same location.
840   TempInst.setLoc(IDLoc);
841   // 1st instruction in expansion is LUi. For load instruction we can use
842   // the dst register as a temporary if base and dst are different,
843   // but for stores we must use $at.
844   TmpRegNum = (isLoad && (BaseRegNum != RegOpNum)) ? RegOpNum : AtRegNum;
845   TempInst.setOpcode(Mips::LUi);
846   TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
847   if (isImmOpnd)
848     TempInst.addOperand(MCOperand::CreateImm(HiOffset));
849   else {
850     if (ExprOffset->getKind() == MCExpr::SymbolRef) {
851       SR = static_cast<const MCSymbolRefExpr *>(ExprOffset);
852       const MCSymbolRefExpr *HiExpr = MCSymbolRefExpr::Create(
853           SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_HI,
854           getContext());
855       TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
856     } else {
857       const MCExpr *HiExpr = evaluateRelocExpr(ExprOffset, "hi");
858       TempInst.addOperand(MCOperand::CreateExpr(HiExpr));
859     }
860   }
861   // Add the instruction to the list.
862   Instructions.push_back(TempInst);
863   // Prepare TempInst for next instruction.
864   TempInst.clear();
865   // Add temp register to base.
866   TempInst.setOpcode(Mips::ADDu);
867   TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
868   TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
869   TempInst.addOperand(MCOperand::CreateReg(BaseRegNum));
870   Instructions.push_back(TempInst);
871   TempInst.clear();
872   // And finaly, create original instruction with low part
873   // of offset and new base.
874   TempInst.setOpcode(Inst.getOpcode());
875   TempInst.addOperand(MCOperand::CreateReg(RegOpNum));
876   TempInst.addOperand(MCOperand::CreateReg(TmpRegNum));
877   if (isImmOpnd)
878     TempInst.addOperand(MCOperand::CreateImm(LoOffset));
879   else {
880     if (ExprOffset->getKind() == MCExpr::SymbolRef) {
881       const MCSymbolRefExpr *LoExpr = MCSymbolRefExpr::Create(
882           SR->getSymbol().getName(), MCSymbolRefExpr::VK_Mips_ABS_LO,
883           getContext());
884       TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
885     } else {
886       const MCExpr *LoExpr = evaluateRelocExpr(ExprOffset, "lo");
887       TempInst.addOperand(MCOperand::CreateExpr(LoExpr));
888     }
889   }
890   Instructions.push_back(TempInst);
891   TempInst.clear();
892 }
893
894 bool MipsAsmParser::MatchAndEmitInstruction(
895     SMLoc IDLoc, unsigned &Opcode,
896     SmallVectorImpl<MCParsedAsmOperand *> &Operands, MCStreamer &Out,
897     unsigned &ErrorInfo, bool MatchingInlineAsm) {
898   MCInst Inst;
899   SmallVector<MCInst, 8> Instructions;
900   unsigned MatchResult =
901       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
902
903   switch (MatchResult) {
904   default:
905     break;
906   case Match_Success: {
907     if (processInstruction(Inst, IDLoc, Instructions))
908       return true;
909     for (unsigned i = 0; i < Instructions.size(); i++)
910       Out.EmitInstruction(Instructions[i]);
911     return false;
912   }
913   case Match_MissingFeature:
914     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
915     return true;
916   case Match_InvalidOperand: {
917     SMLoc ErrorLoc = IDLoc;
918     if (ErrorInfo != ~0U) {
919       if (ErrorInfo >= Operands.size())
920         return Error(IDLoc, "too few operands for instruction");
921
922       ErrorLoc = ((MipsOperand *)Operands[ErrorInfo])->getStartLoc();
923       if (ErrorLoc == SMLoc())
924         ErrorLoc = IDLoc;
925     }
926
927     return Error(ErrorLoc, "invalid operand for instruction");
928   }
929   case Match_MnemonicFail:
930     return Error(IDLoc, "invalid instruction");
931   }
932   return true;
933 }
934
935 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
936   int CC;
937
938   if (Name == "at")
939     return getATReg();
940
941   CC = StringSwitch<unsigned>(Name)
942            .Case("zero", 0)
943            .Case("a0", 4)
944            .Case("a1", 5)
945            .Case("a2", 6)
946            .Case("a3", 7)
947            .Case("v0", 2)
948            .Case("v1", 3)
949            .Case("s0", 16)
950            .Case("s1", 17)
951            .Case("s2", 18)
952            .Case("s3", 19)
953            .Case("s4", 20)
954            .Case("s5", 21)
955            .Case("s6", 22)
956            .Case("s7", 23)
957            .Case("k0", 26)
958            .Case("k1", 27)
959            .Case("sp", 29)
960            .Case("fp", 30)
961            .Case("gp", 28)
962            .Case("ra", 31)
963            .Case("t0", 8)
964            .Case("t1", 9)
965            .Case("t2", 10)
966            .Case("t3", 11)
967            .Case("t4", 12)
968            .Case("t5", 13)
969            .Case("t6", 14)
970            .Case("t7", 15)
971            .Case("t8", 24)
972            .Case("t9", 25)
973            .Default(-1);
974
975   // Although SGI documentation just cuts out t0-t3 for n32/n64,
976   // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
977   // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
978   if (isMips64() && 8 <= CC && CC <= 11)
979     CC += 4;
980
981   if (CC == -1 && isMips64())
982     CC = StringSwitch<unsigned>(Name)
983              .Case("a4", 8)
984              .Case("a5", 9)
985              .Case("a6", 10)
986              .Case("a7", 11)
987              .Case("kt0", 26)
988              .Case("kt1", 27)
989              .Case("s8", 30)
990              .Default(-1);
991
992   return CC;
993 }
994
995 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
996
997   if (Name[0] == 'f') {
998     StringRef NumString = Name.substr(1);
999     unsigned IntVal;
1000     if (NumString.getAsInteger(10, IntVal))
1001       return -1;     // This is not an integer.
1002     if (IntVal > 31) // Maximum index for fpu register.
1003       return -1;
1004     return IntVal;
1005   }
1006   return -1;
1007 }
1008
1009 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
1010
1011   if (Name.startswith("fcc")) {
1012     StringRef NumString = Name.substr(3);
1013     unsigned IntVal;
1014     if (NumString.getAsInteger(10, IntVal))
1015       return -1;    // This is not an integer.
1016     if (IntVal > 7) // There are only 8 fcc registers.
1017       return -1;
1018     return IntVal;
1019   }
1020   return -1;
1021 }
1022
1023 int MipsAsmParser::matchACRegisterName(StringRef Name) {
1024
1025   if (Name.startswith("ac")) {
1026     StringRef NumString = Name.substr(2);
1027     unsigned IntVal;
1028     if (NumString.getAsInteger(10, IntVal))
1029       return -1;    // This is not an integer.
1030     if (IntVal > 3) // There are only 3 acc registers.
1031       return -1;
1032     return IntVal;
1033   }
1034   return -1;
1035 }
1036
1037 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
1038   unsigned IntVal;
1039
1040   if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
1041     return -1;
1042
1043   if (IntVal > 31)
1044     return -1;
1045
1046   return IntVal;
1047 }
1048
1049 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
1050   int CC;
1051
1052   CC = StringSwitch<unsigned>(Name)
1053            .Case("msair", 0)
1054            .Case("msacsr", 1)
1055            .Case("msaaccess", 2)
1056            .Case("msasave", 3)
1057            .Case("msamodify", 4)
1058            .Case("msarequest", 5)
1059            .Case("msamap", 6)
1060            .Case("msaunmap", 7)
1061            .Default(-1);
1062
1063   return CC;
1064 }
1065
1066 int MipsAsmParser::matchRegisterName(StringRef Name, bool is64BitReg) {
1067
1068   int CC;
1069   CC = matchCPURegisterName(Name);
1070   if (CC != -1)
1071     return matchRegisterByNumber(CC, is64BitReg ? Mips::GPR64RegClassID
1072                                                 : Mips::GPR32RegClassID);
1073   CC = matchFPURegisterName(Name);
1074   // TODO: decide about fpu register class
1075   if (CC != -1)
1076     return matchRegisterByNumber(CC, isFP64() ? Mips::FGR64RegClassID
1077                                               : Mips::FGR32RegClassID);
1078   return matchMSA128RegisterName(Name);
1079 }
1080
1081 int MipsAsmParser::regKindToRegClass(int RegKind) {
1082
1083   switch (RegKind) {
1084   case MipsOperand::Kind_GPR32:
1085     return Mips::GPR32RegClassID;
1086   case MipsOperand::Kind_GPR64:
1087     return Mips::GPR64RegClassID;
1088   case MipsOperand::Kind_HWRegs:
1089     return Mips::HWRegsRegClassID;
1090   case MipsOperand::Kind_FGR32Regs:
1091     return Mips::FGR32RegClassID;
1092   case MipsOperand::Kind_FGRH32Regs:
1093     return Mips::FGRH32RegClassID;
1094   case MipsOperand::Kind_FGR64Regs:
1095     return Mips::FGR64RegClassID;
1096   case MipsOperand::Kind_AFGR64Regs:
1097     return Mips::AFGR64RegClassID;
1098   case MipsOperand::Kind_CCRRegs:
1099     return Mips::CCRRegClassID;
1100   case MipsOperand::Kind_ACC64DSP:
1101     return Mips::ACC64DSPRegClassID;
1102   case MipsOperand::Kind_FCCRegs:
1103     return Mips::FCCRegClassID;
1104   case MipsOperand::Kind_MSA128BRegs:
1105     return Mips::MSA128BRegClassID;
1106   case MipsOperand::Kind_MSA128HRegs:
1107     return Mips::MSA128HRegClassID;
1108   case MipsOperand::Kind_MSA128WRegs:
1109     return Mips::MSA128WRegClassID;
1110   case MipsOperand::Kind_MSA128DRegs:
1111     return Mips::MSA128DRegClassID;
1112   case MipsOperand::Kind_MSA128CtrlRegs:
1113     return Mips::MSACtrlRegClassID;
1114   default:
1115     return -1;
1116   }
1117 }
1118
1119 bool MipsAssemblerOptions::setATReg(unsigned Reg) {
1120   if (Reg > 31)
1121     return false;
1122
1123   aTReg = Reg;
1124   return true;
1125 }
1126
1127 int MipsAsmParser::getATReg() { return Options.getATRegNum(); }
1128
1129 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
1130   return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
1131 }
1132
1133 int MipsAsmParser::matchRegisterByNumber(unsigned RegNum, unsigned RegClass) {
1134   if (RegNum >
1135       getContext().getRegisterInfo()->getRegClass(RegClass).getNumRegs())
1136     return -1;
1137
1138   return getReg(RegClass, RegNum);
1139 }
1140
1141 int MipsAsmParser::tryParseRegister(bool is64BitReg) {
1142   const AsmToken &Tok = Parser.getTok();
1143   int RegNum = -1;
1144
1145   if (Tok.is(AsmToken::Identifier)) {
1146     std::string lowerCase = Tok.getString().lower();
1147     RegNum = matchRegisterName(lowerCase, is64BitReg);
1148   } else if (Tok.is(AsmToken::Integer))
1149     RegNum = matchRegisterByNumber(static_cast<unsigned>(Tok.getIntVal()),
1150                                    is64BitReg ? Mips::GPR64RegClassID
1151                                               : Mips::GPR32RegClassID);
1152   return RegNum;
1153 }
1154
1155 bool MipsAsmParser::tryParseRegisterOperand(
1156     SmallVectorImpl<MCParsedAsmOperand *> &Operands, bool is64BitReg) {
1157
1158   SMLoc S = Parser.getTok().getLoc();
1159   int RegNo = -1;
1160
1161   RegNo = tryParseRegister(is64BitReg);
1162   if (RegNo == -1)
1163     return true;
1164
1165   Operands.push_back(
1166       MipsOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
1167   Parser.Lex(); // Eat register token.
1168   return false;
1169 }
1170
1171 bool
1172 MipsAsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
1173                             StringRef Mnemonic) {
1174   // Check if the current operand has a custom associated parser, if so, try to
1175   // custom parse the operand, or fallback to the general approach.
1176   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1177   if (ResTy == MatchOperand_Success)
1178     return false;
1179   // If there wasn't a custom match, try the generic matcher below. Otherwise,
1180   // there was a match, but an error occurred, in which case, just return that
1181   // the operand parsing failed.
1182   if (ResTy == MatchOperand_ParseFail)
1183     return true;
1184
1185   switch (getLexer().getKind()) {
1186   default:
1187     Error(Parser.getTok().getLoc(), "unexpected token in operand");
1188     return true;
1189   case AsmToken::Dollar: {
1190     // Parse the register.
1191     SMLoc S = Parser.getTok().getLoc();
1192     Parser.Lex(); // Eat dollar token.
1193     // Parse the register operand.
1194     if (!tryParseRegisterOperand(Operands, isMips64())) {
1195       if (getLexer().is(AsmToken::LParen)) {
1196         // Check if it is indexed addressing operand.
1197         Operands.push_back(MipsOperand::CreateToken("(", S));
1198         Parser.Lex(); // Eat the parenthesis.
1199         if (getLexer().isNot(AsmToken::Dollar))
1200           return true;
1201
1202         Parser.Lex(); // Eat the dollar
1203         if (tryParseRegisterOperand(Operands, isMips64()))
1204           return true;
1205
1206         if (!getLexer().is(AsmToken::RParen))
1207           return true;
1208
1209         S = Parser.getTok().getLoc();
1210         Operands.push_back(MipsOperand::CreateToken(")", S));
1211         Parser.Lex();
1212       }
1213       return false;
1214     }
1215     // Maybe it is a symbol reference.
1216     StringRef Identifier;
1217     if (Parser.parseIdentifier(Identifier))
1218       return true;
1219
1220     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1221     MCSymbol *Sym = getContext().GetOrCreateSymbol("$" + Identifier);
1222     // Otherwise create a symbol reference.
1223     const MCExpr *Res =
1224         MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
1225
1226     Operands.push_back(MipsOperand::CreateImm(Res, S, E));
1227     return false;
1228   }
1229   case AsmToken::Identifier:
1230     // For instruction aliases like "bc1f $Label" dedicated parser will
1231     // eat the '$' sign before failing. So in order to look for appropriate
1232     // label we must check first if we have already consumed '$'.
1233     if (hasConsumedDollar) {
1234       hasConsumedDollar = false;
1235       SMLoc S = Parser.getTok().getLoc();
1236       StringRef Identifier;
1237       if (Parser.parseIdentifier(Identifier))
1238         return true;
1239       SMLoc E =
1240           SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1241       MCSymbol *Sym = getContext().GetOrCreateSymbol("$" + Identifier);
1242       // Create a symbol reference.
1243       const MCExpr *Res =
1244           MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
1245
1246       Operands.push_back(MipsOperand::CreateImm(Res, S, E));
1247       return false;
1248     }
1249     // Look for the existing symbol, we should check if
1250     // we need to assigne the propper RegisterKind.
1251     if (searchSymbolAlias(Operands, MipsOperand::Kind_None))
1252       return false;
1253   // Else drop to expression parsing.
1254   case AsmToken::LParen:
1255   case AsmToken::Minus:
1256   case AsmToken::Plus:
1257   case AsmToken::Integer:
1258   case AsmToken::String: {
1259     // Quoted label names.
1260     const MCExpr *IdVal;
1261     SMLoc S = Parser.getTok().getLoc();
1262     if (getParser().parseExpression(IdVal))
1263       return true;
1264     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1265     Operands.push_back(MipsOperand::CreateImm(IdVal, S, E));
1266     return false;
1267   }
1268   case AsmToken::Percent: {
1269     // It is a symbol reference or constant expression.
1270     const MCExpr *IdVal;
1271     SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
1272     if (parseRelocOperand(IdVal))
1273       return true;
1274
1275     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1276
1277     Operands.push_back(MipsOperand::CreateImm(IdVal, S, E));
1278     return false;
1279   } // case AsmToken::Percent
1280   } // switch(getLexer().getKind())
1281   return true;
1282 }
1283
1284 const MCExpr *MipsAsmParser::evaluateRelocExpr(const MCExpr *Expr,
1285                                                StringRef RelocStr) {
1286   const MCExpr *Res;
1287   // Check the type of the expression.
1288   if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Expr)) {
1289     // It's a constant, evaluate lo or hi value.
1290     if (RelocStr == "lo") {
1291       short Val = MCE->getValue();
1292       Res = MCConstantExpr::Create(Val, getContext());
1293     } else if (RelocStr == "hi") {
1294       int Val = MCE->getValue();
1295       int LoSign = Val & 0x8000;
1296       Val = (Val & 0xffff0000) >> 16;
1297       // Lower part is treated as a signed int, so if it is negative
1298       // we must add 1 to the hi part to compensate.
1299       if (LoSign)
1300         Val++;
1301       Res = MCConstantExpr::Create(Val, getContext());
1302     } else {
1303       llvm_unreachable("Invalid RelocStr value");
1304     }
1305     return Res;
1306   }
1307
1308   if (const MCSymbolRefExpr *MSRE = dyn_cast<MCSymbolRefExpr>(Expr)) {
1309     // It's a symbol, create a symbolic expression from the symbol.
1310     StringRef Symbol = MSRE->getSymbol().getName();
1311     MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1312     Res = MCSymbolRefExpr::Create(Symbol, VK, getContext());
1313     return Res;
1314   }
1315
1316   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1317     const MCExpr *LExp = evaluateRelocExpr(BE->getLHS(), RelocStr);
1318     const MCExpr *RExp = evaluateRelocExpr(BE->getRHS(), RelocStr);
1319     Res = MCBinaryExpr::Create(BE->getOpcode(), LExp, RExp, getContext());
1320     return Res;
1321   }
1322
1323   if (const MCUnaryExpr *UN = dyn_cast<MCUnaryExpr>(Expr)) {
1324     const MCExpr *UnExp = evaluateRelocExpr(UN->getSubExpr(), RelocStr);
1325     Res = MCUnaryExpr::Create(UN->getOpcode(), UnExp, getContext());
1326     return Res;
1327   }
1328   // Just return the original expression.
1329   return Expr;
1330 }
1331
1332 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
1333
1334   switch (Expr->getKind()) {
1335   case MCExpr::Constant:
1336     return true;
1337   case MCExpr::SymbolRef:
1338     return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
1339   case MCExpr::Binary:
1340     if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1341       if (!isEvaluated(BE->getLHS()))
1342         return false;
1343       return isEvaluated(BE->getRHS());
1344     }
1345   case MCExpr::Unary:
1346     return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
1347   default:
1348     return false;
1349   }
1350   return false;
1351 }
1352
1353 bool MipsAsmParser::parseRelocOperand(const MCExpr *&Res) {
1354   Parser.Lex();                          // Eat the % token.
1355   const AsmToken &Tok = Parser.getTok(); // Get next token, operation.
1356   if (Tok.isNot(AsmToken::Identifier))
1357     return true;
1358
1359   std::string Str = Tok.getIdentifier().str();
1360
1361   Parser.Lex(); // Eat the identifier.
1362   // Now make an expression from the rest of the operand.
1363   const MCExpr *IdVal;
1364   SMLoc EndLoc;
1365
1366   if (getLexer().getKind() == AsmToken::LParen) {
1367     while (1) {
1368       Parser.Lex(); // Eat the '(' token.
1369       if (getLexer().getKind() == AsmToken::Percent) {
1370         Parser.Lex(); // Eat the % token.
1371         const AsmToken &nextTok = Parser.getTok();
1372         if (nextTok.isNot(AsmToken::Identifier))
1373           return true;
1374         Str += "(%";
1375         Str += nextTok.getIdentifier();
1376         Parser.Lex(); // Eat the identifier.
1377         if (getLexer().getKind() != AsmToken::LParen)
1378           return true;
1379       } else
1380         break;
1381     }
1382     if (getParser().parseParenExpression(IdVal, EndLoc))
1383       return true;
1384
1385     while (getLexer().getKind() == AsmToken::RParen)
1386       Parser.Lex(); // Eat the ')' token.
1387
1388   } else
1389     return true; // Parenthesis must follow the relocation operand.
1390
1391   Res = evaluateRelocExpr(IdVal, Str);
1392   return false;
1393 }
1394
1395 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1396                                   SMLoc &EndLoc) {
1397   StartLoc = Parser.getTok().getLoc();
1398   RegNo = tryParseRegister(isMips64());
1399   EndLoc = Parser.getTok().getLoc();
1400   return (RegNo == (unsigned)-1);
1401 }
1402
1403 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
1404   SMLoc S;
1405   bool Result = true;
1406
1407   while (getLexer().getKind() == AsmToken::LParen)
1408     Parser.Lex();
1409
1410   switch (getLexer().getKind()) {
1411   default:
1412     return true;
1413   case AsmToken::Identifier:
1414   case AsmToken::LParen:
1415   case AsmToken::Integer:
1416   case AsmToken::Minus:
1417   case AsmToken::Plus:
1418     if (isParenExpr)
1419       Result = getParser().parseParenExpression(Res, S);
1420     else
1421       Result = (getParser().parseExpression(Res));
1422     while (getLexer().getKind() == AsmToken::RParen)
1423       Parser.Lex();
1424     break;
1425   case AsmToken::Percent:
1426     Result = parseRelocOperand(Res);
1427   }
1428   return Result;
1429 }
1430
1431 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMemOperand(
1432     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1433
1434   const MCExpr *IdVal = 0;
1435   SMLoc S;
1436   bool isParenExpr = false;
1437   MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch;
1438   // First operand is the offset.
1439   S = Parser.getTok().getLoc();
1440
1441   if (getLexer().getKind() == AsmToken::LParen) {
1442     Parser.Lex();
1443     isParenExpr = true;
1444   }
1445
1446   if (getLexer().getKind() != AsmToken::Dollar) {
1447     if (parseMemOffset(IdVal, isParenExpr))
1448       return MatchOperand_ParseFail;
1449
1450     const AsmToken &Tok = Parser.getTok(); // Get the next token.
1451     if (Tok.isNot(AsmToken::LParen)) {
1452       MipsOperand *Mnemonic = static_cast<MipsOperand *>(Operands[0]);
1453       if (Mnemonic->getToken() == "la") {
1454         SMLoc E =
1455             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1456         Operands.push_back(MipsOperand::CreateImm(IdVal, S, E));
1457         return MatchOperand_Success;
1458       }
1459       if (Tok.is(AsmToken::EndOfStatement)) {
1460         SMLoc E =
1461             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1462
1463         // Zero register assumed, add a memory operand with ZERO as its base.
1464         Operands.push_back(MipsOperand::CreateMem(
1465             isMips64() ? Mips::ZERO_64 : Mips::ZERO, IdVal, S, E));
1466         return MatchOperand_Success;
1467       }
1468       Error(Parser.getTok().getLoc(), "'(' expected");
1469       return MatchOperand_ParseFail;
1470     }
1471
1472     Parser.Lex(); // Eat the '(' token.
1473   }
1474
1475   Res = parseRegs(Operands, isMips64() ? (int)MipsOperand::Kind_GPR64
1476                                        : (int)MipsOperand::Kind_GPR32);
1477   if (Res != MatchOperand_Success)
1478     return Res;
1479
1480   if (Parser.getTok().isNot(AsmToken::RParen)) {
1481     Error(Parser.getTok().getLoc(), "')' expected");
1482     return MatchOperand_ParseFail;
1483   }
1484
1485   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1486
1487   Parser.Lex(); // Eat the ')' token.
1488
1489   if (IdVal == 0)
1490     IdVal = MCConstantExpr::Create(0, getContext());
1491
1492   // Replace the register operand with the memory operand.
1493   MipsOperand *op = static_cast<MipsOperand *>(Operands.back());
1494   int RegNo = op->getReg();
1495   // Remove the register from the operands.
1496   Operands.pop_back();
1497   // Add the memory operand.
1498   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
1499     int64_t Imm;
1500     if (IdVal->EvaluateAsAbsolute(Imm))
1501       IdVal = MCConstantExpr::Create(Imm, getContext());
1502     else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
1503       IdVal = MCBinaryExpr::Create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
1504                                    getContext());
1505   }
1506
1507   Operands.push_back(MipsOperand::CreateMem(RegNo, IdVal, S, E));
1508   delete op;
1509   return MatchOperand_Success;
1510 }
1511
1512 bool MipsAsmParser::parsePtrReg(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
1513                                 int RegKind) {
1514   // If the first token is not '$' we have an error.
1515   if (Parser.getTok().isNot(AsmToken::Dollar))
1516     return false;
1517
1518   SMLoc S = Parser.getTok().getLoc();
1519   Parser.Lex();
1520   AsmToken::TokenKind TkKind = getLexer().getKind();
1521   int Reg;
1522
1523   if (TkKind == AsmToken::Integer) {
1524     Reg = matchRegisterByNumber(Parser.getTok().getIntVal(),
1525                                 regKindToRegClass(RegKind));
1526     if (Reg == -1)
1527       return false;
1528   } else if (TkKind == AsmToken::Identifier) {
1529     if ((Reg = matchCPURegisterName(Parser.getTok().getString().lower())) == -1)
1530       return false;
1531     Reg = getReg(regKindToRegClass(RegKind), Reg);
1532   } else {
1533     return false;
1534   }
1535
1536   MipsOperand *Op = MipsOperand::CreatePtrReg(Reg, S, Parser.getTok().getLoc());
1537   Op->setRegKind((MipsOperand::RegisterKind)RegKind);
1538   Operands.push_back(Op);
1539   Parser.Lex();
1540   return true;
1541 }
1542
1543 MipsAsmParser::OperandMatchResultTy
1544 MipsAsmParser::parsePtrReg(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1545   MipsOperand::RegisterKind RegKind =
1546       isN64() ? MipsOperand::Kind_GPR64 : MipsOperand::Kind_GPR32;
1547
1548   // Parse index register.
1549   if (!parsePtrReg(Operands, RegKind))
1550     return MatchOperand_NoMatch;
1551
1552   // Parse '('.
1553   if (Parser.getTok().isNot(AsmToken::LParen))
1554     return MatchOperand_NoMatch;
1555
1556   Operands.push_back(MipsOperand::CreateToken("(", getLexer().getLoc()));
1557   Parser.Lex();
1558
1559   // Parse base register.
1560   if (!parsePtrReg(Operands, RegKind))
1561     return MatchOperand_NoMatch;
1562
1563   // Parse ')'.
1564   if (Parser.getTok().isNot(AsmToken::RParen))
1565     return MatchOperand_NoMatch;
1566
1567   Operands.push_back(MipsOperand::CreateToken(")", getLexer().getLoc()));
1568   Parser.Lex();
1569
1570   return MatchOperand_Success;
1571 }
1572
1573 MipsAsmParser::OperandMatchResultTy
1574 MipsAsmParser::parseRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
1575                          int RegKind) {
1576   MipsOperand::RegisterKind Kind = (MipsOperand::RegisterKind)RegKind;
1577   if (getLexer().getKind() == AsmToken::Identifier && !hasConsumedDollar) {
1578     if (searchSymbolAlias(Operands, Kind))
1579       return MatchOperand_Success;
1580     return MatchOperand_NoMatch;
1581   }
1582   SMLoc S = Parser.getTok().getLoc();
1583   // If the first token is not '$', we have an error.
1584   if (Parser.getTok().isNot(AsmToken::Dollar) && !hasConsumedDollar)
1585     return MatchOperand_NoMatch;
1586   if (!hasConsumedDollar) {
1587     Parser.Lex(); // Eat the '$'
1588     hasConsumedDollar = true;
1589   }
1590   if (getLexer().getKind() == AsmToken::Identifier) {
1591     int RegNum = -1;
1592     std::string RegName = Parser.getTok().getString().lower();
1593     // Match register by name
1594     switch (RegKind) {
1595     case MipsOperand::Kind_GPR32:
1596     case MipsOperand::Kind_GPR64:
1597       RegNum = matchCPURegisterName(RegName);
1598       break;
1599     case MipsOperand::Kind_AFGR64Regs:
1600     case MipsOperand::Kind_FGR64Regs:
1601     case MipsOperand::Kind_FGR32Regs:
1602     case MipsOperand::Kind_FGRH32Regs:
1603       RegNum = matchFPURegisterName(RegName);
1604       if (RegKind == MipsOperand::Kind_AFGR64Regs)
1605         RegNum /= 2;
1606       else if (RegKind == MipsOperand::Kind_FGRH32Regs && !isFP64())
1607         if (RegNum != -1 && RegNum % 2 != 0)
1608           Warning(S, "Float register should be even.");
1609       break;
1610     case MipsOperand::Kind_FCCRegs:
1611       RegNum = matchFCCRegisterName(RegName);
1612       break;
1613     case MipsOperand::Kind_ACC64DSP:
1614       RegNum = matchACRegisterName(RegName);
1615       break;
1616     default:
1617       break; // No match, value is set to -1.
1618     }
1619     // No match found, return _NoMatch to give a chance to other round.
1620     if (RegNum < 0)
1621       return MatchOperand_NoMatch;
1622
1623     int RegVal = getReg(regKindToRegClass(Kind), RegNum);
1624     if (RegVal == -1)
1625       return MatchOperand_NoMatch;
1626
1627     MipsOperand *Op =
1628         MipsOperand::CreateReg(RegVal, S, Parser.getTok().getLoc());
1629     Op->setRegKind(Kind);
1630     Operands.push_back(Op);
1631     hasConsumedDollar = false;
1632     Parser.Lex(); // Eat the register name.
1633     return MatchOperand_Success;
1634   } else if (getLexer().getKind() == AsmToken::Integer) {
1635     unsigned RegNum = Parser.getTok().getIntVal();
1636     if (Kind == MipsOperand::Kind_HWRegs) {
1637       if (RegNum != 29)
1638         return MatchOperand_NoMatch;
1639       // Only hwreg 29 is supported, found at index 0.
1640       RegNum = 0;
1641     }
1642     int Reg = matchRegisterByNumber(RegNum, regKindToRegClass(Kind));
1643     if (Reg == -1)
1644       return MatchOperand_NoMatch;
1645     MipsOperand *Op = MipsOperand::CreateReg(Reg, S, Parser.getTok().getLoc());
1646     Op->setRegKind(Kind);
1647     Operands.push_back(Op);
1648     hasConsumedDollar = false;
1649     Parser.Lex(); // Eat the register number.
1650     if ((RegKind == MipsOperand::Kind_GPR32) &&
1651         (getLexer().is(AsmToken::LParen))) {
1652       // Check if it is indexed addressing operand.
1653       Operands.push_back(MipsOperand::CreateToken("(", getLexer().getLoc()));
1654       Parser.Lex(); // Eat the parenthesis.
1655       if (parseRegs(Operands, RegKind) != MatchOperand_Success)
1656         return MatchOperand_NoMatch;
1657       if (getLexer().isNot(AsmToken::RParen))
1658         return MatchOperand_NoMatch;
1659       Operands.push_back(MipsOperand::CreateToken(")", getLexer().getLoc()));
1660       Parser.Lex();
1661     }
1662     return MatchOperand_Success;
1663   }
1664   return MatchOperand_NoMatch;
1665 }
1666
1667 bool MipsAsmParser::validateMSAIndex(int Val, int RegKind) {
1668   MipsOperand::RegisterKind Kind = (MipsOperand::RegisterKind)RegKind;
1669
1670   if (Val < 0)
1671     return false;
1672
1673   switch (Kind) {
1674   default:
1675     return false;
1676   case MipsOperand::Kind_MSA128BRegs:
1677     return Val < 16;
1678   case MipsOperand::Kind_MSA128HRegs:
1679     return Val < 8;
1680   case MipsOperand::Kind_MSA128WRegs:
1681     return Val < 4;
1682   case MipsOperand::Kind_MSA128DRegs:
1683     return Val < 2;
1684   }
1685 }
1686
1687 MipsAsmParser::OperandMatchResultTy
1688 MipsAsmParser::parseMSARegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
1689                             int RegKind) {
1690   MipsOperand::RegisterKind Kind = (MipsOperand::RegisterKind)RegKind;
1691   SMLoc S = Parser.getTok().getLoc();
1692   std::string RegName;
1693
1694   if (Parser.getTok().isNot(AsmToken::Dollar))
1695     return MatchOperand_NoMatch;
1696
1697   switch (RegKind) {
1698   default:
1699     return MatchOperand_ParseFail;
1700   case MipsOperand::Kind_MSA128BRegs:
1701   case MipsOperand::Kind_MSA128HRegs:
1702   case MipsOperand::Kind_MSA128WRegs:
1703   case MipsOperand::Kind_MSA128DRegs:
1704     break;
1705   }
1706
1707   Parser.Lex(); // Eat the '$'.
1708   if (getLexer().getKind() == AsmToken::Identifier)
1709     RegName = Parser.getTok().getString().lower();
1710   else
1711     return MatchOperand_ParseFail;
1712
1713   int RegNum = matchMSA128RegisterName(RegName);
1714
1715   if (RegNum < 0 || RegNum > 31)
1716     return MatchOperand_ParseFail;
1717
1718   int RegVal = getReg(regKindToRegClass(Kind), RegNum);
1719   if (RegVal == -1)
1720     return MatchOperand_ParseFail;
1721
1722   MipsOperand *Op = MipsOperand::CreateReg(RegVal, S, Parser.getTok().getLoc());
1723   Op->setRegKind(Kind);
1724   Operands.push_back(Op);
1725
1726   Parser.Lex(); // Eat the register identifier.
1727
1728   // MSA registers may be suffixed with an index in the form of:
1729   // 1) Immediate expression.
1730   // 2) General Purpose Register.
1731   // Examples:
1732   //   1) copy_s.b $29,$w0[0]
1733   //   2) sld.b $w0,$w1[$1]
1734
1735   if (Parser.getTok().isNot(AsmToken::LBrac))
1736     return MatchOperand_Success;
1737
1738   MipsOperand *Mnemonic = static_cast<MipsOperand *>(Operands[0]);
1739
1740   Operands.push_back(MipsOperand::CreateToken("[", Parser.getTok().getLoc()));
1741   Parser.Lex(); // Parse the '[' token.
1742
1743   if (Parser.getTok().is(AsmToken::Dollar)) {
1744     // This must be a GPR.
1745     MipsOperand *RegOp;
1746     SMLoc VIdx = Parser.getTok().getLoc();
1747     Parser.Lex(); // Parse the '$' token.
1748
1749     // GPR have aliases and we must account for that. Example: $30 == $fp
1750     if (getLexer().getKind() == AsmToken::Integer) {
1751       unsigned RegNum = Parser.getTok().getIntVal();
1752       int Reg = matchRegisterByNumber(
1753           RegNum, regKindToRegClass(MipsOperand::Kind_GPR32));
1754       if (Reg == -1) {
1755         Error(VIdx, "invalid general purpose register");
1756         return MatchOperand_ParseFail;
1757       }
1758
1759       RegOp = MipsOperand::CreateReg(Reg, VIdx, Parser.getTok().getLoc());
1760     } else if (getLexer().getKind() == AsmToken::Identifier) {
1761       int RegNum = -1;
1762       std::string RegName = Parser.getTok().getString().lower();
1763
1764       RegNum = matchCPURegisterName(RegName);
1765       if (RegNum == -1) {
1766         Error(VIdx, "general purpose register expected");
1767         return MatchOperand_ParseFail;
1768       }
1769       RegNum = getReg(regKindToRegClass(MipsOperand::Kind_GPR32), RegNum);
1770       RegOp = MipsOperand::CreateReg(RegNum, VIdx, Parser.getTok().getLoc());
1771     } else
1772       return MatchOperand_ParseFail;
1773
1774     RegOp->setRegKind(MipsOperand::Kind_GPR32);
1775     Operands.push_back(RegOp);
1776     Parser.Lex(); // Eat the register identifier.
1777
1778     if (Parser.getTok().isNot(AsmToken::RBrac))
1779       return MatchOperand_ParseFail;
1780
1781     Operands.push_back(MipsOperand::CreateToken("]", Parser.getTok().getLoc()));
1782     Parser.Lex(); // Parse the ']' token.
1783
1784     return MatchOperand_Success;
1785   }
1786
1787   // The index must be a constant expression then.
1788   SMLoc VIdx = Parser.getTok().getLoc();
1789   const MCExpr *ImmVal;
1790
1791   if (getParser().parseExpression(ImmVal))
1792     return MatchOperand_ParseFail;
1793
1794   const MCConstantExpr *expr = dyn_cast<MCConstantExpr>(ImmVal);
1795   if (!expr || !validateMSAIndex((int)expr->getValue(), Kind)) {
1796     Error(VIdx, "invalid immediate value");
1797     return MatchOperand_ParseFail;
1798   }
1799
1800   SMLoc E = Parser.getTok().getEndLoc();
1801
1802   if (Parser.getTok().isNot(AsmToken::RBrac))
1803     return MatchOperand_ParseFail;
1804
1805   bool insve =
1806       Mnemonic->getToken() == "insve.b" || Mnemonic->getToken() == "insve.h" ||
1807       Mnemonic->getToken() == "insve.w" || Mnemonic->getToken() == "insve.d";
1808
1809   // The second vector index of insve instructions is always 0.
1810   if (insve && Operands.size() > 6) {
1811     if (expr->getValue() != 0) {
1812       Error(VIdx, "immediate value must be 0");
1813       return MatchOperand_ParseFail;
1814     }
1815     Operands.push_back(MipsOperand::CreateToken("0", VIdx));
1816   } else
1817     Operands.push_back(MipsOperand::CreateImm(expr, VIdx, E));
1818
1819   Operands.push_back(MipsOperand::CreateToken("]", Parser.getTok().getLoc()));
1820
1821   Parser.Lex(); // Parse the ']' token.
1822
1823   return MatchOperand_Success;
1824 }
1825
1826 MipsAsmParser::OperandMatchResultTy
1827 MipsAsmParser::parseMSACtrlRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
1828                                 int RegKind) {
1829   MipsOperand::RegisterKind Kind = (MipsOperand::RegisterKind)RegKind;
1830
1831   if (Kind != MipsOperand::Kind_MSA128CtrlRegs)
1832     return MatchOperand_NoMatch;
1833
1834   if (Parser.getTok().isNot(AsmToken::Dollar))
1835     return MatchOperand_ParseFail;
1836
1837   SMLoc S = Parser.getTok().getLoc();
1838
1839   Parser.Lex(); // Eat the '$' symbol.
1840
1841   int RegNum = -1;
1842   if (getLexer().getKind() == AsmToken::Identifier)
1843     RegNum = matchMSA128CtrlRegisterName(Parser.getTok().getString().lower());
1844   else if (getLexer().getKind() == AsmToken::Integer)
1845     RegNum = Parser.getTok().getIntVal();
1846   else
1847     return MatchOperand_ParseFail;
1848
1849   if (RegNum < 0 || RegNum > 7)
1850     return MatchOperand_ParseFail;
1851
1852   int RegVal = getReg(regKindToRegClass(Kind), RegNum);
1853   if (RegVal == -1)
1854     return MatchOperand_ParseFail;
1855
1856   MipsOperand *RegOp =
1857       MipsOperand::CreateReg(RegVal, S, Parser.getTok().getLoc());
1858   RegOp->setRegKind(MipsOperand::Kind_MSA128CtrlRegs);
1859   Operands.push_back(RegOp);
1860   Parser.Lex(); // Eat the register identifier.
1861
1862   return MatchOperand_Success;
1863 }
1864
1865 MipsAsmParser::OperandMatchResultTy
1866 MipsAsmParser::parseGPR64(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1867
1868   if (!isMips64())
1869     return MatchOperand_NoMatch;
1870   return parseRegs(Operands, (int)MipsOperand::Kind_GPR64);
1871 }
1872
1873 MipsAsmParser::OperandMatchResultTy
1874 MipsAsmParser::parseGPR32(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1875   return parseRegs(Operands, (int)MipsOperand::Kind_GPR32);
1876 }
1877
1878 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseAFGR64Regs(
1879     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1880
1881   if (isFP64())
1882     return MatchOperand_NoMatch;
1883   return parseRegs(Operands, (int)MipsOperand::Kind_AFGR64Regs);
1884 }
1885
1886 MipsAsmParser::OperandMatchResultTy
1887 MipsAsmParser::parseFGR64Regs(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1888   if (!isFP64())
1889     return MatchOperand_NoMatch;
1890   return parseRegs(Operands, (int)MipsOperand::Kind_FGR64Regs);
1891 }
1892
1893 MipsAsmParser::OperandMatchResultTy
1894 MipsAsmParser::parseFGR32Regs(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1895   return parseRegs(Operands, (int)MipsOperand::Kind_FGR32Regs);
1896 }
1897
1898 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseFGRH32Regs(
1899     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1900   return parseRegs(Operands, (int)MipsOperand::Kind_FGRH32Regs);
1901 }
1902
1903 MipsAsmParser::OperandMatchResultTy
1904 MipsAsmParser::parseFCCRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1905   return parseRegs(Operands, (int)MipsOperand::Kind_FCCRegs);
1906 }
1907
1908 MipsAsmParser::OperandMatchResultTy
1909 MipsAsmParser::parseACC64DSP(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1910   return parseRegs(Operands, (int)MipsOperand::Kind_ACC64DSP);
1911 }
1912
1913 MipsAsmParser::OperandMatchResultTy
1914 MipsAsmParser::parseLO32DSP(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1915   // If the first token is not '$' we have an error.
1916   if (Parser.getTok().isNot(AsmToken::Dollar))
1917     return MatchOperand_NoMatch;
1918
1919   SMLoc S = Parser.getTok().getLoc();
1920   Parser.Lex(); // Eat the '$'
1921
1922   const AsmToken &Tok = Parser.getTok(); // Get next token.
1923
1924   if (Tok.isNot(AsmToken::Identifier))
1925     return MatchOperand_NoMatch;
1926
1927   if (!Tok.getIdentifier().startswith("ac"))
1928     return MatchOperand_NoMatch;
1929
1930   StringRef NumString = Tok.getIdentifier().substr(2);
1931
1932   unsigned IntVal;
1933   if (NumString.getAsInteger(10, IntVal))
1934     return MatchOperand_NoMatch;
1935
1936   unsigned Reg = matchRegisterByNumber(IntVal, Mips::LO32DSPRegClassID);
1937
1938   MipsOperand *Op = MipsOperand::CreateReg(Reg, S, Parser.getTok().getLoc());
1939   Op->setRegKind(MipsOperand::Kind_LO32DSP);
1940   Operands.push_back(Op);
1941
1942   Parser.Lex(); // Eat the register number.
1943   return MatchOperand_Success;
1944 }
1945
1946 MipsAsmParser::OperandMatchResultTy
1947 MipsAsmParser::parseHI32DSP(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1948   // If the first token is not '$' we have an error.
1949   if (Parser.getTok().isNot(AsmToken::Dollar))
1950     return MatchOperand_NoMatch;
1951
1952   SMLoc S = Parser.getTok().getLoc();
1953   Parser.Lex(); // Eat the '$'
1954
1955   const AsmToken &Tok = Parser.getTok(); // Get next token.
1956
1957   if (Tok.isNot(AsmToken::Identifier))
1958     return MatchOperand_NoMatch;
1959
1960   if (!Tok.getIdentifier().startswith("ac"))
1961     return MatchOperand_NoMatch;
1962
1963   StringRef NumString = Tok.getIdentifier().substr(2);
1964
1965   unsigned IntVal;
1966   if (NumString.getAsInteger(10, IntVal))
1967     return MatchOperand_NoMatch;
1968
1969   unsigned Reg = matchRegisterByNumber(IntVal, Mips::HI32DSPRegClassID);
1970
1971   MipsOperand *Op = MipsOperand::CreateReg(Reg, S, Parser.getTok().getLoc());
1972   Op->setRegKind(MipsOperand::Kind_HI32DSP);
1973   Operands.push_back(Op);
1974
1975   Parser.Lex(); // Eat the register number.
1976   return MatchOperand_Success;
1977 }
1978
1979 MipsAsmParser::OperandMatchResultTy
1980 MipsAsmParser::parseCOP2(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1981   // If the first token is not '$' we have an error.
1982   if (Parser.getTok().isNot(AsmToken::Dollar))
1983     return MatchOperand_NoMatch;
1984
1985   SMLoc S = Parser.getTok().getLoc();
1986   Parser.Lex(); // Eat the '$'
1987
1988   const AsmToken &Tok = Parser.getTok(); // Get next token.
1989
1990   if (Tok.isNot(AsmToken::Integer))
1991     return MatchOperand_NoMatch;
1992
1993   unsigned IntVal = Tok.getIntVal();
1994
1995   unsigned Reg = matchRegisterByNumber(IntVal, Mips::COP2RegClassID);
1996
1997   MipsOperand *Op = MipsOperand::CreateReg(Reg, S, Parser.getTok().getLoc());
1998   Op->setRegKind(MipsOperand::Kind_COP2);
1999   Operands.push_back(Op);
2000
2001   Parser.Lex(); // Eat the register number.
2002   return MatchOperand_Success;
2003 }
2004
2005 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMSA128BRegs(
2006     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2007   return parseMSARegs(Operands, (int)MipsOperand::Kind_MSA128BRegs);
2008 }
2009
2010 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMSA128HRegs(
2011     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2012   return parseMSARegs(Operands, (int)MipsOperand::Kind_MSA128HRegs);
2013 }
2014
2015 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMSA128WRegs(
2016     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2017   return parseMSARegs(Operands, (int)MipsOperand::Kind_MSA128WRegs);
2018 }
2019
2020 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMSA128DRegs(
2021     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2022   return parseMSARegs(Operands, (int)MipsOperand::Kind_MSA128DRegs);
2023 }
2024
2025 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMSA128CtrlRegs(
2026     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2027   return parseMSACtrlRegs(Operands, (int)MipsOperand::Kind_MSA128CtrlRegs);
2028 }
2029
2030 bool MipsAsmParser::searchSymbolAlias(
2031     SmallVectorImpl<MCParsedAsmOperand *> &Operands, unsigned RegKind) {
2032
2033   MCSymbol *Sym = getContext().LookupSymbol(Parser.getTok().getIdentifier());
2034   if (Sym) {
2035     SMLoc S = Parser.getTok().getLoc();
2036     const MCExpr *Expr;
2037     if (Sym->isVariable())
2038       Expr = Sym->getVariableValue();
2039     else
2040       return false;
2041     if (Expr->getKind() == MCExpr::SymbolRef) {
2042       MipsOperand::RegisterKind Kind = (MipsOperand::RegisterKind)RegKind;
2043       const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
2044       const StringRef DefSymbol = Ref->getSymbol().getName();
2045       if (DefSymbol.startswith("$")) {
2046         int RegNum = -1;
2047         APInt IntVal(32, -1);
2048         if (!DefSymbol.substr(1).getAsInteger(10, IntVal))
2049           RegNum = matchRegisterByNumber(IntVal.getZExtValue(),
2050                                          isMips64() ? Mips::GPR64RegClassID
2051                                                     : Mips::GPR32RegClassID);
2052         else {
2053           // Lookup for the register with the corresponding name.
2054           switch (Kind) {
2055           case MipsOperand::Kind_AFGR64Regs:
2056           case MipsOperand::Kind_FGR64Regs:
2057             RegNum = matchFPURegisterName(DefSymbol.substr(1));
2058             break;
2059           case MipsOperand::Kind_FGR32Regs:
2060             RegNum = matchFPURegisterName(DefSymbol.substr(1));
2061             break;
2062           case MipsOperand::Kind_GPR64:
2063           case MipsOperand::Kind_GPR32:
2064           default:
2065             RegNum = matchCPURegisterName(DefSymbol.substr(1));
2066             break;
2067           }
2068           if (RegNum > -1)
2069             RegNum = getReg(regKindToRegClass(Kind), RegNum);
2070         }
2071         if (RegNum > -1) {
2072           Parser.Lex();
2073           MipsOperand *op =
2074               MipsOperand::CreateReg(RegNum, S, Parser.getTok().getLoc());
2075           op->setRegKind(Kind);
2076           Operands.push_back(op);
2077           return true;
2078         }
2079       }
2080     } else if (Expr->getKind() == MCExpr::Constant) {
2081       Parser.Lex();
2082       const MCConstantExpr *Const = static_cast<const MCConstantExpr *>(Expr);
2083       MipsOperand *op =
2084           MipsOperand::CreateImm(Const, S, Parser.getTok().getLoc());
2085       Operands.push_back(op);
2086       return true;
2087     }
2088   }
2089   return false;
2090 }
2091
2092 MipsAsmParser::OperandMatchResultTy
2093 MipsAsmParser::parseHWRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2094   return parseRegs(Operands, (int)MipsOperand::Kind_HWRegs);
2095 }
2096
2097 MipsAsmParser::OperandMatchResultTy
2098 MipsAsmParser::parseCCRRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2099   return parseRegs(Operands, (int)MipsOperand::Kind_CCRRegs);
2100 }
2101
2102 MipsAsmParser::OperandMatchResultTy
2103 MipsAsmParser::parseInvNum(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2104   const MCExpr *IdVal;
2105   // If the first token is '$' we may have register operand.
2106   if (Parser.getTok().is(AsmToken::Dollar))
2107     return MatchOperand_NoMatch;
2108   SMLoc S = Parser.getTok().getLoc();
2109   if (getParser().parseExpression(IdVal))
2110     return MatchOperand_ParseFail;
2111   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
2112   assert(MCE && "Unexpected MCExpr type.");
2113   int64_t Val = MCE->getValue();
2114   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2115   Operands.push_back(MipsOperand::CreateImm(
2116       MCConstantExpr::Create(0 - Val, getContext()), S, E));
2117   return MatchOperand_Success;
2118 }
2119
2120 MipsAsmParser::OperandMatchResultTy
2121 MipsAsmParser::parseLSAImm(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2122   switch (getLexer().getKind()) {
2123   default:
2124     return MatchOperand_NoMatch;
2125   case AsmToken::LParen:
2126   case AsmToken::Plus:
2127   case AsmToken::Minus:
2128   case AsmToken::Integer:
2129     break;
2130   }
2131
2132   const MCExpr *Expr;
2133   SMLoc S = Parser.getTok().getLoc();
2134
2135   if (getParser().parseExpression(Expr))
2136     return MatchOperand_ParseFail;
2137
2138   int64_t Val;
2139   if (!Expr->EvaluateAsAbsolute(Val)) {
2140     Error(S, "expected immediate value");
2141     return MatchOperand_ParseFail;
2142   }
2143
2144   // The LSA instruction allows a 2-bit unsigned immediate. For this reason
2145   // and because the CPU always adds one to the immediate field, the allowed
2146   // range becomes 1..4. We'll only check the range here and will deal
2147   // with the addition/subtraction when actually decoding/encoding
2148   // the instruction.
2149   if (Val < 1 || Val > 4) {
2150     Error(S, "immediate not in range (1..4)");
2151     return MatchOperand_ParseFail;
2152   }
2153
2154   Operands.push_back(
2155       MipsOperand::CreateLSAImm(Expr, S, Parser.getTok().getLoc()));
2156   return MatchOperand_Success;
2157 }
2158
2159 MCSymbolRefExpr::VariantKind MipsAsmParser::getVariantKind(StringRef Symbol) {
2160
2161   MCSymbolRefExpr::VariantKind VK =
2162       StringSwitch<MCSymbolRefExpr::VariantKind>(Symbol)
2163           .Case("hi", MCSymbolRefExpr::VK_Mips_ABS_HI)
2164           .Case("lo", MCSymbolRefExpr::VK_Mips_ABS_LO)
2165           .Case("gp_rel", MCSymbolRefExpr::VK_Mips_GPREL)
2166           .Case("call16", MCSymbolRefExpr::VK_Mips_GOT_CALL)
2167           .Case("got", MCSymbolRefExpr::VK_Mips_GOT)
2168           .Case("tlsgd", MCSymbolRefExpr::VK_Mips_TLSGD)
2169           .Case("tlsldm", MCSymbolRefExpr::VK_Mips_TLSLDM)
2170           .Case("dtprel_hi", MCSymbolRefExpr::VK_Mips_DTPREL_HI)
2171           .Case("dtprel_lo", MCSymbolRefExpr::VK_Mips_DTPREL_LO)
2172           .Case("gottprel", MCSymbolRefExpr::VK_Mips_GOTTPREL)
2173           .Case("tprel_hi", MCSymbolRefExpr::VK_Mips_TPREL_HI)
2174           .Case("tprel_lo", MCSymbolRefExpr::VK_Mips_TPREL_LO)
2175           .Case("got_disp", MCSymbolRefExpr::VK_Mips_GOT_DISP)
2176           .Case("got_page", MCSymbolRefExpr::VK_Mips_GOT_PAGE)
2177           .Case("got_ofst", MCSymbolRefExpr::VK_Mips_GOT_OFST)
2178           .Case("hi(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_HI)
2179           .Case("lo(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_LO)
2180           .Default(MCSymbolRefExpr::VK_None);
2181
2182   return VK;
2183 }
2184
2185 bool MipsAsmParser::ParseInstruction(
2186     ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
2187     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2188   // Check if we have valid mnemonic
2189   if (!mnemonicIsValid(Name, 0)) {
2190     Parser.eatToEndOfStatement();
2191     return Error(NameLoc, "Unknown instruction");
2192   }
2193   // First operand in MCInst is instruction mnemonic.
2194   Operands.push_back(MipsOperand::CreateToken(Name, NameLoc));
2195
2196   // Read the remaining operands.
2197   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2198     // Read the first operand.
2199     if (ParseOperand(Operands, Name)) {
2200       SMLoc Loc = getLexer().getLoc();
2201       Parser.eatToEndOfStatement();
2202       return Error(Loc, "unexpected token in argument list");
2203     }
2204
2205     while (getLexer().is(AsmToken::Comma)) {
2206       Parser.Lex(); // Eat the comma.
2207       // Parse and remember the operand.
2208       if (ParseOperand(Operands, Name)) {
2209         SMLoc Loc = getLexer().getLoc();
2210         Parser.eatToEndOfStatement();
2211         return Error(Loc, "unexpected token in argument list");
2212       }
2213     }
2214   }
2215   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2216     SMLoc Loc = getLexer().getLoc();
2217     Parser.eatToEndOfStatement();
2218     return Error(Loc, "unexpected token in argument list");
2219   }
2220   Parser.Lex(); // Consume the EndOfStatement.
2221   return false;
2222 }
2223
2224 bool MipsAsmParser::reportParseError(StringRef ErrorMsg) {
2225   SMLoc Loc = getLexer().getLoc();
2226   Parser.eatToEndOfStatement();
2227   return Error(Loc, ErrorMsg);
2228 }
2229
2230 bool MipsAsmParser::parseSetNoAtDirective() {
2231   // Line should look like: ".set noat".
2232   // set at reg to 0.
2233   Options.setATReg(0);
2234   // eat noat
2235   Parser.Lex();
2236   // If this is not the end of the statement, report an error.
2237   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2238     reportParseError("unexpected token in statement");
2239     return false;
2240   }
2241   Parser.Lex(); // Consume the EndOfStatement.
2242   return false;
2243 }
2244
2245 bool MipsAsmParser::parseSetAtDirective() {
2246   // Line can be .set at - defaults to $1
2247   // or .set at=$reg
2248   int AtRegNo;
2249   getParser().Lex();
2250   if (getLexer().is(AsmToken::EndOfStatement)) {
2251     Options.setATReg(1);
2252     Parser.Lex(); // Consume the EndOfStatement.
2253     return false;
2254   } else if (getLexer().is(AsmToken::Equal)) {
2255     getParser().Lex(); // Eat the '='.
2256     if (getLexer().isNot(AsmToken::Dollar)) {
2257       reportParseError("unexpected token in statement");
2258       return false;
2259     }
2260     Parser.Lex(); // Eat the '$'.
2261     const AsmToken &Reg = Parser.getTok();
2262     if (Reg.is(AsmToken::Identifier)) {
2263       AtRegNo = matchCPURegisterName(Reg.getIdentifier());
2264     } else if (Reg.is(AsmToken::Integer)) {
2265       AtRegNo = Reg.getIntVal();
2266     } else {
2267       reportParseError("unexpected token in statement");
2268       return false;
2269     }
2270
2271     if (AtRegNo < 1 || AtRegNo > 31) {
2272       reportParseError("unexpected token in statement");
2273       return false;
2274     }
2275
2276     if (!Options.setATReg(AtRegNo)) {
2277       reportParseError("unexpected token in statement");
2278       return false;
2279     }
2280     getParser().Lex(); // Eat the register.
2281
2282     if (getLexer().isNot(AsmToken::EndOfStatement)) {
2283       reportParseError("unexpected token in statement");
2284       return false;
2285     }
2286     Parser.Lex(); // Consume the EndOfStatement.
2287     return false;
2288   } else {
2289     reportParseError("unexpected token in statement");
2290     return false;
2291   }
2292 }
2293
2294 bool MipsAsmParser::parseSetReorderDirective() {
2295   Parser.Lex();
2296   // If this is not the end of the statement, report an error.
2297   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2298     reportParseError("unexpected token in statement");
2299     return false;
2300   }
2301   Options.setReorder();
2302   Parser.Lex(); // Consume the EndOfStatement.
2303   return false;
2304 }
2305
2306 bool MipsAsmParser::parseSetNoReorderDirective() {
2307   Parser.Lex();
2308   // If this is not the end of the statement, report an error.
2309   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2310     reportParseError("unexpected token in statement");
2311     return false;
2312   }
2313   Options.setNoreorder();
2314   Parser.Lex(); // Consume the EndOfStatement.
2315   return false;
2316 }
2317
2318 bool MipsAsmParser::parseSetMacroDirective() {
2319   Parser.Lex();
2320   // If this is not the end of the statement, report an error.
2321   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2322     reportParseError("unexpected token in statement");
2323     return false;
2324   }
2325   Options.setMacro();
2326   Parser.Lex(); // Consume the EndOfStatement.
2327   return false;
2328 }
2329
2330 bool MipsAsmParser::parseSetNoMacroDirective() {
2331   Parser.Lex();
2332   // If this is not the end of the statement, report an error.
2333   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2334     reportParseError("`noreorder' must be set before `nomacro'");
2335     return false;
2336   }
2337   if (Options.isReorder()) {
2338     reportParseError("`noreorder' must be set before `nomacro'");
2339     return false;
2340   }
2341   Options.setNomacro();
2342   Parser.Lex(); // Consume the EndOfStatement.
2343   return false;
2344 }
2345
2346 bool MipsAsmParser::parseSetMips16Directive() {
2347   Parser.Lex();
2348   // If this is not the end of the statement, report an error.
2349   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2350     reportParseError("unexpected token in statement");
2351     return false;
2352   }
2353   getTargetStreamer().emitDirectiveSetMips16();
2354   Parser.Lex(); // Consume the EndOfStatement.
2355   return false;
2356 }
2357
2358 bool MipsAsmParser::parseSetNoMips16Directive() {
2359   Parser.Lex();
2360   // If this is not the end of the statement, report an error.
2361   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2362     reportParseError("unexpected token in statement");
2363     return false;
2364   }
2365   // For now do nothing.
2366   Parser.Lex(); // Consume the EndOfStatement.
2367   return false;
2368 }
2369
2370 bool MipsAsmParser::parseSetAssignment() {
2371   StringRef Name;
2372   const MCExpr *Value;
2373
2374   if (Parser.parseIdentifier(Name))
2375     reportParseError("expected identifier after .set");
2376
2377   if (getLexer().isNot(AsmToken::Comma))
2378     return reportParseError("unexpected token in .set directive");
2379   Lex(); // Eat comma
2380
2381   if (Parser.parseExpression(Value))
2382     return reportParseError("expected valid expression after comma");
2383
2384   // Check if the Name already exists as a symbol.
2385   MCSymbol *Sym = getContext().LookupSymbol(Name);
2386   if (Sym)
2387     return reportParseError("symbol already defined");
2388   Sym = getContext().GetOrCreateSymbol(Name);
2389   Sym->setVariableValue(Value);
2390
2391   return false;
2392 }
2393
2394 bool MipsAsmParser::parseDirectiveSet() {
2395
2396   // Get the next token.
2397   const AsmToken &Tok = Parser.getTok();
2398
2399   if (Tok.getString() == "noat") {
2400     return parseSetNoAtDirective();
2401   } else if (Tok.getString() == "at") {
2402     return parseSetAtDirective();
2403   } else if (Tok.getString() == "reorder") {
2404     return parseSetReorderDirective();
2405   } else if (Tok.getString() == "noreorder") {
2406     return parseSetNoReorderDirective();
2407   } else if (Tok.getString() == "macro") {
2408     return parseSetMacroDirective();
2409   } else if (Tok.getString() == "nomacro") {
2410     return parseSetNoMacroDirective();
2411   } else if (Tok.getString() == "mips16") {
2412     return parseSetMips16Directive();
2413   } else if (Tok.getString() == "nomips16") {
2414     return parseSetNoMips16Directive();
2415   } else if (Tok.getString() == "nomicromips") {
2416     getTargetStreamer().emitDirectiveSetNoMicroMips();
2417     Parser.eatToEndOfStatement();
2418     return false;
2419   } else if (Tok.getString() == "micromips") {
2420     getTargetStreamer().emitDirectiveSetMicroMips();
2421     Parser.eatToEndOfStatement();
2422     return false;
2423   } else {
2424     // It is just an identifier, look for an assignment.
2425     parseSetAssignment();
2426     return false;
2427   }
2428
2429   return true;
2430 }
2431
2432 bool MipsAsmParser::parseDirectiveMipsHackELFFlags() {
2433   int64_t Flags = 0;
2434   if (Parser.parseAbsoluteExpression(Flags)) {
2435     TokError("unexpected token");
2436     return false;
2437   }
2438
2439   getTargetStreamer().emitMipsHackELFFlags(Flags);
2440   return false;
2441 }
2442
2443 /// parseDirectiveWord
2444 ///  ::= .word [ expression (, expression)* ]
2445 bool MipsAsmParser::parseDirectiveWord(unsigned Size, SMLoc L) {
2446   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2447     for (;;) {
2448       const MCExpr *Value;
2449       if (getParser().parseExpression(Value))
2450         return true;
2451
2452       getParser().getStreamer().EmitValue(Value, Size);
2453
2454       if (getLexer().is(AsmToken::EndOfStatement))
2455         break;
2456
2457       // FIXME: Improve diagnostic.
2458       if (getLexer().isNot(AsmToken::Comma))
2459         return Error(L, "unexpected token in directive");
2460       Parser.Lex();
2461     }
2462   }
2463
2464   Parser.Lex();
2465   return false;
2466 }
2467
2468 /// parseDirectiveGpWord
2469 ///  ::= .gpword local_sym
2470 bool MipsAsmParser::parseDirectiveGpWord() {
2471   const MCExpr *Value;
2472   // EmitGPRel32Value requires an expression, so we are using base class
2473   // method to evaluate the expression.
2474   if (getParser().parseExpression(Value))
2475     return true;
2476   getParser().getStreamer().EmitGPRel32Value(Value);
2477
2478   if (getLexer().isNot(AsmToken::EndOfStatement))
2479     return Error(getLexer().getLoc(), "unexpected token in directive");
2480   Parser.Lex(); // Eat EndOfStatement token.
2481   return false;
2482 }
2483
2484 bool MipsAsmParser::parseDirectiveOption() {
2485   // Get the option token.
2486   AsmToken Tok = Parser.getTok();
2487   // At the moment only identifiers are supported.
2488   if (Tok.isNot(AsmToken::Identifier)) {
2489     Error(Parser.getTok().getLoc(), "unexpected token in .option directive");
2490     Parser.eatToEndOfStatement();
2491     return false;
2492   }
2493
2494   StringRef Option = Tok.getIdentifier();
2495
2496   if (Option == "pic0") {
2497     getTargetStreamer().emitDirectiveOptionPic0();
2498     Parser.Lex();
2499     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2500       Error(Parser.getTok().getLoc(),
2501             "unexpected token in .option pic0 directive");
2502       Parser.eatToEndOfStatement();
2503     }
2504     return false;
2505   }
2506
2507   // Unknown option.
2508   Warning(Parser.getTok().getLoc(), "unknown option in .option directive");
2509   Parser.eatToEndOfStatement();
2510   return false;
2511 }
2512
2513 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
2514   StringRef IDVal = DirectiveID.getString();
2515
2516   if (IDVal == ".ent") {
2517     // Ignore this directive for now.
2518     Parser.Lex();
2519     return false;
2520   }
2521
2522   if (IDVal == ".end") {
2523     // Ignore this directive for now.
2524     Parser.Lex();
2525     return false;
2526   }
2527
2528   if (IDVal == ".frame") {
2529     // Ignore this directive for now.
2530     Parser.eatToEndOfStatement();
2531     return false;
2532   }
2533
2534   if (IDVal == ".set") {
2535     return parseDirectiveSet();
2536   }
2537
2538   if (IDVal == ".fmask") {
2539     // Ignore this directive for now.
2540     Parser.eatToEndOfStatement();
2541     return false;
2542   }
2543
2544   if (IDVal == ".mask") {
2545     // Ignore this directive for now.
2546     Parser.eatToEndOfStatement();
2547     return false;
2548   }
2549
2550   if (IDVal == ".gpword") {
2551     // Ignore this directive for now.
2552     parseDirectiveGpWord();
2553     return false;
2554   }
2555
2556   if (IDVal == ".word") {
2557     parseDirectiveWord(4, DirectiveID.getLoc());
2558     return false;
2559   }
2560
2561   if (IDVal == ".mips_hack_elf_flags")
2562     return parseDirectiveMipsHackELFFlags();
2563
2564   if (IDVal == ".option")
2565     return parseDirectiveOption();
2566
2567   if (IDVal == ".abicalls") {
2568     getTargetStreamer().emitDirectiveAbiCalls();
2569     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2570       Error(Parser.getTok().getLoc(), "unexpected token in directive");
2571       // Clear line
2572       Parser.eatToEndOfStatement();
2573     }
2574     return false;
2575   }
2576
2577   return true;
2578 }
2579
2580 extern "C" void LLVMInitializeMipsAsmParser() {
2581   RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
2582   RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
2583   RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
2584   RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
2585 }
2586
2587 #define GET_REGISTER_MATCHER
2588 #define GET_MATCHER_IMPLEMENTATION
2589 #include "MipsGenAsmMatcher.inc"