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