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