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