5bc8f9d4b63429f5214d9cc7382a27925dd21b2d
[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 isMips64() const {
219     return (STI.getFeatureBits() & Mips::FeatureMips64) != 0;
220   }
221
222   bool isFP64() const {
223     return (STI.getFeatureBits() & Mips::FeatureFP64Bit) != 0;
224   }
225
226   bool 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       (isMips64()) ? 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((isMips64()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID,
1214                  RegNo);
1215 }
1216
1217
1218 int MipsAsmParser::matchRegisterByNumber(unsigned RegNum, unsigned RegClass) {
1219   if (RegNum >
1220       getContext().getRegisterInfo()->getRegClass(RegClass).getNumRegs() - 1)
1221     return -1;
1222
1223   if (RegClass == Mips::GPR32RegClassID || RegClass == Mips::GPR64RegClassID)
1224     warnIfAssemblerTemporary(RegNum);
1225
1226   return getReg(RegClass, RegNum);
1227 }
1228
1229 int MipsAsmParser::tryParseRegister(bool is64BitReg) {
1230   const AsmToken &Tok = Parser.getTok();
1231   int RegNum = -1;
1232
1233   if (Tok.is(AsmToken::Identifier)) {
1234     std::string lowerCase = Tok.getString().lower();
1235     RegNum = matchRegisterName(lowerCase, is64BitReg);
1236   } else if (Tok.is(AsmToken::Integer))
1237     RegNum = matchRegisterByNumber(static_cast<unsigned>(Tok.getIntVal()),
1238                                    is64BitReg ? Mips::GPR64RegClassID
1239                                               : Mips::GPR32RegClassID);
1240   return RegNum;
1241 }
1242
1243 bool MipsAsmParser::tryParseRegisterOperand(
1244     SmallVectorImpl<MCParsedAsmOperand *> &Operands, bool is64BitReg) {
1245
1246   SMLoc S = Parser.getTok().getLoc();
1247   int RegNo = -1;
1248
1249   RegNo = tryParseRegister(is64BitReg);
1250   if (RegNo == -1)
1251     return true;
1252
1253   Operands.push_back(
1254       MipsOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
1255   Parser.Lex(); // Eat register token.
1256   return false;
1257 }
1258
1259 bool
1260 MipsAsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
1261                             StringRef Mnemonic) {
1262   // Check if the current operand has a custom associated parser, if so, try to
1263   // custom parse the operand, or fallback to the general approach.
1264   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1265   if (ResTy == MatchOperand_Success)
1266     return false;
1267   // If there wasn't a custom match, try the generic matcher below. Otherwise,
1268   // there was a match, but an error occurred, in which case, just return that
1269   // the operand parsing failed.
1270   if (ResTy == MatchOperand_ParseFail)
1271     return true;
1272
1273   switch (getLexer().getKind()) {
1274   default:
1275     Error(Parser.getTok().getLoc(), "unexpected token in operand");
1276     return true;
1277   case AsmToken::Dollar: {
1278     // Parse the register.
1279     SMLoc S = Parser.getTok().getLoc();
1280     Parser.Lex(); // Eat dollar token.
1281     // Parse the register operand.
1282     if (!tryParseRegisterOperand(Operands, isMips64())) {
1283       if (getLexer().is(AsmToken::LParen)) {
1284         // Check if it is indexed addressing operand.
1285         Operands.push_back(MipsOperand::CreateToken("(", S));
1286         Parser.Lex(); // Eat the parenthesis.
1287         if (getLexer().isNot(AsmToken::Dollar))
1288           return true;
1289
1290         Parser.Lex(); // Eat the dollar
1291         if (tryParseRegisterOperand(Operands, isMips64()))
1292           return true;
1293
1294         if (!getLexer().is(AsmToken::RParen))
1295           return true;
1296
1297         S = Parser.getTok().getLoc();
1298         Operands.push_back(MipsOperand::CreateToken(")", S));
1299         Parser.Lex();
1300       }
1301       return false;
1302     }
1303     // Maybe it is a symbol reference.
1304     StringRef Identifier;
1305     if (Parser.parseIdentifier(Identifier))
1306       return true;
1307
1308     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1309     MCSymbol *Sym = getContext().GetOrCreateSymbol("$" + Identifier);
1310     // Otherwise create a symbol reference.
1311     const MCExpr *Res =
1312         MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
1313
1314     Operands.push_back(MipsOperand::CreateImm(Res, S, E));
1315     return false;
1316   }
1317   case AsmToken::Identifier:
1318     // For instruction aliases like "bc1f $Label" dedicated parser will
1319     // eat the '$' sign before failing. So in order to look for appropriate
1320     // label we must check first if we have already consumed '$'.
1321     if (hasConsumedDollar) {
1322       hasConsumedDollar = false;
1323       SMLoc S = Parser.getTok().getLoc();
1324       StringRef Identifier;
1325       if (Parser.parseIdentifier(Identifier))
1326         return true;
1327       SMLoc E =
1328           SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1329       MCSymbol *Sym = getContext().GetOrCreateSymbol("$" + Identifier);
1330       // Create a symbol reference.
1331       const MCExpr *Res =
1332           MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
1333
1334       Operands.push_back(MipsOperand::CreateImm(Res, S, E));
1335       return false;
1336     }
1337     // Look for the existing symbol, we should check if
1338     // we need to assign the proper RegisterKind.
1339     if (searchSymbolAlias(Operands, MipsOperand::Kind_None))
1340       return false;
1341   // Else drop to expression parsing.
1342   case AsmToken::LParen:
1343   case AsmToken::Minus:
1344   case AsmToken::Plus:
1345   case AsmToken::Integer:
1346   case AsmToken::String: {
1347     // Quoted label names.
1348     const MCExpr *IdVal;
1349     SMLoc S = Parser.getTok().getLoc();
1350     if (getParser().parseExpression(IdVal))
1351       return true;
1352     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1353     Operands.push_back(MipsOperand::CreateImm(IdVal, S, E));
1354     return false;
1355   }
1356   case AsmToken::Percent: {
1357     // It is a symbol reference or constant expression.
1358     const MCExpr *IdVal;
1359     SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
1360     if (parseRelocOperand(IdVal))
1361       return true;
1362
1363     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1364
1365     Operands.push_back(MipsOperand::CreateImm(IdVal, S, E));
1366     return false;
1367   } // case AsmToken::Percent
1368   } // switch(getLexer().getKind())
1369   return true;
1370 }
1371
1372 const MCExpr *MipsAsmParser::evaluateRelocExpr(const MCExpr *Expr,
1373                                                StringRef RelocStr) {
1374   const MCExpr *Res;
1375   // Check the type of the expression.
1376   if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Expr)) {
1377     // It's a constant, evaluate lo or hi value.
1378     if (RelocStr == "lo") {
1379       short Val = MCE->getValue();
1380       Res = MCConstantExpr::Create(Val, getContext());
1381     } else if (RelocStr == "hi") {
1382       int Val = MCE->getValue();
1383       int LoSign = Val & 0x8000;
1384       Val = (Val & 0xffff0000) >> 16;
1385       // Lower part is treated as a signed int, so if it is negative
1386       // we must add 1 to the hi part to compensate.
1387       if (LoSign)
1388         Val++;
1389       Res = MCConstantExpr::Create(Val, getContext());
1390     } else {
1391       llvm_unreachable("Invalid RelocStr value");
1392     }
1393     return Res;
1394   }
1395
1396   if (const MCSymbolRefExpr *MSRE = dyn_cast<MCSymbolRefExpr>(Expr)) {
1397     // It's a symbol, create a symbolic expression from the symbol.
1398     StringRef Symbol = MSRE->getSymbol().getName();
1399     MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1400     Res = MCSymbolRefExpr::Create(Symbol, VK, getContext());
1401     return Res;
1402   }
1403
1404   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1405     MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
1406
1407     // Check for %hi(sym1-sym2) and %lo(sym1-sym2) expressions.
1408     if (isa<MCSymbolRefExpr>(BE->getLHS()) && isa<MCSymbolRefExpr>(BE->getRHS())
1409         && (VK == MCSymbolRefExpr::VK_Mips_ABS_HI
1410             || VK == MCSymbolRefExpr::VK_Mips_ABS_LO)) {
1411       // Create target expression for %hi(sym1-sym2) and %lo(sym1-sym2).
1412       if (VK == MCSymbolRefExpr::VK_Mips_ABS_HI)
1413         return MipsMCExpr::CreateHi(Expr, getContext());
1414       return MipsMCExpr::CreateLo(Expr, getContext());
1415     }
1416
1417     const MCExpr *LExp = evaluateRelocExpr(BE->getLHS(), RelocStr);
1418     const MCExpr *RExp = evaluateRelocExpr(BE->getRHS(), RelocStr);
1419     Res = MCBinaryExpr::Create(BE->getOpcode(), LExp, RExp, getContext());
1420     return Res;
1421   }
1422
1423   if (const MCUnaryExpr *UN = dyn_cast<MCUnaryExpr>(Expr)) {
1424     const MCExpr *UnExp = evaluateRelocExpr(UN->getSubExpr(), RelocStr);
1425     Res = MCUnaryExpr::Create(UN->getOpcode(), UnExp, getContext());
1426     return Res;
1427   }
1428   // Just return the original expression.
1429   return Expr;
1430 }
1431
1432 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
1433
1434   switch (Expr->getKind()) {
1435   case MCExpr::Constant:
1436     return true;
1437   case MCExpr::SymbolRef:
1438     return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
1439   case MCExpr::Binary:
1440     if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
1441       if (!isEvaluated(BE->getLHS()))
1442         return false;
1443       return isEvaluated(BE->getRHS());
1444     }
1445   case MCExpr::Unary:
1446     return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
1447   case MCExpr::Target:
1448     return true;
1449   }
1450   return false;
1451 }
1452
1453 bool MipsAsmParser::parseRelocOperand(const MCExpr *&Res) {
1454   Parser.Lex();                          // Eat the % token.
1455   const AsmToken &Tok = Parser.getTok(); // Get next token, operation.
1456   if (Tok.isNot(AsmToken::Identifier))
1457     return true;
1458
1459   std::string Str = Tok.getIdentifier().str();
1460
1461   Parser.Lex(); // Eat the identifier.
1462   // Now make an expression from the rest of the operand.
1463   const MCExpr *IdVal;
1464   SMLoc EndLoc;
1465
1466   if (getLexer().getKind() == AsmToken::LParen) {
1467     while (1) {
1468       Parser.Lex(); // Eat the '(' token.
1469       if (getLexer().getKind() == AsmToken::Percent) {
1470         Parser.Lex(); // Eat the % token.
1471         const AsmToken &nextTok = Parser.getTok();
1472         if (nextTok.isNot(AsmToken::Identifier))
1473           return true;
1474         Str += "(%";
1475         Str += nextTok.getIdentifier();
1476         Parser.Lex(); // Eat the identifier.
1477         if (getLexer().getKind() != AsmToken::LParen)
1478           return true;
1479       } else
1480         break;
1481     }
1482     if (getParser().parseParenExpression(IdVal, EndLoc))
1483       return true;
1484
1485     while (getLexer().getKind() == AsmToken::RParen)
1486       Parser.Lex(); // Eat the ')' token.
1487
1488   } else
1489     return true; // Parenthesis must follow the relocation operand.
1490
1491   Res = evaluateRelocExpr(IdVal, Str);
1492   return false;
1493 }
1494
1495 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1496                                   SMLoc &EndLoc) {
1497   StartLoc = Parser.getTok().getLoc();
1498   RegNo = tryParseRegister(isMips64());
1499   EndLoc = Parser.getTok().getLoc();
1500   return (RegNo == (unsigned)-1);
1501 }
1502
1503 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
1504   SMLoc S;
1505   bool Result = true;
1506
1507   while (getLexer().getKind() == AsmToken::LParen)
1508     Parser.Lex();
1509
1510   switch (getLexer().getKind()) {
1511   default:
1512     return true;
1513   case AsmToken::Identifier:
1514   case AsmToken::LParen:
1515   case AsmToken::Integer:
1516   case AsmToken::Minus:
1517   case AsmToken::Plus:
1518     if (isParenExpr)
1519       Result = getParser().parseParenExpression(Res, S);
1520     else
1521       Result = (getParser().parseExpression(Res));
1522     while (getLexer().getKind() == AsmToken::RParen)
1523       Parser.Lex();
1524     break;
1525   case AsmToken::Percent:
1526     Result = parseRelocOperand(Res);
1527   }
1528   return Result;
1529 }
1530
1531 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMemOperand(
1532     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1533
1534   const MCExpr *IdVal = 0;
1535   SMLoc S;
1536   bool isParenExpr = false;
1537   MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch;
1538   // First operand is the offset.
1539   S = Parser.getTok().getLoc();
1540
1541   if (getLexer().getKind() == AsmToken::LParen) {
1542     Parser.Lex();
1543     isParenExpr = true;
1544   }
1545
1546   if (getLexer().getKind() != AsmToken::Dollar) {
1547     if (parseMemOffset(IdVal, isParenExpr))
1548       return MatchOperand_ParseFail;
1549
1550     const AsmToken &Tok = Parser.getTok(); // Get the next token.
1551     if (Tok.isNot(AsmToken::LParen)) {
1552       MipsOperand *Mnemonic = static_cast<MipsOperand *>(Operands[0]);
1553       if (Mnemonic->getToken() == "la") {
1554         SMLoc E =
1555             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1556         Operands.push_back(MipsOperand::CreateImm(IdVal, S, E));
1557         return MatchOperand_Success;
1558       }
1559       if (Tok.is(AsmToken::EndOfStatement)) {
1560         SMLoc E =
1561             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1562
1563         // Zero register assumed, add a memory operand with ZERO as its base.
1564         Operands.push_back(MipsOperand::CreateMem(
1565             isMips64() ? Mips::ZERO_64 : Mips::ZERO, IdVal, S, E));
1566         return MatchOperand_Success;
1567       }
1568       Error(Parser.getTok().getLoc(), "'(' expected");
1569       return MatchOperand_ParseFail;
1570     }
1571
1572     Parser.Lex(); // Eat the '(' token.
1573   }
1574
1575   Res = parseRegs(Operands, isMips64() ? (int)MipsOperand::Kind_GPR64
1576                                        : (int)MipsOperand::Kind_GPR32);
1577   if (Res != MatchOperand_Success)
1578     return Res;
1579
1580   if (Parser.getTok().isNot(AsmToken::RParen)) {
1581     Error(Parser.getTok().getLoc(), "')' expected");
1582     return MatchOperand_ParseFail;
1583   }
1584
1585   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1586
1587   Parser.Lex(); // Eat the ')' token.
1588
1589   if (IdVal == 0)
1590     IdVal = MCConstantExpr::Create(0, getContext());
1591
1592   // Replace the register operand with the memory operand.
1593   MipsOperand *op = static_cast<MipsOperand *>(Operands.back());
1594   int RegNo = op->getReg();
1595   // Remove the register from the operands.
1596   Operands.pop_back();
1597   // Add the memory operand.
1598   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
1599     int64_t Imm;
1600     if (IdVal->EvaluateAsAbsolute(Imm))
1601       IdVal = MCConstantExpr::Create(Imm, getContext());
1602     else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
1603       IdVal = MCBinaryExpr::Create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
1604                                    getContext());
1605   }
1606
1607   Operands.push_back(MipsOperand::CreateMem(RegNo, IdVal, S, E));
1608   delete op;
1609   return MatchOperand_Success;
1610 }
1611
1612 bool MipsAsmParser::parsePtrReg(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
1613                                 int RegKind) {
1614   // If the first token is not '$' we have an error.
1615   if (Parser.getTok().isNot(AsmToken::Dollar))
1616     return false;
1617
1618   SMLoc S = Parser.getTok().getLoc();
1619   Parser.Lex();
1620   AsmToken::TokenKind TkKind = getLexer().getKind();
1621   int Reg;
1622
1623   if (TkKind == AsmToken::Integer) {
1624     Reg = matchRegisterByNumber(Parser.getTok().getIntVal(),
1625                                 regKindToRegClass(RegKind));
1626     if (Reg == -1)
1627       return false;
1628   } else if (TkKind == AsmToken::Identifier) {
1629     if ((Reg = matchCPURegisterName(Parser.getTok().getString().lower())) == -1)
1630       return false;
1631     Reg = getReg(regKindToRegClass(RegKind), Reg);
1632   } else {
1633     return false;
1634   }
1635
1636   MipsOperand *Op = MipsOperand::CreatePtrReg(Reg, S, Parser.getTok().getLoc());
1637   Op->setRegKind((MipsOperand::RegisterKind)RegKind);
1638   Operands.push_back(Op);
1639   Parser.Lex();
1640   return true;
1641 }
1642
1643 MipsAsmParser::OperandMatchResultTy
1644 MipsAsmParser::parsePtrReg(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1645   MipsOperand::RegisterKind RegKind =
1646       isN64() ? MipsOperand::Kind_GPR64 : MipsOperand::Kind_GPR32;
1647
1648   // Parse index register.
1649   if (!parsePtrReg(Operands, RegKind))
1650     return MatchOperand_NoMatch;
1651
1652   // Parse '('.
1653   if (Parser.getTok().isNot(AsmToken::LParen))
1654     return MatchOperand_NoMatch;
1655
1656   Operands.push_back(MipsOperand::CreateToken("(", getLexer().getLoc()));
1657   Parser.Lex();
1658
1659   // Parse base register.
1660   if (!parsePtrReg(Operands, RegKind))
1661     return MatchOperand_NoMatch;
1662
1663   // Parse ')'.
1664   if (Parser.getTok().isNot(AsmToken::RParen))
1665     return MatchOperand_NoMatch;
1666
1667   Operands.push_back(MipsOperand::CreateToken(")", getLexer().getLoc()));
1668   Parser.Lex();
1669
1670   return MatchOperand_Success;
1671 }
1672
1673 MipsAsmParser::OperandMatchResultTy
1674 MipsAsmParser::parseRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
1675                          int RegKind) {
1676   MipsOperand::RegisterKind Kind = (MipsOperand::RegisterKind)RegKind;
1677   if (getLexer().getKind() == AsmToken::Identifier && !hasConsumedDollar) {
1678     if (searchSymbolAlias(Operands, Kind))
1679       return MatchOperand_Success;
1680     return MatchOperand_NoMatch;
1681   }
1682   SMLoc S = Parser.getTok().getLoc();
1683   // If the first token is not '$', we have an error.
1684   if (Parser.getTok().isNot(AsmToken::Dollar) && !hasConsumedDollar)
1685     return MatchOperand_NoMatch;
1686   if (!hasConsumedDollar) {
1687     Parser.Lex(); // Eat the '$'
1688     hasConsumedDollar = true;
1689   }
1690   if (getLexer().getKind() == AsmToken::Identifier) {
1691     int RegNum = -1;
1692     std::string RegName = Parser.getTok().getString().lower();
1693     // Match register by name
1694     switch (RegKind) {
1695     case MipsOperand::Kind_GPR32:
1696     case MipsOperand::Kind_GPR64:
1697       RegNum = matchCPURegisterName(RegName);
1698       break;
1699     case MipsOperand::Kind_AFGR64Regs:
1700     case MipsOperand::Kind_FGR64Regs:
1701     case MipsOperand::Kind_FGR32Regs:
1702     case MipsOperand::Kind_FGRH32Regs:
1703       RegNum = matchFPURegisterName(RegName);
1704       if (RegKind == MipsOperand::Kind_AFGR64Regs)
1705         RegNum /= 2;
1706       else if (RegKind == MipsOperand::Kind_FGRH32Regs && !isFP64())
1707         if (RegNum != -1 && RegNum % 2 != 0)
1708           Warning(S, "Float register should be even.");
1709       break;
1710     case MipsOperand::Kind_FCCRegs:
1711       RegNum = matchFCCRegisterName(RegName);
1712       break;
1713     case MipsOperand::Kind_ACC64DSP:
1714       RegNum = matchACRegisterName(RegName);
1715       break;
1716     default:
1717       break; // No match, value is set to -1.
1718     }
1719     // No match found, return _NoMatch to give a chance to other round.
1720     if (RegNum < 0)
1721       return MatchOperand_NoMatch;
1722
1723     int RegVal = getReg(regKindToRegClass(Kind), RegNum);
1724     if (RegVal == -1)
1725       return MatchOperand_NoMatch;
1726
1727     MipsOperand *Op =
1728         MipsOperand::CreateReg(RegVal, S, Parser.getTok().getLoc());
1729     Op->setRegKind(Kind);
1730     Operands.push_back(Op);
1731     hasConsumedDollar = false;
1732     Parser.Lex(); // Eat the register name.
1733     return MatchOperand_Success;
1734   } else if (getLexer().getKind() == AsmToken::Integer) {
1735     unsigned RegNum = Parser.getTok().getIntVal();
1736     if (Kind == MipsOperand::Kind_HWRegs) {
1737       if (RegNum != 29)
1738         return MatchOperand_NoMatch;
1739       // Only hwreg 29 is supported, found at index 0.
1740       RegNum = 0;
1741     }
1742     int Reg = matchRegisterByNumber(RegNum, regKindToRegClass(Kind));
1743     if (Reg == -1)
1744       return MatchOperand_NoMatch;
1745     MipsOperand *Op = MipsOperand::CreateReg(Reg, S, Parser.getTok().getLoc());
1746     Op->setRegKind(Kind);
1747     Operands.push_back(Op);
1748     hasConsumedDollar = false;
1749     Parser.Lex(); // Eat the register number.
1750     if ((RegKind == MipsOperand::Kind_GPR32) &&
1751         (getLexer().is(AsmToken::LParen))) {
1752       // Check if it is indexed addressing operand.
1753       Operands.push_back(MipsOperand::CreateToken("(", getLexer().getLoc()));
1754       Parser.Lex(); // Eat the parenthesis.
1755       if (parseRegs(Operands, RegKind) != MatchOperand_Success)
1756         return MatchOperand_NoMatch;
1757       if (getLexer().isNot(AsmToken::RParen))
1758         return MatchOperand_NoMatch;
1759       Operands.push_back(MipsOperand::CreateToken(")", getLexer().getLoc()));
1760       Parser.Lex();
1761     }
1762     return MatchOperand_Success;
1763   }
1764   return MatchOperand_NoMatch;
1765 }
1766
1767 bool MipsAsmParser::validateMSAIndex(int Val, int RegKind) {
1768   MipsOperand::RegisterKind Kind = (MipsOperand::RegisterKind)RegKind;
1769
1770   if (Val < 0)
1771     return false;
1772
1773   switch (Kind) {
1774   default:
1775     return false;
1776   case MipsOperand::Kind_MSA128BRegs:
1777     return Val < 16;
1778   case MipsOperand::Kind_MSA128HRegs:
1779     return Val < 8;
1780   case MipsOperand::Kind_MSA128WRegs:
1781     return Val < 4;
1782   case MipsOperand::Kind_MSA128DRegs:
1783     return Val < 2;
1784   }
1785 }
1786
1787 MipsAsmParser::OperandMatchResultTy
1788 MipsAsmParser::parseMSARegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
1789                             int RegKind) {
1790   MipsOperand::RegisterKind Kind = (MipsOperand::RegisterKind)RegKind;
1791   SMLoc S = Parser.getTok().getLoc();
1792   std::string RegName;
1793
1794   if (Parser.getTok().isNot(AsmToken::Dollar))
1795     return MatchOperand_NoMatch;
1796
1797   switch (RegKind) {
1798   default:
1799     return MatchOperand_ParseFail;
1800   case MipsOperand::Kind_MSA128BRegs:
1801   case MipsOperand::Kind_MSA128HRegs:
1802   case MipsOperand::Kind_MSA128WRegs:
1803   case MipsOperand::Kind_MSA128DRegs:
1804     break;
1805   }
1806
1807   Parser.Lex(); // Eat the '$'.
1808   if (getLexer().getKind() == AsmToken::Identifier)
1809     RegName = Parser.getTok().getString().lower();
1810   else
1811     return MatchOperand_ParseFail;
1812
1813   int RegNum = matchMSA128RegisterName(RegName);
1814
1815   if (RegNum < 0 || RegNum > 31)
1816     return MatchOperand_ParseFail;
1817
1818   int RegVal = getReg(regKindToRegClass(Kind), RegNum);
1819   if (RegVal == -1)
1820     return MatchOperand_ParseFail;
1821
1822   MipsOperand *Op = MipsOperand::CreateReg(RegVal, S, Parser.getTok().getLoc());
1823   Op->setRegKind(Kind);
1824   Operands.push_back(Op);
1825
1826   Parser.Lex(); // Eat the register identifier.
1827
1828   // MSA registers may be suffixed with an index in the form of:
1829   // 1) Immediate expression.
1830   // 2) General Purpose Register.
1831   // Examples:
1832   //   1) copy_s.b $29,$w0[0]
1833   //   2) sld.b $w0,$w1[$1]
1834
1835   if (Parser.getTok().isNot(AsmToken::LBrac))
1836     return MatchOperand_Success;
1837
1838   MipsOperand *Mnemonic = static_cast<MipsOperand *>(Operands[0]);
1839
1840   Operands.push_back(MipsOperand::CreateToken("[", Parser.getTok().getLoc()));
1841   Parser.Lex(); // Parse the '[' token.
1842
1843   if (Parser.getTok().is(AsmToken::Dollar)) {
1844     // This must be a GPR.
1845     MipsOperand *RegOp;
1846     SMLoc VIdx = Parser.getTok().getLoc();
1847     Parser.Lex(); // Parse the '$' token.
1848
1849     // GPR have aliases and we must account for that. Example: $30 == $fp
1850     if (getLexer().getKind() == AsmToken::Integer) {
1851       unsigned RegNum = Parser.getTok().getIntVal();
1852       int Reg = matchRegisterByNumber(
1853           RegNum, regKindToRegClass(MipsOperand::Kind_GPR32));
1854       if (Reg == -1) {
1855         Error(VIdx, "invalid general purpose register");
1856         return MatchOperand_ParseFail;
1857       }
1858
1859       RegOp = MipsOperand::CreateReg(Reg, VIdx, Parser.getTok().getLoc());
1860     } else if (getLexer().getKind() == AsmToken::Identifier) {
1861       int RegNum = -1;
1862       std::string RegName = Parser.getTok().getString().lower();
1863
1864       RegNum = matchCPURegisterName(RegName);
1865       if (RegNum == -1) {
1866         Error(VIdx, "general purpose register expected");
1867         return MatchOperand_ParseFail;
1868       }
1869       RegNum = getReg(regKindToRegClass(MipsOperand::Kind_GPR32), RegNum);
1870       RegOp = MipsOperand::CreateReg(RegNum, VIdx, Parser.getTok().getLoc());
1871     } else
1872       return MatchOperand_ParseFail;
1873
1874     RegOp->setRegKind(MipsOperand::Kind_GPR32);
1875     Operands.push_back(RegOp);
1876     Parser.Lex(); // Eat the register identifier.
1877
1878     if (Parser.getTok().isNot(AsmToken::RBrac))
1879       return MatchOperand_ParseFail;
1880
1881     Operands.push_back(MipsOperand::CreateToken("]", Parser.getTok().getLoc()));
1882     Parser.Lex(); // Parse the ']' token.
1883
1884     return MatchOperand_Success;
1885   }
1886
1887   // The index must be a constant expression then.
1888   SMLoc VIdx = Parser.getTok().getLoc();
1889   const MCExpr *ImmVal;
1890
1891   if (getParser().parseExpression(ImmVal))
1892     return MatchOperand_ParseFail;
1893
1894   const MCConstantExpr *expr = dyn_cast<MCConstantExpr>(ImmVal);
1895   if (!expr || !validateMSAIndex((int)expr->getValue(), Kind)) {
1896     Error(VIdx, "invalid immediate value");
1897     return MatchOperand_ParseFail;
1898   }
1899
1900   SMLoc E = Parser.getTok().getEndLoc();
1901
1902   if (Parser.getTok().isNot(AsmToken::RBrac))
1903     return MatchOperand_ParseFail;
1904
1905   bool insve =
1906       Mnemonic->getToken() == "insve.b" || Mnemonic->getToken() == "insve.h" ||
1907       Mnemonic->getToken() == "insve.w" || Mnemonic->getToken() == "insve.d";
1908
1909   // The second vector index of insve instructions is always 0.
1910   if (insve && Operands.size() > 6) {
1911     if (expr->getValue() != 0) {
1912       Error(VIdx, "immediate value must be 0");
1913       return MatchOperand_ParseFail;
1914     }
1915     Operands.push_back(MipsOperand::CreateToken("0", VIdx));
1916   } else
1917     Operands.push_back(MipsOperand::CreateImm(expr, VIdx, E));
1918
1919   Operands.push_back(MipsOperand::CreateToken("]", Parser.getTok().getLoc()));
1920
1921   Parser.Lex(); // Parse the ']' token.
1922
1923   return MatchOperand_Success;
1924 }
1925
1926 MipsAsmParser::OperandMatchResultTy
1927 MipsAsmParser::parseMSACtrlRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands,
1928                                 int RegKind) {
1929   MipsOperand::RegisterKind Kind = (MipsOperand::RegisterKind)RegKind;
1930
1931   if (Kind != MipsOperand::Kind_MSA128CtrlRegs)
1932     return MatchOperand_NoMatch;
1933
1934   if (Parser.getTok().isNot(AsmToken::Dollar))
1935     return MatchOperand_ParseFail;
1936
1937   SMLoc S = Parser.getTok().getLoc();
1938
1939   Parser.Lex(); // Eat the '$' symbol.
1940
1941   int RegNum = -1;
1942   if (getLexer().getKind() == AsmToken::Identifier)
1943     RegNum = matchMSA128CtrlRegisterName(Parser.getTok().getString().lower());
1944   else if (getLexer().getKind() == AsmToken::Integer)
1945     RegNum = Parser.getTok().getIntVal();
1946   else
1947     return MatchOperand_ParseFail;
1948
1949   if (RegNum < 0 || RegNum > 7)
1950     return MatchOperand_ParseFail;
1951
1952   int RegVal = getReg(regKindToRegClass(Kind), RegNum);
1953   if (RegVal == -1)
1954     return MatchOperand_ParseFail;
1955
1956   MipsOperand *RegOp =
1957       MipsOperand::CreateReg(RegVal, S, Parser.getTok().getLoc());
1958   RegOp->setRegKind(MipsOperand::Kind_MSA128CtrlRegs);
1959   Operands.push_back(RegOp);
1960   Parser.Lex(); // Eat the register identifier.
1961
1962   return MatchOperand_Success;
1963 }
1964
1965 MipsAsmParser::OperandMatchResultTy
1966 MipsAsmParser::parseGPR64(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1967
1968   if (!isMips64())
1969     return MatchOperand_NoMatch;
1970   return parseRegs(Operands, (int)MipsOperand::Kind_GPR64);
1971 }
1972
1973 MipsAsmParser::OperandMatchResultTy
1974 MipsAsmParser::parseGPR32(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1975   return parseRegs(Operands, (int)MipsOperand::Kind_GPR32);
1976 }
1977
1978 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseAFGR64Regs(
1979     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1980
1981   if (isFP64())
1982     return MatchOperand_NoMatch;
1983   return parseRegs(Operands, (int)MipsOperand::Kind_AFGR64Regs);
1984 }
1985
1986 MipsAsmParser::OperandMatchResultTy
1987 MipsAsmParser::parseFGR64Regs(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1988   if (!isFP64())
1989     return MatchOperand_NoMatch;
1990   return parseRegs(Operands, (int)MipsOperand::Kind_FGR64Regs);
1991 }
1992
1993 MipsAsmParser::OperandMatchResultTy
1994 MipsAsmParser::parseFGR32Regs(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
1995   return parseRegs(Operands, (int)MipsOperand::Kind_FGR32Regs);
1996 }
1997
1998 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseFGRH32Regs(
1999     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2000   return parseRegs(Operands, (int)MipsOperand::Kind_FGRH32Regs);
2001 }
2002
2003 MipsAsmParser::OperandMatchResultTy
2004 MipsAsmParser::parseFCCRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2005   return parseRegs(Operands, (int)MipsOperand::Kind_FCCRegs);
2006 }
2007
2008 MipsAsmParser::OperandMatchResultTy
2009 MipsAsmParser::parseACC64DSP(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2010   return parseRegs(Operands, (int)MipsOperand::Kind_ACC64DSP);
2011 }
2012
2013 MipsAsmParser::OperandMatchResultTy
2014 MipsAsmParser::parseLO32DSP(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2015   // If the first token is not '$' we have an error.
2016   if (Parser.getTok().isNot(AsmToken::Dollar))
2017     return MatchOperand_NoMatch;
2018
2019   SMLoc S = Parser.getTok().getLoc();
2020   Parser.Lex(); // Eat the '$'
2021
2022   const AsmToken &Tok = Parser.getTok(); // Get next token.
2023
2024   if (Tok.isNot(AsmToken::Identifier))
2025     return MatchOperand_NoMatch;
2026
2027   if (!Tok.getIdentifier().startswith("ac"))
2028     return MatchOperand_NoMatch;
2029
2030   StringRef NumString = Tok.getIdentifier().substr(2);
2031
2032   unsigned IntVal;
2033   if (NumString.getAsInteger(10, IntVal))
2034     return MatchOperand_NoMatch;
2035
2036   unsigned Reg = matchRegisterByNumber(IntVal, Mips::LO32DSPRegClassID);
2037
2038   MipsOperand *Op = MipsOperand::CreateReg(Reg, S, Parser.getTok().getLoc());
2039   Op->setRegKind(MipsOperand::Kind_LO32DSP);
2040   Operands.push_back(Op);
2041
2042   Parser.Lex(); // Eat the register number.
2043   return MatchOperand_Success;
2044 }
2045
2046 MipsAsmParser::OperandMatchResultTy
2047 MipsAsmParser::parseHI32DSP(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2048   // If the first token is not '$' we have an error.
2049   if (Parser.getTok().isNot(AsmToken::Dollar))
2050     return MatchOperand_NoMatch;
2051
2052   SMLoc S = Parser.getTok().getLoc();
2053   Parser.Lex(); // Eat the '$'
2054
2055   const AsmToken &Tok = Parser.getTok(); // Get next token.
2056
2057   if (Tok.isNot(AsmToken::Identifier))
2058     return MatchOperand_NoMatch;
2059
2060   if (!Tok.getIdentifier().startswith("ac"))
2061     return MatchOperand_NoMatch;
2062
2063   StringRef NumString = Tok.getIdentifier().substr(2);
2064
2065   unsigned IntVal;
2066   if (NumString.getAsInteger(10, IntVal))
2067     return MatchOperand_NoMatch;
2068
2069   unsigned Reg = matchRegisterByNumber(IntVal, Mips::HI32DSPRegClassID);
2070
2071   MipsOperand *Op = MipsOperand::CreateReg(Reg, S, Parser.getTok().getLoc());
2072   Op->setRegKind(MipsOperand::Kind_HI32DSP);
2073   Operands.push_back(Op);
2074
2075   Parser.Lex(); // Eat the register number.
2076   return MatchOperand_Success;
2077 }
2078
2079 MipsAsmParser::OperandMatchResultTy
2080 MipsAsmParser::parseCOP2(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2081   // If the first token is not '$' we have an error.
2082   if (Parser.getTok().isNot(AsmToken::Dollar))
2083     return MatchOperand_NoMatch;
2084
2085   SMLoc S = Parser.getTok().getLoc();
2086   Parser.Lex(); // Eat the '$'
2087
2088   const AsmToken &Tok = Parser.getTok(); // Get next token.
2089
2090   if (Tok.isNot(AsmToken::Integer))
2091     return MatchOperand_NoMatch;
2092
2093   unsigned IntVal = Tok.getIntVal();
2094
2095   unsigned Reg = matchRegisterByNumber(IntVal, Mips::COP2RegClassID);
2096
2097   MipsOperand *Op = MipsOperand::CreateReg(Reg, S, Parser.getTok().getLoc());
2098   Op->setRegKind(MipsOperand::Kind_COP2);
2099   Operands.push_back(Op);
2100
2101   Parser.Lex(); // Eat the register number.
2102   return MatchOperand_Success;
2103 }
2104
2105 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMSA128BRegs(
2106     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2107   return parseMSARegs(Operands, (int)MipsOperand::Kind_MSA128BRegs);
2108 }
2109
2110 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMSA128HRegs(
2111     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2112   return parseMSARegs(Operands, (int)MipsOperand::Kind_MSA128HRegs);
2113 }
2114
2115 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMSA128WRegs(
2116     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2117   return parseMSARegs(Operands, (int)MipsOperand::Kind_MSA128WRegs);
2118 }
2119
2120 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMSA128DRegs(
2121     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2122   return parseMSARegs(Operands, (int)MipsOperand::Kind_MSA128DRegs);
2123 }
2124
2125 MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMSA128CtrlRegs(
2126     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2127   return parseMSACtrlRegs(Operands, (int)MipsOperand::Kind_MSA128CtrlRegs);
2128 }
2129
2130 bool MipsAsmParser::searchSymbolAlias(
2131     SmallVectorImpl<MCParsedAsmOperand *> &Operands, unsigned RegKind) {
2132
2133   MCSymbol *Sym = getContext().LookupSymbol(Parser.getTok().getIdentifier());
2134   if (Sym) {
2135     SMLoc S = Parser.getTok().getLoc();
2136     const MCExpr *Expr;
2137     if (Sym->isVariable())
2138       Expr = Sym->getVariableValue();
2139     else
2140       return false;
2141     if (Expr->getKind() == MCExpr::SymbolRef) {
2142       MipsOperand::RegisterKind Kind = (MipsOperand::RegisterKind)RegKind;
2143       const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
2144       const StringRef DefSymbol = Ref->getSymbol().getName();
2145       if (DefSymbol.startswith("$")) {
2146         int RegNum = -1;
2147         APInt IntVal(32, -1);
2148         if (!DefSymbol.substr(1).getAsInteger(10, IntVal))
2149           RegNum = matchRegisterByNumber(IntVal.getZExtValue(),
2150                                          isMips64() ? Mips::GPR64RegClassID
2151                                                     : Mips::GPR32RegClassID);
2152         else {
2153           // Lookup for the register with the corresponding name.
2154           switch (Kind) {
2155           case MipsOperand::Kind_AFGR64Regs:
2156           case MipsOperand::Kind_FGR64Regs:
2157             RegNum = matchFPURegisterName(DefSymbol.substr(1));
2158             break;
2159           case MipsOperand::Kind_FGR32Regs:
2160             RegNum = matchFPURegisterName(DefSymbol.substr(1));
2161             break;
2162           case MipsOperand::Kind_GPR64:
2163           case MipsOperand::Kind_GPR32:
2164           default:
2165             RegNum = matchCPURegisterName(DefSymbol.substr(1));
2166             break;
2167           }
2168           if (RegNum > -1)
2169             RegNum = getReg(regKindToRegClass(Kind), RegNum);
2170         }
2171         if (RegNum > -1) {
2172           Parser.Lex();
2173           MipsOperand *op =
2174               MipsOperand::CreateReg(RegNum, S, Parser.getTok().getLoc());
2175           op->setRegKind(Kind);
2176           Operands.push_back(op);
2177           return true;
2178         }
2179       }
2180     } else if (Expr->getKind() == MCExpr::Constant) {
2181       Parser.Lex();
2182       const MCConstantExpr *Const = static_cast<const MCConstantExpr *>(Expr);
2183       MipsOperand *op =
2184           MipsOperand::CreateImm(Const, S, Parser.getTok().getLoc());
2185       Operands.push_back(op);
2186       return true;
2187     }
2188   }
2189   return false;
2190 }
2191
2192 MipsAsmParser::OperandMatchResultTy
2193 MipsAsmParser::parseHWRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2194   return parseRegs(Operands, (int)MipsOperand::Kind_HWRegs);
2195 }
2196
2197 MipsAsmParser::OperandMatchResultTy
2198 MipsAsmParser::parseCCRRegs(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2199   return parseRegs(Operands, (int)MipsOperand::Kind_CCRRegs);
2200 }
2201
2202 MipsAsmParser::OperandMatchResultTy
2203 MipsAsmParser::parseInvNum(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2204   const MCExpr *IdVal;
2205   // If the first token is '$' we may have register operand.
2206   if (Parser.getTok().is(AsmToken::Dollar))
2207     return MatchOperand_NoMatch;
2208   SMLoc S = Parser.getTok().getLoc();
2209   if (getParser().parseExpression(IdVal))
2210     return MatchOperand_ParseFail;
2211   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
2212   assert(MCE && "Unexpected MCExpr type.");
2213   int64_t Val = MCE->getValue();
2214   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2215   Operands.push_back(MipsOperand::CreateImm(
2216       MCConstantExpr::Create(0 - Val, getContext()), S, E));
2217   return MatchOperand_Success;
2218 }
2219
2220 MipsAsmParser::OperandMatchResultTy
2221 MipsAsmParser::parseLSAImm(SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2222   switch (getLexer().getKind()) {
2223   default:
2224     return MatchOperand_NoMatch;
2225   case AsmToken::LParen:
2226   case AsmToken::Plus:
2227   case AsmToken::Minus:
2228   case AsmToken::Integer:
2229     break;
2230   }
2231
2232   const MCExpr *Expr;
2233   SMLoc S = Parser.getTok().getLoc();
2234
2235   if (getParser().parseExpression(Expr))
2236     return MatchOperand_ParseFail;
2237
2238   int64_t Val;
2239   if (!Expr->EvaluateAsAbsolute(Val)) {
2240     Error(S, "expected immediate value");
2241     return MatchOperand_ParseFail;
2242   }
2243
2244   // The LSA instruction allows a 2-bit unsigned immediate. For this reason
2245   // and because the CPU always adds one to the immediate field, the allowed
2246   // range becomes 1..4. We'll only check the range here and will deal
2247   // with the addition/subtraction when actually decoding/encoding
2248   // the instruction.
2249   if (Val < 1 || Val > 4) {
2250     Error(S, "immediate not in range (1..4)");
2251     return MatchOperand_ParseFail;
2252   }
2253
2254   Operands.push_back(
2255       MipsOperand::CreateLSAImm(Expr, S, Parser.getTok().getLoc()));
2256   return MatchOperand_Success;
2257 }
2258
2259 MCSymbolRefExpr::VariantKind MipsAsmParser::getVariantKind(StringRef Symbol) {
2260
2261   MCSymbolRefExpr::VariantKind VK =
2262       StringSwitch<MCSymbolRefExpr::VariantKind>(Symbol)
2263           .Case("hi", MCSymbolRefExpr::VK_Mips_ABS_HI)
2264           .Case("lo", MCSymbolRefExpr::VK_Mips_ABS_LO)
2265           .Case("gp_rel", MCSymbolRefExpr::VK_Mips_GPREL)
2266           .Case("call16", MCSymbolRefExpr::VK_Mips_GOT_CALL)
2267           .Case("got", MCSymbolRefExpr::VK_Mips_GOT)
2268           .Case("tlsgd", MCSymbolRefExpr::VK_Mips_TLSGD)
2269           .Case("tlsldm", MCSymbolRefExpr::VK_Mips_TLSLDM)
2270           .Case("dtprel_hi", MCSymbolRefExpr::VK_Mips_DTPREL_HI)
2271           .Case("dtprel_lo", MCSymbolRefExpr::VK_Mips_DTPREL_LO)
2272           .Case("gottprel", MCSymbolRefExpr::VK_Mips_GOTTPREL)
2273           .Case("tprel_hi", MCSymbolRefExpr::VK_Mips_TPREL_HI)
2274           .Case("tprel_lo", MCSymbolRefExpr::VK_Mips_TPREL_LO)
2275           .Case("got_disp", MCSymbolRefExpr::VK_Mips_GOT_DISP)
2276           .Case("got_page", MCSymbolRefExpr::VK_Mips_GOT_PAGE)
2277           .Case("got_ofst", MCSymbolRefExpr::VK_Mips_GOT_OFST)
2278           .Case("hi(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_HI)
2279           .Case("lo(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_LO)
2280           .Default(MCSymbolRefExpr::VK_None);
2281
2282   return VK;
2283 }
2284
2285 bool MipsAsmParser::ParseInstruction(
2286     ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
2287     SmallVectorImpl<MCParsedAsmOperand *> &Operands) {
2288   // Check if we have valid mnemonic
2289   if (!mnemonicIsValid(Name, 0)) {
2290     Parser.eatToEndOfStatement();
2291     return Error(NameLoc, "Unknown instruction");
2292   }
2293   // First operand in MCInst is instruction mnemonic.
2294   Operands.push_back(MipsOperand::CreateToken(Name, NameLoc));
2295
2296   // Read the remaining operands.
2297   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2298     // Read the first operand.
2299     if (ParseOperand(Operands, Name)) {
2300       SMLoc Loc = getLexer().getLoc();
2301       Parser.eatToEndOfStatement();
2302       return Error(Loc, "unexpected token in argument list");
2303     }
2304
2305     while (getLexer().is(AsmToken::Comma)) {
2306       Parser.Lex(); // Eat the comma.
2307       // Parse and remember the operand.
2308       if (ParseOperand(Operands, Name)) {
2309         SMLoc Loc = getLexer().getLoc();
2310         Parser.eatToEndOfStatement();
2311         return Error(Loc, "unexpected token in argument list");
2312       }
2313     }
2314   }
2315   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2316     SMLoc Loc = getLexer().getLoc();
2317     Parser.eatToEndOfStatement();
2318     return Error(Loc, "unexpected token in argument list");
2319   }
2320   Parser.Lex(); // Consume the EndOfStatement.
2321   return false;
2322 }
2323
2324 bool MipsAsmParser::reportParseError(StringRef ErrorMsg) {
2325   SMLoc Loc = getLexer().getLoc();
2326   Parser.eatToEndOfStatement();
2327   return Error(Loc, ErrorMsg);
2328 }
2329
2330 bool MipsAsmParser::parseSetNoAtDirective() {
2331   // Line should look like: ".set noat".
2332   // set at reg to 0.
2333   Options.setATReg(0);
2334   // eat noat
2335   Parser.Lex();
2336   // If this is not the end of the statement, report an error.
2337   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2338     reportParseError("unexpected token in statement");
2339     return false;
2340   }
2341   Parser.Lex(); // Consume the EndOfStatement.
2342   return false;
2343 }
2344
2345 bool MipsAsmParser::parseSetAtDirective() {
2346   // Line can be .set at - defaults to $1
2347   // or .set at=$reg
2348   int AtRegNo;
2349   getParser().Lex();
2350   if (getLexer().is(AsmToken::EndOfStatement)) {
2351     Options.setATReg(1);
2352     Parser.Lex(); // Consume the EndOfStatement.
2353     return false;
2354   } else if (getLexer().is(AsmToken::Equal)) {
2355     getParser().Lex(); // Eat the '='.
2356     if (getLexer().isNot(AsmToken::Dollar)) {
2357       reportParseError("unexpected token in statement");
2358       return false;
2359     }
2360     Parser.Lex(); // Eat the '$'.
2361     const AsmToken &Reg = Parser.getTok();
2362     if (Reg.is(AsmToken::Identifier)) {
2363       AtRegNo = matchCPURegisterName(Reg.getIdentifier());
2364     } else if (Reg.is(AsmToken::Integer)) {
2365       AtRegNo = Reg.getIntVal();
2366     } else {
2367       reportParseError("unexpected token in statement");
2368       return false;
2369     }
2370
2371     if (AtRegNo < 0 || AtRegNo > 31) {
2372       reportParseError("unexpected token in statement");
2373       return false;
2374     }
2375
2376     if (!Options.setATReg(AtRegNo)) {
2377       reportParseError("unexpected token in statement");
2378       return false;
2379     }
2380     getParser().Lex(); // Eat the register.
2381
2382     if (getLexer().isNot(AsmToken::EndOfStatement)) {
2383       reportParseError("unexpected token in statement");
2384       return false;
2385     }
2386     Parser.Lex(); // Consume the EndOfStatement.
2387     return false;
2388   } else {
2389     reportParseError("unexpected token in statement");
2390     return false;
2391   }
2392 }
2393
2394 bool MipsAsmParser::parseSetReorderDirective() {
2395   Parser.Lex();
2396   // If this is not the end of the statement, report an error.
2397   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2398     reportParseError("unexpected token in statement");
2399     return false;
2400   }
2401   Options.setReorder();
2402   getTargetStreamer().emitDirectiveSetReorder();
2403   Parser.Lex(); // Consume the EndOfStatement.
2404   return false;
2405 }
2406
2407 bool MipsAsmParser::parseSetNoReorderDirective() {
2408   Parser.Lex();
2409   // If this is not the end of the statement, report an error.
2410   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2411     reportParseError("unexpected token in statement");
2412     return false;
2413   }
2414   Options.setNoreorder();
2415   getTargetStreamer().emitDirectiveSetNoReorder();
2416   Parser.Lex(); // Consume the EndOfStatement.
2417   return false;
2418 }
2419
2420 bool MipsAsmParser::parseSetMacroDirective() {
2421   Parser.Lex();
2422   // If this is not the end of the statement, report an error.
2423   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2424     reportParseError("unexpected token in statement");
2425     return false;
2426   }
2427   Options.setMacro();
2428   Parser.Lex(); // Consume the EndOfStatement.
2429   return false;
2430 }
2431
2432 bool MipsAsmParser::parseSetNoMacroDirective() {
2433   Parser.Lex();
2434   // If this is not the end of the statement, report an error.
2435   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2436     reportParseError("`noreorder' must be set before `nomacro'");
2437     return false;
2438   }
2439   if (Options.isReorder()) {
2440     reportParseError("`noreorder' must be set before `nomacro'");
2441     return false;
2442   }
2443   Options.setNomacro();
2444   Parser.Lex(); // Consume the EndOfStatement.
2445   return false;
2446 }
2447
2448 bool MipsAsmParser::parseSetNoMips16Directive() {
2449   Parser.Lex();
2450   // If this is not the end of the statement, report an error.
2451   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2452     reportParseError("unexpected token in statement");
2453     return false;
2454   }
2455   // For now do nothing.
2456   Parser.Lex(); // Consume the EndOfStatement.
2457   return false;
2458 }
2459
2460 bool MipsAsmParser::parseSetAssignment() {
2461   StringRef Name;
2462   const MCExpr *Value;
2463
2464   if (Parser.parseIdentifier(Name))
2465     reportParseError("expected identifier after .set");
2466
2467   if (getLexer().isNot(AsmToken::Comma))
2468     return reportParseError("unexpected token in .set directive");
2469   Lex(); // Eat comma
2470
2471   if (Parser.parseExpression(Value))
2472     return reportParseError("expected valid expression after comma");
2473
2474   // Check if the Name already exists as a symbol.
2475   MCSymbol *Sym = getContext().LookupSymbol(Name);
2476   if (Sym)
2477     return reportParseError("symbol already defined");
2478   Sym = getContext().GetOrCreateSymbol(Name);
2479   Sym->setVariableValue(Value);
2480
2481   return false;
2482 }
2483
2484 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
2485   Parser.Lex();
2486   if (getLexer().isNot(AsmToken::EndOfStatement))
2487     return reportParseError("unexpected token in .set directive");
2488
2489   switch(Feature) {
2490     default: llvm_unreachable("Unimplemented feature");
2491     case Mips::FeatureDSP:
2492       setFeatureBits(Mips::FeatureDSP, "dsp");
2493       getTargetStreamer().emitDirectiveSetDsp();
2494     break;
2495     case Mips::FeatureMicroMips:
2496       getTargetStreamer().emitDirectiveSetMicroMips();
2497     break;
2498     case Mips::FeatureMips16:
2499       getTargetStreamer().emitDirectiveSetMips16();
2500     break;
2501     case Mips::FeatureMips32r2:
2502       setFeatureBits(Mips::FeatureMips32r2, "mips32r2");
2503       getTargetStreamer().emitDirectiveSetMips32R2();
2504     break;
2505     case Mips::FeatureMips64:
2506       setFeatureBits(Mips::FeatureMips64, "mips64");
2507       getTargetStreamer().emitDirectiveSetMips64();
2508     break;
2509     case Mips::FeatureMips64r2:
2510       setFeatureBits(Mips::FeatureMips64r2, "mips64r2");
2511       getTargetStreamer().emitDirectiveSetMips64R2();
2512     break;
2513   }
2514   return false;
2515 }
2516
2517 bool MipsAsmParser::parseRegister(unsigned &RegNum) {
2518   if (!getLexer().is(AsmToken::Dollar))
2519     return false;
2520
2521   Parser.Lex();
2522
2523   const AsmToken &Reg = Parser.getTok();
2524   if (Reg.is(AsmToken::Identifier)) {
2525     RegNum = matchCPURegisterName(Reg.getIdentifier());
2526   } else if (Reg.is(AsmToken::Integer)) {
2527     RegNum = Reg.getIntVal();
2528   } else {
2529     return false;
2530   }
2531
2532   Parser.Lex();
2533   return true;
2534 }
2535
2536 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
2537   if (getLexer().isNot(AsmToken::Comma)) {
2538     SMLoc Loc = getLexer().getLoc();
2539     Parser.eatToEndOfStatement();
2540     return Error(Loc, ErrorStr);
2541   }
2542
2543   Parser.Lex();  // Eat the comma.
2544   return true;
2545 }
2546
2547 bool MipsAsmParser::parseDirectiveCPSetup() {
2548   unsigned FuncReg;
2549   unsigned Save;
2550   bool SaveIsReg = true;
2551
2552   if (!parseRegister(FuncReg))
2553     return reportParseError("expected register containing function address");
2554   FuncReg = getGPR(FuncReg);
2555
2556   if (!eatComma("expected comma parsing directive"))
2557     return true;
2558
2559   if (!parseRegister(Save)) {
2560     const AsmToken &Tok = Parser.getTok();
2561     if (Tok.is(AsmToken::Integer)) {
2562       Save = Tok.getIntVal();
2563       SaveIsReg = false;
2564       Parser.Lex();
2565     } else
2566       return reportParseError("expected save register or stack offset");
2567   } else
2568     Save = getGPR(Save);
2569
2570   if (!eatComma("expected comma parsing directive"))
2571     return true;
2572
2573   StringRef Name;
2574   if (Parser.parseIdentifier(Name))
2575     reportParseError("expected identifier");
2576   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2577   unsigned GPReg = getGPR(matchCPURegisterName("gp"));
2578
2579   // FIXME: The code below this point should be in the TargetStreamers.
2580   // Only N32 and N64 emit anything for .cpsetup
2581   // FIXME: We should only emit something for PIC mode too.
2582   if (!isN32() && !isN64())
2583     return false;
2584
2585   MCStreamer &TS = getStreamer();
2586   MCInst Inst;
2587   // Either store the old $gp in a register or on the stack
2588   if (SaveIsReg) {
2589     // move $save, $gpreg
2590     Inst.setOpcode(Mips::DADDu);
2591     Inst.addOperand(MCOperand::CreateReg(Save));
2592     Inst.addOperand(MCOperand::CreateReg(GPReg));
2593     Inst.addOperand(MCOperand::CreateReg(getGPR(0)));
2594   } else {
2595     // sd $gpreg, offset($sp)
2596     Inst.setOpcode(Mips::SD);
2597     Inst.addOperand(MCOperand::CreateReg(GPReg));
2598     Inst.addOperand(MCOperand::CreateReg(getGPR(matchCPURegisterName("sp"))));
2599     Inst.addOperand(MCOperand::CreateImm(Save));
2600   }
2601   TS.EmitInstruction(Inst, STI);
2602   Inst.clear();
2603
2604   const MCSymbolRefExpr *HiExpr = MCSymbolRefExpr::Create(
2605       Sym->getName(), MCSymbolRefExpr::VK_Mips_GPOFF_HI,
2606       getContext());
2607   const MCSymbolRefExpr *LoExpr = MCSymbolRefExpr::Create(
2608       Sym->getName(), MCSymbolRefExpr::VK_Mips_GPOFF_LO,
2609       getContext());
2610   // lui $gp, %hi(%neg(%gp_rel(funcSym)))
2611   Inst.setOpcode(Mips::LUi);
2612   Inst.addOperand(MCOperand::CreateReg(GPReg));
2613   Inst.addOperand(MCOperand::CreateExpr(HiExpr));
2614   TS.EmitInstruction(Inst, STI);
2615   Inst.clear();
2616
2617   // addiu  $gp, $gp, %lo(%neg(%gp_rel(funcSym)))
2618   Inst.setOpcode(Mips::ADDiu);
2619   Inst.addOperand(MCOperand::CreateReg(GPReg));
2620   Inst.addOperand(MCOperand::CreateReg(GPReg));
2621   Inst.addOperand(MCOperand::CreateExpr(LoExpr));
2622   TS.EmitInstruction(Inst, STI);
2623   Inst.clear();
2624
2625   // daddu  $gp, $gp, $funcreg
2626   Inst.setOpcode(Mips::DADDu);
2627   Inst.addOperand(MCOperand::CreateReg(GPReg));
2628   Inst.addOperand(MCOperand::CreateReg(GPReg));
2629   Inst.addOperand(MCOperand::CreateReg(FuncReg));
2630   TS.EmitInstruction(Inst, STI);
2631   return false;
2632 }
2633
2634 bool MipsAsmParser::parseDirectiveSet() {
2635
2636   // Get the next token.
2637   const AsmToken &Tok = Parser.getTok();
2638
2639   if (Tok.getString() == "noat") {
2640     return parseSetNoAtDirective();
2641   } else if (Tok.getString() == "at") {
2642     return parseSetAtDirective();
2643   } else if (Tok.getString() == "reorder") {
2644     return parseSetReorderDirective();
2645   } else if (Tok.getString() == "noreorder") {
2646     return parseSetNoReorderDirective();
2647   } else if (Tok.getString() == "macro") {
2648     return parseSetMacroDirective();
2649   } else if (Tok.getString() == "nomacro") {
2650     return parseSetNoMacroDirective();
2651   } else if (Tok.getString() == "mips16") {
2652     return parseSetFeature(Mips::FeatureMips16);
2653   } else if (Tok.getString() == "nomips16") {
2654     return parseSetNoMips16Directive();
2655   } else if (Tok.getString() == "nomicromips") {
2656     getTargetStreamer().emitDirectiveSetNoMicroMips();
2657     Parser.eatToEndOfStatement();
2658     return false;
2659   } else if (Tok.getString() == "micromips") {
2660       return parseSetFeature(Mips::FeatureMicroMips);
2661   } else if (Tok.getString() == "mips32r2") {
2662       return parseSetFeature(Mips::FeatureMips32r2);
2663   } else if (Tok.getString() == "mips64") {
2664       return parseSetFeature(Mips::FeatureMips64);
2665   } else if (Tok.getString() == "mips64r2") {
2666       return parseSetFeature(Mips::FeatureMips64r2);
2667   } else if (Tok.getString() == "dsp") {
2668       return parseSetFeature(Mips::FeatureDSP);
2669   } else {
2670     // It is just an identifier, look for an assignment.
2671     parseSetAssignment();
2672     return false;
2673   }
2674
2675   return true;
2676 }
2677
2678 /// parseDataDirective
2679 ///  ::= .word [ expression (, expression)* ]
2680 bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) {
2681   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2682     for (;;) {
2683       const MCExpr *Value;
2684       if (getParser().parseExpression(Value))
2685         return true;
2686
2687       getParser().getStreamer().EmitValue(Value, Size);
2688
2689       if (getLexer().is(AsmToken::EndOfStatement))
2690         break;
2691
2692       // FIXME: Improve diagnostic.
2693       if (getLexer().isNot(AsmToken::Comma))
2694         return Error(L, "unexpected token in directive");
2695       Parser.Lex();
2696     }
2697   }
2698
2699   Parser.Lex();
2700   return false;
2701 }
2702
2703 /// parseDirectiveGpWord
2704 ///  ::= .gpword local_sym
2705 bool MipsAsmParser::parseDirectiveGpWord() {
2706   const MCExpr *Value;
2707   // EmitGPRel32Value requires an expression, so we are using base class
2708   // method to evaluate the expression.
2709   if (getParser().parseExpression(Value))
2710     return true;
2711   getParser().getStreamer().EmitGPRel32Value(Value);
2712
2713   if (getLexer().isNot(AsmToken::EndOfStatement))
2714     return Error(getLexer().getLoc(), "unexpected token in directive");
2715   Parser.Lex(); // Eat EndOfStatement token.
2716   return false;
2717 }
2718
2719 bool MipsAsmParser::parseDirectiveOption() {
2720   // Get the option token.
2721   AsmToken Tok = Parser.getTok();
2722   // At the moment only identifiers are supported.
2723   if (Tok.isNot(AsmToken::Identifier)) {
2724     Error(Parser.getTok().getLoc(), "unexpected token in .option directive");
2725     Parser.eatToEndOfStatement();
2726     return false;
2727   }
2728
2729   StringRef Option = Tok.getIdentifier();
2730
2731   if (Option == "pic0") {
2732     getTargetStreamer().emitDirectiveOptionPic0();
2733     Parser.Lex();
2734     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2735       Error(Parser.getTok().getLoc(),
2736             "unexpected token in .option pic0 directive");
2737       Parser.eatToEndOfStatement();
2738     }
2739     return false;
2740   }
2741
2742   if (Option == "pic2") {
2743     getTargetStreamer().emitDirectiveOptionPic2();
2744     Parser.Lex();
2745     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2746       Error(Parser.getTok().getLoc(),
2747             "unexpected token in .option pic2 directive");
2748       Parser.eatToEndOfStatement();
2749     }
2750     return false;
2751   }
2752
2753   // Unknown option.
2754   Warning(Parser.getTok().getLoc(), "unknown option in .option directive");
2755   Parser.eatToEndOfStatement();
2756   return false;
2757 }
2758
2759 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
2760   StringRef IDVal = DirectiveID.getString();
2761
2762   if (IDVal == ".dword") {
2763     parseDataDirective(8, DirectiveID.getLoc());
2764     return false;
2765   }
2766
2767   if (IDVal == ".ent") {
2768     // Ignore this directive for now.
2769     Parser.Lex();
2770     return false;
2771   }
2772
2773   if (IDVal == ".end") {
2774     // Ignore this directive for now.
2775     Parser.Lex();
2776     return false;
2777   }
2778
2779   if (IDVal == ".frame") {
2780     // Ignore this directive for now.
2781     Parser.eatToEndOfStatement();
2782     return false;
2783   }
2784
2785   if (IDVal == ".set") {
2786     return parseDirectiveSet();
2787   }
2788
2789   if (IDVal == ".fmask") {
2790     // Ignore this directive for now.
2791     Parser.eatToEndOfStatement();
2792     return false;
2793   }
2794
2795   if (IDVal == ".mask") {
2796     // Ignore this directive for now.
2797     Parser.eatToEndOfStatement();
2798     return false;
2799   }
2800
2801   if (IDVal == ".gpword") {
2802     // Ignore this directive for now.
2803     parseDirectiveGpWord();
2804     return false;
2805   }
2806
2807   if (IDVal == ".word") {
2808     parseDataDirective(4, DirectiveID.getLoc());
2809     return false;
2810   }
2811
2812   if (IDVal == ".option")
2813     return parseDirectiveOption();
2814
2815   if (IDVal == ".abicalls") {
2816     getTargetStreamer().emitDirectiveAbiCalls();
2817     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
2818       Error(Parser.getTok().getLoc(), "unexpected token in directive");
2819       // Clear line
2820       Parser.eatToEndOfStatement();
2821     }
2822     return false;
2823   }
2824
2825   if (IDVal == ".cpsetup")
2826     return parseDirectiveCPSetup();
2827
2828   return true;
2829 }
2830
2831 extern "C" void LLVMInitializeMipsAsmParser() {
2832   RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
2833   RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
2834   RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
2835   RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
2836 }
2837
2838 #define GET_REGISTER_MATCHER
2839 #define GET_MATCHER_IMPLEMENTATION
2840 #include "MipsGenAsmMatcher.inc"