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