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/MipsABIInfo.h"
11 #include "MCTargetDesc/MipsMCExpr.h"
12 #include "MCTargetDesc/MipsMCTargetDesc.h"
13 #include "MipsRegisterInfo.h"
14 #include "MipsTargetObjectFile.h"
15 #include "MipsTargetStreamer.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstBuilder.h"
23 #include "llvm/MC/MCParser/MCAsmLexer.h"
24 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
25 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
26 #include "llvm/MC/MCSectionELF.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ELF.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <memory>
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "mips-asm-parser"
41 
42 namespace llvm {
43 class MCInstrInfo;
44 }
45 
46 namespace {
47 class MipsAssemblerOptions {
48 public:
49   MipsAssemblerOptions(const FeatureBitset &Features_) :
50     ATReg(1), Reorder(true), Macro(true), Features(Features_) {}
51 
52   MipsAssemblerOptions(const MipsAssemblerOptions *Opts) {
53     ATReg = Opts->getATRegIndex();
54     Reorder = Opts->isReorder();
55     Macro = Opts->isMacro();
56     Features = Opts->getFeatures();
57   }
58 
59   unsigned getATRegIndex() const { return ATReg; }
60   bool setATRegIndex(unsigned Reg) {
61     if (Reg > 31)
62       return false;
63 
64     ATReg = Reg;
65     return true;
66   }
67 
68   bool isReorder() const { return Reorder; }
69   void setReorder() { Reorder = true; }
70   void setNoReorder() { Reorder = false; }
71 
72   bool isMacro() const { return Macro; }
73   void setMacro() { Macro = true; }
74   void setNoMacro() { Macro = false; }
75 
76   const FeatureBitset &getFeatures() const { return Features; }
77   void setFeatures(const FeatureBitset &Features_) { Features = Features_; }
78 
79   // Set of features that are either architecture features or referenced
80   // by them (e.g.: FeatureNaN2008 implied by FeatureMips32r6).
81   // The full table can be found in MipsGenSubtargetInfo.inc (MipsFeatureKV[]).
82   // The reason we need this mask is explained in the selectArch function.
83   // FIXME: Ideally we would like TableGen to generate this information.
84   static const FeatureBitset AllArchRelatedMask;
85 
86 private:
87   unsigned ATReg;
88   bool Reorder;
89   bool Macro;
90   FeatureBitset Features;
91 };
92 }
93 
94 const FeatureBitset MipsAssemblerOptions::AllArchRelatedMask = {
95     Mips::FeatureMips1, Mips::FeatureMips2, Mips::FeatureMips3,
96     Mips::FeatureMips3_32, Mips::FeatureMips3_32r2, Mips::FeatureMips4,
97     Mips::FeatureMips4_32, Mips::FeatureMips4_32r2, Mips::FeatureMips5,
98     Mips::FeatureMips5_32r2, Mips::FeatureMips32, Mips::FeatureMips32r2,
99     Mips::FeatureMips32r3, Mips::FeatureMips32r5, Mips::FeatureMips32r6,
100     Mips::FeatureMips64, Mips::FeatureMips64r2, Mips::FeatureMips64r3,
101     Mips::FeatureMips64r5, Mips::FeatureMips64r6, Mips::FeatureCnMips,
102     Mips::FeatureFP64Bit, Mips::FeatureGP64Bit, Mips::FeatureNaN2008
103 };
104 
105 namespace {
106 class MipsAsmParser : public MCTargetAsmParser {
107   MipsTargetStreamer &getTargetStreamer() {
108     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
109     return static_cast<MipsTargetStreamer &>(TS);
110   }
111 
112   MipsABIInfo ABI;
113   SmallVector<std::unique_ptr<MipsAssemblerOptions>, 2> AssemblerOptions;
114   MCSymbol *CurrentFn; // Pointer to the function being parsed. It may be a
115                        // nullptr, which indicates that no function is currently
116                        // selected. This usually happens after an '.end func'
117                        // directive.
118   bool IsLittleEndian;
119   bool IsPicEnabled;
120   bool IsCpRestoreSet;
121   int CpRestoreOffset;
122   unsigned CpSaveLocation;
123   /// If true, then CpSaveLocation is a register, otherwise it's an offset.
124   bool     CpSaveLocationIsRegister;
125 
126   // Print a warning along with its fix-it message at the given range.
127   void printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
128                              SMRange Range, bool ShowColors = true);
129 
130 #define GET_ASSEMBLER_HEADER
131 #include "MipsGenAsmMatcher.inc"
132 
133   unsigned
134   checkEarlyTargetMatchPredicate(MCInst &Inst,
135                                  const OperandVector &Operands) override;
136   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
137 
138   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
139                                OperandVector &Operands, MCStreamer &Out,
140                                uint64_t &ErrorInfo,
141                                bool MatchingInlineAsm) override;
142 
143   /// Parse a register as used in CFI directives
144   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
145 
146   bool parseParenSuffix(StringRef Name, OperandVector &Operands);
147 
148   bool parseBracketSuffix(StringRef Name, OperandVector &Operands);
149 
150   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
151                         SMLoc NameLoc, OperandVector &Operands) override;
152 
153   bool ParseDirective(AsmToken DirectiveID) override;
154 
155   OperandMatchResultTy parseMemOperand(OperandVector &Operands);
156   OperandMatchResultTy
157   matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
158                                     StringRef Identifier, SMLoc S);
159   OperandMatchResultTy matchAnyRegisterWithoutDollar(OperandVector &Operands,
160                                                      SMLoc S);
161   OperandMatchResultTy parseAnyRegister(OperandVector &Operands);
162   OperandMatchResultTy parseImm(OperandVector &Operands);
163   OperandMatchResultTy parseJumpTarget(OperandVector &Operands);
164   OperandMatchResultTy parseInvNum(OperandVector &Operands);
165   OperandMatchResultTy parseRegisterPair(OperandVector &Operands);
166   OperandMatchResultTy parseMovePRegPair(OperandVector &Operands);
167   OperandMatchResultTy parseRegisterList(OperandVector &Operands);
168 
169   bool searchSymbolAlias(OperandVector &Operands);
170 
171   bool parseOperand(OperandVector &, StringRef Mnemonic);
172 
173   enum MacroExpanderResultTy {
174     MER_NotAMacro,
175     MER_Success,
176     MER_Fail,
177   };
178 
179   // Expands assembly pseudo instructions.
180   MacroExpanderResultTy tryExpandInstruction(MCInst &Inst, SMLoc IDLoc,
181                                              MCStreamer &Out,
182                                              const MCSubtargetInfo *STI);
183 
184   bool expandJalWithRegs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
185                          const MCSubtargetInfo *STI);
186 
187   bool loadImmediate(int64_t ImmValue, unsigned DstReg, unsigned SrcReg,
188                      bool Is32BitImm, bool IsAddress, SMLoc IDLoc,
189                      MCStreamer &Out, const MCSubtargetInfo *STI);
190 
191   bool loadAndAddSymbolAddress(const MCExpr *SymExpr, unsigned DstReg,
192                                unsigned SrcReg, bool Is32BitSym, SMLoc IDLoc,
193                                MCStreamer &Out, const MCSubtargetInfo *STI);
194 
195   bool expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
196                      MCStreamer &Out, const MCSubtargetInfo *STI);
197 
198   bool expandLoadAddress(unsigned DstReg, unsigned BaseReg,
199                          const MCOperand &Offset, bool Is32BitAddress,
200                          SMLoc IDLoc, MCStreamer &Out,
201                          const MCSubtargetInfo *STI);
202 
203   bool expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
204                                   const MCSubtargetInfo *STI);
205 
206   void expandMemInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
207                      const MCSubtargetInfo *STI, bool IsLoad, bool IsImmOpnd);
208 
209   void expandLoadInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
210                       const MCSubtargetInfo *STI, bool IsImmOpnd);
211 
212   void expandStoreInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
213                        const MCSubtargetInfo *STI, bool IsImmOpnd);
214 
215   bool expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
216                                const MCSubtargetInfo *STI);
217 
218   bool expandAliasImmediate(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
219                             const MCSubtargetInfo *STI);
220 
221   bool expandBranchImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
222                        const MCSubtargetInfo *STI);
223 
224   bool expandCondBranches(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
225                           const MCSubtargetInfo *STI);
226 
227   bool expandDiv(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
228                  const MCSubtargetInfo *STI, const bool IsMips64,
229                  const bool Signed);
230 
231   bool expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU, SMLoc IDLoc,
232                    MCStreamer &Out, const MCSubtargetInfo *STI);
233 
234   bool expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc, MCStreamer &Out,
235                  const MCSubtargetInfo *STI);
236 
237   bool expandUlw(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
238                  const MCSubtargetInfo *STI);
239 
240   bool expandRotation(MCInst &Inst, SMLoc IDLoc,
241                       MCStreamer &Out, const MCSubtargetInfo *STI);
242   bool expandRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
243                          const MCSubtargetInfo *STI);
244   bool expandDRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
245                        const MCSubtargetInfo *STI);
246   bool expandDRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
247                           const MCSubtargetInfo *STI);
248 
249   bool expandAbs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
250                  const MCSubtargetInfo *STI);
251 
252   bool reportParseError(Twine ErrorMsg);
253   bool reportParseError(SMLoc Loc, Twine ErrorMsg);
254 
255   bool parseMemOffset(const MCExpr *&Res, bool isParenExpr);
256 
257   bool isEvaluated(const MCExpr *Expr);
258   bool parseSetMips0Directive();
259   bool parseSetArchDirective();
260   bool parseSetFeature(uint64_t Feature);
261   bool isPicAndNotNxxAbi(); // Used by .cpload, .cprestore, and .cpsetup.
262   bool parseDirectiveCpLoad(SMLoc Loc);
263   bool parseDirectiveCpRestore(SMLoc Loc);
264   bool parseDirectiveCPSetup();
265   bool parseDirectiveCPReturn();
266   bool parseDirectiveNaN();
267   bool parseDirectiveSet();
268   bool parseDirectiveOption();
269   bool parseInsnDirective();
270   bool parseSSectionDirective(StringRef Section, unsigned Type);
271 
272   bool parseSetAtDirective();
273   bool parseSetNoAtDirective();
274   bool parseSetMacroDirective();
275   bool parseSetNoMacroDirective();
276   bool parseSetMsaDirective();
277   bool parseSetNoMsaDirective();
278   bool parseSetNoDspDirective();
279   bool parseSetReorderDirective();
280   bool parseSetNoReorderDirective();
281   bool parseSetMips16Directive();
282   bool parseSetNoMips16Directive();
283   bool parseSetFpDirective();
284   bool parseSetOddSPRegDirective();
285   bool parseSetNoOddSPRegDirective();
286   bool parseSetPopDirective();
287   bool parseSetPushDirective();
288   bool parseSetSoftFloatDirective();
289   bool parseSetHardFloatDirective();
290 
291   bool parseSetAssignment();
292 
293   bool parseDataDirective(unsigned Size, SMLoc L);
294   bool parseDirectiveGpWord();
295   bool parseDirectiveGpDWord();
296   bool parseDirectiveDtpRelWord();
297   bool parseDirectiveDtpRelDWord();
298   bool parseDirectiveTpRelWord();
299   bool parseDirectiveTpRelDWord();
300   bool parseDirectiveModule();
301   bool parseDirectiveModuleFP();
302   bool parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
303                        StringRef Directive);
304 
305   bool parseInternalDirectiveReallowModule();
306 
307   bool eatComma(StringRef ErrorStr);
308 
309   int matchCPURegisterName(StringRef Symbol);
310 
311   int matchHWRegsRegisterName(StringRef Symbol);
312 
313   int matchFPURegisterName(StringRef Name);
314 
315   int matchFCCRegisterName(StringRef Name);
316 
317   int matchACRegisterName(StringRef Name);
318 
319   int matchMSA128RegisterName(StringRef Name);
320 
321   int matchMSA128CtrlRegisterName(StringRef Name);
322 
323   unsigned getReg(int RC, int RegNo);
324 
325   /// Returns the internal register number for the current AT. Also checks if
326   /// the current AT is unavailable (set to $0) and gives an error if it is.
327   /// This should be used in pseudo-instruction expansions which need AT.
328   unsigned getATReg(SMLoc Loc);
329 
330   bool processInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
331                           const MCSubtargetInfo *STI);
332 
333   // Helper function that checks if the value of a vector index is within the
334   // boundaries of accepted values for each RegisterKind
335   // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
336   bool validateMSAIndex(int Val, int RegKind);
337 
338   // Selects a new architecture by updating the FeatureBits with the necessary
339   // info including implied dependencies.
340   // Internally, it clears all the feature bits related to *any* architecture
341   // and selects the new one using the ToggleFeature functionality of the
342   // MCSubtargetInfo object that handles implied dependencies. The reason we
343   // clear all the arch related bits manually is because ToggleFeature only
344   // clears the features that imply the feature being cleared and not the
345   // features implied by the feature being cleared. This is easier to see
346   // with an example:
347   //  --------------------------------------------------
348   // | Feature         | Implies                        |
349   // | -------------------------------------------------|
350   // | FeatureMips1    | None                           |
351   // | FeatureMips2    | FeatureMips1                   |
352   // | FeatureMips3    | FeatureMips2 | FeatureMipsGP64 |
353   // | FeatureMips4    | FeatureMips3                   |
354   // | ...             |                                |
355   //  --------------------------------------------------
356   //
357   // Setting Mips3 is equivalent to set: (FeatureMips3 | FeatureMips2 |
358   // FeatureMipsGP64 | FeatureMips1)
359   // Clearing Mips3 is equivalent to clear (FeatureMips3 | FeatureMips4).
360   void selectArch(StringRef ArchFeature) {
361     MCSubtargetInfo &STI = copySTI();
362     FeatureBitset FeatureBits = STI.getFeatureBits();
363     FeatureBits &= ~MipsAssemblerOptions::AllArchRelatedMask;
364     STI.setFeatureBits(FeatureBits);
365     setAvailableFeatures(
366         ComputeAvailableFeatures(STI.ToggleFeature(ArchFeature)));
367     AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
368   }
369 
370   void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
371     if (!(getSTI().getFeatureBits()[Feature])) {
372       MCSubtargetInfo &STI = copySTI();
373       setAvailableFeatures(
374           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
375       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
376     }
377   }
378 
379   void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
380     if (getSTI().getFeatureBits()[Feature]) {
381       MCSubtargetInfo &STI = copySTI();
382       setAvailableFeatures(
383           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
384       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
385     }
386   }
387 
388   void setModuleFeatureBits(uint64_t Feature, StringRef FeatureString) {
389     setFeatureBits(Feature, FeatureString);
390     AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits());
391   }
392 
393   void clearModuleFeatureBits(uint64_t Feature, StringRef FeatureString) {
394     clearFeatureBits(Feature, FeatureString);
395     AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits());
396   }
397 
398 public:
399   enum MipsMatchResultTy {
400     Match_RequiresDifferentSrcAndDst = FIRST_TARGET_MATCH_RESULT_TY,
401     Match_RequiresDifferentOperands,
402     Match_RequiresNoZeroRegister,
403     Match_RequiresSameSrcAndDst,
404 #define GET_OPERAND_DIAGNOSTIC_TYPES
405 #include "MipsGenAsmMatcher.inc"
406 #undef GET_OPERAND_DIAGNOSTIC_TYPES
407   };
408 
409   MipsAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser,
410                 const MCInstrInfo &MII, const MCTargetOptions &Options)
411     : MCTargetAsmParser(Options, sti),
412         ABI(MipsABIInfo::computeTargetABI(Triple(sti.getTargetTriple()),
413                                           sti.getCPU(), Options)) {
414     MCAsmParserExtension::Initialize(parser);
415 
416     parser.addAliasForDirective(".asciiz", ".asciz");
417 
418     // Initialize the set of available features.
419     setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
420 
421     // Remember the initial assembler options. The user can not modify these.
422     AssemblerOptions.push_back(
423         llvm::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits()));
424 
425     // Create an assembler options environment for the user to modify.
426     AssemblerOptions.push_back(
427         llvm::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits()));
428 
429     getTargetStreamer().updateABIInfo(*this);
430 
431     if (!isABI_O32() && !useOddSPReg() != 0)
432       report_fatal_error("-mno-odd-spreg requires the O32 ABI");
433 
434     CurrentFn = nullptr;
435 
436     IsPicEnabled = getContext().getObjectFileInfo()->isPositionIndependent();
437 
438     IsCpRestoreSet = false;
439     CpRestoreOffset = -1;
440 
441     const Triple &TheTriple = sti.getTargetTriple();
442     if ((TheTriple.getArch() == Triple::mips) ||
443         (TheTriple.getArch() == Triple::mips64))
444       IsLittleEndian = false;
445     else
446       IsLittleEndian = true;
447   }
448 
449   /// True if all of $fcc0 - $fcc7 exist for the current ISA.
450   bool hasEightFccRegisters() const { return hasMips4() || hasMips32(); }
451 
452   bool isGP64bit() const {
453     return getSTI().getFeatureBits()[Mips::FeatureGP64Bit];
454   }
455   bool isFP64bit() const {
456     return getSTI().getFeatureBits()[Mips::FeatureFP64Bit];
457   }
458   const MipsABIInfo &getABI() const { return ABI; }
459   bool isABI_N32() const { return ABI.IsN32(); }
460   bool isABI_N64() const { return ABI.IsN64(); }
461   bool isABI_O32() const { return ABI.IsO32(); }
462   bool isABI_FPXX() const {
463     return getSTI().getFeatureBits()[Mips::FeatureFPXX];
464   }
465 
466   bool useOddSPReg() const {
467     return !(getSTI().getFeatureBits()[Mips::FeatureNoOddSPReg]);
468   }
469 
470   bool inMicroMipsMode() const {
471     return getSTI().getFeatureBits()[Mips::FeatureMicroMips];
472   }
473   bool hasMips1() const {
474     return getSTI().getFeatureBits()[Mips::FeatureMips1];
475   }
476   bool hasMips2() const {
477     return getSTI().getFeatureBits()[Mips::FeatureMips2];
478   }
479   bool hasMips3() const {
480     return getSTI().getFeatureBits()[Mips::FeatureMips3];
481   }
482   bool hasMips4() const {
483     return getSTI().getFeatureBits()[Mips::FeatureMips4];
484   }
485   bool hasMips5() const {
486     return getSTI().getFeatureBits()[Mips::FeatureMips5];
487   }
488   bool hasMips32() const {
489     return getSTI().getFeatureBits()[Mips::FeatureMips32];
490   }
491   bool hasMips64() const {
492     return getSTI().getFeatureBits()[Mips::FeatureMips64];
493   }
494   bool hasMips32r2() const {
495     return getSTI().getFeatureBits()[Mips::FeatureMips32r2];
496   }
497   bool hasMips64r2() const {
498     return getSTI().getFeatureBits()[Mips::FeatureMips64r2];
499   }
500   bool hasMips32r3() const {
501     return (getSTI().getFeatureBits()[Mips::FeatureMips32r3]);
502   }
503   bool hasMips64r3() const {
504     return (getSTI().getFeatureBits()[Mips::FeatureMips64r3]);
505   }
506   bool hasMips32r5() const {
507     return (getSTI().getFeatureBits()[Mips::FeatureMips32r5]);
508   }
509   bool hasMips64r5() const {
510     return (getSTI().getFeatureBits()[Mips::FeatureMips64r5]);
511   }
512   bool hasMips32r6() const {
513     return getSTI().getFeatureBits()[Mips::FeatureMips32r6];
514   }
515   bool hasMips64r6() const {
516     return getSTI().getFeatureBits()[Mips::FeatureMips64r6];
517   }
518 
519   bool hasDSP() const {
520     return getSTI().getFeatureBits()[Mips::FeatureDSP];
521   }
522   bool hasDSPR2() const {
523     return getSTI().getFeatureBits()[Mips::FeatureDSPR2];
524   }
525   bool hasDSPR3() const {
526     return getSTI().getFeatureBits()[Mips::FeatureDSPR3];
527   }
528   bool hasMSA() const {
529     return getSTI().getFeatureBits()[Mips::FeatureMSA];
530   }
531   bool hasCnMips() const {
532     return (getSTI().getFeatureBits()[Mips::FeatureCnMips]);
533   }
534 
535   bool inPicMode() {
536     return IsPicEnabled;
537   }
538 
539   bool inMips16Mode() const {
540     return getSTI().getFeatureBits()[Mips::FeatureMips16];
541   }
542 
543   bool useTraps() const {
544     return getSTI().getFeatureBits()[Mips::FeatureUseTCCInDIV];
545   }
546 
547   bool useSoftFloat() const {
548     return getSTI().getFeatureBits()[Mips::FeatureSoftFloat];
549   }
550 
551   /// Warn if RegIndex is the same as the current AT.
552   void warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc);
553 
554   void warnIfNoMacro(SMLoc Loc);
555 
556   bool isLittle() const { return IsLittleEndian; }
557 
558   const MCExpr *createTargetUnaryExpr(const MCExpr *E,
559                                       AsmToken::TokenKind OperatorToken,
560                                       MCContext &Ctx) override {
561     switch(OperatorToken) {
562     default:
563       llvm_unreachable("Unknown token");
564       return nullptr;
565     case AsmToken::PercentCall16:
566       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, E, Ctx);
567     case AsmToken::PercentCall_Hi:
568       return MipsMCExpr::create(MipsMCExpr::MEK_CALL_HI16, E, Ctx);
569     case AsmToken::PercentCall_Lo:
570       return MipsMCExpr::create(MipsMCExpr::MEK_CALL_LO16, E, Ctx);
571     case AsmToken::PercentDtprel_Hi:
572       return MipsMCExpr::create(MipsMCExpr::MEK_DTPREL_HI, E, Ctx);
573     case AsmToken::PercentDtprel_Lo:
574       return MipsMCExpr::create(MipsMCExpr::MEK_DTPREL_LO, E, Ctx);
575     case AsmToken::PercentGot:
576       return MipsMCExpr::create(MipsMCExpr::MEK_GOT, E, Ctx);
577     case AsmToken::PercentGot_Disp:
578       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_DISP, E, Ctx);
579     case AsmToken::PercentGot_Hi:
580       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_HI16, E, Ctx);
581     case AsmToken::PercentGot_Lo:
582       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_LO16, E, Ctx);
583     case AsmToken::PercentGot_Ofst:
584       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_OFST, E, Ctx);
585     case AsmToken::PercentGot_Page:
586       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_PAGE, E, Ctx);
587     case AsmToken::PercentGottprel:
588       return MipsMCExpr::create(MipsMCExpr::MEK_GOTTPREL, E, Ctx);
589     case AsmToken::PercentGp_Rel:
590       return MipsMCExpr::create(MipsMCExpr::MEK_GPREL, E, Ctx);
591     case AsmToken::PercentHi:
592       return MipsMCExpr::create(MipsMCExpr::MEK_HI, E, Ctx);
593     case AsmToken::PercentHigher:
594       return MipsMCExpr::create(MipsMCExpr::MEK_HIGHER, E, Ctx);
595     case AsmToken::PercentHighest:
596       return MipsMCExpr::create(MipsMCExpr::MEK_HIGHEST, E, Ctx);
597     case AsmToken::PercentLo:
598       return MipsMCExpr::create(MipsMCExpr::MEK_LO, E, Ctx);
599     case AsmToken::PercentNeg:
600       return MipsMCExpr::create(MipsMCExpr::MEK_NEG, E, Ctx);
601     case AsmToken::PercentPcrel_Hi:
602       return MipsMCExpr::create(MipsMCExpr::MEK_PCREL_HI16, E, Ctx);
603     case AsmToken::PercentPcrel_Lo:
604       return MipsMCExpr::create(MipsMCExpr::MEK_PCREL_LO16, E, Ctx);
605     case AsmToken::PercentTlsgd:
606       return MipsMCExpr::create(MipsMCExpr::MEK_TLSGD, E, Ctx);
607     case AsmToken::PercentTlsldm:
608       return MipsMCExpr::create(MipsMCExpr::MEK_TLSLDM, E, Ctx);
609     case AsmToken::PercentTprel_Hi:
610       return MipsMCExpr::create(MipsMCExpr::MEK_TPREL_HI, E, Ctx);
611     case AsmToken::PercentTprel_Lo:
612       return MipsMCExpr::create(MipsMCExpr::MEK_TPREL_LO, E, Ctx);
613     }
614   }
615 };
616 }
617 
618 namespace {
619 
620 /// MipsOperand - Instances of this class represent a parsed Mips machine
621 /// instruction.
622 class MipsOperand : public MCParsedAsmOperand {
623 public:
624   /// Broad categories of register classes
625   /// The exact class is finalized by the render method.
626   enum RegKind {
627     RegKind_GPR = 1,      /// GPR32 and GPR64 (depending on isGP64bit())
628     RegKind_FGR = 2,      /// FGR32, FGR64, AFGR64 (depending on context and
629                           /// isFP64bit())
630     RegKind_FCC = 4,      /// FCC
631     RegKind_MSA128 = 8,   /// MSA128[BHWD] (makes no difference which)
632     RegKind_MSACtrl = 16, /// MSA control registers
633     RegKind_COP2 = 32,    /// COP2
634     RegKind_ACC = 64,     /// HI32DSP, LO32DSP, and ACC64DSP (depending on
635                           /// context).
636     RegKind_CCR = 128,    /// CCR
637     RegKind_HWRegs = 256, /// HWRegs
638     RegKind_COP3 = 512,   /// COP3
639     RegKind_COP0 = 1024,  /// COP0
640     /// Potentially any (e.g. $1)
641     RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 |
642                       RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC |
643                       RegKind_CCR | RegKind_HWRegs | RegKind_COP3 | RegKind_COP0
644   };
645 
646 private:
647   enum KindTy {
648     k_Immediate,     /// An immediate (possibly involving symbol references)
649     k_Memory,        /// Base + Offset Memory Address
650     k_RegisterIndex, /// A register index in one or more RegKind.
651     k_Token,         /// A simple token
652     k_RegList,       /// A physical register list
653     k_RegPair        /// A pair of physical register
654   } Kind;
655 
656 public:
657   MipsOperand(KindTy K, MipsAsmParser &Parser)
658       : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {}
659 
660 private:
661   /// For diagnostics, and checking the assembler temporary
662   MipsAsmParser &AsmParser;
663 
664   struct Token {
665     const char *Data;
666     unsigned Length;
667   };
668 
669   struct RegIdxOp {
670     unsigned Index; /// Index into the register class
671     RegKind Kind;   /// Bitfield of the kinds it could possibly be
672     struct Token Tok; /// The input token this operand originated from.
673     const MCRegisterInfo *RegInfo;
674   };
675 
676   struct ImmOp {
677     const MCExpr *Val;
678   };
679 
680   struct MemOp {
681     MipsOperand *Base;
682     const MCExpr *Off;
683   };
684 
685   struct RegListOp {
686     SmallVector<unsigned, 10> *List;
687   };
688 
689   union {
690     struct Token Tok;
691     struct RegIdxOp RegIdx;
692     struct ImmOp Imm;
693     struct MemOp Mem;
694     struct RegListOp RegList;
695   };
696 
697   SMLoc StartLoc, EndLoc;
698 
699   /// Internal constructor for register kinds
700   static std::unique_ptr<MipsOperand> CreateReg(unsigned Index, StringRef Str,
701                                                 RegKind RegKind,
702                                                 const MCRegisterInfo *RegInfo,
703                                                 SMLoc S, SMLoc E,
704                                                 MipsAsmParser &Parser) {
705     auto Op = make_unique<MipsOperand>(k_RegisterIndex, Parser);
706     Op->RegIdx.Index = Index;
707     Op->RegIdx.RegInfo = RegInfo;
708     Op->RegIdx.Kind = RegKind;
709     Op->RegIdx.Tok.Data = Str.data();
710     Op->RegIdx.Tok.Length = Str.size();
711     Op->StartLoc = S;
712     Op->EndLoc = E;
713     return Op;
714   }
715 
716 public:
717   /// Coerce the register to GPR32 and return the real register for the current
718   /// target.
719   unsigned getGPR32Reg() const {
720     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
721     AsmParser.warnIfRegIndexIsAT(RegIdx.Index, StartLoc);
722     unsigned ClassID = Mips::GPR32RegClassID;
723     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
724   }
725 
726   /// Coerce the register to GPR32 and return the real register for the current
727   /// target.
728   unsigned getGPRMM16Reg() const {
729     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
730     unsigned ClassID = Mips::GPR32RegClassID;
731     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
732   }
733 
734   /// Coerce the register to GPR64 and return the real register for the current
735   /// target.
736   unsigned getGPR64Reg() const {
737     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
738     unsigned ClassID = Mips::GPR64RegClassID;
739     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
740   }
741 
742 private:
743   /// Coerce the register to AFGR64 and return the real register for the current
744   /// target.
745   unsigned getAFGR64Reg() const {
746     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
747     if (RegIdx.Index % 2 != 0)
748       AsmParser.Warning(StartLoc, "Float register should be even.");
749     return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID)
750         .getRegister(RegIdx.Index / 2);
751   }
752 
753   /// Coerce the register to FGR64 and return the real register for the current
754   /// target.
755   unsigned getFGR64Reg() const {
756     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
757     return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID)
758         .getRegister(RegIdx.Index);
759   }
760 
761   /// Coerce the register to FGR32 and return the real register for the current
762   /// target.
763   unsigned getFGR32Reg() const {
764     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
765     return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID)
766         .getRegister(RegIdx.Index);
767   }
768 
769   /// Coerce the register to FGRH32 and return the real register for the current
770   /// target.
771   unsigned getFGRH32Reg() const {
772     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
773     return RegIdx.RegInfo->getRegClass(Mips::FGRH32RegClassID)
774         .getRegister(RegIdx.Index);
775   }
776 
777   /// Coerce the register to FCC and return the real register for the current
778   /// target.
779   unsigned getFCCReg() const {
780     assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!");
781     return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID)
782         .getRegister(RegIdx.Index);
783   }
784 
785   /// Coerce the register to MSA128 and return the real register for the current
786   /// target.
787   unsigned getMSA128Reg() const {
788     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!");
789     // It doesn't matter which of the MSA128[BHWD] classes we use. They are all
790     // identical
791     unsigned ClassID = Mips::MSA128BRegClassID;
792     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
793   }
794 
795   /// Coerce the register to MSACtrl and return the real register for the
796   /// current target.
797   unsigned getMSACtrlReg() const {
798     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!");
799     unsigned ClassID = Mips::MSACtrlRegClassID;
800     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
801   }
802 
803   /// Coerce the register to COP0 and return the real register for the
804   /// current target.
805   unsigned getCOP0Reg() const {
806     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP0) && "Invalid access!");
807     unsigned ClassID = Mips::COP0RegClassID;
808     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
809   }
810 
811   /// Coerce the register to COP2 and return the real register for the
812   /// current target.
813   unsigned getCOP2Reg() const {
814     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!");
815     unsigned ClassID = Mips::COP2RegClassID;
816     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
817   }
818 
819   /// Coerce the register to COP3 and return the real register for the
820   /// current target.
821   unsigned getCOP3Reg() const {
822     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP3) && "Invalid access!");
823     unsigned ClassID = Mips::COP3RegClassID;
824     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
825   }
826 
827   /// Coerce the register to ACC64DSP and return the real register for the
828   /// current target.
829   unsigned getACC64DSPReg() const {
830     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
831     unsigned ClassID = Mips::ACC64DSPRegClassID;
832     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
833   }
834 
835   /// Coerce the register to HI32DSP and return the real register for the
836   /// current target.
837   unsigned getHI32DSPReg() const {
838     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
839     unsigned ClassID = Mips::HI32DSPRegClassID;
840     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
841   }
842 
843   /// Coerce the register to LO32DSP and return the real register for the
844   /// current target.
845   unsigned getLO32DSPReg() const {
846     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
847     unsigned ClassID = Mips::LO32DSPRegClassID;
848     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
849   }
850 
851   /// Coerce the register to CCR and return the real register for the
852   /// current target.
853   unsigned getCCRReg() const {
854     assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!");
855     unsigned ClassID = Mips::CCRRegClassID;
856     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
857   }
858 
859   /// Coerce the register to HWRegs and return the real register for the
860   /// current target.
861   unsigned getHWRegsReg() const {
862     assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!");
863     unsigned ClassID = Mips::HWRegsRegClassID;
864     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
865   }
866 
867 public:
868   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
869     // Add as immediate when possible.  Null MCExpr = 0.
870     if (!Expr)
871       Inst.addOperand(MCOperand::createImm(0));
872     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
873       Inst.addOperand(MCOperand::createImm(CE->getValue()));
874     else
875       Inst.addOperand(MCOperand::createExpr(Expr));
876   }
877 
878   void addRegOperands(MCInst &Inst, unsigned N) const {
879     llvm_unreachable("Use a custom parser instead");
880   }
881 
882   /// Render the operand to an MCInst as a GPR32
883   /// Asserts if the wrong number of operands are requested, or the operand
884   /// is not a k_RegisterIndex compatible with RegKind_GPR
885   void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const {
886     assert(N == 1 && "Invalid number of operands!");
887     Inst.addOperand(MCOperand::createReg(getGPR32Reg()));
888   }
889 
890   void addGPRMM16AsmRegOperands(MCInst &Inst, unsigned N) const {
891     assert(N == 1 && "Invalid number of operands!");
892     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
893   }
894 
895   void addGPRMM16AsmRegZeroOperands(MCInst &Inst, unsigned N) const {
896     assert(N == 1 && "Invalid number of operands!");
897     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
898   }
899 
900   void addGPRMM16AsmRegMovePOperands(MCInst &Inst, unsigned N) const {
901     assert(N == 1 && "Invalid number of operands!");
902     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
903   }
904 
905   /// Render the operand to an MCInst as a GPR64
906   /// Asserts if the wrong number of operands are requested, or the operand
907   /// is not a k_RegisterIndex compatible with RegKind_GPR
908   void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const {
909     assert(N == 1 && "Invalid number of operands!");
910     Inst.addOperand(MCOperand::createReg(getGPR64Reg()));
911   }
912 
913   void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
914     assert(N == 1 && "Invalid number of operands!");
915     Inst.addOperand(MCOperand::createReg(getAFGR64Reg()));
916   }
917 
918   void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
919     assert(N == 1 && "Invalid number of operands!");
920     Inst.addOperand(MCOperand::createReg(getFGR64Reg()));
921   }
922 
923   void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
924     assert(N == 1 && "Invalid number of operands!");
925     Inst.addOperand(MCOperand::createReg(getFGR32Reg()));
926     // FIXME: We ought to do this for -integrated-as without -via-file-asm too.
927     if (!AsmParser.useOddSPReg() && RegIdx.Index & 1)
928       AsmParser.Error(StartLoc, "-mno-odd-spreg prohibits the use of odd FPU "
929                                 "registers");
930   }
931 
932   void addFGRH32AsmRegOperands(MCInst &Inst, unsigned N) const {
933     assert(N == 1 && "Invalid number of operands!");
934     Inst.addOperand(MCOperand::createReg(getFGRH32Reg()));
935   }
936 
937   void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const {
938     assert(N == 1 && "Invalid number of operands!");
939     Inst.addOperand(MCOperand::createReg(getFCCReg()));
940   }
941 
942   void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const {
943     assert(N == 1 && "Invalid number of operands!");
944     Inst.addOperand(MCOperand::createReg(getMSA128Reg()));
945   }
946 
947   void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const {
948     assert(N == 1 && "Invalid number of operands!");
949     Inst.addOperand(MCOperand::createReg(getMSACtrlReg()));
950   }
951 
952   void addCOP0AsmRegOperands(MCInst &Inst, unsigned N) const {
953     assert(N == 1 && "Invalid number of operands!");
954     Inst.addOperand(MCOperand::createReg(getCOP0Reg()));
955   }
956 
957   void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const {
958     assert(N == 1 && "Invalid number of operands!");
959     Inst.addOperand(MCOperand::createReg(getCOP2Reg()));
960   }
961 
962   void addCOP3AsmRegOperands(MCInst &Inst, unsigned N) const {
963     assert(N == 1 && "Invalid number of operands!");
964     Inst.addOperand(MCOperand::createReg(getCOP3Reg()));
965   }
966 
967   void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
968     assert(N == 1 && "Invalid number of operands!");
969     Inst.addOperand(MCOperand::createReg(getACC64DSPReg()));
970   }
971 
972   void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
973     assert(N == 1 && "Invalid number of operands!");
974     Inst.addOperand(MCOperand::createReg(getHI32DSPReg()));
975   }
976 
977   void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
978     assert(N == 1 && "Invalid number of operands!");
979     Inst.addOperand(MCOperand::createReg(getLO32DSPReg()));
980   }
981 
982   void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const {
983     assert(N == 1 && "Invalid number of operands!");
984     Inst.addOperand(MCOperand::createReg(getCCRReg()));
985   }
986 
987   void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const {
988     assert(N == 1 && "Invalid number of operands!");
989     Inst.addOperand(MCOperand::createReg(getHWRegsReg()));
990   }
991 
992   template <unsigned Bits, int Offset = 0, int AdjustOffset = 0>
993   void addConstantUImmOperands(MCInst &Inst, unsigned N) const {
994     assert(N == 1 && "Invalid number of operands!");
995     uint64_t Imm = getConstantImm() - Offset;
996     Imm &= (1 << Bits) - 1;
997     Imm += Offset;
998     Imm += AdjustOffset;
999     Inst.addOperand(MCOperand::createImm(Imm));
1000   }
1001 
1002   template <unsigned Bits>
1003   void addSImmOperands(MCInst &Inst, unsigned N) const {
1004     if (isImm() && !isConstantImm()) {
1005       addExpr(Inst, getImm());
1006       return;
1007     }
1008     addConstantSImmOperands<Bits, 0, 0>(Inst, N);
1009   }
1010 
1011   template <unsigned Bits>
1012   void addUImmOperands(MCInst &Inst, unsigned N) const {
1013     if (isImm() && !isConstantImm()) {
1014       addExpr(Inst, getImm());
1015       return;
1016     }
1017     addConstantUImmOperands<Bits, 0, 0>(Inst, N);
1018   }
1019 
1020   template <unsigned Bits, int Offset = 0, int AdjustOffset = 0>
1021   void addConstantSImmOperands(MCInst &Inst, unsigned N) const {
1022     assert(N == 1 && "Invalid number of operands!");
1023     int64_t Imm = getConstantImm() - Offset;
1024     Imm = SignExtend64<Bits>(Imm);
1025     Imm += Offset;
1026     Imm += AdjustOffset;
1027     Inst.addOperand(MCOperand::createImm(Imm));
1028   }
1029 
1030   void addImmOperands(MCInst &Inst, unsigned N) const {
1031     assert(N == 1 && "Invalid number of operands!");
1032     const MCExpr *Expr = getImm();
1033     addExpr(Inst, Expr);
1034   }
1035 
1036   void addMemOperands(MCInst &Inst, unsigned N) const {
1037     assert(N == 2 && "Invalid number of operands!");
1038 
1039     Inst.addOperand(MCOperand::createReg(AsmParser.getABI().ArePtrs64bit()
1040                                              ? getMemBase()->getGPR64Reg()
1041                                              : getMemBase()->getGPR32Reg()));
1042 
1043     const MCExpr *Expr = getMemOff();
1044     addExpr(Inst, Expr);
1045   }
1046 
1047   void addMicroMipsMemOperands(MCInst &Inst, unsigned N) const {
1048     assert(N == 2 && "Invalid number of operands!");
1049 
1050     Inst.addOperand(MCOperand::createReg(getMemBase()->getGPRMM16Reg()));
1051 
1052     const MCExpr *Expr = getMemOff();
1053     addExpr(Inst, Expr);
1054   }
1055 
1056   void addRegListOperands(MCInst &Inst, unsigned N) const {
1057     assert(N == 1 && "Invalid number of operands!");
1058 
1059     for (auto RegNo : getRegList())
1060       Inst.addOperand(MCOperand::createReg(RegNo));
1061   }
1062 
1063   void addRegPairOperands(MCInst &Inst, unsigned N) const {
1064     assert(N == 2 && "Invalid number of operands!");
1065     assert((RegIdx.Kind & RegKind_GPR) && "Invalid access!");
1066     unsigned RegNo = getRegPair();
1067     AsmParser.warnIfRegIndexIsAT(RegNo, StartLoc);
1068     Inst.addOperand(MCOperand::createReg(
1069       RegIdx.RegInfo->getRegClass(
1070         AsmParser.getABI().AreGprs64bit()
1071           ? Mips::GPR64RegClassID
1072           : Mips::GPR32RegClassID).getRegister(RegNo++)));
1073     Inst.addOperand(MCOperand::createReg(
1074       RegIdx.RegInfo->getRegClass(
1075         AsmParser.getABI().AreGprs64bit()
1076           ? Mips::GPR64RegClassID
1077           : Mips::GPR32RegClassID).getRegister(RegNo)));
1078   }
1079 
1080   void addMovePRegPairOperands(MCInst &Inst, unsigned N) const {
1081     assert(N == 2 && "Invalid number of operands!");
1082     for (auto RegNo : getRegList())
1083       Inst.addOperand(MCOperand::createReg(RegNo));
1084   }
1085 
1086   bool isReg() const override {
1087     // As a special case until we sort out the definition of div/divu, accept
1088     // $0/$zero here so that MCK_ZERO works correctly.
1089     return isGPRAsmReg() && RegIdx.Index == 0;
1090   }
1091   bool isRegIdx() const { return Kind == k_RegisterIndex; }
1092   bool isImm() const override { return Kind == k_Immediate; }
1093   bool isConstantImm() const {
1094     return isImm() && isa<MCConstantExpr>(getImm());
1095   }
1096   bool isConstantImmz() const {
1097     return isConstantImm() && getConstantImm() == 0;
1098   }
1099   template <unsigned Bits, int Offset = 0> bool isConstantUImm() const {
1100     return isConstantImm() && isUInt<Bits>(getConstantImm() - Offset);
1101   }
1102   template <unsigned Bits> bool isSImm() const {
1103     return isConstantImm() ? isInt<Bits>(getConstantImm()) : isImm();
1104   }
1105   template <unsigned Bits> bool isUImm() const {
1106     return isConstantImm() ? isUInt<Bits>(getConstantImm()) : isImm();
1107   }
1108   template <unsigned Bits> bool isAnyImm() const {
1109     return isConstantImm() ? (isInt<Bits>(getConstantImm()) ||
1110                               isUInt<Bits>(getConstantImm()))
1111                            : isImm();
1112   }
1113   template <unsigned Bits, int Offset = 0> bool isConstantSImm() const {
1114     return isConstantImm() && isInt<Bits>(getConstantImm() - Offset);
1115   }
1116   template <unsigned Bottom, unsigned Top> bool isConstantUImmRange() const {
1117     return isConstantImm() && getConstantImm() >= Bottom &&
1118            getConstantImm() <= Top;
1119   }
1120   bool isToken() const override {
1121     // Note: It's not possible to pretend that other operand kinds are tokens.
1122     // The matcher emitter checks tokens first.
1123     return Kind == k_Token;
1124   }
1125   bool isMem() const override { return Kind == k_Memory; }
1126   bool isConstantMemOff() const {
1127     return isMem() && isa<MCConstantExpr>(getMemOff());
1128   }
1129   // Allow relocation operators.
1130   // FIXME: This predicate and others need to look through binary expressions
1131   //        and determine whether a Value is a constant or not.
1132   template <unsigned Bits, unsigned ShiftAmount = 0>
1133   bool isMemWithSimmOffset() const {
1134     if (!isMem())
1135       return false;
1136     if (!getMemBase()->isGPRAsmReg())
1137       return false;
1138     if (isa<MCTargetExpr>(getMemOff()) ||
1139         (isConstantMemOff() &&
1140          isShiftedInt<Bits, ShiftAmount>(getConstantMemOff())))
1141       return true;
1142     MCValue Res;
1143     bool IsReloc = getMemOff()->evaluateAsRelocatable(Res, nullptr, nullptr);
1144     return IsReloc && isShiftedInt<Bits, ShiftAmount>(Res.getConstant());
1145   }
1146   bool isMemWithGRPMM16Base() const {
1147     return isMem() && getMemBase()->isMM16AsmReg();
1148   }
1149   template <unsigned Bits> bool isMemWithUimmOffsetSP() const {
1150     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
1151       && getMemBase()->isRegIdx() && (getMemBase()->getGPR32Reg() == Mips::SP);
1152   }
1153   template <unsigned Bits> bool isMemWithUimmWordAlignedOffsetSP() const {
1154     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
1155       && (getConstantMemOff() % 4 == 0) && getMemBase()->isRegIdx()
1156       && (getMemBase()->getGPR32Reg() == Mips::SP);
1157   }
1158   template <unsigned Bits> bool isMemWithSimmWordAlignedOffsetGP() const {
1159     return isMem() && isConstantMemOff() && isInt<Bits>(getConstantMemOff())
1160       && (getConstantMemOff() % 4 == 0) && getMemBase()->isRegIdx()
1161       && (getMemBase()->getGPR32Reg() == Mips::GP);
1162   }
1163   template <unsigned Bits, unsigned ShiftLeftAmount>
1164   bool isScaledUImm() const {
1165     return isConstantImm() &&
1166            isShiftedUInt<Bits, ShiftLeftAmount>(getConstantImm());
1167   }
1168   template <unsigned Bits, unsigned ShiftLeftAmount>
1169   bool isScaledSImm() const {
1170     if (isConstantImm() && isShiftedInt<Bits, ShiftLeftAmount>(getConstantImm()))
1171       return true;
1172     // Operand can also be a symbol or symbol plus offset in case of relocations.
1173     if (Kind != k_Immediate)
1174       return false;
1175     MCValue Res;
1176     bool Success = getImm()->evaluateAsRelocatable(Res, nullptr, nullptr);
1177     return Success && isShiftedInt<Bits, ShiftLeftAmount>(Res.getConstant());
1178   }
1179   bool isRegList16() const {
1180     if (!isRegList())
1181       return false;
1182 
1183     int Size = RegList.List->size();
1184     if (Size < 2 || Size > 5)
1185       return false;
1186 
1187     unsigned R0 = RegList.List->front();
1188     unsigned R1 = RegList.List->back();
1189     if (!((R0 == Mips::S0 && R1 == Mips::RA) ||
1190           (R0 == Mips::S0_64 && R1 == Mips::RA_64)))
1191       return false;
1192 
1193     int PrevReg = *RegList.List->begin();
1194     for (int i = 1; i < Size - 1; i++) {
1195       int Reg = (*(RegList.List))[i];
1196       if ( Reg != PrevReg + 1)
1197         return false;
1198       PrevReg = Reg;
1199     }
1200 
1201     return true;
1202   }
1203   bool isInvNum() const { return Kind == k_Immediate; }
1204   bool isLSAImm() const {
1205     if (!isConstantImm())
1206       return false;
1207     int64_t Val = getConstantImm();
1208     return 1 <= Val && Val <= 4;
1209   }
1210   bool isRegList() const { return Kind == k_RegList; }
1211   bool isMovePRegPair() const {
1212     if (Kind != k_RegList || RegList.List->size() != 2)
1213       return false;
1214 
1215     unsigned R0 = RegList.List->front();
1216     unsigned R1 = RegList.List->back();
1217 
1218     if ((R0 == Mips::A1 && R1 == Mips::A2) ||
1219         (R0 == Mips::A1 && R1 == Mips::A3) ||
1220         (R0 == Mips::A2 && R1 == Mips::A3) ||
1221         (R0 == Mips::A0 && R1 == Mips::S5) ||
1222         (R0 == Mips::A0 && R1 == Mips::S6) ||
1223         (R0 == Mips::A0 && R1 == Mips::A1) ||
1224         (R0 == Mips::A0 && R1 == Mips::A2) ||
1225         (R0 == Mips::A0 && R1 == Mips::A3) ||
1226         (R0 == Mips::A1_64 && R1 == Mips::A2_64) ||
1227         (R0 == Mips::A1_64 && R1 == Mips::A3_64) ||
1228         (R0 == Mips::A2_64 && R1 == Mips::A3_64) ||
1229         (R0 == Mips::A0_64 && R1 == Mips::S5_64) ||
1230         (R0 == Mips::A0_64 && R1 == Mips::S6_64) ||
1231         (R0 == Mips::A0_64 && R1 == Mips::A1_64) ||
1232         (R0 == Mips::A0_64 && R1 == Mips::A2_64) ||
1233         (R0 == Mips::A0_64 && R1 == Mips::A3_64))
1234       return true;
1235 
1236     return false;
1237   }
1238 
1239   StringRef getToken() const {
1240     assert(Kind == k_Token && "Invalid access!");
1241     return StringRef(Tok.Data, Tok.Length);
1242   }
1243   bool isRegPair() const {
1244     return Kind == k_RegPair && RegIdx.Index <= 30;
1245   }
1246 
1247   unsigned getReg() const override {
1248     // As a special case until we sort out the definition of div/divu, accept
1249     // $0/$zero here so that MCK_ZERO works correctly.
1250     if (Kind == k_RegisterIndex && RegIdx.Index == 0 &&
1251         RegIdx.Kind & RegKind_GPR)
1252       return getGPR32Reg(); // FIXME: GPR64 too
1253 
1254     llvm_unreachable("Invalid access!");
1255     return 0;
1256   }
1257 
1258   const MCExpr *getImm() const {
1259     assert((Kind == k_Immediate) && "Invalid access!");
1260     return Imm.Val;
1261   }
1262 
1263   int64_t getConstantImm() const {
1264     const MCExpr *Val = getImm();
1265     return static_cast<const MCConstantExpr *>(Val)->getValue();
1266   }
1267 
1268   MipsOperand *getMemBase() const {
1269     assert((Kind == k_Memory) && "Invalid access!");
1270     return Mem.Base;
1271   }
1272 
1273   const MCExpr *getMemOff() const {
1274     assert((Kind == k_Memory) && "Invalid access!");
1275     return Mem.Off;
1276   }
1277 
1278   int64_t getConstantMemOff() const {
1279     return static_cast<const MCConstantExpr *>(getMemOff())->getValue();
1280   }
1281 
1282   const SmallVectorImpl<unsigned> &getRegList() const {
1283     assert((Kind == k_RegList) && "Invalid access!");
1284     return *(RegList.List);
1285   }
1286 
1287   unsigned getRegPair() const {
1288     assert((Kind == k_RegPair) && "Invalid access!");
1289     return RegIdx.Index;
1290   }
1291 
1292   static std::unique_ptr<MipsOperand> CreateToken(StringRef Str, SMLoc S,
1293                                                   MipsAsmParser &Parser) {
1294     auto Op = make_unique<MipsOperand>(k_Token, Parser);
1295     Op->Tok.Data = Str.data();
1296     Op->Tok.Length = Str.size();
1297     Op->StartLoc = S;
1298     Op->EndLoc = S;
1299     return Op;
1300   }
1301 
1302   /// Create a numeric register (e.g. $1). The exact register remains
1303   /// unresolved until an instruction successfully matches
1304   static std::unique_ptr<MipsOperand>
1305   createNumericReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1306                    SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1307     DEBUG(dbgs() << "createNumericReg(" << Index << ", ...)\n");
1308     return CreateReg(Index, Str, RegKind_Numeric, RegInfo, S, E, Parser);
1309   }
1310 
1311   /// Create a register that is definitely a GPR.
1312   /// This is typically only used for named registers such as $gp.
1313   static std::unique_ptr<MipsOperand>
1314   createGPRReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1315                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1316     return CreateReg(Index, Str, RegKind_GPR, RegInfo, S, E, Parser);
1317   }
1318 
1319   /// Create a register that is definitely a FGR.
1320   /// This is typically only used for named registers such as $f0.
1321   static std::unique_ptr<MipsOperand>
1322   createFGRReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1323                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1324     return CreateReg(Index, Str, RegKind_FGR, RegInfo, S, E, Parser);
1325   }
1326 
1327   /// Create a register that is definitely a HWReg.
1328   /// This is typically only used for named registers such as $hwr_cpunum.
1329   static std::unique_ptr<MipsOperand>
1330   createHWRegsReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1331                   SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1332     return CreateReg(Index, Str, RegKind_HWRegs, RegInfo, S, E, Parser);
1333   }
1334 
1335   /// Create a register that is definitely an FCC.
1336   /// This is typically only used for named registers such as $fcc0.
1337   static std::unique_ptr<MipsOperand>
1338   createFCCReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1339                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1340     return CreateReg(Index, Str, RegKind_FCC, RegInfo, S, E, Parser);
1341   }
1342 
1343   /// Create a register that is definitely an ACC.
1344   /// This is typically only used for named registers such as $ac0.
1345   static std::unique_ptr<MipsOperand>
1346   createACCReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1347                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1348     return CreateReg(Index, Str, RegKind_ACC, RegInfo, S, E, Parser);
1349   }
1350 
1351   /// Create a register that is definitely an MSA128.
1352   /// This is typically only used for named registers such as $w0.
1353   static std::unique_ptr<MipsOperand>
1354   createMSA128Reg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1355                   SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1356     return CreateReg(Index, Str, RegKind_MSA128, RegInfo, S, E, Parser);
1357   }
1358 
1359   /// Create a register that is definitely an MSACtrl.
1360   /// This is typically only used for named registers such as $msaaccess.
1361   static std::unique_ptr<MipsOperand>
1362   createMSACtrlReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1363                    SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1364     return CreateReg(Index, Str, RegKind_MSACtrl, RegInfo, S, E, Parser);
1365   }
1366 
1367   static std::unique_ptr<MipsOperand>
1368   CreateImm(const MCExpr *Val, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1369     auto Op = make_unique<MipsOperand>(k_Immediate, Parser);
1370     Op->Imm.Val = Val;
1371     Op->StartLoc = S;
1372     Op->EndLoc = E;
1373     return Op;
1374   }
1375 
1376   static std::unique_ptr<MipsOperand>
1377   CreateMem(std::unique_ptr<MipsOperand> Base, const MCExpr *Off, SMLoc S,
1378             SMLoc E, MipsAsmParser &Parser) {
1379     auto Op = make_unique<MipsOperand>(k_Memory, Parser);
1380     Op->Mem.Base = Base.release();
1381     Op->Mem.Off = Off;
1382     Op->StartLoc = S;
1383     Op->EndLoc = E;
1384     return Op;
1385   }
1386 
1387   static std::unique_ptr<MipsOperand>
1388   CreateRegList(SmallVectorImpl<unsigned> &Regs, SMLoc StartLoc, SMLoc EndLoc,
1389                 MipsAsmParser &Parser) {
1390     assert (Regs.size() > 0 && "Empty list not allowed");
1391 
1392     auto Op = make_unique<MipsOperand>(k_RegList, Parser);
1393     Op->RegList.List = new SmallVector<unsigned, 10>(Regs.begin(), Regs.end());
1394     Op->StartLoc = StartLoc;
1395     Op->EndLoc = EndLoc;
1396     return Op;
1397   }
1398 
1399   static std::unique_ptr<MipsOperand> CreateRegPair(const MipsOperand &MOP,
1400                                                     SMLoc S, SMLoc E,
1401                                                     MipsAsmParser &Parser) {
1402     auto Op = make_unique<MipsOperand>(k_RegPair, Parser);
1403     Op->RegIdx.Index = MOP.RegIdx.Index;
1404     Op->RegIdx.RegInfo = MOP.RegIdx.RegInfo;
1405     Op->RegIdx.Kind = MOP.RegIdx.Kind;
1406     Op->StartLoc = S;
1407     Op->EndLoc = E;
1408     return Op;
1409   }
1410 
1411   bool isGPRAsmReg() const {
1412     return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31;
1413   }
1414   bool isMM16AsmReg() const {
1415     if (!(isRegIdx() && RegIdx.Kind))
1416       return false;
1417     return ((RegIdx.Index >= 2 && RegIdx.Index <= 7)
1418             || RegIdx.Index == 16 || RegIdx.Index == 17);
1419   }
1420   bool isMM16AsmRegZero() const {
1421     if (!(isRegIdx() && RegIdx.Kind))
1422       return false;
1423     return (RegIdx.Index == 0 ||
1424             (RegIdx.Index >= 2 && RegIdx.Index <= 7) ||
1425             RegIdx.Index == 17);
1426   }
1427   bool isMM16AsmRegMoveP() const {
1428     if (!(isRegIdx() && RegIdx.Kind))
1429       return false;
1430     return (RegIdx.Index == 0 || (RegIdx.Index >= 2 && RegIdx.Index <= 3) ||
1431       (RegIdx.Index >= 16 && RegIdx.Index <= 20));
1432   }
1433   bool isFGRAsmReg() const {
1434     // AFGR64 is $0-$15 but we handle this in getAFGR64()
1435     return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31;
1436   }
1437   bool isHWRegsAsmReg() const {
1438     return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31;
1439   }
1440   bool isCCRAsmReg() const {
1441     return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31;
1442   }
1443   bool isFCCAsmReg() const {
1444     if (!(isRegIdx() && RegIdx.Kind & RegKind_FCC))
1445       return false;
1446     if (!AsmParser.hasEightFccRegisters())
1447       return RegIdx.Index == 0;
1448     return RegIdx.Index <= 7;
1449   }
1450   bool isACCAsmReg() const {
1451     return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3;
1452   }
1453   bool isCOP0AsmReg() const {
1454     return isRegIdx() && RegIdx.Kind & RegKind_COP0 && RegIdx.Index <= 31;
1455   }
1456   bool isCOP2AsmReg() const {
1457     return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31;
1458   }
1459   bool isCOP3AsmReg() const {
1460     return isRegIdx() && RegIdx.Kind & RegKind_COP3 && RegIdx.Index <= 31;
1461   }
1462   bool isMSA128AsmReg() const {
1463     return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31;
1464   }
1465   bool isMSACtrlAsmReg() const {
1466     return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7;
1467   }
1468 
1469   /// getStartLoc - Get the location of the first token of this operand.
1470   SMLoc getStartLoc() const override { return StartLoc; }
1471   /// getEndLoc - Get the location of the last token of this operand.
1472   SMLoc getEndLoc() const override { return EndLoc; }
1473 
1474   virtual ~MipsOperand() {
1475     switch (Kind) {
1476     case k_Immediate:
1477       break;
1478     case k_Memory:
1479       delete Mem.Base;
1480       break;
1481     case k_RegList:
1482       delete RegList.List;
1483     case k_RegisterIndex:
1484     case k_Token:
1485     case k_RegPair:
1486       break;
1487     }
1488   }
1489 
1490   void print(raw_ostream &OS) const override {
1491     switch (Kind) {
1492     case k_Immediate:
1493       OS << "Imm<";
1494       OS << *Imm.Val;
1495       OS << ">";
1496       break;
1497     case k_Memory:
1498       OS << "Mem<";
1499       Mem.Base->print(OS);
1500       OS << ", ";
1501       OS << *Mem.Off;
1502       OS << ">";
1503       break;
1504     case k_RegisterIndex:
1505       OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ", "
1506          << StringRef(RegIdx.Tok.Data, RegIdx.Tok.Length) << ">";
1507       break;
1508     case k_Token:
1509       OS << getToken();
1510       break;
1511     case k_RegList:
1512       OS << "RegList< ";
1513       for (auto Reg : (*RegList.List))
1514         OS << Reg << " ";
1515       OS <<  ">";
1516       break;
1517     case k_RegPair:
1518       OS << "RegPair<" << RegIdx.Index << "," << RegIdx.Index + 1 << ">";
1519       break;
1520     }
1521   }
1522 
1523   bool isValidForTie(const MipsOperand &Other) const {
1524     if (Kind != Other.Kind)
1525       return false;
1526 
1527     switch (Kind) {
1528     default:
1529       llvm_unreachable("Unexpected kind");
1530       return false;
1531     case k_RegisterIndex: {
1532       StringRef Token(RegIdx.Tok.Data, RegIdx.Tok.Length);
1533       StringRef OtherToken(Other.RegIdx.Tok.Data, Other.RegIdx.Tok.Length);
1534       return Token == OtherToken;
1535     }
1536     }
1537   }
1538 }; // class MipsOperand
1539 } // namespace
1540 
1541 namespace llvm {
1542 extern const MCInstrDesc MipsInsts[];
1543 }
1544 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
1545   return MipsInsts[Opcode];
1546 }
1547 
1548 static bool hasShortDelaySlot(unsigned Opcode) {
1549   switch (Opcode) {
1550     case Mips::JALS_MM:
1551     case Mips::JALRS_MM:
1552     case Mips::JALRS16_MM:
1553     case Mips::BGEZALS_MM:
1554     case Mips::BLTZALS_MM:
1555       return true;
1556     default:
1557       return false;
1558   }
1559 }
1560 
1561 static const MCSymbol *getSingleMCSymbol(const MCExpr *Expr) {
1562   if (const MCSymbolRefExpr *SRExpr = dyn_cast<MCSymbolRefExpr>(Expr)) {
1563     return &SRExpr->getSymbol();
1564   }
1565 
1566   if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr)) {
1567     const MCSymbol *LHSSym = getSingleMCSymbol(BExpr->getLHS());
1568     const MCSymbol *RHSSym = getSingleMCSymbol(BExpr->getRHS());
1569 
1570     if (LHSSym)
1571       return LHSSym;
1572 
1573     if (RHSSym)
1574       return RHSSym;
1575 
1576     return nullptr;
1577   }
1578 
1579   if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr))
1580     return getSingleMCSymbol(UExpr->getSubExpr());
1581 
1582   return nullptr;
1583 }
1584 
1585 static unsigned countMCSymbolRefExpr(const MCExpr *Expr) {
1586   if (isa<MCSymbolRefExpr>(Expr))
1587     return 1;
1588 
1589   if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr))
1590     return countMCSymbolRefExpr(BExpr->getLHS()) +
1591            countMCSymbolRefExpr(BExpr->getRHS());
1592 
1593   if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr))
1594     return countMCSymbolRefExpr(UExpr->getSubExpr());
1595 
1596   return 0;
1597 }
1598 
1599 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
1600                                        MCStreamer &Out,
1601                                        const MCSubtargetInfo *STI) {
1602   MipsTargetStreamer &TOut = getTargetStreamer();
1603   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
1604   bool ExpandedJalSym = false;
1605 
1606   Inst.setLoc(IDLoc);
1607 
1608   if (MCID.isBranch() || MCID.isCall()) {
1609     const unsigned Opcode = Inst.getOpcode();
1610     MCOperand Offset;
1611 
1612     switch (Opcode) {
1613     default:
1614       break;
1615     case Mips::BBIT0:
1616     case Mips::BBIT032:
1617     case Mips::BBIT1:
1618     case Mips::BBIT132:
1619       assert(hasCnMips() && "instruction only valid for octeon cpus");
1620       LLVM_FALLTHROUGH;
1621 
1622     case Mips::BEQ:
1623     case Mips::BNE:
1624     case Mips::BEQ_MM:
1625     case Mips::BNE_MM:
1626       assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1627       Offset = Inst.getOperand(2);
1628       if (!Offset.isImm())
1629         break; // We'll deal with this situation later on when applying fixups.
1630       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1631         return Error(IDLoc, "branch target out of range");
1632       if (OffsetToAlignment(Offset.getImm(),
1633                             1LL << (inMicroMipsMode() ? 1 : 2)))
1634         return Error(IDLoc, "branch to misaligned address");
1635       break;
1636     case Mips::BGEZ:
1637     case Mips::BGTZ:
1638     case Mips::BLEZ:
1639     case Mips::BLTZ:
1640     case Mips::BGEZAL:
1641     case Mips::BLTZAL:
1642     case Mips::BC1F:
1643     case Mips::BC1T:
1644     case Mips::BGEZ_MM:
1645     case Mips::BGTZ_MM:
1646     case Mips::BLEZ_MM:
1647     case Mips::BLTZ_MM:
1648     case Mips::BGEZAL_MM:
1649     case Mips::BLTZAL_MM:
1650     case Mips::BC1F_MM:
1651     case Mips::BC1T_MM:
1652     case Mips::BC1EQZC_MMR6:
1653     case Mips::BC1NEZC_MMR6:
1654     case Mips::BC2EQZC_MMR6:
1655     case Mips::BC2NEZC_MMR6:
1656       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1657       Offset = Inst.getOperand(1);
1658       if (!Offset.isImm())
1659         break; // We'll deal with this situation later on when applying fixups.
1660       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1661         return Error(IDLoc, "branch target out of range");
1662       if (OffsetToAlignment(Offset.getImm(),
1663                             1LL << (inMicroMipsMode() ? 1 : 2)))
1664         return Error(IDLoc, "branch to misaligned address");
1665       break;
1666     case Mips::BGEC:    case Mips::BGEC_MMR6:
1667     case Mips::BLTC:    case Mips::BLTC_MMR6:
1668     case Mips::BGEUC:   case Mips::BGEUC_MMR6:
1669     case Mips::BLTUC:   case Mips::BLTUC_MMR6:
1670     case Mips::BEQC:    case Mips::BEQC_MMR6:
1671     case Mips::BNEC:    case Mips::BNEC_MMR6:
1672       assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1673       Offset = Inst.getOperand(2);
1674       if (!Offset.isImm())
1675         break; // We'll deal with this situation later on when applying fixups.
1676       if (!isIntN(18, Offset.getImm()))
1677         return Error(IDLoc, "branch target out of range");
1678       if (OffsetToAlignment(Offset.getImm(), 1LL << 2))
1679         return Error(IDLoc, "branch to misaligned address");
1680       break;
1681     case Mips::BLEZC:   case Mips::BLEZC_MMR6:
1682     case Mips::BGEZC:   case Mips::BGEZC_MMR6:
1683     case Mips::BGTZC:   case Mips::BGTZC_MMR6:
1684     case Mips::BLTZC:   case Mips::BLTZC_MMR6:
1685       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1686       Offset = Inst.getOperand(1);
1687       if (!Offset.isImm())
1688         break; // We'll deal with this situation later on when applying fixups.
1689       if (!isIntN(18, Offset.getImm()))
1690         return Error(IDLoc, "branch target out of range");
1691       if (OffsetToAlignment(Offset.getImm(), 1LL << 2))
1692         return Error(IDLoc, "branch to misaligned address");
1693       break;
1694     case Mips::BEQZC:   case Mips::BEQZC_MMR6:
1695     case Mips::BNEZC:   case Mips::BNEZC_MMR6:
1696       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1697       Offset = Inst.getOperand(1);
1698       if (!Offset.isImm())
1699         break; // We'll deal with this situation later on when applying fixups.
1700       if (!isIntN(23, Offset.getImm()))
1701         return Error(IDLoc, "branch target out of range");
1702       if (OffsetToAlignment(Offset.getImm(), 1LL << 2))
1703         return Error(IDLoc, "branch to misaligned address");
1704       break;
1705     case Mips::BEQZ16_MM:
1706     case Mips::BEQZC16_MMR6:
1707     case Mips::BNEZ16_MM:
1708     case Mips::BNEZC16_MMR6:
1709       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1710       Offset = Inst.getOperand(1);
1711       if (!Offset.isImm())
1712         break; // We'll deal with this situation later on when applying fixups.
1713       if (!isInt<8>(Offset.getImm()))
1714         return Error(IDLoc, "branch target out of range");
1715       if (OffsetToAlignment(Offset.getImm(), 2LL))
1716         return Error(IDLoc, "branch to misaligned address");
1717       break;
1718     }
1719   }
1720 
1721   // SSNOP is deprecated on MIPS32r6/MIPS64r6
1722   // We still accept it but it is a normal nop.
1723   if (hasMips32r6() && Inst.getOpcode() == Mips::SSNOP) {
1724     std::string ISA = hasMips64r6() ? "MIPS64r6" : "MIPS32r6";
1725     Warning(IDLoc, "ssnop is deprecated for " + ISA + " and is equivalent to a "
1726                                                       "nop instruction");
1727   }
1728 
1729   if (hasCnMips()) {
1730     const unsigned Opcode = Inst.getOpcode();
1731     MCOperand Opnd;
1732     int Imm;
1733 
1734     switch (Opcode) {
1735       default:
1736         break;
1737 
1738       case Mips::BBIT0:
1739       case Mips::BBIT032:
1740       case Mips::BBIT1:
1741       case Mips::BBIT132:
1742         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1743         // The offset is handled above
1744         Opnd = Inst.getOperand(1);
1745         if (!Opnd.isImm())
1746           return Error(IDLoc, "expected immediate operand kind");
1747         Imm = Opnd.getImm();
1748         if (Imm < 0 || Imm > (Opcode == Mips::BBIT0 ||
1749                               Opcode == Mips::BBIT1 ? 63 : 31))
1750           return Error(IDLoc, "immediate operand value out of range");
1751         if (Imm > 31) {
1752           Inst.setOpcode(Opcode == Mips::BBIT0 ? Mips::BBIT032
1753                                                : Mips::BBIT132);
1754           Inst.getOperand(1).setImm(Imm - 32);
1755         }
1756         break;
1757 
1758       case Mips::SEQi:
1759       case Mips::SNEi:
1760         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1761         Opnd = Inst.getOperand(2);
1762         if (!Opnd.isImm())
1763           return Error(IDLoc, "expected immediate operand kind");
1764         Imm = Opnd.getImm();
1765         if (!isInt<10>(Imm))
1766           return Error(IDLoc, "immediate operand value out of range");
1767         break;
1768     }
1769   }
1770 
1771   // This expansion is not in a function called by tryExpandInstruction()
1772   // because the pseudo-instruction doesn't have a distinct opcode.
1773   if ((Inst.getOpcode() == Mips::JAL || Inst.getOpcode() == Mips::JAL_MM) &&
1774       inPicMode()) {
1775     warnIfNoMacro(IDLoc);
1776 
1777     const MCExpr *JalExpr = Inst.getOperand(0).getExpr();
1778 
1779     // We can do this expansion if there's only 1 symbol in the argument
1780     // expression.
1781     if (countMCSymbolRefExpr(JalExpr) > 1)
1782       return Error(IDLoc, "jal doesn't support multiple symbols in PIC mode");
1783 
1784     // FIXME: This is checking the expression can be handled by the later stages
1785     //        of the assembler. We ought to leave it to those later stages.
1786     const MCSymbol *JalSym = getSingleMCSymbol(JalExpr);
1787 
1788     // FIXME: Add support for label+offset operands (currently causes an error).
1789     // FIXME: Add support for forward-declared local symbols.
1790     // FIXME: Add expansion for when the LargeGOT option is enabled.
1791     if (JalSym->isInSection() || JalSym->isTemporary()) {
1792       if (isABI_O32()) {
1793         // If it's a local symbol and the O32 ABI is being used, we expand to:
1794         //  lw $25, 0($gp)
1795         //    R_(MICRO)MIPS_GOT16  label
1796         //  addiu $25, $25, 0
1797         //    R_(MICRO)MIPS_LO16   label
1798         //  jalr  $25
1799         const MCExpr *Got16RelocExpr =
1800             MipsMCExpr::create(MipsMCExpr::MEK_GOT, JalExpr, getContext());
1801         const MCExpr *Lo16RelocExpr =
1802             MipsMCExpr::create(MipsMCExpr::MEK_LO, JalExpr, getContext());
1803 
1804         TOut.emitRRX(Mips::LW, Mips::T9, Mips::GP,
1805                      MCOperand::createExpr(Got16RelocExpr), IDLoc, STI);
1806         TOut.emitRRX(Mips::ADDiu, Mips::T9, Mips::T9,
1807                      MCOperand::createExpr(Lo16RelocExpr), IDLoc, STI);
1808       } else if (isABI_N32() || isABI_N64()) {
1809         // If it's a local symbol and the N32/N64 ABIs are being used,
1810         // we expand to:
1811         //  lw/ld $25, 0($gp)
1812         //    R_(MICRO)MIPS_GOT_DISP  label
1813         //  jalr  $25
1814         const MCExpr *GotDispRelocExpr =
1815             MipsMCExpr::create(MipsMCExpr::MEK_GOT_DISP, JalExpr, getContext());
1816 
1817         TOut.emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9,
1818                      Mips::GP, MCOperand::createExpr(GotDispRelocExpr), IDLoc,
1819                      STI);
1820       }
1821     } else {
1822       // If it's an external/weak symbol, we expand to:
1823       //  lw/ld    $25, 0($gp)
1824       //    R_(MICRO)MIPS_CALL16  label
1825       //  jalr  $25
1826       const MCExpr *Call16RelocExpr =
1827           MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, JalExpr, getContext());
1828 
1829       TOut.emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9, Mips::GP,
1830                    MCOperand::createExpr(Call16RelocExpr), IDLoc, STI);
1831     }
1832 
1833     MCInst JalrInst;
1834     if (IsCpRestoreSet && inMicroMipsMode())
1835       JalrInst.setOpcode(Mips::JALRS_MM);
1836     else
1837       JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR);
1838     JalrInst.addOperand(MCOperand::createReg(Mips::RA));
1839     JalrInst.addOperand(MCOperand::createReg(Mips::T9));
1840 
1841     // FIXME: Add an R_(MICRO)MIPS_JALR relocation after the JALR.
1842     // This relocation is supposed to be an optimization hint for the linker
1843     // and is not necessary for correctness.
1844 
1845     Inst = JalrInst;
1846     ExpandedJalSym = true;
1847   }
1848 
1849   bool IsPCRelativeLoad = (MCID.TSFlags & MipsII::IsPCRelativeLoad) != 0;
1850   if ((MCID.mayLoad() || MCID.mayStore()) && !IsPCRelativeLoad) {
1851     // Check the offset of memory operand, if it is a symbol
1852     // reference or immediate we may have to expand instructions.
1853     for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
1854       const MCOperandInfo &OpInfo = MCID.OpInfo[i];
1855       if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
1856           (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
1857         MCOperand &Op = Inst.getOperand(i);
1858         if (Op.isImm()) {
1859           int MemOffset = Op.getImm();
1860           if (MemOffset < -32768 || MemOffset > 32767) {
1861             // Offset can't exceed 16bit value.
1862             expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad(), true);
1863             return false;
1864           }
1865         } else if (Op.isExpr()) {
1866           const MCExpr *Expr = Op.getExpr();
1867           if (Expr->getKind() == MCExpr::SymbolRef) {
1868             const MCSymbolRefExpr *SR =
1869                 static_cast<const MCSymbolRefExpr *>(Expr);
1870             if (SR->getKind() == MCSymbolRefExpr::VK_None) {
1871               // Expand symbol.
1872               expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad(), false);
1873               return false;
1874             }
1875           } else if (!isEvaluated(Expr)) {
1876             expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad(), false);
1877             return false;
1878           }
1879         }
1880       }
1881     } // for
1882   }   // if load/store
1883 
1884   if (inMicroMipsMode()) {
1885     if (MCID.mayLoad()) {
1886       // Try to create 16-bit GP relative load instruction.
1887       for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
1888         const MCOperandInfo &OpInfo = MCID.OpInfo[i];
1889         if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
1890             (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
1891           MCOperand &Op = Inst.getOperand(i);
1892           if (Op.isImm()) {
1893             int MemOffset = Op.getImm();
1894             MCOperand &DstReg = Inst.getOperand(0);
1895             MCOperand &BaseReg = Inst.getOperand(1);
1896             if (isInt<9>(MemOffset) && (MemOffset % 4 == 0) &&
1897                 getContext().getRegisterInfo()->getRegClass(
1898                   Mips::GPRMM16RegClassID).contains(DstReg.getReg()) &&
1899                 (BaseReg.getReg() == Mips::GP ||
1900                 BaseReg.getReg() == Mips::GP_64)) {
1901 
1902               TOut.emitRRI(Mips::LWGP_MM, DstReg.getReg(), Mips::GP, MemOffset,
1903                            IDLoc, STI);
1904               return false;
1905             }
1906           }
1907         }
1908       } // for
1909     }   // if load
1910 
1911     // TODO: Handle this with the AsmOperandClass.PredicateMethod.
1912 
1913     MCOperand Opnd;
1914     int Imm;
1915 
1916     switch (Inst.getOpcode()) {
1917       default:
1918         break;
1919       case Mips::ADDIUSP_MM:
1920         Opnd = Inst.getOperand(0);
1921         if (!Opnd.isImm())
1922           return Error(IDLoc, "expected immediate operand kind");
1923         Imm = Opnd.getImm();
1924         if (Imm < -1032 || Imm > 1028 || (Imm < 8 && Imm > -12) ||
1925             Imm % 4 != 0)
1926           return Error(IDLoc, "immediate operand value out of range");
1927         break;
1928       case Mips::SLL16_MM:
1929       case Mips::SRL16_MM:
1930         Opnd = Inst.getOperand(2);
1931         if (!Opnd.isImm())
1932           return Error(IDLoc, "expected immediate operand kind");
1933         Imm = Opnd.getImm();
1934         if (Imm < 1 || Imm > 8)
1935           return Error(IDLoc, "immediate operand value out of range");
1936         break;
1937       case Mips::LI16_MM:
1938         Opnd = Inst.getOperand(1);
1939         if (!Opnd.isImm())
1940           return Error(IDLoc, "expected immediate operand kind");
1941         Imm = Opnd.getImm();
1942         if (Imm < -1 || Imm > 126)
1943           return Error(IDLoc, "immediate operand value out of range");
1944         break;
1945       case Mips::ADDIUR2_MM:
1946         Opnd = Inst.getOperand(2);
1947         if (!Opnd.isImm())
1948           return Error(IDLoc, "expected immediate operand kind");
1949         Imm = Opnd.getImm();
1950         if (!(Imm == 1 || Imm == -1 ||
1951               ((Imm % 4 == 0) && Imm < 28 && Imm > 0)))
1952           return Error(IDLoc, "immediate operand value out of range");
1953         break;
1954       case Mips::ANDI16_MM:
1955         Opnd = Inst.getOperand(2);
1956         if (!Opnd.isImm())
1957           return Error(IDLoc, "expected immediate operand kind");
1958         Imm = Opnd.getImm();
1959         if (!(Imm == 128 || (Imm >= 1 && Imm <= 4) || Imm == 7 || Imm == 8 ||
1960               Imm == 15 || Imm == 16 || Imm == 31 || Imm == 32 || Imm == 63 ||
1961               Imm == 64 || Imm == 255 || Imm == 32768 || Imm == 65535))
1962           return Error(IDLoc, "immediate operand value out of range");
1963         break;
1964       case Mips::LBU16_MM:
1965         Opnd = Inst.getOperand(2);
1966         if (!Opnd.isImm())
1967           return Error(IDLoc, "expected immediate operand kind");
1968         Imm = Opnd.getImm();
1969         if (Imm < -1 || Imm > 14)
1970           return Error(IDLoc, "immediate operand value out of range");
1971         break;
1972       case Mips::SB16_MM:
1973       case Mips::SB16_MMR6:
1974         Opnd = Inst.getOperand(2);
1975         if (!Opnd.isImm())
1976           return Error(IDLoc, "expected immediate operand kind");
1977         Imm = Opnd.getImm();
1978         if (Imm < 0 || Imm > 15)
1979           return Error(IDLoc, "immediate operand value out of range");
1980         break;
1981       case Mips::LHU16_MM:
1982       case Mips::SH16_MM:
1983       case Mips::SH16_MMR6:
1984         Opnd = Inst.getOperand(2);
1985         if (!Opnd.isImm())
1986           return Error(IDLoc, "expected immediate operand kind");
1987         Imm = Opnd.getImm();
1988         if (Imm < 0 || Imm > 30 || (Imm % 2 != 0))
1989           return Error(IDLoc, "immediate operand value out of range");
1990         break;
1991       case Mips::LW16_MM:
1992       case Mips::SW16_MM:
1993       case Mips::SW16_MMR6:
1994         Opnd = Inst.getOperand(2);
1995         if (!Opnd.isImm())
1996           return Error(IDLoc, "expected immediate operand kind");
1997         Imm = Opnd.getImm();
1998         if (Imm < 0 || Imm > 60 || (Imm % 4 != 0))
1999           return Error(IDLoc, "immediate operand value out of range");
2000         break;
2001       case Mips::ADDIUPC_MM:
2002         MCOperand Opnd = Inst.getOperand(1);
2003         if (!Opnd.isImm())
2004           return Error(IDLoc, "expected immediate operand kind");
2005         int Imm = Opnd.getImm();
2006         if ((Imm % 4 != 0) || !isInt<25>(Imm))
2007           return Error(IDLoc, "immediate operand value out of range");
2008         break;
2009     }
2010   }
2011 
2012   bool FillDelaySlot =
2013       MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder();
2014   if (FillDelaySlot)
2015     TOut.emitDirectiveSetNoReorder();
2016 
2017   MacroExpanderResultTy ExpandResult =
2018       tryExpandInstruction(Inst, IDLoc, Out, STI);
2019   switch (ExpandResult) {
2020   case MER_NotAMacro:
2021     Out.EmitInstruction(Inst, *STI);
2022     break;
2023   case MER_Success:
2024     break;
2025   case MER_Fail:
2026     return true;
2027   }
2028 
2029   // We know we emitted an instruction on the MER_NotAMacro or MER_Success path.
2030   // If we're in microMIPS mode then we must also set EF_MIPS_MICROMIPS.
2031   if (inMicroMipsMode())
2032     TOut.setUsesMicroMips();
2033 
2034   // If this instruction has a delay slot and .set reorder is active,
2035   // emit a NOP after it.
2036   if (FillDelaySlot) {
2037     TOut.emitEmptyDelaySlot(hasShortDelaySlot(Inst.getOpcode()), IDLoc, STI);
2038     TOut.emitDirectiveSetReorder();
2039   }
2040 
2041   if ((Inst.getOpcode() == Mips::JalOneReg ||
2042        Inst.getOpcode() == Mips::JalTwoReg || ExpandedJalSym) &&
2043       isPicAndNotNxxAbi()) {
2044     if (IsCpRestoreSet) {
2045       // We need a NOP between the JALR and the LW:
2046       // If .set reorder has been used, we've already emitted a NOP.
2047       // If .set noreorder has been used, we need to emit a NOP at this point.
2048       if (!AssemblerOptions.back()->isReorder())
2049         TOut.emitEmptyDelaySlot(hasShortDelaySlot(Inst.getOpcode()), IDLoc,
2050                                 STI);
2051 
2052       // Load the $gp from the stack.
2053       TOut.emitGPRestore(CpRestoreOffset, IDLoc, STI);
2054     } else
2055       Warning(IDLoc, "no .cprestore used in PIC mode");
2056   }
2057 
2058   return false;
2059 }
2060 
2061 MipsAsmParser::MacroExpanderResultTy
2062 MipsAsmParser::tryExpandInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2063                                     const MCSubtargetInfo *STI) {
2064   switch (Inst.getOpcode()) {
2065   default:
2066     return MER_NotAMacro;
2067   case Mips::LoadImm32:
2068     return expandLoadImm(Inst, true, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2069   case Mips::LoadImm64:
2070     return expandLoadImm(Inst, false, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2071   case Mips::LoadAddrImm32:
2072   case Mips::LoadAddrImm64:
2073     assert(Inst.getOperand(0).isReg() && "expected register operand kind");
2074     assert((Inst.getOperand(1).isImm() || Inst.getOperand(1).isExpr()) &&
2075            "expected immediate operand kind");
2076 
2077     return expandLoadAddress(Inst.getOperand(0).getReg(), Mips::NoRegister,
2078                              Inst.getOperand(1),
2079                              Inst.getOpcode() == Mips::LoadAddrImm32, IDLoc,
2080                              Out, STI)
2081                ? MER_Fail
2082                : MER_Success;
2083   case Mips::LoadAddrReg32:
2084   case Mips::LoadAddrReg64:
2085     assert(Inst.getOperand(0).isReg() && "expected register operand kind");
2086     assert(Inst.getOperand(1).isReg() && "expected register operand kind");
2087     assert((Inst.getOperand(2).isImm() || Inst.getOperand(2).isExpr()) &&
2088            "expected immediate operand kind");
2089 
2090     return expandLoadAddress(Inst.getOperand(0).getReg(),
2091                              Inst.getOperand(1).getReg(), Inst.getOperand(2),
2092                              Inst.getOpcode() == Mips::LoadAddrReg32, IDLoc,
2093                              Out, STI)
2094                ? MER_Fail
2095                : MER_Success;
2096   case Mips::B_MM_Pseudo:
2097   case Mips::B_MMR6_Pseudo:
2098     return expandUncondBranchMMPseudo(Inst, IDLoc, Out, STI) ? MER_Fail
2099                                                              : MER_Success;
2100   case Mips::SWM_MM:
2101   case Mips::LWM_MM:
2102     return expandLoadStoreMultiple(Inst, IDLoc, Out, STI) ? MER_Fail
2103                                                           : MER_Success;
2104   case Mips::JalOneReg:
2105   case Mips::JalTwoReg:
2106     return expandJalWithRegs(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2107   case Mips::BneImm:
2108   case Mips::BeqImm:
2109     return expandBranchImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2110   case Mips::BLT:
2111   case Mips::BLE:
2112   case Mips::BGE:
2113   case Mips::BGT:
2114   case Mips::BLTU:
2115   case Mips::BLEU:
2116   case Mips::BGEU:
2117   case Mips::BGTU:
2118   case Mips::BLTL:
2119   case Mips::BLEL:
2120   case Mips::BGEL:
2121   case Mips::BGTL:
2122   case Mips::BLTUL:
2123   case Mips::BLEUL:
2124   case Mips::BGEUL:
2125   case Mips::BGTUL:
2126   case Mips::BLTImmMacro:
2127   case Mips::BLEImmMacro:
2128   case Mips::BGEImmMacro:
2129   case Mips::BGTImmMacro:
2130   case Mips::BLTUImmMacro:
2131   case Mips::BLEUImmMacro:
2132   case Mips::BGEUImmMacro:
2133   case Mips::BGTUImmMacro:
2134   case Mips::BLTLImmMacro:
2135   case Mips::BLELImmMacro:
2136   case Mips::BGELImmMacro:
2137   case Mips::BGTLImmMacro:
2138   case Mips::BLTULImmMacro:
2139   case Mips::BLEULImmMacro:
2140   case Mips::BGEULImmMacro:
2141   case Mips::BGTULImmMacro:
2142     return expandCondBranches(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2143   case Mips::SDivMacro:
2144     return expandDiv(Inst, IDLoc, Out, STI, false, true) ? MER_Fail
2145                                                          : MER_Success;
2146   case Mips::DSDivMacro:
2147     return expandDiv(Inst, IDLoc, Out, STI, true, true) ? MER_Fail
2148                                                         : MER_Success;
2149   case Mips::UDivMacro:
2150     return expandDiv(Inst, IDLoc, Out, STI, false, false) ? MER_Fail
2151                                                           : MER_Success;
2152   case Mips::DUDivMacro:
2153     return expandDiv(Inst, IDLoc, Out, STI, true, false) ? MER_Fail
2154                                                          : MER_Success;
2155   case Mips::PseudoTRUNC_W_S:
2156     return expandTrunc(Inst, false, false, IDLoc, Out, STI) ? MER_Fail
2157                                                             : MER_Success;
2158   case Mips::PseudoTRUNC_W_D32:
2159     return expandTrunc(Inst, true, false, IDLoc, Out, STI) ? MER_Fail
2160                                                            : MER_Success;
2161   case Mips::PseudoTRUNC_W_D:
2162     return expandTrunc(Inst, true, true, IDLoc, Out, STI) ? MER_Fail
2163                                                           : MER_Success;
2164   case Mips::Ulh:
2165     return expandUlh(Inst, true, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2166   case Mips::Ulhu:
2167     return expandUlh(Inst, false, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2168   case Mips::Ulw:
2169     return expandUlw(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2170   case Mips::NORImm:
2171     return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2172   case Mips::ADDi:
2173   case Mips::ADDiu:
2174   case Mips::SLTi:
2175   case Mips::SLTiu:
2176     if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() &&
2177         Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) {
2178       int64_t ImmValue = Inst.getOperand(2).getImm();
2179       if (isInt<16>(ImmValue))
2180         return MER_NotAMacro;
2181       return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail
2182                                                          : MER_Success;
2183     }
2184     return MER_NotAMacro;
2185   case Mips::ANDi:
2186   case Mips::ORi:
2187   case Mips::XORi:
2188     if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() &&
2189         Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) {
2190       int64_t ImmValue = Inst.getOperand(2).getImm();
2191       if (isUInt<16>(ImmValue))
2192         return MER_NotAMacro;
2193       return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail
2194                                                          : MER_Success;
2195     }
2196     return MER_NotAMacro;
2197   case Mips::ROL:
2198   case Mips::ROR:
2199     return expandRotation(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2200   case Mips::ROLImm:
2201   case Mips::RORImm:
2202     return expandRotationImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2203   case Mips::DROL:
2204   case Mips::DROR:
2205     return expandDRotation(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2206   case Mips::DROLImm:
2207   case Mips::DRORImm:
2208     return expandDRotationImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2209   case Mips::ABSMacro:
2210     return expandAbs(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2211   }
2212 }
2213 
2214 bool MipsAsmParser::expandJalWithRegs(MCInst &Inst, SMLoc IDLoc,
2215                                       MCStreamer &Out,
2216                                       const MCSubtargetInfo *STI) {
2217   MipsTargetStreamer &TOut = getTargetStreamer();
2218 
2219   // Create a JALR instruction which is going to replace the pseudo-JAL.
2220   MCInst JalrInst;
2221   JalrInst.setLoc(IDLoc);
2222   const MCOperand FirstRegOp = Inst.getOperand(0);
2223   const unsigned Opcode = Inst.getOpcode();
2224 
2225   if (Opcode == Mips::JalOneReg) {
2226     // jal $rs => jalr $rs
2227     if (IsCpRestoreSet && inMicroMipsMode()) {
2228       JalrInst.setOpcode(Mips::JALRS16_MM);
2229       JalrInst.addOperand(FirstRegOp);
2230     } else if (inMicroMipsMode()) {
2231       JalrInst.setOpcode(hasMips32r6() ? Mips::JALRC16_MMR6 : Mips::JALR16_MM);
2232       JalrInst.addOperand(FirstRegOp);
2233     } else {
2234       JalrInst.setOpcode(Mips::JALR);
2235       JalrInst.addOperand(MCOperand::createReg(Mips::RA));
2236       JalrInst.addOperand(FirstRegOp);
2237     }
2238   } else if (Opcode == Mips::JalTwoReg) {
2239     // jal $rd, $rs => jalr $rd, $rs
2240     if (IsCpRestoreSet && inMicroMipsMode())
2241       JalrInst.setOpcode(Mips::JALRS_MM);
2242     else
2243       JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR);
2244     JalrInst.addOperand(FirstRegOp);
2245     const MCOperand SecondRegOp = Inst.getOperand(1);
2246     JalrInst.addOperand(SecondRegOp);
2247   }
2248   Out.EmitInstruction(JalrInst, *STI);
2249 
2250   // If .set reorder is active and branch instruction has a delay slot,
2251   // emit a NOP after it.
2252   const MCInstrDesc &MCID = getInstDesc(JalrInst.getOpcode());
2253   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder())
2254     TOut.emitEmptyDelaySlot(hasShortDelaySlot(JalrInst.getOpcode()), IDLoc,
2255                             STI);
2256 
2257   return false;
2258 }
2259 
2260 /// Can the value be represented by a unsigned N-bit value and a shift left?
2261 template <unsigned N> static bool isShiftedUIntAtAnyPosition(uint64_t x) {
2262   unsigned BitNum = findFirstSet(x);
2263 
2264   return (x == x >> BitNum << BitNum) && isUInt<N>(x >> BitNum);
2265 }
2266 
2267 /// Load (or add) an immediate into a register.
2268 ///
2269 /// @param ImmValue     The immediate to load.
2270 /// @param DstReg       The register that will hold the immediate.
2271 /// @param SrcReg       A register to add to the immediate or Mips::NoRegister
2272 ///                     for a simple initialization.
2273 /// @param Is32BitImm   Is ImmValue 32-bit or 64-bit?
2274 /// @param IsAddress    True if the immediate represents an address. False if it
2275 ///                     is an integer.
2276 /// @param IDLoc        Location of the immediate in the source file.
2277 bool MipsAsmParser::loadImmediate(int64_t ImmValue, unsigned DstReg,
2278                                   unsigned SrcReg, bool Is32BitImm,
2279                                   bool IsAddress, SMLoc IDLoc, MCStreamer &Out,
2280                                   const MCSubtargetInfo *STI) {
2281   MipsTargetStreamer &TOut = getTargetStreamer();
2282 
2283   if (!Is32BitImm && !isGP64bit()) {
2284     Error(IDLoc, "instruction requires a 64-bit architecture");
2285     return true;
2286   }
2287 
2288   if (Is32BitImm) {
2289     if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) {
2290       // Sign extend up to 64-bit so that the predicates match the hardware
2291       // behaviour. In particular, isInt<16>(0xffff8000) and similar should be
2292       // true.
2293       ImmValue = SignExtend64<32>(ImmValue);
2294     } else {
2295       Error(IDLoc, "instruction requires a 32-bit immediate");
2296       return true;
2297     }
2298   }
2299 
2300   unsigned ZeroReg = IsAddress ? ABI.GetNullPtr() : ABI.GetZeroReg();
2301   unsigned AdduOp = !Is32BitImm ? Mips::DADDu : Mips::ADDu;
2302 
2303   bool UseSrcReg = false;
2304   if (SrcReg != Mips::NoRegister)
2305     UseSrcReg = true;
2306 
2307   unsigned TmpReg = DstReg;
2308   if (UseSrcReg &&
2309       getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) {
2310     // At this point we need AT to perform the expansions and we exit if it is
2311     // not available.
2312     unsigned ATReg = getATReg(IDLoc);
2313     if (!ATReg)
2314       return true;
2315     TmpReg = ATReg;
2316   }
2317 
2318   if (isInt<16>(ImmValue)) {
2319     if (!UseSrcReg)
2320       SrcReg = ZeroReg;
2321 
2322     // This doesn't quite follow the usual ABI expectations for N32 but matches
2323     // traditional assembler behaviour. N32 would normally use addiu for both
2324     // integers and addresses.
2325     if (IsAddress && !Is32BitImm) {
2326       TOut.emitRRI(Mips::DADDiu, DstReg, SrcReg, ImmValue, IDLoc, STI);
2327       return false;
2328     }
2329 
2330     TOut.emitRRI(Mips::ADDiu, DstReg, SrcReg, ImmValue, IDLoc, STI);
2331     return false;
2332   }
2333 
2334   if (isUInt<16>(ImmValue)) {
2335     unsigned TmpReg = DstReg;
2336     if (SrcReg == DstReg) {
2337       TmpReg = getATReg(IDLoc);
2338       if (!TmpReg)
2339         return true;
2340     }
2341 
2342     TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, ImmValue, IDLoc, STI);
2343     if (UseSrcReg)
2344       TOut.emitRRR(ABI.GetPtrAdduOp(), DstReg, TmpReg, SrcReg, IDLoc, STI);
2345     return false;
2346   }
2347 
2348   if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) {
2349     warnIfNoMacro(IDLoc);
2350 
2351     uint16_t Bits31To16 = (ImmValue >> 16) & 0xffff;
2352     uint16_t Bits15To0 = ImmValue & 0xffff;
2353 
2354     if (!Is32BitImm && !isInt<32>(ImmValue)) {
2355       // Traditional behaviour seems to special case this particular value. It's
2356       // not clear why other masks are handled differently.
2357       if (ImmValue == 0xffffffff) {
2358         TOut.emitRI(Mips::LUi, TmpReg, 0xffff, IDLoc, STI);
2359         TOut.emitRRI(Mips::DSRL32, TmpReg, TmpReg, 0, IDLoc, STI);
2360         if (UseSrcReg)
2361           TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2362         return false;
2363       }
2364 
2365       // Expand to an ORi instead of a LUi to avoid sign-extending into the
2366       // upper 32 bits.
2367       TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits31To16, IDLoc, STI);
2368       TOut.emitRRI(Mips::DSLL, TmpReg, TmpReg, 16, IDLoc, STI);
2369       if (Bits15To0)
2370         TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, STI);
2371       if (UseSrcReg)
2372         TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2373       return false;
2374     }
2375 
2376     TOut.emitRI(Mips::LUi, TmpReg, Bits31To16, IDLoc, STI);
2377     if (Bits15To0)
2378       TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, STI);
2379     if (UseSrcReg)
2380       TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2381     return false;
2382   }
2383 
2384   if (isShiftedUIntAtAnyPosition<16>(ImmValue)) {
2385     if (Is32BitImm) {
2386       Error(IDLoc, "instruction requires a 32-bit immediate");
2387       return true;
2388     }
2389 
2390     // Traditionally, these immediates are shifted as little as possible and as
2391     // such we align the most significant bit to bit 15 of our temporary.
2392     unsigned FirstSet = findFirstSet((uint64_t)ImmValue);
2393     unsigned LastSet = findLastSet((uint64_t)ImmValue);
2394     unsigned ShiftAmount = FirstSet - (15 - (LastSet - FirstSet));
2395     uint16_t Bits = (ImmValue >> ShiftAmount) & 0xffff;
2396     TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits, IDLoc, STI);
2397     TOut.emitRRI(Mips::DSLL, TmpReg, TmpReg, ShiftAmount, IDLoc, STI);
2398 
2399     if (UseSrcReg)
2400       TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2401 
2402     return false;
2403   }
2404 
2405   warnIfNoMacro(IDLoc);
2406 
2407   // The remaining case is packed with a sequence of dsll and ori with zeros
2408   // being omitted and any neighbouring dsll's being coalesced.
2409   // The highest 32-bit's are equivalent to a 32-bit immediate load.
2410 
2411   // Load bits 32-63 of ImmValue into bits 0-31 of the temporary register.
2412   if (loadImmediate(ImmValue >> 32, TmpReg, Mips::NoRegister, true, false,
2413                     IDLoc, Out, STI))
2414     return false;
2415 
2416   // Shift and accumulate into the register. If a 16-bit chunk is zero, then
2417   // skip it and defer the shift to the next chunk.
2418   unsigned ShiftCarriedForwards = 16;
2419   for (int BitNum = 16; BitNum >= 0; BitNum -= 16) {
2420     uint16_t ImmChunk = (ImmValue >> BitNum) & 0xffff;
2421 
2422     if (ImmChunk != 0) {
2423       TOut.emitDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc, STI);
2424       TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, ImmChunk, IDLoc, STI);
2425       ShiftCarriedForwards = 0;
2426     }
2427 
2428     ShiftCarriedForwards += 16;
2429   }
2430   ShiftCarriedForwards -= 16;
2431 
2432   // Finish any remaining shifts left by trailing zeros.
2433   if (ShiftCarriedForwards)
2434     TOut.emitDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc, STI);
2435 
2436   if (UseSrcReg)
2437     TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2438 
2439   return false;
2440 }
2441 
2442 bool MipsAsmParser::expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
2443                                   MCStreamer &Out, const MCSubtargetInfo *STI) {
2444   const MCOperand &ImmOp = Inst.getOperand(1);
2445   assert(ImmOp.isImm() && "expected immediate operand kind");
2446   const MCOperand &DstRegOp = Inst.getOperand(0);
2447   assert(DstRegOp.isReg() && "expected register operand kind");
2448 
2449   if (loadImmediate(ImmOp.getImm(), DstRegOp.getReg(), Mips::NoRegister,
2450                     Is32BitImm, false, IDLoc, Out, STI))
2451     return true;
2452 
2453   return false;
2454 }
2455 
2456 bool MipsAsmParser::expandLoadAddress(unsigned DstReg, unsigned BaseReg,
2457                                       const MCOperand &Offset,
2458                                       bool Is32BitAddress, SMLoc IDLoc,
2459                                       MCStreamer &Out,
2460                                       const MCSubtargetInfo *STI) {
2461   // la can't produce a usable address when addresses are 64-bit.
2462   if (Is32BitAddress && ABI.ArePtrs64bit()) {
2463     // FIXME: Demote this to a warning and continue as if we had 'dla' instead.
2464     //        We currently can't do this because we depend on the equality
2465     //        operator and N64 can end up with a GPR32/GPR64 mismatch.
2466     Error(IDLoc, "la used to load 64-bit address");
2467     // Continue as if we had 'dla' instead.
2468     Is32BitAddress = false;
2469   }
2470 
2471   // dla requires 64-bit addresses.
2472   if (!Is32BitAddress && !hasMips3()) {
2473     Error(IDLoc, "instruction requires a 64-bit architecture");
2474     return true;
2475   }
2476 
2477   if (!Offset.isImm())
2478     return loadAndAddSymbolAddress(Offset.getExpr(), DstReg, BaseReg,
2479                                    Is32BitAddress, IDLoc, Out, STI);
2480 
2481   if (!ABI.ArePtrs64bit()) {
2482     // Continue as if we had 'la' whether we had 'la' or 'dla'.
2483     Is32BitAddress = true;
2484   }
2485 
2486   return loadImmediate(Offset.getImm(), DstReg, BaseReg, Is32BitAddress, true,
2487                        IDLoc, Out, STI);
2488 }
2489 
2490 bool MipsAsmParser::loadAndAddSymbolAddress(const MCExpr *SymExpr,
2491                                             unsigned DstReg, unsigned SrcReg,
2492                                             bool Is32BitSym, SMLoc IDLoc,
2493                                             MCStreamer &Out,
2494                                             const MCSubtargetInfo *STI) {
2495   MipsTargetStreamer &TOut = getTargetStreamer();
2496   bool UseSrcReg = SrcReg != Mips::NoRegister;
2497   warnIfNoMacro(IDLoc);
2498 
2499   if (inPicMode() && ABI.IsO32()) {
2500     MCValue Res;
2501     if (!SymExpr->evaluateAsRelocatable(Res, nullptr, nullptr)) {
2502       Error(IDLoc, "expected relocatable expression");
2503       return true;
2504     }
2505     if (Res.getSymB() != nullptr) {
2506       Error(IDLoc, "expected relocatable expression with only one symbol");
2507       return true;
2508     }
2509 
2510     // The case where the result register is $25 is somewhat special. If the
2511     // symbol in the final relocation is external and not modified with a
2512     // constant then we must use R_MIPS_CALL16 instead of R_MIPS_GOT16.
2513     if ((DstReg == Mips::T9 || DstReg == Mips::T9_64) && !UseSrcReg &&
2514         Res.getConstant() == 0 && !Res.getSymA()->getSymbol().isInSection() &&
2515         !Res.getSymA()->getSymbol().isTemporary()) {
2516       const MCExpr *CallExpr =
2517           MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, SymExpr, getContext());
2518       TOut.emitRRX(Mips::LW, DstReg, ABI.GetGlobalPtr(),
2519                    MCOperand::createExpr(CallExpr), IDLoc, STI);
2520       return false;
2521     }
2522 
2523     // The remaining cases are:
2524     //   External GOT: lw $tmp, %got(symbol+offset)($gp)
2525     //                >addiu $tmp, $tmp, %lo(offset)
2526     //                >addiu $rd, $tmp, $rs
2527     //   Local GOT:    lw $tmp, %got(symbol+offset)($gp)
2528     //                 addiu $tmp, $tmp, %lo(symbol+offset)($gp)
2529     //                >addiu $rd, $tmp, $rs
2530     // The addiu's marked with a '>' may be omitted if they are redundant. If
2531     // this happens then the last instruction must use $rd as the result
2532     // register.
2533     const MipsMCExpr *GotExpr =
2534         MipsMCExpr::create(MipsMCExpr::MEK_GOT, SymExpr, getContext());
2535     const MCExpr *LoExpr = nullptr;
2536     if (Res.getSymA()->getSymbol().isInSection() ||
2537         Res.getSymA()->getSymbol().isTemporary())
2538       LoExpr = MipsMCExpr::create(MipsMCExpr::MEK_LO, SymExpr, getContext());
2539     else if (Res.getConstant() != 0) {
2540       // External symbols fully resolve the symbol with just the %got(symbol)
2541       // but we must still account for any offset to the symbol for expressions
2542       // like symbol+8.
2543       LoExpr = MCConstantExpr::create(Res.getConstant(), getContext());
2544     }
2545 
2546     unsigned TmpReg = DstReg;
2547     if (UseSrcReg &&
2548         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg,
2549                                                                SrcReg)) {
2550       // If $rs is the same as $rd, we need to use AT.
2551       // If it is not available we exit.
2552       unsigned ATReg = getATReg(IDLoc);
2553       if (!ATReg)
2554         return true;
2555       TmpReg = ATReg;
2556     }
2557 
2558     TOut.emitRRX(Mips::LW, TmpReg, ABI.GetGlobalPtr(),
2559                  MCOperand::createExpr(GotExpr), IDLoc, STI);
2560 
2561     if (LoExpr)
2562       TOut.emitRRX(Mips::ADDiu, TmpReg, TmpReg, MCOperand::createExpr(LoExpr),
2563                    IDLoc, STI);
2564 
2565     if (UseSrcReg)
2566       TOut.emitRRR(Mips::ADDu, DstReg, TmpReg, SrcReg, IDLoc, STI);
2567 
2568     return false;
2569   }
2570 
2571   const MipsMCExpr *HiExpr =
2572       MipsMCExpr::create(MipsMCExpr::MEK_HI, SymExpr, getContext());
2573   const MipsMCExpr *LoExpr =
2574       MipsMCExpr::create(MipsMCExpr::MEK_LO, SymExpr, getContext());
2575 
2576   // This is the 64-bit symbol address expansion.
2577   if (ABI.ArePtrs64bit() && isGP64bit()) {
2578     // We always need AT for the 64-bit expansion.
2579     // If it is not available we exit.
2580     unsigned ATReg = getATReg(IDLoc);
2581     if (!ATReg)
2582       return true;
2583 
2584     const MipsMCExpr *HighestExpr =
2585         MipsMCExpr::create(MipsMCExpr::MEK_HIGHEST, SymExpr, getContext());
2586     const MipsMCExpr *HigherExpr =
2587         MipsMCExpr::create(MipsMCExpr::MEK_HIGHER, SymExpr, getContext());
2588 
2589     if (UseSrcReg &&
2590         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg,
2591                                                                SrcReg)) {
2592       // If $rs is the same as $rd:
2593       // (d)la $rd, sym($rd) => lui    $at, %highest(sym)
2594       //                        daddiu $at, $at, %higher(sym)
2595       //                        dsll   $at, $at, 16
2596       //                        daddiu $at, $at, %hi(sym)
2597       //                        dsll   $at, $at, 16
2598       //                        daddiu $at, $at, %lo(sym)
2599       //                        daddu  $rd, $at, $rd
2600       TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HighestExpr), IDLoc,
2601                   STI);
2602       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg,
2603                    MCOperand::createExpr(HigherExpr), IDLoc, STI);
2604       TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI);
2605       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(HiExpr),
2606                    IDLoc, STI);
2607       TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI);
2608       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr),
2609                    IDLoc, STI);
2610       TOut.emitRRR(Mips::DADDu, DstReg, ATReg, SrcReg, IDLoc, STI);
2611 
2612       return false;
2613     }
2614 
2615     // Otherwise, if the $rs is different from $rd or if $rs isn't specified:
2616     // (d)la $rd, sym/sym($rs) => lui    $rd, %highest(sym)
2617     //                            lui    $at, %hi(sym)
2618     //                            daddiu $rd, $rd, %higher(sym)
2619     //                            daddiu $at, $at, %lo(sym)
2620     //                            dsll32 $rd, $rd, 0
2621     //                            daddu  $rd, $rd, $at
2622     //                            (daddu  $rd, $rd, $rs)
2623     TOut.emitRX(Mips::LUi, DstReg, MCOperand::createExpr(HighestExpr), IDLoc,
2624                 STI);
2625     TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HiExpr), IDLoc, STI);
2626     TOut.emitRRX(Mips::DADDiu, DstReg, DstReg,
2627                  MCOperand::createExpr(HigherExpr), IDLoc, STI);
2628     TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr),
2629                  IDLoc, STI);
2630     TOut.emitRRI(Mips::DSLL32, DstReg, DstReg, 0, IDLoc, STI);
2631     TOut.emitRRR(Mips::DADDu, DstReg, DstReg, ATReg, IDLoc, STI);
2632     if (UseSrcReg)
2633       TOut.emitRRR(Mips::DADDu, DstReg, DstReg, SrcReg, IDLoc, STI);
2634 
2635     return false;
2636   }
2637 
2638   // And now, the 32-bit symbol address expansion:
2639   // If $rs is the same as $rd:
2640   // (d)la $rd, sym($rd)     => lui   $at, %hi(sym)
2641   //                            ori   $at, $at, %lo(sym)
2642   //                            addu  $rd, $at, $rd
2643   // Otherwise, if the $rs is different from $rd or if $rs isn't specified:
2644   // (d)la $rd, sym/sym($rs) => lui   $rd, %hi(sym)
2645   //                            ori   $rd, $rd, %lo(sym)
2646   //                            (addu $rd, $rd, $rs)
2647   unsigned TmpReg = DstReg;
2648   if (UseSrcReg &&
2649       getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) {
2650     // If $rs is the same as $rd, we need to use AT.
2651     // If it is not available we exit.
2652     unsigned ATReg = getATReg(IDLoc);
2653     if (!ATReg)
2654       return true;
2655     TmpReg = ATReg;
2656   }
2657 
2658   TOut.emitRX(Mips::LUi, TmpReg, MCOperand::createExpr(HiExpr), IDLoc, STI);
2659   TOut.emitRRX(Mips::ADDiu, TmpReg, TmpReg, MCOperand::createExpr(LoExpr),
2660                IDLoc, STI);
2661 
2662   if (UseSrcReg)
2663     TOut.emitRRR(Mips::ADDu, DstReg, TmpReg, SrcReg, IDLoc, STI);
2664   else
2665     assert(
2666         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, TmpReg));
2667 
2668   return false;
2669 }
2670 
2671 bool MipsAsmParser::expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc,
2672                                                MCStreamer &Out,
2673                                                const MCSubtargetInfo *STI) {
2674   MipsTargetStreamer &TOut = getTargetStreamer();
2675 
2676   assert(getInstDesc(Inst.getOpcode()).getNumOperands() == 1 &&
2677          "unexpected number of operands");
2678 
2679   MCOperand Offset = Inst.getOperand(0);
2680   if (Offset.isExpr()) {
2681     Inst.clear();
2682     Inst.setOpcode(Mips::BEQ_MM);
2683     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2684     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2685     Inst.addOperand(MCOperand::createExpr(Offset.getExpr()));
2686   } else {
2687     assert(Offset.isImm() && "expected immediate operand kind");
2688     if (isInt<11>(Offset.getImm())) {
2689       // If offset fits into 11 bits then this instruction becomes microMIPS
2690       // 16-bit unconditional branch instruction.
2691       if (inMicroMipsMode())
2692         Inst.setOpcode(hasMips32r6() ? Mips::BC16_MMR6 : Mips::B16_MM);
2693     } else {
2694       if (!isInt<17>(Offset.getImm()))
2695         Error(IDLoc, "branch target out of range");
2696       if (OffsetToAlignment(Offset.getImm(), 1LL << 1))
2697         Error(IDLoc, "branch to misaligned address");
2698       Inst.clear();
2699       Inst.setOpcode(Mips::BEQ_MM);
2700       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2701       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2702       Inst.addOperand(MCOperand::createImm(Offset.getImm()));
2703     }
2704   }
2705   Out.EmitInstruction(Inst, *STI);
2706 
2707   // If .set reorder is active and branch instruction has a delay slot,
2708   // emit a NOP after it.
2709   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
2710   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder())
2711     TOut.emitEmptyDelaySlot(true, IDLoc, STI);
2712 
2713   return false;
2714 }
2715 
2716 bool MipsAsmParser::expandBranchImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2717                                     const MCSubtargetInfo *STI) {
2718   MipsTargetStreamer &TOut = getTargetStreamer();
2719   const MCOperand &DstRegOp = Inst.getOperand(0);
2720   assert(DstRegOp.isReg() && "expected register operand kind");
2721 
2722   const MCOperand &ImmOp = Inst.getOperand(1);
2723   assert(ImmOp.isImm() && "expected immediate operand kind");
2724 
2725   const MCOperand &MemOffsetOp = Inst.getOperand(2);
2726   assert((MemOffsetOp.isImm() || MemOffsetOp.isExpr()) &&
2727          "expected immediate or expression operand");
2728 
2729   unsigned OpCode = 0;
2730   switch(Inst.getOpcode()) {
2731     case Mips::BneImm:
2732       OpCode = Mips::BNE;
2733       break;
2734     case Mips::BeqImm:
2735       OpCode = Mips::BEQ;
2736       break;
2737     default:
2738       llvm_unreachable("Unknown immediate branch pseudo-instruction.");
2739       break;
2740   }
2741 
2742   int64_t ImmValue = ImmOp.getImm();
2743   if (ImmValue == 0)
2744     TOut.emitRRX(OpCode, DstRegOp.getReg(), Mips::ZERO, MemOffsetOp, IDLoc,
2745                  STI);
2746   else {
2747     warnIfNoMacro(IDLoc);
2748 
2749     unsigned ATReg = getATReg(IDLoc);
2750     if (!ATReg)
2751       return true;
2752 
2753     if (loadImmediate(ImmValue, ATReg, Mips::NoRegister, !isGP64bit(), true,
2754                       IDLoc, Out, STI))
2755       return true;
2756 
2757     TOut.emitRRX(OpCode, DstRegOp.getReg(), ATReg, MemOffsetOp, IDLoc, STI);
2758   }
2759   return false;
2760 }
2761 
2762 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2763                                   const MCSubtargetInfo *STI, bool IsLoad,
2764                                   bool IsImmOpnd) {
2765   if (IsLoad) {
2766     expandLoadInst(Inst, IDLoc, Out, STI, IsImmOpnd);
2767     return;
2768   }
2769   expandStoreInst(Inst, IDLoc, Out, STI, IsImmOpnd);
2770 }
2771 
2772 void MipsAsmParser::expandLoadInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2773                                    const MCSubtargetInfo *STI, bool IsImmOpnd) {
2774   MipsTargetStreamer &TOut = getTargetStreamer();
2775 
2776   unsigned DstReg = Inst.getOperand(0).getReg();
2777   unsigned BaseReg = Inst.getOperand(1).getReg();
2778 
2779   const MCInstrDesc &Desc = getInstDesc(Inst.getOpcode());
2780   int16_t DstRegClass = Desc.OpInfo[0].RegClass;
2781   unsigned DstRegClassID =
2782       getContext().getRegisterInfo()->getRegClass(DstRegClass).getID();
2783   bool IsGPR = (DstRegClassID == Mips::GPR32RegClassID) ||
2784                (DstRegClassID == Mips::GPR64RegClassID);
2785 
2786   if (IsImmOpnd) {
2787     // Try to use DstReg as the temporary.
2788     if (IsGPR && (BaseReg != DstReg)) {
2789       TOut.emitLoadWithImmOffset(Inst.getOpcode(), DstReg, BaseReg,
2790                                  Inst.getOperand(2).getImm(), DstReg, IDLoc,
2791                                  STI);
2792       return;
2793     }
2794 
2795     // At this point we need AT to perform the expansions and we exit if it is
2796     // not available.
2797     unsigned ATReg = getATReg(IDLoc);
2798     if (!ATReg)
2799       return;
2800 
2801     TOut.emitLoadWithImmOffset(Inst.getOpcode(), DstReg, BaseReg,
2802                                Inst.getOperand(2).getImm(), ATReg, IDLoc, STI);
2803     return;
2804   }
2805 
2806   const MCExpr *ExprOffset = Inst.getOperand(2).getExpr();
2807   MCOperand LoOperand = MCOperand::createExpr(
2808       MipsMCExpr::create(MipsMCExpr::MEK_LO, ExprOffset, getContext()));
2809   MCOperand HiOperand = MCOperand::createExpr(
2810       MipsMCExpr::create(MipsMCExpr::MEK_HI, ExprOffset, getContext()));
2811 
2812   // Try to use DstReg as the temporary.
2813   if (IsGPR && (BaseReg != DstReg)) {
2814     TOut.emitLoadWithSymOffset(Inst.getOpcode(), DstReg, BaseReg, HiOperand,
2815                                LoOperand, DstReg, IDLoc, STI);
2816     return;
2817   }
2818 
2819   // At this point we need AT to perform the expansions and we exit if it is
2820   // not available.
2821   unsigned ATReg = getATReg(IDLoc);
2822   if (!ATReg)
2823     return;
2824 
2825   TOut.emitLoadWithSymOffset(Inst.getOpcode(), DstReg, BaseReg, HiOperand,
2826                              LoOperand, ATReg, IDLoc, STI);
2827 }
2828 
2829 void MipsAsmParser::expandStoreInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2830                                     const MCSubtargetInfo *STI,
2831                                     bool IsImmOpnd) {
2832   MipsTargetStreamer &TOut = getTargetStreamer();
2833 
2834   unsigned SrcReg = Inst.getOperand(0).getReg();
2835   unsigned BaseReg = Inst.getOperand(1).getReg();
2836 
2837   if (IsImmOpnd) {
2838     TOut.emitStoreWithImmOffset(Inst.getOpcode(), SrcReg, BaseReg,
2839                                 Inst.getOperand(2).getImm(),
2840                                 [&]() { return getATReg(IDLoc); }, IDLoc, STI);
2841     return;
2842   }
2843 
2844   unsigned ATReg = getATReg(IDLoc);
2845   if (!ATReg)
2846     return;
2847 
2848   const MCExpr *ExprOffset = Inst.getOperand(2).getExpr();
2849   MCOperand LoOperand = MCOperand::createExpr(
2850       MipsMCExpr::create(MipsMCExpr::MEK_LO, ExprOffset, getContext()));
2851   MCOperand HiOperand = MCOperand::createExpr(
2852       MipsMCExpr::create(MipsMCExpr::MEK_HI, ExprOffset, getContext()));
2853   TOut.emitStoreWithSymOffset(Inst.getOpcode(), SrcReg, BaseReg, HiOperand,
2854                               LoOperand, ATReg, IDLoc, STI);
2855 }
2856 
2857 bool MipsAsmParser::expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc,
2858                                             MCStreamer &Out,
2859                                             const MCSubtargetInfo *STI) {
2860   unsigned OpNum = Inst.getNumOperands();
2861   unsigned Opcode = Inst.getOpcode();
2862   unsigned NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM32_MM : Mips::LWM32_MM;
2863 
2864   assert (Inst.getOperand(OpNum - 1).isImm() &&
2865           Inst.getOperand(OpNum - 2).isReg() &&
2866           Inst.getOperand(OpNum - 3).isReg() && "Invalid instruction operand.");
2867 
2868   if (OpNum < 8 && Inst.getOperand(OpNum - 1).getImm() <= 60 &&
2869       Inst.getOperand(OpNum - 1).getImm() >= 0 &&
2870       (Inst.getOperand(OpNum - 2).getReg() == Mips::SP ||
2871        Inst.getOperand(OpNum - 2).getReg() == Mips::SP_64) &&
2872       (Inst.getOperand(OpNum - 3).getReg() == Mips::RA ||
2873        Inst.getOperand(OpNum - 3).getReg() == Mips::RA_64)) {
2874     // It can be implemented as SWM16 or LWM16 instruction.
2875     if (inMicroMipsMode() && hasMips32r6())
2876       NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MMR6 : Mips::LWM16_MMR6;
2877     else
2878       NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MM : Mips::LWM16_MM;
2879   }
2880 
2881   Inst.setOpcode(NewOpcode);
2882   Out.EmitInstruction(Inst, *STI);
2883   return false;
2884 }
2885 
2886 bool MipsAsmParser::expandCondBranches(MCInst &Inst, SMLoc IDLoc,
2887                                        MCStreamer &Out,
2888                                        const MCSubtargetInfo *STI) {
2889   MipsTargetStreamer &TOut = getTargetStreamer();
2890   bool EmittedNoMacroWarning = false;
2891   unsigned PseudoOpcode = Inst.getOpcode();
2892   unsigned SrcReg = Inst.getOperand(0).getReg();
2893   const MCOperand &TrgOp = Inst.getOperand(1);
2894   const MCExpr *OffsetExpr = Inst.getOperand(2).getExpr();
2895 
2896   unsigned ZeroSrcOpcode, ZeroTrgOpcode;
2897   bool ReverseOrderSLT, IsUnsigned, IsLikely, AcceptsEquality;
2898 
2899   unsigned TrgReg;
2900   if (TrgOp.isReg())
2901     TrgReg = TrgOp.getReg();
2902   else if (TrgOp.isImm()) {
2903     warnIfNoMacro(IDLoc);
2904     EmittedNoMacroWarning = true;
2905 
2906     TrgReg = getATReg(IDLoc);
2907     if (!TrgReg)
2908       return true;
2909 
2910     switch(PseudoOpcode) {
2911     default:
2912       llvm_unreachable("unknown opcode for branch pseudo-instruction");
2913     case Mips::BLTImmMacro:
2914       PseudoOpcode = Mips::BLT;
2915       break;
2916     case Mips::BLEImmMacro:
2917       PseudoOpcode = Mips::BLE;
2918       break;
2919     case Mips::BGEImmMacro:
2920       PseudoOpcode = Mips::BGE;
2921       break;
2922     case Mips::BGTImmMacro:
2923       PseudoOpcode = Mips::BGT;
2924       break;
2925     case Mips::BLTUImmMacro:
2926       PseudoOpcode = Mips::BLTU;
2927       break;
2928     case Mips::BLEUImmMacro:
2929       PseudoOpcode = Mips::BLEU;
2930       break;
2931     case Mips::BGEUImmMacro:
2932       PseudoOpcode = Mips::BGEU;
2933       break;
2934     case Mips::BGTUImmMacro:
2935       PseudoOpcode = Mips::BGTU;
2936       break;
2937     case Mips::BLTLImmMacro:
2938       PseudoOpcode = Mips::BLTL;
2939       break;
2940     case Mips::BLELImmMacro:
2941       PseudoOpcode = Mips::BLEL;
2942       break;
2943     case Mips::BGELImmMacro:
2944       PseudoOpcode = Mips::BGEL;
2945       break;
2946     case Mips::BGTLImmMacro:
2947       PseudoOpcode = Mips::BGTL;
2948       break;
2949     case Mips::BLTULImmMacro:
2950       PseudoOpcode = Mips::BLTUL;
2951       break;
2952     case Mips::BLEULImmMacro:
2953       PseudoOpcode = Mips::BLEUL;
2954       break;
2955     case Mips::BGEULImmMacro:
2956       PseudoOpcode = Mips::BGEUL;
2957       break;
2958     case Mips::BGTULImmMacro:
2959       PseudoOpcode = Mips::BGTUL;
2960       break;
2961     }
2962 
2963     if (loadImmediate(TrgOp.getImm(), TrgReg, Mips::NoRegister, !isGP64bit(),
2964                       false, IDLoc, Out, STI))
2965       return true;
2966   }
2967 
2968   switch (PseudoOpcode) {
2969   case Mips::BLT:
2970   case Mips::BLTU:
2971   case Mips::BLTL:
2972   case Mips::BLTUL:
2973     AcceptsEquality = false;
2974     ReverseOrderSLT = false;
2975     IsUnsigned = ((PseudoOpcode == Mips::BLTU) || (PseudoOpcode == Mips::BLTUL));
2976     IsLikely = ((PseudoOpcode == Mips::BLTL) || (PseudoOpcode == Mips::BLTUL));
2977     ZeroSrcOpcode = Mips::BGTZ;
2978     ZeroTrgOpcode = Mips::BLTZ;
2979     break;
2980   case Mips::BLE:
2981   case Mips::BLEU:
2982   case Mips::BLEL:
2983   case Mips::BLEUL:
2984     AcceptsEquality = true;
2985     ReverseOrderSLT = true;
2986     IsUnsigned = ((PseudoOpcode == Mips::BLEU) || (PseudoOpcode == Mips::BLEUL));
2987     IsLikely = ((PseudoOpcode == Mips::BLEL) || (PseudoOpcode == Mips::BLEUL));
2988     ZeroSrcOpcode = Mips::BGEZ;
2989     ZeroTrgOpcode = Mips::BLEZ;
2990     break;
2991   case Mips::BGE:
2992   case Mips::BGEU:
2993   case Mips::BGEL:
2994   case Mips::BGEUL:
2995     AcceptsEquality = true;
2996     ReverseOrderSLT = false;
2997     IsUnsigned = ((PseudoOpcode == Mips::BGEU) || (PseudoOpcode == Mips::BGEUL));
2998     IsLikely = ((PseudoOpcode == Mips::BGEL) || (PseudoOpcode == Mips::BGEUL));
2999     ZeroSrcOpcode = Mips::BLEZ;
3000     ZeroTrgOpcode = Mips::BGEZ;
3001     break;
3002   case Mips::BGT:
3003   case Mips::BGTU:
3004   case Mips::BGTL:
3005   case Mips::BGTUL:
3006     AcceptsEquality = false;
3007     ReverseOrderSLT = true;
3008     IsUnsigned = ((PseudoOpcode == Mips::BGTU) || (PseudoOpcode == Mips::BGTUL));
3009     IsLikely = ((PseudoOpcode == Mips::BGTL) || (PseudoOpcode == Mips::BGTUL));
3010     ZeroSrcOpcode = Mips::BLTZ;
3011     ZeroTrgOpcode = Mips::BGTZ;
3012     break;
3013   default:
3014     llvm_unreachable("unknown opcode for branch pseudo-instruction");
3015   }
3016 
3017   bool IsTrgRegZero = (TrgReg == Mips::ZERO);
3018   bool IsSrcRegZero = (SrcReg == Mips::ZERO);
3019   if (IsSrcRegZero && IsTrgRegZero) {
3020     // FIXME: All of these Opcode-specific if's are needed for compatibility
3021     // with GAS' behaviour. However, they may not generate the most efficient
3022     // code in some circumstances.
3023     if (PseudoOpcode == Mips::BLT) {
3024       TOut.emitRX(Mips::BLTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
3025                   IDLoc, STI);
3026       return false;
3027     }
3028     if (PseudoOpcode == Mips::BLE) {
3029       TOut.emitRX(Mips::BLEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
3030                   IDLoc, STI);
3031       Warning(IDLoc, "branch is always taken");
3032       return false;
3033     }
3034     if (PseudoOpcode == Mips::BGE) {
3035       TOut.emitRX(Mips::BGEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
3036                   IDLoc, STI);
3037       Warning(IDLoc, "branch is always taken");
3038       return false;
3039     }
3040     if (PseudoOpcode == Mips::BGT) {
3041       TOut.emitRX(Mips::BGTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
3042                   IDLoc, STI);
3043       return false;
3044     }
3045     if (PseudoOpcode == Mips::BGTU) {
3046       TOut.emitRRX(Mips::BNE, Mips::ZERO, Mips::ZERO,
3047                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3048       return false;
3049     }
3050     if (AcceptsEquality) {
3051       // If both registers are $0 and the pseudo-branch accepts equality, it
3052       // will always be taken, so we emit an unconditional branch.
3053       TOut.emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO,
3054                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3055       Warning(IDLoc, "branch is always taken");
3056       return false;
3057     }
3058     // If both registers are $0 and the pseudo-branch does not accept
3059     // equality, it will never be taken, so we don't have to emit anything.
3060     return false;
3061   }
3062   if (IsSrcRegZero || IsTrgRegZero) {
3063     if ((IsSrcRegZero && PseudoOpcode == Mips::BGTU) ||
3064         (IsTrgRegZero && PseudoOpcode == Mips::BLTU)) {
3065       // If the $rs is $0 and the pseudo-branch is BGTU (0 > x) or
3066       // if the $rt is $0 and the pseudo-branch is BLTU (x < 0),
3067       // the pseudo-branch will never be taken, so we don't emit anything.
3068       // This only applies to unsigned pseudo-branches.
3069       return false;
3070     }
3071     if ((IsSrcRegZero && PseudoOpcode == Mips::BLEU) ||
3072         (IsTrgRegZero && PseudoOpcode == Mips::BGEU)) {
3073       // If the $rs is $0 and the pseudo-branch is BLEU (0 <= x) or
3074       // if the $rt is $0 and the pseudo-branch is BGEU (x >= 0),
3075       // the pseudo-branch will always be taken, so we emit an unconditional
3076       // branch.
3077       // This only applies to unsigned pseudo-branches.
3078       TOut.emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO,
3079                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3080       Warning(IDLoc, "branch is always taken");
3081       return false;
3082     }
3083     if (IsUnsigned) {
3084       // If the $rs is $0 and the pseudo-branch is BLTU (0 < x) or
3085       // if the $rt is $0 and the pseudo-branch is BGTU (x > 0),
3086       // the pseudo-branch will be taken only when the non-zero register is
3087       // different from 0, so we emit a BNEZ.
3088       //
3089       // If the $rs is $0 and the pseudo-branch is BGEU (0 >= x) or
3090       // if the $rt is $0 and the pseudo-branch is BLEU (x <= 0),
3091       // the pseudo-branch will be taken only when the non-zero register is
3092       // equal to 0, so we emit a BEQZ.
3093       //
3094       // Because only BLEU and BGEU branch on equality, we can use the
3095       // AcceptsEquality variable to decide when to emit the BEQZ.
3096       TOut.emitRRX(AcceptsEquality ? Mips::BEQ : Mips::BNE,
3097                    IsSrcRegZero ? TrgReg : SrcReg, Mips::ZERO,
3098                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3099       return false;
3100     }
3101     // If we have a signed pseudo-branch and one of the registers is $0,
3102     // we can use an appropriate compare-to-zero branch. We select which one
3103     // to use in the switch statement above.
3104     TOut.emitRX(IsSrcRegZero ? ZeroSrcOpcode : ZeroTrgOpcode,
3105                 IsSrcRegZero ? TrgReg : SrcReg,
3106                 MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3107     return false;
3108   }
3109 
3110   // If neither the SrcReg nor the TrgReg are $0, we need AT to perform the
3111   // expansions. If it is not available, we return.
3112   unsigned ATRegNum = getATReg(IDLoc);
3113   if (!ATRegNum)
3114     return true;
3115 
3116   if (!EmittedNoMacroWarning)
3117     warnIfNoMacro(IDLoc);
3118 
3119   // SLT fits well with 2 of our 4 pseudo-branches:
3120   //   BLT, where $rs < $rt, translates into "slt $at, $rs, $rt" and
3121   //   BGT, where $rs > $rt, translates into "slt $at, $rt, $rs".
3122   // If the result of the SLT is 1, we branch, and if it's 0, we don't.
3123   // This is accomplished by using a BNEZ with the result of the SLT.
3124   //
3125   // The other 2 pseudo-branches are opposites of the above 2 (BGE with BLT
3126   // and BLE with BGT), so we change the BNEZ into a a BEQZ.
3127   // Because only BGE and BLE branch on equality, we can use the
3128   // AcceptsEquality variable to decide when to emit the BEQZ.
3129   // Note that the order of the SLT arguments doesn't change between
3130   // opposites.
3131   //
3132   // The same applies to the unsigned variants, except that SLTu is used
3133   // instead of SLT.
3134   TOut.emitRRR(IsUnsigned ? Mips::SLTu : Mips::SLT, ATRegNum,
3135                ReverseOrderSLT ? TrgReg : SrcReg,
3136                ReverseOrderSLT ? SrcReg : TrgReg, IDLoc, STI);
3137 
3138   TOut.emitRRX(IsLikely ? (AcceptsEquality ? Mips::BEQL : Mips::BNEL)
3139                         : (AcceptsEquality ? Mips::BEQ : Mips::BNE),
3140                ATRegNum, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
3141                STI);
3142   return false;
3143 }
3144 
3145 bool MipsAsmParser::expandDiv(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3146                               const MCSubtargetInfo *STI, const bool IsMips64,
3147                               const bool Signed) {
3148   MipsTargetStreamer &TOut = getTargetStreamer();
3149 
3150   warnIfNoMacro(IDLoc);
3151 
3152   const MCOperand &RdRegOp = Inst.getOperand(0);
3153   assert(RdRegOp.isReg() && "expected register operand kind");
3154   unsigned RdReg = RdRegOp.getReg();
3155 
3156   const MCOperand &RsRegOp = Inst.getOperand(1);
3157   assert(RsRegOp.isReg() && "expected register operand kind");
3158   unsigned RsReg = RsRegOp.getReg();
3159 
3160   const MCOperand &RtRegOp = Inst.getOperand(2);
3161   assert(RtRegOp.isReg() && "expected register operand kind");
3162   unsigned RtReg = RtRegOp.getReg();
3163   unsigned DivOp;
3164   unsigned ZeroReg;
3165 
3166   if (IsMips64) {
3167     DivOp = Signed ? Mips::DSDIV : Mips::DUDIV;
3168     ZeroReg = Mips::ZERO_64;
3169   } else {
3170     DivOp = Signed ? Mips::SDIV : Mips::UDIV;
3171     ZeroReg = Mips::ZERO;
3172   }
3173 
3174   bool UseTraps = useTraps();
3175 
3176   if (RsReg == Mips::ZERO || RsReg == Mips::ZERO_64) {
3177     if (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64)
3178       Warning(IDLoc, "dividing zero by zero");
3179     if (IsMips64) {
3180       if (Signed && (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64)) {
3181         if (UseTraps) {
3182           TOut.emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, STI);
3183           return false;
3184         }
3185 
3186         TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI);
3187         return false;
3188       }
3189     } else {
3190       TOut.emitRR(DivOp, RsReg, RtReg, IDLoc, STI);
3191       return false;
3192     }
3193   }
3194 
3195   if (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64) {
3196     Warning(IDLoc, "division by zero");
3197     if (Signed) {
3198       if (UseTraps) {
3199         TOut.emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, STI);
3200         return false;
3201       }
3202 
3203       TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI);
3204       return false;
3205     }
3206   }
3207 
3208   // FIXME: The values for these two BranchTarget variables may be different in
3209   // micromips. These magic numbers need to be removed.
3210   unsigned BranchTargetNoTraps;
3211   unsigned BranchTarget;
3212 
3213   if (UseTraps) {
3214     BranchTarget = IsMips64 ? 12 : 8;
3215     TOut.emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, STI);
3216   } else {
3217     BranchTarget = IsMips64 ? 20 : 16;
3218     BranchTargetNoTraps = 8;
3219     // Branch to the li instruction.
3220     TOut.emitRRI(Mips::BNE, RtReg, ZeroReg, BranchTargetNoTraps, IDLoc, STI);
3221   }
3222 
3223   TOut.emitRR(DivOp, RsReg, RtReg, IDLoc, STI);
3224 
3225   if (!UseTraps)
3226     TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI);
3227 
3228   if (!Signed) {
3229     TOut.emitR(Mips::MFLO, RdReg, IDLoc, STI);
3230     return false;
3231   }
3232 
3233   unsigned ATReg = getATReg(IDLoc);
3234   if (!ATReg)
3235     return true;
3236 
3237   TOut.emitRRI(Mips::ADDiu, ATReg, ZeroReg, -1, IDLoc, STI);
3238   if (IsMips64) {
3239     // Branch to the mflo instruction.
3240     TOut.emitRRI(Mips::BNE, RtReg, ATReg, BranchTarget, IDLoc, STI);
3241     TOut.emitRRI(Mips::ADDiu, ATReg, ZeroReg, 1, IDLoc, STI);
3242     TOut.emitRRI(Mips::DSLL32, ATReg, ATReg, 0x1f, IDLoc, STI);
3243   } else {
3244     // Branch to the mflo instruction.
3245     TOut.emitRRI(Mips::BNE, RtReg, ATReg, BranchTarget, IDLoc, STI);
3246     TOut.emitRI(Mips::LUi, ATReg, (uint16_t)0x8000, IDLoc, STI);
3247   }
3248 
3249   if (UseTraps)
3250     TOut.emitRRI(Mips::TEQ, RsReg, ATReg, 0x6, IDLoc, STI);
3251   else {
3252     // Branch to the mflo instruction.
3253     TOut.emitRRI(Mips::BNE, RsReg, ATReg, BranchTargetNoTraps, IDLoc, STI);
3254     TOut.emitRRI(Mips::SLL, ZeroReg, ZeroReg, 0, IDLoc, STI);
3255     TOut.emitII(Mips::BREAK, 0x6, 0, IDLoc, STI);
3256   }
3257   TOut.emitR(Mips::MFLO, RdReg, IDLoc, STI);
3258   return false;
3259 }
3260 
3261 bool MipsAsmParser::expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU,
3262                                 SMLoc IDLoc, MCStreamer &Out,
3263                                 const MCSubtargetInfo *STI) {
3264   MipsTargetStreamer &TOut = getTargetStreamer();
3265 
3266   assert(Inst.getNumOperands() == 3 && "Invalid operand count");
3267   assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg() &&
3268          Inst.getOperand(2).isReg() && "Invalid instruction operand.");
3269 
3270   unsigned FirstReg = Inst.getOperand(0).getReg();
3271   unsigned SecondReg = Inst.getOperand(1).getReg();
3272   unsigned ThirdReg = Inst.getOperand(2).getReg();
3273 
3274   if (hasMips1() && !hasMips2()) {
3275     unsigned ATReg = getATReg(IDLoc);
3276     if (!ATReg)
3277       return true;
3278     TOut.emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, STI);
3279     TOut.emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, STI);
3280     TOut.emitNop(IDLoc, STI);
3281     TOut.emitRRI(Mips::ORi, ATReg, ThirdReg, 0x3, IDLoc, STI);
3282     TOut.emitRRI(Mips::XORi, ATReg, ATReg, 0x2, IDLoc, STI);
3283     TOut.emitRR(Mips::CTC1, Mips::RA, ATReg, IDLoc, STI);
3284     TOut.emitNop(IDLoc, STI);
3285     TOut.emitRR(IsDouble ? (Is64FPU ? Mips::CVT_W_D64 : Mips::CVT_W_D32)
3286                          : Mips::CVT_W_S,
3287                 FirstReg, SecondReg, IDLoc, STI);
3288     TOut.emitRR(Mips::CTC1, Mips::RA, ThirdReg, IDLoc, STI);
3289     TOut.emitNop(IDLoc, STI);
3290     return false;
3291   }
3292 
3293   TOut.emitRR(IsDouble ? (Is64FPU ? Mips::TRUNC_W_D64 : Mips::TRUNC_W_D32)
3294                        : Mips::TRUNC_W_S,
3295               FirstReg, SecondReg, IDLoc, STI);
3296 
3297   return false;
3298 }
3299 
3300 bool MipsAsmParser::expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc,
3301                               MCStreamer &Out, const MCSubtargetInfo *STI) {
3302   MipsTargetStreamer &TOut = getTargetStreamer();
3303 
3304   if (hasMips32r6() || hasMips64r6()) {
3305     Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
3306     return false;
3307   }
3308 
3309   warnIfNoMacro(IDLoc);
3310 
3311   const MCOperand &DstRegOp = Inst.getOperand(0);
3312   assert(DstRegOp.isReg() && "expected register operand kind");
3313 
3314   const MCOperand &SrcRegOp = Inst.getOperand(1);
3315   assert(SrcRegOp.isReg() && "expected register operand kind");
3316 
3317   const MCOperand &OffsetImmOp = Inst.getOperand(2);
3318   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
3319 
3320   unsigned DstReg = DstRegOp.getReg();
3321   unsigned SrcReg = SrcRegOp.getReg();
3322   int64_t OffsetValue = OffsetImmOp.getImm();
3323 
3324   // NOTE: We always need AT for ULHU, as it is always used as the source
3325   // register for one of the LBu's.
3326   unsigned ATReg = getATReg(IDLoc);
3327   if (!ATReg)
3328     return true;
3329 
3330   // When the value of offset+1 does not fit in 16 bits, we have to load the
3331   // offset in AT, (D)ADDu the original source register (if there was one), and
3332   // then use AT as the source register for the 2 generated LBu's.
3333   bool LoadedOffsetInAT = false;
3334   if (!isInt<16>(OffsetValue + 1) || !isInt<16>(OffsetValue)) {
3335     LoadedOffsetInAT = true;
3336 
3337     if (loadImmediate(OffsetValue, ATReg, Mips::NoRegister, !ABI.ArePtrs64bit(),
3338                       true, IDLoc, Out, STI))
3339       return true;
3340 
3341     // NOTE: We do this (D)ADDu here instead of doing it in loadImmediate()
3342     // because it will make our output more similar to GAS'. For example,
3343     // generating an "ori $1, $zero, 32768" followed by an "addu $1, $1, $9",
3344     // instead of just an "ori $1, $9, 32768".
3345     // NOTE: If there is no source register specified in the ULHU, the parser
3346     // will interpret it as $0.
3347     if (SrcReg != Mips::ZERO && SrcReg != Mips::ZERO_64)
3348       TOut.emitAddu(ATReg, ATReg, SrcReg, ABI.ArePtrs64bit(), STI);
3349   }
3350 
3351   unsigned FirstLbuDstReg = LoadedOffsetInAT ? DstReg : ATReg;
3352   unsigned SecondLbuDstReg = LoadedOffsetInAT ? ATReg : DstReg;
3353   unsigned LbuSrcReg = LoadedOffsetInAT ? ATReg : SrcReg;
3354 
3355   int64_t FirstLbuOffset = 0, SecondLbuOffset = 0;
3356   if (isLittle()) {
3357     FirstLbuOffset = LoadedOffsetInAT ? 1 : (OffsetValue + 1);
3358     SecondLbuOffset = LoadedOffsetInAT ? 0 : OffsetValue;
3359   } else {
3360     FirstLbuOffset = LoadedOffsetInAT ? 0 : OffsetValue;
3361     SecondLbuOffset = LoadedOffsetInAT ? 1 : (OffsetValue + 1);
3362   }
3363 
3364   unsigned SllReg = LoadedOffsetInAT ? DstReg : ATReg;
3365 
3366   TOut.emitRRI(Signed ? Mips::LB : Mips::LBu, FirstLbuDstReg, LbuSrcReg,
3367                FirstLbuOffset, IDLoc, STI);
3368 
3369   TOut.emitRRI(Mips::LBu, SecondLbuDstReg, LbuSrcReg, SecondLbuOffset, IDLoc,
3370                STI);
3371 
3372   TOut.emitRRI(Mips::SLL, SllReg, SllReg, 8, IDLoc, STI);
3373 
3374   TOut.emitRRR(Mips::OR, DstReg, DstReg, ATReg, IDLoc, STI);
3375 
3376   return false;
3377 }
3378 
3379 bool MipsAsmParser::expandUlw(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3380                               const MCSubtargetInfo *STI) {
3381   MipsTargetStreamer &TOut = getTargetStreamer();
3382 
3383   if (hasMips32r6() || hasMips64r6()) {
3384     Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
3385     return false;
3386   }
3387 
3388   const MCOperand &DstRegOp = Inst.getOperand(0);
3389   assert(DstRegOp.isReg() && "expected register operand kind");
3390 
3391   const MCOperand &SrcRegOp = Inst.getOperand(1);
3392   assert(SrcRegOp.isReg() && "expected register operand kind");
3393 
3394   const MCOperand &OffsetImmOp = Inst.getOperand(2);
3395   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
3396 
3397   unsigned SrcReg = SrcRegOp.getReg();
3398   int64_t OffsetValue = OffsetImmOp.getImm();
3399   unsigned ATReg = 0;
3400 
3401   // When the value of offset+3 does not fit in 16 bits, we have to load the
3402   // offset in AT, (D)ADDu the original source register (if there was one), and
3403   // then use AT as the source register for the generated LWL and LWR.
3404   bool LoadedOffsetInAT = false;
3405   if (!isInt<16>(OffsetValue + 3) || !isInt<16>(OffsetValue)) {
3406     ATReg = getATReg(IDLoc);
3407     if (!ATReg)
3408       return true;
3409     LoadedOffsetInAT = true;
3410 
3411     warnIfNoMacro(IDLoc);
3412 
3413     if (loadImmediate(OffsetValue, ATReg, Mips::NoRegister, !ABI.ArePtrs64bit(),
3414                       true, IDLoc, Out, STI))
3415       return true;
3416 
3417     // NOTE: We do this (D)ADDu here instead of doing it in loadImmediate()
3418     // because it will make our output more similar to GAS'. For example,
3419     // generating an "ori $1, $zero, 32768" followed by an "addu $1, $1, $9",
3420     // instead of just an "ori $1, $9, 32768".
3421     // NOTE: If there is no source register specified in the ULW, the parser
3422     // will interpret it as $0.
3423     if (SrcReg != Mips::ZERO && SrcReg != Mips::ZERO_64)
3424       TOut.emitAddu(ATReg, ATReg, SrcReg, ABI.ArePtrs64bit(), STI);
3425   }
3426 
3427   unsigned FinalSrcReg = LoadedOffsetInAT ? ATReg : SrcReg;
3428   int64_t LeftLoadOffset = 0, RightLoadOffset  = 0;
3429   if (isLittle()) {
3430     LeftLoadOffset = LoadedOffsetInAT ? 3 : (OffsetValue + 3);
3431     RightLoadOffset  = LoadedOffsetInAT ? 0 : OffsetValue;
3432   } else {
3433     LeftLoadOffset = LoadedOffsetInAT ? 0 : OffsetValue;
3434     RightLoadOffset  = LoadedOffsetInAT ? 3 : (OffsetValue + 3);
3435   }
3436 
3437   TOut.emitRRI(Mips::LWL, DstRegOp.getReg(), FinalSrcReg, LeftLoadOffset, IDLoc,
3438                STI);
3439 
3440   TOut.emitRRI(Mips::LWR, DstRegOp.getReg(), FinalSrcReg, RightLoadOffset,
3441                IDLoc, STI);
3442 
3443   return false;
3444 }
3445 
3446 bool MipsAsmParser::expandAliasImmediate(MCInst &Inst, SMLoc IDLoc,
3447                                          MCStreamer &Out,
3448                                          const MCSubtargetInfo *STI) {
3449   MipsTargetStreamer &TOut = getTargetStreamer();
3450 
3451   assert (Inst.getNumOperands() == 3 && "Invalid operand count");
3452   assert (Inst.getOperand(0).isReg() &&
3453           Inst.getOperand(1).isReg() &&
3454           Inst.getOperand(2).isImm() && "Invalid instruction operand.");
3455 
3456   unsigned ATReg = Mips::NoRegister;
3457   unsigned FinalDstReg = Mips::NoRegister;
3458   unsigned DstReg = Inst.getOperand(0).getReg();
3459   unsigned SrcReg = Inst.getOperand(1).getReg();
3460   int64_t ImmValue = Inst.getOperand(2).getImm();
3461 
3462   bool Is32Bit = isInt<32>(ImmValue) || isUInt<32>(ImmValue);
3463 
3464   unsigned FinalOpcode = Inst.getOpcode();
3465 
3466   if (DstReg == SrcReg) {
3467     ATReg = getATReg(Inst.getLoc());
3468     if (!ATReg)
3469       return true;
3470     FinalDstReg = DstReg;
3471     DstReg = ATReg;
3472   }
3473 
3474   if (!loadImmediate(ImmValue, DstReg, Mips::NoRegister, Is32Bit, false, Inst.getLoc(), Out, STI)) {
3475     switch (FinalOpcode) {
3476     default:
3477       llvm_unreachable("unimplemented expansion");
3478     case (Mips::ADDi):
3479       FinalOpcode = Mips::ADD;
3480       break;
3481     case (Mips::ADDiu):
3482       FinalOpcode = Mips::ADDu;
3483       break;
3484     case (Mips::ANDi):
3485       FinalOpcode = Mips::AND;
3486       break;
3487     case (Mips::NORImm):
3488       FinalOpcode = Mips::NOR;
3489       break;
3490     case (Mips::ORi):
3491       FinalOpcode = Mips::OR;
3492       break;
3493     case (Mips::SLTi):
3494       FinalOpcode = Mips::SLT;
3495       break;
3496     case (Mips::SLTiu):
3497       FinalOpcode = Mips::SLTu;
3498       break;
3499     case (Mips::XORi):
3500       FinalOpcode = Mips::XOR;
3501       break;
3502     }
3503 
3504     if (FinalDstReg == Mips::NoRegister)
3505       TOut.emitRRR(FinalOpcode, DstReg, DstReg, SrcReg, IDLoc, STI);
3506     else
3507       TOut.emitRRR(FinalOpcode, FinalDstReg, FinalDstReg, DstReg, IDLoc, STI);
3508     return false;
3509   }
3510   return true;
3511 }
3512 
3513 bool MipsAsmParser::expandRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3514                                    const MCSubtargetInfo *STI) {
3515   MipsTargetStreamer &TOut = getTargetStreamer();
3516   unsigned ATReg = Mips::NoRegister;
3517   unsigned DReg = Inst.getOperand(0).getReg();
3518   unsigned SReg = Inst.getOperand(1).getReg();
3519   unsigned TReg = Inst.getOperand(2).getReg();
3520   unsigned TmpReg = DReg;
3521 
3522   unsigned FirstShift = Mips::NOP;
3523   unsigned SecondShift = Mips::NOP;
3524 
3525   if (hasMips32r2()) {
3526 
3527     if (DReg == SReg) {
3528       TmpReg = getATReg(Inst.getLoc());
3529       if (!TmpReg)
3530         return true;
3531     }
3532 
3533     if (Inst.getOpcode() == Mips::ROL) {
3534       TOut.emitRRR(Mips::SUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
3535       TOut.emitRRR(Mips::ROTRV, DReg, SReg, TmpReg, Inst.getLoc(), STI);
3536       return false;
3537     }
3538 
3539     if (Inst.getOpcode() == Mips::ROR) {
3540       TOut.emitRRR(Mips::ROTRV, DReg, SReg, TReg, Inst.getLoc(), STI);
3541       return false;
3542     }
3543 
3544     return true;
3545   }
3546 
3547   if (hasMips32()) {
3548 
3549     switch (Inst.getOpcode()) {
3550     default:
3551       llvm_unreachable("unexpected instruction opcode");
3552     case Mips::ROL:
3553       FirstShift = Mips::SRLV;
3554       SecondShift = Mips::SLLV;
3555       break;
3556     case Mips::ROR:
3557       FirstShift = Mips::SLLV;
3558       SecondShift = Mips::SRLV;
3559       break;
3560     }
3561 
3562     ATReg = getATReg(Inst.getLoc());
3563     if (!ATReg)
3564       return true;
3565 
3566     TOut.emitRRR(Mips::SUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
3567     TOut.emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), STI);
3568     TOut.emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), STI);
3569     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
3570 
3571     return false;
3572   }
3573 
3574   return true;
3575 }
3576 
3577 bool MipsAsmParser::expandRotationImm(MCInst &Inst, SMLoc IDLoc,
3578                                       MCStreamer &Out,
3579                                       const MCSubtargetInfo *STI) {
3580   MipsTargetStreamer &TOut = getTargetStreamer();
3581   unsigned ATReg = Mips::NoRegister;
3582   unsigned DReg = Inst.getOperand(0).getReg();
3583   unsigned SReg = Inst.getOperand(1).getReg();
3584   int64_t ImmValue = Inst.getOperand(2).getImm();
3585 
3586   unsigned FirstShift = Mips::NOP;
3587   unsigned SecondShift = Mips::NOP;
3588 
3589   if (hasMips32r2()) {
3590 
3591     if (Inst.getOpcode() == Mips::ROLImm) {
3592       uint64_t MaxShift = 32;
3593       uint64_t ShiftValue = ImmValue;
3594       if (ImmValue != 0)
3595         ShiftValue = MaxShift - ImmValue;
3596       TOut.emitRRI(Mips::ROTR, DReg, SReg, ShiftValue, Inst.getLoc(), STI);
3597       return false;
3598     }
3599 
3600     if (Inst.getOpcode() == Mips::RORImm) {
3601       TOut.emitRRI(Mips::ROTR, DReg, SReg, ImmValue, Inst.getLoc(), STI);
3602       return false;
3603     }
3604 
3605     return true;
3606   }
3607 
3608   if (hasMips32()) {
3609 
3610     if (ImmValue == 0) {
3611       TOut.emitRRI(Mips::SRL, DReg, SReg, 0, Inst.getLoc(), STI);
3612       return false;
3613     }
3614 
3615     switch (Inst.getOpcode()) {
3616     default:
3617       llvm_unreachable("unexpected instruction opcode");
3618     case Mips::ROLImm:
3619       FirstShift = Mips::SLL;
3620       SecondShift = Mips::SRL;
3621       break;
3622     case Mips::RORImm:
3623       FirstShift = Mips::SRL;
3624       SecondShift = Mips::SLL;
3625       break;
3626     }
3627 
3628     ATReg = getATReg(Inst.getLoc());
3629     if (!ATReg)
3630       return true;
3631 
3632     TOut.emitRRI(FirstShift, ATReg, SReg, ImmValue, Inst.getLoc(), STI);
3633     TOut.emitRRI(SecondShift, DReg, SReg, 32 - ImmValue, Inst.getLoc(), STI);
3634     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
3635 
3636     return false;
3637   }
3638 
3639   return true;
3640 }
3641 
3642 bool MipsAsmParser::expandDRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3643                                     const MCSubtargetInfo *STI) {
3644   MipsTargetStreamer &TOut = getTargetStreamer();
3645   unsigned ATReg = Mips::NoRegister;
3646   unsigned DReg = Inst.getOperand(0).getReg();
3647   unsigned SReg = Inst.getOperand(1).getReg();
3648   unsigned TReg = Inst.getOperand(2).getReg();
3649   unsigned TmpReg = DReg;
3650 
3651   unsigned FirstShift = Mips::NOP;
3652   unsigned SecondShift = Mips::NOP;
3653 
3654   if (hasMips64r2()) {
3655 
3656     if (TmpReg == SReg) {
3657       TmpReg = getATReg(Inst.getLoc());
3658       if (!TmpReg)
3659         return true;
3660     }
3661 
3662     if (Inst.getOpcode() == Mips::DROL) {
3663       TOut.emitRRR(Mips::DSUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
3664       TOut.emitRRR(Mips::DROTRV, DReg, SReg, TmpReg, Inst.getLoc(), STI);
3665       return false;
3666     }
3667 
3668     if (Inst.getOpcode() == Mips::DROR) {
3669       TOut.emitRRR(Mips::DROTRV, DReg, SReg, TReg, Inst.getLoc(), STI);
3670       return false;
3671     }
3672 
3673     return true;
3674   }
3675 
3676   if (hasMips64()) {
3677 
3678     switch (Inst.getOpcode()) {
3679     default:
3680       llvm_unreachable("unexpected instruction opcode");
3681     case Mips::DROL:
3682       FirstShift = Mips::DSRLV;
3683       SecondShift = Mips::DSLLV;
3684       break;
3685     case Mips::DROR:
3686       FirstShift = Mips::DSLLV;
3687       SecondShift = Mips::DSRLV;
3688       break;
3689     }
3690 
3691     ATReg = getATReg(Inst.getLoc());
3692     if (!ATReg)
3693       return true;
3694 
3695     TOut.emitRRR(Mips::DSUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
3696     TOut.emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), STI);
3697     TOut.emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), STI);
3698     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
3699 
3700     return false;
3701   }
3702 
3703   return true;
3704 }
3705 
3706 bool MipsAsmParser::expandDRotationImm(MCInst &Inst, SMLoc IDLoc,
3707                                        MCStreamer &Out,
3708                                        const MCSubtargetInfo *STI) {
3709   MipsTargetStreamer &TOut = getTargetStreamer();
3710   unsigned ATReg = Mips::NoRegister;
3711   unsigned DReg = Inst.getOperand(0).getReg();
3712   unsigned SReg = Inst.getOperand(1).getReg();
3713   int64_t ImmValue = Inst.getOperand(2).getImm() % 64;
3714 
3715   unsigned FirstShift = Mips::NOP;
3716   unsigned SecondShift = Mips::NOP;
3717 
3718   MCInst TmpInst;
3719 
3720   if (hasMips64r2()) {
3721 
3722     unsigned FinalOpcode = Mips::NOP;
3723     if (ImmValue == 0)
3724       FinalOpcode = Mips::DROTR;
3725     else if (ImmValue % 32 == 0)
3726       FinalOpcode = Mips::DROTR32;
3727     else if ((ImmValue >= 1) && (ImmValue <= 32)) {
3728       if (Inst.getOpcode() == Mips::DROLImm)
3729         FinalOpcode = Mips::DROTR32;
3730       else
3731         FinalOpcode = Mips::DROTR;
3732     } else if (ImmValue >= 33) {
3733       if (Inst.getOpcode() == Mips::DROLImm)
3734         FinalOpcode = Mips::DROTR;
3735       else
3736         FinalOpcode = Mips::DROTR32;
3737     }
3738 
3739     uint64_t ShiftValue = ImmValue % 32;
3740     if (Inst.getOpcode() == Mips::DROLImm)
3741       ShiftValue = (32 - ImmValue % 32) % 32;
3742 
3743     TOut.emitRRI(FinalOpcode, DReg, SReg, ShiftValue, Inst.getLoc(), STI);
3744 
3745     return false;
3746   }
3747 
3748   if (hasMips64()) {
3749 
3750     if (ImmValue == 0) {
3751       TOut.emitRRI(Mips::DSRL, DReg, SReg, 0, Inst.getLoc(), STI);
3752       return false;
3753     }
3754 
3755     switch (Inst.getOpcode()) {
3756     default:
3757       llvm_unreachable("unexpected instruction opcode");
3758     case Mips::DROLImm:
3759       if ((ImmValue >= 1) && (ImmValue <= 31)) {
3760         FirstShift = Mips::DSLL;
3761         SecondShift = Mips::DSRL32;
3762       }
3763       if (ImmValue == 32) {
3764         FirstShift = Mips::DSLL32;
3765         SecondShift = Mips::DSRL32;
3766       }
3767       if ((ImmValue >= 33) && (ImmValue <= 63)) {
3768         FirstShift = Mips::DSLL32;
3769         SecondShift = Mips::DSRL;
3770       }
3771       break;
3772     case Mips::DRORImm:
3773       if ((ImmValue >= 1) && (ImmValue <= 31)) {
3774         FirstShift = Mips::DSRL;
3775         SecondShift = Mips::DSLL32;
3776       }
3777       if (ImmValue == 32) {
3778         FirstShift = Mips::DSRL32;
3779         SecondShift = Mips::DSLL32;
3780       }
3781       if ((ImmValue >= 33) && (ImmValue <= 63)) {
3782         FirstShift = Mips::DSRL32;
3783         SecondShift = Mips::DSLL;
3784       }
3785       break;
3786     }
3787 
3788     ATReg = getATReg(Inst.getLoc());
3789     if (!ATReg)
3790       return true;
3791 
3792     TOut.emitRRI(FirstShift, ATReg, SReg, ImmValue % 32, Inst.getLoc(), STI);
3793     TOut.emitRRI(SecondShift, DReg, SReg, (32 - ImmValue % 32) % 32,
3794                  Inst.getLoc(), STI);
3795     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
3796 
3797     return false;
3798   }
3799 
3800   return true;
3801 }
3802 
3803 bool MipsAsmParser::expandAbs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3804                               const MCSubtargetInfo *STI) {
3805   MipsTargetStreamer &TOut = getTargetStreamer();
3806   unsigned FirstRegOp = Inst.getOperand(0).getReg();
3807   unsigned SecondRegOp = Inst.getOperand(1).getReg();
3808 
3809   TOut.emitRI(Mips::BGEZ, SecondRegOp, 8, IDLoc, STI);
3810   if (FirstRegOp != SecondRegOp)
3811     TOut.emitRRR(Mips::ADDu, FirstRegOp, SecondRegOp, Mips::ZERO, IDLoc, STI);
3812   else
3813     TOut.emitEmptyDelaySlot(false, IDLoc, STI);
3814   TOut.emitRRR(Mips::SUB, FirstRegOp, Mips::ZERO, SecondRegOp, IDLoc, STI);
3815 
3816   return false;
3817 }
3818 
3819 unsigned
3820 MipsAsmParser::checkEarlyTargetMatchPredicate(MCInst &Inst,
3821                                               const OperandVector &Operands) {
3822   switch (Inst.getOpcode()) {
3823   default:
3824     return Match_Success;
3825   case Mips::DATI:
3826   case Mips::DAHI:
3827     if (static_cast<MipsOperand &>(*Operands[1])
3828             .isValidForTie(static_cast<MipsOperand &>(*Operands[2])))
3829       return Match_Success;
3830     return Match_RequiresSameSrcAndDst;
3831   }
3832 }
3833 unsigned MipsAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
3834   switch (Inst.getOpcode()) {
3835   // As described by the Mips32r2 spec, the registers Rd and Rs for
3836   // jalr.hb must be different.
3837   // It also applies for registers Rt and Rs of microMIPSr6 jalrc.hb instruction
3838   // and registers Rd and Base for microMIPS lwp instruction
3839   case Mips::JALR_HB:
3840   case Mips::JALRC_HB_MMR6:
3841   case Mips::JALRC_MMR6:
3842     if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg())
3843       return Match_RequiresDifferentSrcAndDst;
3844     return Match_Success;
3845   case Mips::LWP_MM:
3846   case Mips::LWP_MMR6:
3847     if (Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg())
3848       return Match_RequiresDifferentSrcAndDst;
3849     return Match_Success;
3850   // As described the MIPSR6 spec, the compact branches that compare registers
3851   // must:
3852   // a) Not use the zero register.
3853   // b) Not use the same register twice.
3854   // c) rs < rt for bnec, beqc.
3855   //    NB: For this case, the encoding will swap the operands as their
3856   //    ordering doesn't matter. GAS performs this transformation  too.
3857   //    Hence, that constraint does not have to be enforced.
3858   //
3859   // The compact branches that branch iff the signed addition of two registers
3860   // would overflow must have rs >= rt. That can be handled like beqc/bnec with
3861   // operand swapping. They do not have restriction of using the zero register.
3862   case Mips::BLEZC:   case Mips::BLEZC_MMR6:
3863   case Mips::BGEZC:   case Mips::BGEZC_MMR6:
3864   case Mips::BGTZC:   case Mips::BGTZC_MMR6:
3865   case Mips::BLTZC:   case Mips::BLTZC_MMR6:
3866   case Mips::BEQZC:   case Mips::BEQZC_MMR6:
3867   case Mips::BNEZC:   case Mips::BNEZC_MMR6:
3868   case Mips::BLEZC64:
3869   case Mips::BGEZC64:
3870   case Mips::BGTZC64:
3871   case Mips::BLTZC64:
3872   case Mips::BEQZC64:
3873   case Mips::BNEZC64:
3874     if (Inst.getOperand(0).getReg() == Mips::ZERO ||
3875         Inst.getOperand(0).getReg() == Mips::ZERO_64)
3876       return Match_RequiresNoZeroRegister;
3877     return Match_Success;
3878   case Mips::BGEC:    case Mips::BGEC_MMR6:
3879   case Mips::BLTC:    case Mips::BLTC_MMR6:
3880   case Mips::BGEUC:   case Mips::BGEUC_MMR6:
3881   case Mips::BLTUC:   case Mips::BLTUC_MMR6:
3882   case Mips::BEQC:    case Mips::BEQC_MMR6:
3883   case Mips::BNEC:    case Mips::BNEC_MMR6:
3884   case Mips::BGEC64:
3885   case Mips::BLTC64:
3886   case Mips::BGEUC64:
3887   case Mips::BLTUC64:
3888   case Mips::BEQC64:
3889   case Mips::BNEC64:
3890     if (Inst.getOperand(0).getReg() == Mips::ZERO ||
3891         Inst.getOperand(0).getReg() == Mips::ZERO_64)
3892       return Match_RequiresNoZeroRegister;
3893     if (Inst.getOperand(1).getReg() == Mips::ZERO ||
3894         Inst.getOperand(1).getReg() == Mips::ZERO_64)
3895       return Match_RequiresNoZeroRegister;
3896     if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg())
3897       return Match_RequiresDifferentOperands;
3898     return Match_Success;
3899   default:
3900     return Match_Success;
3901   }
3902 }
3903 
3904 static SMLoc RefineErrorLoc(const SMLoc Loc, const OperandVector &Operands,
3905                             uint64_t ErrorInfo) {
3906   if (ErrorInfo != ~0ULL && ErrorInfo < Operands.size()) {
3907     SMLoc ErrorLoc = Operands[ErrorInfo]->getStartLoc();
3908     if (ErrorLoc == SMLoc())
3909       return Loc;
3910     return ErrorLoc;
3911   }
3912   return Loc;
3913 }
3914 
3915 bool MipsAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
3916                                             OperandVector &Operands,
3917                                             MCStreamer &Out,
3918                                             uint64_t &ErrorInfo,
3919                                             bool MatchingInlineAsm) {
3920 
3921   MCInst Inst;
3922   unsigned MatchResult =
3923       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
3924 
3925   switch (MatchResult) {
3926   case Match_Success: {
3927     if (processInstruction(Inst, IDLoc, Out, STI))
3928       return true;
3929     return false;
3930   }
3931   case Match_MissingFeature:
3932     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
3933     return true;
3934   case Match_InvalidOperand: {
3935     SMLoc ErrorLoc = IDLoc;
3936     if (ErrorInfo != ~0ULL) {
3937       if (ErrorInfo >= Operands.size())
3938         return Error(IDLoc, "too few operands for instruction");
3939 
3940       ErrorLoc = Operands[ErrorInfo]->getStartLoc();
3941       if (ErrorLoc == SMLoc())
3942         ErrorLoc = IDLoc;
3943     }
3944 
3945     return Error(ErrorLoc, "invalid operand for instruction");
3946   }
3947   case Match_MnemonicFail:
3948     return Error(IDLoc, "invalid instruction");
3949   case Match_RequiresDifferentSrcAndDst:
3950     return Error(IDLoc, "source and destination must be different");
3951   case Match_RequiresDifferentOperands:
3952     return Error(IDLoc, "registers must be different");
3953   case Match_RequiresNoZeroRegister:
3954     return Error(IDLoc, "invalid operand ($zero) for instruction");
3955   case Match_RequiresSameSrcAndDst:
3956     return Error(IDLoc, "source and destination must match");
3957   case Match_Immz:
3958     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected '0'");
3959   case Match_UImm1_0:
3960     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3961                  "expected 1-bit unsigned immediate");
3962   case Match_UImm2_0:
3963     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3964                  "expected 2-bit unsigned immediate");
3965   case Match_UImm2_1:
3966     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3967                  "expected immediate in range 1 .. 4");
3968   case Match_UImm3_0:
3969     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3970                  "expected 3-bit unsigned immediate");
3971   case Match_UImm4_0:
3972     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3973                  "expected 4-bit unsigned immediate");
3974   case Match_SImm4_0:
3975     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3976                  "expected 4-bit signed immediate");
3977   case Match_UImm5_0:
3978     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3979                  "expected 5-bit unsigned immediate");
3980   case Match_SImm5_0:
3981     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3982                  "expected 5-bit signed immediate");
3983   case Match_UImm5_1:
3984     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3985                  "expected immediate in range 1 .. 32");
3986   case Match_UImm5_32:
3987     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3988                  "expected immediate in range 32 .. 63");
3989   case Match_UImm5_33:
3990     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3991                  "expected immediate in range 33 .. 64");
3992   case Match_UImm5_0_Report_UImm6:
3993     // This is used on UImm5 operands that have a corresponding UImm5_32
3994     // operand to avoid confusing the user.
3995     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3996                  "expected 6-bit unsigned immediate");
3997   case Match_UImm5_Lsl2:
3998     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3999                  "expected both 7-bit unsigned immediate and multiple of 4");
4000   case Match_UImmRange2_64:
4001     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4002                  "expected immediate in range 2 .. 64");
4003   case Match_UImm6_0:
4004     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4005                  "expected 6-bit unsigned immediate");
4006   case Match_UImm6_Lsl2:
4007     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4008                  "expected both 8-bit unsigned immediate and multiple of 4");
4009   case Match_SImm6_0:
4010     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4011                  "expected 6-bit signed immediate");
4012   case Match_UImm7_0:
4013     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4014                  "expected 7-bit unsigned immediate");
4015   case Match_UImm7_N1:
4016     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4017                  "expected immediate in range -1 .. 126");
4018   case Match_SImm7_Lsl2:
4019     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4020                  "expected both 9-bit signed immediate and multiple of 4");
4021   case Match_UImm8_0:
4022     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4023                  "expected 8-bit unsigned immediate");
4024   case Match_UImm10_0:
4025     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4026                  "expected 10-bit unsigned immediate");
4027   case Match_SImm10_0:
4028     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4029                  "expected 10-bit signed immediate");
4030   case Match_SImm11_0:
4031     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4032                  "expected 11-bit signed immediate");
4033   case Match_UImm16:
4034   case Match_UImm16_Relaxed:
4035     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4036                  "expected 16-bit unsigned immediate");
4037   case Match_SImm16:
4038   case Match_SImm16_Relaxed:
4039     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4040                  "expected 16-bit signed immediate");
4041   case Match_SImm19_Lsl2:
4042     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4043                  "expected both 19-bit signed immediate and multiple of 4");
4044   case Match_UImm20_0:
4045     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4046                  "expected 20-bit unsigned immediate");
4047   case Match_UImm26_0:
4048     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4049                  "expected 26-bit unsigned immediate");
4050   case Match_SImm32:
4051   case Match_SImm32_Relaxed:
4052     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4053                  "expected 32-bit signed immediate");
4054   case Match_MemSImm9:
4055     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4056                  "expected memory with 9-bit signed offset");
4057   case Match_MemSImm10:
4058     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4059                  "expected memory with 10-bit signed offset");
4060   case Match_MemSImm10Lsl1:
4061     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4062                  "expected memory with 11-bit signed offset and multiple of 2");
4063   case Match_MemSImm10Lsl2:
4064     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4065                  "expected memory with 12-bit signed offset and multiple of 4");
4066   case Match_MemSImm10Lsl3:
4067     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4068                  "expected memory with 13-bit signed offset and multiple of 8");
4069   case Match_MemSImm11:
4070     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4071                  "expected memory with 11-bit signed offset");
4072   case Match_MemSImm12:
4073     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4074                  "expected memory with 12-bit signed offset");
4075   case Match_MemSImm16:
4076     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
4077                  "expected memory with 16-bit signed offset");
4078   }
4079 
4080   llvm_unreachable("Implement any new match types added!");
4081 }
4082 
4083 void MipsAsmParser::warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc) {
4084   if (RegIndex != 0 && AssemblerOptions.back()->getATRegIndex() == RegIndex)
4085     Warning(Loc, "used $at (currently $" + Twine(RegIndex) +
4086                      ") without \".set noat\"");
4087 }
4088 
4089 void MipsAsmParser::warnIfNoMacro(SMLoc Loc) {
4090   if (!AssemblerOptions.back()->isMacro())
4091     Warning(Loc, "macro instruction expanded into multiple instructions");
4092 }
4093 
4094 void
4095 MipsAsmParser::printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
4096                                      SMRange Range, bool ShowColors) {
4097   getSourceManager().PrintMessage(Range.Start, SourceMgr::DK_Warning, Msg,
4098                                   Range, SMFixIt(Range, FixMsg),
4099                                   ShowColors);
4100 }
4101 
4102 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
4103   int CC;
4104 
4105   CC = StringSwitch<unsigned>(Name)
4106            .Case("zero", 0)
4107            .Case("at", 1)
4108            .Case("a0", 4)
4109            .Case("a1", 5)
4110            .Case("a2", 6)
4111            .Case("a3", 7)
4112            .Case("v0", 2)
4113            .Case("v1", 3)
4114            .Case("s0", 16)
4115            .Case("s1", 17)
4116            .Case("s2", 18)
4117            .Case("s3", 19)
4118            .Case("s4", 20)
4119            .Case("s5", 21)
4120            .Case("s6", 22)
4121            .Case("s7", 23)
4122            .Case("k0", 26)
4123            .Case("k1", 27)
4124            .Case("gp", 28)
4125            .Case("sp", 29)
4126            .Case("fp", 30)
4127            .Case("s8", 30)
4128            .Case("ra", 31)
4129            .Case("t0", 8)
4130            .Case("t1", 9)
4131            .Case("t2", 10)
4132            .Case("t3", 11)
4133            .Case("t4", 12)
4134            .Case("t5", 13)
4135            .Case("t6", 14)
4136            .Case("t7", 15)
4137            .Case("t8", 24)
4138            .Case("t9", 25)
4139            .Default(-1);
4140 
4141   if (!(isABI_N32() || isABI_N64()))
4142     return CC;
4143 
4144   if (12 <= CC && CC <= 15) {
4145     // Name is one of t4-t7
4146     AsmToken RegTok = getLexer().peekTok();
4147     SMRange RegRange = RegTok.getLocRange();
4148 
4149     StringRef FixedName = StringSwitch<StringRef>(Name)
4150                               .Case("t4", "t0")
4151                               .Case("t5", "t1")
4152                               .Case("t6", "t2")
4153                               .Case("t7", "t3")
4154                               .Default("");
4155     assert(FixedName != "" &&  "Register name is not one of t4-t7.");
4156 
4157     printWarningWithFixIt("register names $t4-$t7 are only available in O32.",
4158                           "Did you mean $" + FixedName + "?", RegRange);
4159   }
4160 
4161   // Although SGI documentation just cuts out t0-t3 for n32/n64,
4162   // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
4163   // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
4164   if (8 <= CC && CC <= 11)
4165     CC += 4;
4166 
4167   if (CC == -1)
4168     CC = StringSwitch<unsigned>(Name)
4169              .Case("a4", 8)
4170              .Case("a5", 9)
4171              .Case("a6", 10)
4172              .Case("a7", 11)
4173              .Case("kt0", 26)
4174              .Case("kt1", 27)
4175              .Default(-1);
4176 
4177   return CC;
4178 }
4179 
4180 int MipsAsmParser::matchHWRegsRegisterName(StringRef Name) {
4181   int CC;
4182 
4183   CC = StringSwitch<unsigned>(Name)
4184             .Case("hwr_cpunum", 0)
4185             .Case("hwr_synci_step", 1)
4186             .Case("hwr_cc", 2)
4187             .Case("hwr_ccres", 3)
4188             .Case("hwr_ulr", 29)
4189             .Default(-1);
4190 
4191   return CC;
4192 }
4193 
4194 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
4195 
4196   if (Name[0] == 'f') {
4197     StringRef NumString = Name.substr(1);
4198     unsigned IntVal;
4199     if (NumString.getAsInteger(10, IntVal))
4200       return -1;     // This is not an integer.
4201     if (IntVal > 31) // Maximum index for fpu register.
4202       return -1;
4203     return IntVal;
4204   }
4205   return -1;
4206 }
4207 
4208 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
4209 
4210   if (Name.startswith("fcc")) {
4211     StringRef NumString = Name.substr(3);
4212     unsigned IntVal;
4213     if (NumString.getAsInteger(10, IntVal))
4214       return -1;    // This is not an integer.
4215     if (IntVal > 7) // There are only 8 fcc registers.
4216       return -1;
4217     return IntVal;
4218   }
4219   return -1;
4220 }
4221 
4222 int MipsAsmParser::matchACRegisterName(StringRef Name) {
4223 
4224   if (Name.startswith("ac")) {
4225     StringRef NumString = Name.substr(2);
4226     unsigned IntVal;
4227     if (NumString.getAsInteger(10, IntVal))
4228       return -1;    // This is not an integer.
4229     if (IntVal > 3) // There are only 3 acc registers.
4230       return -1;
4231     return IntVal;
4232   }
4233   return -1;
4234 }
4235 
4236 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
4237   unsigned IntVal;
4238 
4239   if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
4240     return -1;
4241 
4242   if (IntVal > 31)
4243     return -1;
4244 
4245   return IntVal;
4246 }
4247 
4248 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
4249   int CC;
4250 
4251   CC = StringSwitch<unsigned>(Name)
4252            .Case("msair", 0)
4253            .Case("msacsr", 1)
4254            .Case("msaaccess", 2)
4255            .Case("msasave", 3)
4256            .Case("msamodify", 4)
4257            .Case("msarequest", 5)
4258            .Case("msamap", 6)
4259            .Case("msaunmap", 7)
4260            .Default(-1);
4261 
4262   return CC;
4263 }
4264 
4265 unsigned MipsAsmParser::getATReg(SMLoc Loc) {
4266   unsigned ATIndex = AssemblerOptions.back()->getATRegIndex();
4267   if (ATIndex == 0) {
4268     reportParseError(Loc,
4269                      "pseudo-instruction requires $at, which is not available");
4270     return 0;
4271   }
4272   unsigned AT = getReg(
4273       (isGP64bit()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, ATIndex);
4274   return AT;
4275 }
4276 
4277 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
4278   return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
4279 }
4280 
4281 bool MipsAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
4282   MCAsmParser &Parser = getParser();
4283   DEBUG(dbgs() << "parseOperand\n");
4284 
4285   // Check if the current operand has a custom associated parser, if so, try to
4286   // custom parse the operand, or fallback to the general approach.
4287   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
4288   if (ResTy == MatchOperand_Success)
4289     return false;
4290   // If there wasn't a custom match, try the generic matcher below. Otherwise,
4291   // there was a match, but an error occurred, in which case, just return that
4292   // the operand parsing failed.
4293   if (ResTy == MatchOperand_ParseFail)
4294     return true;
4295 
4296   DEBUG(dbgs() << ".. Generic Parser\n");
4297 
4298   switch (getLexer().getKind()) {
4299   case AsmToken::Dollar: {
4300     // Parse the register.
4301     SMLoc S = Parser.getTok().getLoc();
4302 
4303     // Almost all registers have been parsed by custom parsers. There is only
4304     // one exception to this. $zero (and it's alias $0) will reach this point
4305     // for div, divu, and similar instructions because it is not an operand
4306     // to the instruction definition but an explicit register. Special case
4307     // this situation for now.
4308     if (parseAnyRegister(Operands) != MatchOperand_NoMatch)
4309       return false;
4310 
4311     // Maybe it is a symbol reference.
4312     StringRef Identifier;
4313     if (Parser.parseIdentifier(Identifier))
4314       return true;
4315 
4316     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4317     MCSymbol *Sym = getContext().getOrCreateSymbol("$" + Identifier);
4318     // Otherwise create a symbol reference.
4319     const MCExpr *Res =
4320         MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
4321 
4322     Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this));
4323     return false;
4324   }
4325   default: {
4326     DEBUG(dbgs() << ".. generic integer expression\n");
4327 
4328     const MCExpr *Expr;
4329     SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
4330     if (getParser().parseExpression(Expr))
4331       return true;
4332 
4333     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4334 
4335     Operands.push_back(MipsOperand::CreateImm(Expr, S, E, *this));
4336     return false;
4337   }
4338   } // switch(getLexer().getKind())
4339   return true;
4340 }
4341 
4342 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
4343 
4344   switch (Expr->getKind()) {
4345   case MCExpr::Constant:
4346     return true;
4347   case MCExpr::SymbolRef:
4348     return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
4349   case MCExpr::Binary:
4350     if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
4351       if (!isEvaluated(BE->getLHS()))
4352         return false;
4353       return isEvaluated(BE->getRHS());
4354     }
4355   case MCExpr::Unary:
4356     return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
4357   case MCExpr::Target:
4358     return true;
4359   }
4360   return false;
4361 }
4362 
4363 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
4364                                   SMLoc &EndLoc) {
4365   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
4366   OperandMatchResultTy ResTy = parseAnyRegister(Operands);
4367   if (ResTy == MatchOperand_Success) {
4368     assert(Operands.size() == 1);
4369     MipsOperand &Operand = static_cast<MipsOperand &>(*Operands.front());
4370     StartLoc = Operand.getStartLoc();
4371     EndLoc = Operand.getEndLoc();
4372 
4373     // AFAIK, we only support numeric registers and named GPR's in CFI
4374     // directives.
4375     // Don't worry about eating tokens before failing. Using an unrecognised
4376     // register is a parse error.
4377     if (Operand.isGPRAsmReg()) {
4378       // Resolve to GPR32 or GPR64 appropriately.
4379       RegNo = isGP64bit() ? Operand.getGPR64Reg() : Operand.getGPR32Reg();
4380     }
4381 
4382     return (RegNo == (unsigned)-1);
4383   }
4384 
4385   assert(Operands.size() == 0);
4386   return (RegNo == (unsigned)-1);
4387 }
4388 
4389 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
4390   SMLoc S;
4391 
4392   if (isParenExpr)
4393     return getParser().parseParenExprOfDepth(0, Res, S);
4394   return getParser().parseExpression(Res);
4395 }
4396 
4397 MipsAsmParser::OperandMatchResultTy
4398 MipsAsmParser::parseMemOperand(OperandVector &Operands) {
4399   MCAsmParser &Parser = getParser();
4400   DEBUG(dbgs() << "parseMemOperand\n");
4401   const MCExpr *IdVal = nullptr;
4402   SMLoc S;
4403   bool isParenExpr = false;
4404   MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch;
4405   // First operand is the offset.
4406   S = Parser.getTok().getLoc();
4407 
4408   if (getLexer().getKind() == AsmToken::LParen) {
4409     Parser.Lex();
4410     isParenExpr = true;
4411   }
4412 
4413   if (getLexer().getKind() != AsmToken::Dollar) {
4414     if (parseMemOffset(IdVal, isParenExpr))
4415       return MatchOperand_ParseFail;
4416 
4417     const AsmToken &Tok = Parser.getTok(); // Get the next token.
4418     if (Tok.isNot(AsmToken::LParen)) {
4419       MipsOperand &Mnemonic = static_cast<MipsOperand &>(*Operands[0]);
4420       if (Mnemonic.getToken() == "la" || Mnemonic.getToken() == "dla") {
4421         SMLoc E =
4422             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4423         Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
4424         return MatchOperand_Success;
4425       }
4426       if (Tok.is(AsmToken::EndOfStatement)) {
4427         SMLoc E =
4428             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4429 
4430         // Zero register assumed, add a memory operand with ZERO as its base.
4431         // "Base" will be managed by k_Memory.
4432         auto Base = MipsOperand::createGPRReg(
4433             0, "0", getContext().getRegisterInfo(), S, E, *this);
4434         Operands.push_back(
4435             MipsOperand::CreateMem(std::move(Base), IdVal, S, E, *this));
4436         return MatchOperand_Success;
4437       }
4438       Error(Parser.getTok().getLoc(), "'(' expected");
4439       return MatchOperand_ParseFail;
4440     }
4441 
4442     Parser.Lex(); // Eat the '(' token.
4443   }
4444 
4445   Res = parseAnyRegister(Operands);
4446   if (Res != MatchOperand_Success)
4447     return Res;
4448 
4449   if (Parser.getTok().isNot(AsmToken::RParen)) {
4450     Error(Parser.getTok().getLoc(), "')' expected");
4451     return MatchOperand_ParseFail;
4452   }
4453 
4454   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4455 
4456   Parser.Lex(); // Eat the ')' token.
4457 
4458   if (!IdVal)
4459     IdVal = MCConstantExpr::create(0, getContext());
4460 
4461   // Replace the register operand with the memory operand.
4462   std::unique_ptr<MipsOperand> op(
4463       static_cast<MipsOperand *>(Operands.back().release()));
4464   // Remove the register from the operands.
4465   // "op" will be managed by k_Memory.
4466   Operands.pop_back();
4467   // Add the memory operand.
4468   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
4469     int64_t Imm;
4470     if (IdVal->evaluateAsAbsolute(Imm))
4471       IdVal = MCConstantExpr::create(Imm, getContext());
4472     else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
4473       IdVal = MCBinaryExpr::create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
4474                                    getContext());
4475   }
4476 
4477   Operands.push_back(MipsOperand::CreateMem(std::move(op), IdVal, S, E, *this));
4478   return MatchOperand_Success;
4479 }
4480 
4481 bool MipsAsmParser::searchSymbolAlias(OperandVector &Operands) {
4482   MCAsmParser &Parser = getParser();
4483   MCSymbol *Sym = getContext().lookupSymbol(Parser.getTok().getIdentifier());
4484   if (Sym) {
4485     SMLoc S = Parser.getTok().getLoc();
4486     const MCExpr *Expr;
4487     if (Sym->isVariable())
4488       Expr = Sym->getVariableValue();
4489     else
4490       return false;
4491     if (Expr->getKind() == MCExpr::SymbolRef) {
4492       const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
4493       StringRef DefSymbol = Ref->getSymbol().getName();
4494       if (DefSymbol.startswith("$")) {
4495         OperandMatchResultTy ResTy =
4496             matchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S);
4497         if (ResTy == MatchOperand_Success) {
4498           Parser.Lex();
4499           return true;
4500         } else if (ResTy == MatchOperand_ParseFail)
4501           llvm_unreachable("Should never ParseFail");
4502         return false;
4503       }
4504     }
4505   }
4506   return false;
4507 }
4508 
4509 MipsAsmParser::OperandMatchResultTy
4510 MipsAsmParser::matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
4511                                                  StringRef Identifier,
4512                                                  SMLoc S) {
4513   int Index = matchCPURegisterName(Identifier);
4514   if (Index != -1) {
4515     Operands.push_back(MipsOperand::createGPRReg(
4516         Index, Identifier, getContext().getRegisterInfo(), S,
4517         getLexer().getLoc(), *this));
4518     return MatchOperand_Success;
4519   }
4520 
4521   Index = matchHWRegsRegisterName(Identifier);
4522   if (Index != -1) {
4523     Operands.push_back(MipsOperand::createHWRegsReg(
4524         Index, Identifier, getContext().getRegisterInfo(), S,
4525         getLexer().getLoc(), *this));
4526     return MatchOperand_Success;
4527   }
4528 
4529   Index = matchFPURegisterName(Identifier);
4530   if (Index != -1) {
4531     Operands.push_back(MipsOperand::createFGRReg(
4532         Index, Identifier, getContext().getRegisterInfo(), S,
4533         getLexer().getLoc(), *this));
4534     return MatchOperand_Success;
4535   }
4536 
4537   Index = matchFCCRegisterName(Identifier);
4538   if (Index != -1) {
4539     Operands.push_back(MipsOperand::createFCCReg(
4540         Index, Identifier, getContext().getRegisterInfo(), S,
4541         getLexer().getLoc(), *this));
4542     return MatchOperand_Success;
4543   }
4544 
4545   Index = matchACRegisterName(Identifier);
4546   if (Index != -1) {
4547     Operands.push_back(MipsOperand::createACCReg(
4548         Index, Identifier, getContext().getRegisterInfo(), S,
4549         getLexer().getLoc(), *this));
4550     return MatchOperand_Success;
4551   }
4552 
4553   Index = matchMSA128RegisterName(Identifier);
4554   if (Index != -1) {
4555     Operands.push_back(MipsOperand::createMSA128Reg(
4556         Index, Identifier, getContext().getRegisterInfo(), S,
4557         getLexer().getLoc(), *this));
4558     return MatchOperand_Success;
4559   }
4560 
4561   Index = matchMSA128CtrlRegisterName(Identifier);
4562   if (Index != -1) {
4563     Operands.push_back(MipsOperand::createMSACtrlReg(
4564         Index, Identifier, getContext().getRegisterInfo(), S,
4565         getLexer().getLoc(), *this));
4566     return MatchOperand_Success;
4567   }
4568 
4569   return MatchOperand_NoMatch;
4570 }
4571 
4572 MipsAsmParser::OperandMatchResultTy
4573 MipsAsmParser::matchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S) {
4574   MCAsmParser &Parser = getParser();
4575   auto Token = Parser.getLexer().peekTok(false);
4576 
4577   if (Token.is(AsmToken::Identifier)) {
4578     DEBUG(dbgs() << ".. identifier\n");
4579     StringRef Identifier = Token.getIdentifier();
4580     OperandMatchResultTy ResTy =
4581         matchAnyRegisterNameWithoutDollar(Operands, Identifier, S);
4582     return ResTy;
4583   } else if (Token.is(AsmToken::Integer)) {
4584     DEBUG(dbgs() << ".. integer\n");
4585     Operands.push_back(MipsOperand::createNumericReg(
4586         Token.getIntVal(), Token.getString(), getContext().getRegisterInfo(), S,
4587         Token.getLoc(), *this));
4588     return MatchOperand_Success;
4589   }
4590 
4591   DEBUG(dbgs() << Parser.getTok().getKind() << "\n");
4592 
4593   return MatchOperand_NoMatch;
4594 }
4595 
4596 MipsAsmParser::OperandMatchResultTy
4597 MipsAsmParser::parseAnyRegister(OperandVector &Operands) {
4598   MCAsmParser &Parser = getParser();
4599   DEBUG(dbgs() << "parseAnyRegister\n");
4600 
4601   auto Token = Parser.getTok();
4602 
4603   SMLoc S = Token.getLoc();
4604 
4605   if (Token.isNot(AsmToken::Dollar)) {
4606     DEBUG(dbgs() << ".. !$ -> try sym aliasing\n");
4607     if (Token.is(AsmToken::Identifier)) {
4608       if (searchSymbolAlias(Operands))
4609         return MatchOperand_Success;
4610     }
4611     DEBUG(dbgs() << ".. !symalias -> NoMatch\n");
4612     return MatchOperand_NoMatch;
4613   }
4614   DEBUG(dbgs() << ".. $\n");
4615 
4616   OperandMatchResultTy ResTy = matchAnyRegisterWithoutDollar(Operands, S);
4617   if (ResTy == MatchOperand_Success) {
4618     Parser.Lex(); // $
4619     Parser.Lex(); // identifier
4620   }
4621   return ResTy;
4622 }
4623 
4624 MipsAsmParser::OperandMatchResultTy
4625 MipsAsmParser::parseJumpTarget(OperandVector &Operands) {
4626   MCAsmParser &Parser = getParser();
4627   DEBUG(dbgs() << "parseJumpTarget\n");
4628 
4629   SMLoc S = getLexer().getLoc();
4630 
4631   // Registers are a valid target and have priority over symbols.
4632   OperandMatchResultTy ResTy = parseAnyRegister(Operands);
4633   if (ResTy != MatchOperand_NoMatch)
4634     return ResTy;
4635 
4636   // Integers and expressions are acceptable
4637   const MCExpr *Expr = nullptr;
4638   if (Parser.parseExpression(Expr)) {
4639     // We have no way of knowing if a symbol was consumed so we must ParseFail
4640     return MatchOperand_ParseFail;
4641   }
4642   Operands.push_back(
4643       MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this));
4644   return MatchOperand_Success;
4645 }
4646 
4647 MipsAsmParser::OperandMatchResultTy
4648 MipsAsmParser::parseInvNum(OperandVector &Operands) {
4649   MCAsmParser &Parser = getParser();
4650   const MCExpr *IdVal;
4651   // If the first token is '$' we may have register operand.
4652   if (Parser.getTok().is(AsmToken::Dollar))
4653     return MatchOperand_NoMatch;
4654   SMLoc S = Parser.getTok().getLoc();
4655   if (getParser().parseExpression(IdVal))
4656     return MatchOperand_ParseFail;
4657   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
4658   assert(MCE && "Unexpected MCExpr type.");
4659   int64_t Val = MCE->getValue();
4660   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4661   Operands.push_back(MipsOperand::CreateImm(
4662       MCConstantExpr::create(0 - Val, getContext()), S, E, *this));
4663   return MatchOperand_Success;
4664 }
4665 
4666 MipsAsmParser::OperandMatchResultTy
4667 MipsAsmParser::parseRegisterList(OperandVector &Operands) {
4668   MCAsmParser &Parser = getParser();
4669   SmallVector<unsigned, 10> Regs;
4670   unsigned RegNo;
4671   unsigned PrevReg = Mips::NoRegister;
4672   bool RegRange = false;
4673   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands;
4674 
4675   if (Parser.getTok().isNot(AsmToken::Dollar))
4676     return MatchOperand_ParseFail;
4677 
4678   SMLoc S = Parser.getTok().getLoc();
4679   while (parseAnyRegister(TmpOperands) == MatchOperand_Success) {
4680     SMLoc E = getLexer().getLoc();
4681     MipsOperand &Reg = static_cast<MipsOperand &>(*TmpOperands.back());
4682     RegNo = isGP64bit() ? Reg.getGPR64Reg() : Reg.getGPR32Reg();
4683     if (RegRange) {
4684       // Remove last register operand because registers from register range
4685       // should be inserted first.
4686       if ((isGP64bit() && RegNo == Mips::RA_64) ||
4687           (!isGP64bit() && RegNo == Mips::RA)) {
4688         Regs.push_back(RegNo);
4689       } else {
4690         unsigned TmpReg = PrevReg + 1;
4691         while (TmpReg <= RegNo) {
4692           if ((((TmpReg < Mips::S0) || (TmpReg > Mips::S7)) && !isGP64bit()) ||
4693               (((TmpReg < Mips::S0_64) || (TmpReg > Mips::S7_64)) &&
4694                isGP64bit())) {
4695             Error(E, "invalid register operand");
4696             return MatchOperand_ParseFail;
4697           }
4698 
4699           PrevReg = TmpReg;
4700           Regs.push_back(TmpReg++);
4701         }
4702       }
4703 
4704       RegRange = false;
4705     } else {
4706       if ((PrevReg == Mips::NoRegister) &&
4707           ((isGP64bit() && (RegNo != Mips::S0_64) && (RegNo != Mips::RA_64)) ||
4708           (!isGP64bit() && (RegNo != Mips::S0) && (RegNo != Mips::RA)))) {
4709         Error(E, "$16 or $31 expected");
4710         return MatchOperand_ParseFail;
4711       } else if (!(((RegNo == Mips::FP || RegNo == Mips::RA ||
4712                     (RegNo >= Mips::S0 && RegNo <= Mips::S7)) &&
4713                     !isGP64bit()) ||
4714                    ((RegNo == Mips::FP_64 || RegNo == Mips::RA_64 ||
4715                     (RegNo >= Mips::S0_64 && RegNo <= Mips::S7_64)) &&
4716                     isGP64bit()))) {
4717         Error(E, "invalid register operand");
4718         return MatchOperand_ParseFail;
4719       } else if ((PrevReg != Mips::NoRegister) && (RegNo != PrevReg + 1) &&
4720                  ((RegNo != Mips::FP && RegNo != Mips::RA && !isGP64bit()) ||
4721                   (RegNo != Mips::FP_64 && RegNo != Mips::RA_64 &&
4722                    isGP64bit()))) {
4723         Error(E, "consecutive register numbers expected");
4724         return MatchOperand_ParseFail;
4725       }
4726 
4727       Regs.push_back(RegNo);
4728     }
4729 
4730     if (Parser.getTok().is(AsmToken::Minus))
4731       RegRange = true;
4732 
4733     if (!Parser.getTok().isNot(AsmToken::Minus) &&
4734         !Parser.getTok().isNot(AsmToken::Comma)) {
4735       Error(E, "',' or '-' expected");
4736       return MatchOperand_ParseFail;
4737     }
4738 
4739     Lex(); // Consume comma or minus
4740     if (Parser.getTok().isNot(AsmToken::Dollar))
4741       break;
4742 
4743     PrevReg = RegNo;
4744   }
4745 
4746   SMLoc E = Parser.getTok().getLoc();
4747   Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this));
4748   parseMemOperand(Operands);
4749   return MatchOperand_Success;
4750 }
4751 
4752 MipsAsmParser::OperandMatchResultTy
4753 MipsAsmParser::parseRegisterPair(OperandVector &Operands) {
4754   MCAsmParser &Parser = getParser();
4755 
4756   SMLoc S = Parser.getTok().getLoc();
4757   if (parseAnyRegister(Operands) != MatchOperand_Success)
4758     return MatchOperand_ParseFail;
4759 
4760   SMLoc E = Parser.getTok().getLoc();
4761   MipsOperand Op = static_cast<MipsOperand &>(*Operands.back());
4762 
4763   Operands.pop_back();
4764   Operands.push_back(MipsOperand::CreateRegPair(Op, S, E, *this));
4765   return MatchOperand_Success;
4766 }
4767 
4768 MipsAsmParser::OperandMatchResultTy
4769 MipsAsmParser::parseMovePRegPair(OperandVector &Operands) {
4770   MCAsmParser &Parser = getParser();
4771   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands;
4772   SmallVector<unsigned, 10> Regs;
4773 
4774   if (Parser.getTok().isNot(AsmToken::Dollar))
4775     return MatchOperand_ParseFail;
4776 
4777   SMLoc S = Parser.getTok().getLoc();
4778 
4779   if (parseAnyRegister(TmpOperands) != MatchOperand_Success)
4780     return MatchOperand_ParseFail;
4781 
4782   MipsOperand *Reg = &static_cast<MipsOperand &>(*TmpOperands.back());
4783   unsigned RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg();
4784   Regs.push_back(RegNo);
4785 
4786   SMLoc E = Parser.getTok().getLoc();
4787   if (Parser.getTok().isNot(AsmToken::Comma)) {
4788     Error(E, "',' expected");
4789     return MatchOperand_ParseFail;
4790   }
4791 
4792   // Remove comma.
4793   Parser.Lex();
4794 
4795   if (parseAnyRegister(TmpOperands) != MatchOperand_Success)
4796     return MatchOperand_ParseFail;
4797 
4798   Reg = &static_cast<MipsOperand &>(*TmpOperands.back());
4799   RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg();
4800   Regs.push_back(RegNo);
4801 
4802   Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this));
4803 
4804   return MatchOperand_Success;
4805 }
4806 
4807 /// Sometimes (i.e. load/stores) the operand may be followed immediately by
4808 /// either this.
4809 /// ::= '(', register, ')'
4810 /// handle it before we iterate so we don't get tripped up by the lack of
4811 /// a comma.
4812 bool MipsAsmParser::parseParenSuffix(StringRef Name, OperandVector &Operands) {
4813   MCAsmParser &Parser = getParser();
4814   if (getLexer().is(AsmToken::LParen)) {
4815     Operands.push_back(
4816         MipsOperand::CreateToken("(", getLexer().getLoc(), *this));
4817     Parser.Lex();
4818     if (parseOperand(Operands, Name)) {
4819       SMLoc Loc = getLexer().getLoc();
4820       Parser.eatToEndOfStatement();
4821       return Error(Loc, "unexpected token in argument list");
4822     }
4823     if (Parser.getTok().isNot(AsmToken::RParen)) {
4824       SMLoc Loc = getLexer().getLoc();
4825       Parser.eatToEndOfStatement();
4826       return Error(Loc, "unexpected token, expected ')'");
4827     }
4828     Operands.push_back(
4829         MipsOperand::CreateToken(")", getLexer().getLoc(), *this));
4830     Parser.Lex();
4831   }
4832   return false;
4833 }
4834 
4835 /// Sometimes (i.e. in MSA) the operand may be followed immediately by
4836 /// either one of these.
4837 /// ::= '[', register, ']'
4838 /// ::= '[', integer, ']'
4839 /// handle it before we iterate so we don't get tripped up by the lack of
4840 /// a comma.
4841 bool MipsAsmParser::parseBracketSuffix(StringRef Name,
4842                                        OperandVector &Operands) {
4843   MCAsmParser &Parser = getParser();
4844   if (getLexer().is(AsmToken::LBrac)) {
4845     Operands.push_back(
4846         MipsOperand::CreateToken("[", getLexer().getLoc(), *this));
4847     Parser.Lex();
4848     if (parseOperand(Operands, Name)) {
4849       SMLoc Loc = getLexer().getLoc();
4850       Parser.eatToEndOfStatement();
4851       return Error(Loc, "unexpected token in argument list");
4852     }
4853     if (Parser.getTok().isNot(AsmToken::RBrac)) {
4854       SMLoc Loc = getLexer().getLoc();
4855       Parser.eatToEndOfStatement();
4856       return Error(Loc, "unexpected token, expected ']'");
4857     }
4858     Operands.push_back(
4859         MipsOperand::CreateToken("]", getLexer().getLoc(), *this));
4860     Parser.Lex();
4861   }
4862   return false;
4863 }
4864 
4865 bool MipsAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
4866                                      SMLoc NameLoc, OperandVector &Operands) {
4867   MCAsmParser &Parser = getParser();
4868   DEBUG(dbgs() << "ParseInstruction\n");
4869 
4870   // We have reached first instruction, module directive are now forbidden.
4871   getTargetStreamer().forbidModuleDirective();
4872 
4873   // Check if we have valid mnemonic
4874   if (!mnemonicIsValid(Name, 0)) {
4875     Parser.eatToEndOfStatement();
4876     return Error(NameLoc, "unknown instruction");
4877   }
4878   // First operand in MCInst is instruction mnemonic.
4879   Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this));
4880 
4881   // Read the remaining operands.
4882   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4883     // Read the first operand.
4884     if (parseOperand(Operands, Name)) {
4885       SMLoc Loc = getLexer().getLoc();
4886       Parser.eatToEndOfStatement();
4887       return Error(Loc, "unexpected token in argument list");
4888     }
4889     if (getLexer().is(AsmToken::LBrac) && parseBracketSuffix(Name, Operands))
4890       return true;
4891     // AFAIK, parenthesis suffixes are never on the first operand
4892 
4893     while (getLexer().is(AsmToken::Comma)) {
4894       Parser.Lex(); // Eat the comma.
4895       // Parse and remember the operand.
4896       if (parseOperand(Operands, Name)) {
4897         SMLoc Loc = getLexer().getLoc();
4898         Parser.eatToEndOfStatement();
4899         return Error(Loc, "unexpected token in argument list");
4900       }
4901       // Parse bracket and parenthesis suffixes before we iterate
4902       if (getLexer().is(AsmToken::LBrac)) {
4903         if (parseBracketSuffix(Name, Operands))
4904           return true;
4905       } else if (getLexer().is(AsmToken::LParen) &&
4906                  parseParenSuffix(Name, Operands))
4907         return true;
4908     }
4909   }
4910   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4911     SMLoc Loc = getLexer().getLoc();
4912     Parser.eatToEndOfStatement();
4913     return Error(Loc, "unexpected token in argument list");
4914   }
4915   Parser.Lex(); // Consume the EndOfStatement.
4916   return false;
4917 }
4918 
4919 // FIXME: Given that these have the same name, these should both be
4920 // consistent on affecting the Parser.
4921 bool MipsAsmParser::reportParseError(Twine ErrorMsg) {
4922   MCAsmParser &Parser = getParser();
4923   SMLoc Loc = getLexer().getLoc();
4924   Parser.eatToEndOfStatement();
4925   return Error(Loc, ErrorMsg);
4926 }
4927 
4928 bool MipsAsmParser::reportParseError(SMLoc Loc, Twine ErrorMsg) {
4929   return Error(Loc, ErrorMsg);
4930 }
4931 
4932 bool MipsAsmParser::parseSetNoAtDirective() {
4933   MCAsmParser &Parser = getParser();
4934   // Line should look like: ".set noat".
4935 
4936   // Set the $at register to $0.
4937   AssemblerOptions.back()->setATRegIndex(0);
4938 
4939   Parser.Lex(); // Eat "noat".
4940 
4941   // If this is not the end of the statement, report an error.
4942   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4943     reportParseError("unexpected token, expected end of statement");
4944     return false;
4945   }
4946 
4947   getTargetStreamer().emitDirectiveSetNoAt();
4948   Parser.Lex(); // Consume the EndOfStatement.
4949   return false;
4950 }
4951 
4952 bool MipsAsmParser::parseSetAtDirective() {
4953   // Line can be: ".set at", which sets $at to $1
4954   //          or  ".set at=$reg", which sets $at to $reg.
4955   MCAsmParser &Parser = getParser();
4956   Parser.Lex(); // Eat "at".
4957 
4958   if (getLexer().is(AsmToken::EndOfStatement)) {
4959     // No register was specified, so we set $at to $1.
4960     AssemblerOptions.back()->setATRegIndex(1);
4961 
4962     getTargetStreamer().emitDirectiveSetAt();
4963     Parser.Lex(); // Consume the EndOfStatement.
4964     return false;
4965   }
4966 
4967   if (getLexer().isNot(AsmToken::Equal)) {
4968     reportParseError("unexpected token, expected equals sign");
4969     return false;
4970   }
4971   Parser.Lex(); // Eat "=".
4972 
4973   if (getLexer().isNot(AsmToken::Dollar)) {
4974     if (getLexer().is(AsmToken::EndOfStatement)) {
4975       reportParseError("no register specified");
4976       return false;
4977     } else {
4978       reportParseError("unexpected token, expected dollar sign '$'");
4979       return false;
4980     }
4981   }
4982   Parser.Lex(); // Eat "$".
4983 
4984   // Find out what "reg" is.
4985   unsigned AtRegNo;
4986   const AsmToken &Reg = Parser.getTok();
4987   if (Reg.is(AsmToken::Identifier)) {
4988     AtRegNo = matchCPURegisterName(Reg.getIdentifier());
4989   } else if (Reg.is(AsmToken::Integer)) {
4990     AtRegNo = Reg.getIntVal();
4991   } else {
4992     reportParseError("unexpected token, expected identifier or integer");
4993     return false;
4994   }
4995 
4996   // Check if $reg is a valid register. If it is, set $at to $reg.
4997   if (!AssemblerOptions.back()->setATRegIndex(AtRegNo)) {
4998     reportParseError("invalid register");
4999     return false;
5000   }
5001   Parser.Lex(); // Eat "reg".
5002 
5003   // If this is not the end of the statement, report an error.
5004   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5005     reportParseError("unexpected token, expected end of statement");
5006     return false;
5007   }
5008 
5009   getTargetStreamer().emitDirectiveSetAtWithArg(AtRegNo);
5010 
5011   Parser.Lex(); // Consume the EndOfStatement.
5012   return false;
5013 }
5014 
5015 bool MipsAsmParser::parseSetReorderDirective() {
5016   MCAsmParser &Parser = getParser();
5017   Parser.Lex();
5018   // If this is not the end of the statement, report an error.
5019   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5020     reportParseError("unexpected token, expected end of statement");
5021     return false;
5022   }
5023   AssemblerOptions.back()->setReorder();
5024   getTargetStreamer().emitDirectiveSetReorder();
5025   Parser.Lex(); // Consume the EndOfStatement.
5026   return false;
5027 }
5028 
5029 bool MipsAsmParser::parseSetNoReorderDirective() {
5030   MCAsmParser &Parser = getParser();
5031   Parser.Lex();
5032   // If this is not the end of the statement, report an error.
5033   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5034     reportParseError("unexpected token, expected end of statement");
5035     return false;
5036   }
5037   AssemblerOptions.back()->setNoReorder();
5038   getTargetStreamer().emitDirectiveSetNoReorder();
5039   Parser.Lex(); // Consume the EndOfStatement.
5040   return false;
5041 }
5042 
5043 bool MipsAsmParser::parseSetMacroDirective() {
5044   MCAsmParser &Parser = getParser();
5045   Parser.Lex();
5046   // If this is not the end of the statement, report an error.
5047   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5048     reportParseError("unexpected token, expected end of statement");
5049     return false;
5050   }
5051   AssemblerOptions.back()->setMacro();
5052   getTargetStreamer().emitDirectiveSetMacro();
5053   Parser.Lex(); // Consume the EndOfStatement.
5054   return false;
5055 }
5056 
5057 bool MipsAsmParser::parseSetNoMacroDirective() {
5058   MCAsmParser &Parser = getParser();
5059   Parser.Lex();
5060   // If this is not the end of the statement, report an error.
5061   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5062     reportParseError("unexpected token, expected end of statement");
5063     return false;
5064   }
5065   if (AssemblerOptions.back()->isReorder()) {
5066     reportParseError("`noreorder' must be set before `nomacro'");
5067     return false;
5068   }
5069   AssemblerOptions.back()->setNoMacro();
5070   getTargetStreamer().emitDirectiveSetNoMacro();
5071   Parser.Lex(); // Consume the EndOfStatement.
5072   return false;
5073 }
5074 
5075 bool MipsAsmParser::parseSetMsaDirective() {
5076   MCAsmParser &Parser = getParser();
5077   Parser.Lex();
5078 
5079   // If this is not the end of the statement, report an error.
5080   if (getLexer().isNot(AsmToken::EndOfStatement))
5081     return reportParseError("unexpected token, expected end of statement");
5082 
5083   setFeatureBits(Mips::FeatureMSA, "msa");
5084   getTargetStreamer().emitDirectiveSetMsa();
5085   return false;
5086 }
5087 
5088 bool MipsAsmParser::parseSetNoMsaDirective() {
5089   MCAsmParser &Parser = getParser();
5090   Parser.Lex();
5091 
5092   // If this is not the end of the statement, report an error.
5093   if (getLexer().isNot(AsmToken::EndOfStatement))
5094     return reportParseError("unexpected token, expected end of statement");
5095 
5096   clearFeatureBits(Mips::FeatureMSA, "msa");
5097   getTargetStreamer().emitDirectiveSetNoMsa();
5098   return false;
5099 }
5100 
5101 bool MipsAsmParser::parseSetNoDspDirective() {
5102   MCAsmParser &Parser = getParser();
5103   Parser.Lex(); // Eat "nodsp".
5104 
5105   // If this is not the end of the statement, report an error.
5106   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5107     reportParseError("unexpected token, expected end of statement");
5108     return false;
5109   }
5110 
5111   clearFeatureBits(Mips::FeatureDSP, "dsp");
5112   getTargetStreamer().emitDirectiveSetNoDsp();
5113   return false;
5114 }
5115 
5116 bool MipsAsmParser::parseSetMips16Directive() {
5117   MCAsmParser &Parser = getParser();
5118   Parser.Lex(); // Eat "mips16".
5119 
5120   // If this is not the end of the statement, report an error.
5121   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5122     reportParseError("unexpected token, expected end of statement");
5123     return false;
5124   }
5125 
5126   setFeatureBits(Mips::FeatureMips16, "mips16");
5127   getTargetStreamer().emitDirectiveSetMips16();
5128   Parser.Lex(); // Consume the EndOfStatement.
5129   return false;
5130 }
5131 
5132 bool MipsAsmParser::parseSetNoMips16Directive() {
5133   MCAsmParser &Parser = getParser();
5134   Parser.Lex(); // Eat "nomips16".
5135 
5136   // If this is not the end of the statement, report an error.
5137   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5138     reportParseError("unexpected token, expected end of statement");
5139     return false;
5140   }
5141 
5142   clearFeatureBits(Mips::FeatureMips16, "mips16");
5143   getTargetStreamer().emitDirectiveSetNoMips16();
5144   Parser.Lex(); // Consume the EndOfStatement.
5145   return false;
5146 }
5147 
5148 bool MipsAsmParser::parseSetFpDirective() {
5149   MCAsmParser &Parser = getParser();
5150   MipsABIFlagsSection::FpABIKind FpAbiVal;
5151   // Line can be: .set fp=32
5152   //              .set fp=xx
5153   //              .set fp=64
5154   Parser.Lex(); // Eat fp token
5155   AsmToken Tok = Parser.getTok();
5156   if (Tok.isNot(AsmToken::Equal)) {
5157     reportParseError("unexpected token, expected equals sign '='");
5158     return false;
5159   }
5160   Parser.Lex(); // Eat '=' token.
5161   Tok = Parser.getTok();
5162 
5163   if (!parseFpABIValue(FpAbiVal, ".set"))
5164     return false;
5165 
5166   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5167     reportParseError("unexpected token, expected end of statement");
5168     return false;
5169   }
5170   getTargetStreamer().emitDirectiveSetFp(FpAbiVal);
5171   Parser.Lex(); // Consume the EndOfStatement.
5172   return false;
5173 }
5174 
5175 bool MipsAsmParser::parseSetOddSPRegDirective() {
5176   MCAsmParser &Parser = getParser();
5177 
5178   Parser.Lex(); // Eat "oddspreg".
5179   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5180     reportParseError("unexpected token, expected end of statement");
5181     return false;
5182   }
5183 
5184   clearFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5185   getTargetStreamer().emitDirectiveSetOddSPReg();
5186   return false;
5187 }
5188 
5189 bool MipsAsmParser::parseSetNoOddSPRegDirective() {
5190   MCAsmParser &Parser = getParser();
5191 
5192   Parser.Lex(); // Eat "nooddspreg".
5193   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5194     reportParseError("unexpected token, expected end of statement");
5195     return false;
5196   }
5197 
5198   setFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5199   getTargetStreamer().emitDirectiveSetNoOddSPReg();
5200   return false;
5201 }
5202 
5203 bool MipsAsmParser::parseSetPopDirective() {
5204   MCAsmParser &Parser = getParser();
5205   SMLoc Loc = getLexer().getLoc();
5206 
5207   Parser.Lex();
5208   if (getLexer().isNot(AsmToken::EndOfStatement))
5209     return reportParseError("unexpected token, expected end of statement");
5210 
5211   // Always keep an element on the options "stack" to prevent the user
5212   // from changing the initial options. This is how we remember them.
5213   if (AssemblerOptions.size() == 2)
5214     return reportParseError(Loc, ".set pop with no .set push");
5215 
5216   MCSubtargetInfo &STI = copySTI();
5217   AssemblerOptions.pop_back();
5218   setAvailableFeatures(
5219       ComputeAvailableFeatures(AssemblerOptions.back()->getFeatures()));
5220   STI.setFeatureBits(AssemblerOptions.back()->getFeatures());
5221 
5222   getTargetStreamer().emitDirectiveSetPop();
5223   return false;
5224 }
5225 
5226 bool MipsAsmParser::parseSetPushDirective() {
5227   MCAsmParser &Parser = getParser();
5228   Parser.Lex();
5229   if (getLexer().isNot(AsmToken::EndOfStatement))
5230     return reportParseError("unexpected token, expected end of statement");
5231 
5232   // Create a copy of the current assembler options environment and push it.
5233   AssemblerOptions.push_back(
5234               make_unique<MipsAssemblerOptions>(AssemblerOptions.back().get()));
5235 
5236   getTargetStreamer().emitDirectiveSetPush();
5237   return false;
5238 }
5239 
5240 bool MipsAsmParser::parseSetSoftFloatDirective() {
5241   MCAsmParser &Parser = getParser();
5242   Parser.Lex();
5243   if (getLexer().isNot(AsmToken::EndOfStatement))
5244     return reportParseError("unexpected token, expected end of statement");
5245 
5246   setFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5247   getTargetStreamer().emitDirectiveSetSoftFloat();
5248   return false;
5249 }
5250 
5251 bool MipsAsmParser::parseSetHardFloatDirective() {
5252   MCAsmParser &Parser = getParser();
5253   Parser.Lex();
5254   if (getLexer().isNot(AsmToken::EndOfStatement))
5255     return reportParseError("unexpected token, expected end of statement");
5256 
5257   clearFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5258   getTargetStreamer().emitDirectiveSetHardFloat();
5259   return false;
5260 }
5261 
5262 bool MipsAsmParser::parseSetAssignment() {
5263   StringRef Name;
5264   const MCExpr *Value;
5265   MCAsmParser &Parser = getParser();
5266 
5267   if (Parser.parseIdentifier(Name))
5268     reportParseError("expected identifier after .set");
5269 
5270   if (getLexer().isNot(AsmToken::Comma))
5271     return reportParseError("unexpected token, expected comma");
5272   Lex(); // Eat comma
5273 
5274   if (Parser.parseExpression(Value))
5275     return reportParseError("expected valid expression after comma");
5276 
5277   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5278   Sym->setVariableValue(Value);
5279 
5280   return false;
5281 }
5282 
5283 bool MipsAsmParser::parseSetMips0Directive() {
5284   MCAsmParser &Parser = getParser();
5285   Parser.Lex();
5286   if (getLexer().isNot(AsmToken::EndOfStatement))
5287     return reportParseError("unexpected token, expected end of statement");
5288 
5289   // Reset assembler options to their initial values.
5290   MCSubtargetInfo &STI = copySTI();
5291   setAvailableFeatures(
5292       ComputeAvailableFeatures(AssemblerOptions.front()->getFeatures()));
5293   STI.setFeatureBits(AssemblerOptions.front()->getFeatures());
5294   AssemblerOptions.back()->setFeatures(AssemblerOptions.front()->getFeatures());
5295 
5296   getTargetStreamer().emitDirectiveSetMips0();
5297   return false;
5298 }
5299 
5300 bool MipsAsmParser::parseSetArchDirective() {
5301   MCAsmParser &Parser = getParser();
5302   Parser.Lex();
5303   if (getLexer().isNot(AsmToken::Equal))
5304     return reportParseError("unexpected token, expected equals sign");
5305 
5306   Parser.Lex();
5307   StringRef Arch;
5308   if (Parser.parseIdentifier(Arch))
5309     return reportParseError("expected arch identifier");
5310 
5311   StringRef ArchFeatureName =
5312       StringSwitch<StringRef>(Arch)
5313           .Case("mips1", "mips1")
5314           .Case("mips2", "mips2")
5315           .Case("mips3", "mips3")
5316           .Case("mips4", "mips4")
5317           .Case("mips5", "mips5")
5318           .Case("mips32", "mips32")
5319           .Case("mips32r2", "mips32r2")
5320           .Case("mips32r3", "mips32r3")
5321           .Case("mips32r5", "mips32r5")
5322           .Case("mips32r6", "mips32r6")
5323           .Case("mips64", "mips64")
5324           .Case("mips64r2", "mips64r2")
5325           .Case("mips64r3", "mips64r3")
5326           .Case("mips64r5", "mips64r5")
5327           .Case("mips64r6", "mips64r6")
5328           .Case("octeon", "cnmips")
5329           .Case("r4000", "mips3") // This is an implementation of Mips3.
5330           .Default("");
5331 
5332   if (ArchFeatureName.empty())
5333     return reportParseError("unsupported architecture");
5334 
5335   selectArch(ArchFeatureName);
5336   getTargetStreamer().emitDirectiveSetArch(Arch);
5337   return false;
5338 }
5339 
5340 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
5341   MCAsmParser &Parser = getParser();
5342   Parser.Lex();
5343   if (getLexer().isNot(AsmToken::EndOfStatement))
5344     return reportParseError("unexpected token, expected end of statement");
5345 
5346   switch (Feature) {
5347   default:
5348     llvm_unreachable("Unimplemented feature");
5349   case Mips::FeatureDSP:
5350     setFeatureBits(Mips::FeatureDSP, "dsp");
5351     getTargetStreamer().emitDirectiveSetDsp();
5352     break;
5353   case Mips::FeatureMicroMips:
5354     setFeatureBits(Mips::FeatureMicroMips, "micromips");
5355     getTargetStreamer().emitDirectiveSetMicroMips();
5356     break;
5357   case Mips::FeatureMips1:
5358     selectArch("mips1");
5359     getTargetStreamer().emitDirectiveSetMips1();
5360     break;
5361   case Mips::FeatureMips2:
5362     selectArch("mips2");
5363     getTargetStreamer().emitDirectiveSetMips2();
5364     break;
5365   case Mips::FeatureMips3:
5366     selectArch("mips3");
5367     getTargetStreamer().emitDirectiveSetMips3();
5368     break;
5369   case Mips::FeatureMips4:
5370     selectArch("mips4");
5371     getTargetStreamer().emitDirectiveSetMips4();
5372     break;
5373   case Mips::FeatureMips5:
5374     selectArch("mips5");
5375     getTargetStreamer().emitDirectiveSetMips5();
5376     break;
5377   case Mips::FeatureMips32:
5378     selectArch("mips32");
5379     getTargetStreamer().emitDirectiveSetMips32();
5380     break;
5381   case Mips::FeatureMips32r2:
5382     selectArch("mips32r2");
5383     getTargetStreamer().emitDirectiveSetMips32R2();
5384     break;
5385   case Mips::FeatureMips32r3:
5386     selectArch("mips32r3");
5387     getTargetStreamer().emitDirectiveSetMips32R3();
5388     break;
5389   case Mips::FeatureMips32r5:
5390     selectArch("mips32r5");
5391     getTargetStreamer().emitDirectiveSetMips32R5();
5392     break;
5393   case Mips::FeatureMips32r6:
5394     selectArch("mips32r6");
5395     getTargetStreamer().emitDirectiveSetMips32R6();
5396     break;
5397   case Mips::FeatureMips64:
5398     selectArch("mips64");
5399     getTargetStreamer().emitDirectiveSetMips64();
5400     break;
5401   case Mips::FeatureMips64r2:
5402     selectArch("mips64r2");
5403     getTargetStreamer().emitDirectiveSetMips64R2();
5404     break;
5405   case Mips::FeatureMips64r3:
5406     selectArch("mips64r3");
5407     getTargetStreamer().emitDirectiveSetMips64R3();
5408     break;
5409   case Mips::FeatureMips64r5:
5410     selectArch("mips64r5");
5411     getTargetStreamer().emitDirectiveSetMips64R5();
5412     break;
5413   case Mips::FeatureMips64r6:
5414     selectArch("mips64r6");
5415     getTargetStreamer().emitDirectiveSetMips64R6();
5416     break;
5417   }
5418   return false;
5419 }
5420 
5421 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
5422   MCAsmParser &Parser = getParser();
5423   if (getLexer().isNot(AsmToken::Comma)) {
5424     SMLoc Loc = getLexer().getLoc();
5425     Parser.eatToEndOfStatement();
5426     return Error(Loc, ErrorStr);
5427   }
5428 
5429   Parser.Lex(); // Eat the comma.
5430   return true;
5431 }
5432 
5433 // Used to determine if .cpload, .cprestore, and .cpsetup have any effect.
5434 // In this class, it is only used for .cprestore.
5435 // FIXME: Only keep track of IsPicEnabled in one place, instead of in both
5436 // MipsTargetELFStreamer and MipsAsmParser.
5437 bool MipsAsmParser::isPicAndNotNxxAbi() {
5438   return inPicMode() && !(isABI_N32() || isABI_N64());
5439 }
5440 
5441 bool MipsAsmParser::parseDirectiveCpLoad(SMLoc Loc) {
5442   if (AssemblerOptions.back()->isReorder())
5443     Warning(Loc, ".cpload should be inside a noreorder section");
5444 
5445   if (inMips16Mode()) {
5446     reportParseError(".cpload is not supported in Mips16 mode");
5447     return false;
5448   }
5449 
5450   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Reg;
5451   OperandMatchResultTy ResTy = parseAnyRegister(Reg);
5452   if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
5453     reportParseError("expected register containing function address");
5454     return false;
5455   }
5456 
5457   MipsOperand &RegOpnd = static_cast<MipsOperand &>(*Reg[0]);
5458   if (!RegOpnd.isGPRAsmReg()) {
5459     reportParseError(RegOpnd.getStartLoc(), "invalid register");
5460     return false;
5461   }
5462 
5463   // If this is not the end of the statement, report an error.
5464   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5465     reportParseError("unexpected token, expected end of statement");
5466     return false;
5467   }
5468 
5469   getTargetStreamer().emitDirectiveCpLoad(RegOpnd.getGPR32Reg());
5470   return false;
5471 }
5472 
5473 bool MipsAsmParser::parseDirectiveCpRestore(SMLoc Loc) {
5474   MCAsmParser &Parser = getParser();
5475 
5476   // Note that .cprestore is ignored if used with the N32 and N64 ABIs or if it
5477   // is used in non-PIC mode.
5478 
5479   if (inMips16Mode()) {
5480     reportParseError(".cprestore is not supported in Mips16 mode");
5481     return false;
5482   }
5483 
5484   // Get the stack offset value.
5485   const MCExpr *StackOffset;
5486   int64_t StackOffsetVal;
5487   if (Parser.parseExpression(StackOffset)) {
5488     reportParseError("expected stack offset value");
5489     return false;
5490   }
5491 
5492   if (!StackOffset->evaluateAsAbsolute(StackOffsetVal)) {
5493     reportParseError("stack offset is not an absolute expression");
5494     return false;
5495   }
5496 
5497   if (StackOffsetVal < 0) {
5498     Warning(Loc, ".cprestore with negative stack offset has no effect");
5499     IsCpRestoreSet = false;
5500   } else {
5501     IsCpRestoreSet = true;
5502     CpRestoreOffset = StackOffsetVal;
5503   }
5504 
5505   // If this is not the end of the statement, report an error.
5506   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5507     reportParseError("unexpected token, expected end of statement");
5508     return false;
5509   }
5510 
5511   if (!getTargetStreamer().emitDirectiveCpRestore(
5512           CpRestoreOffset, [&]() { return getATReg(Loc); }, Loc, STI))
5513     return true;
5514   Parser.Lex(); // Consume the EndOfStatement.
5515   return false;
5516 }
5517 
5518 bool MipsAsmParser::parseDirectiveCPSetup() {
5519   MCAsmParser &Parser = getParser();
5520   unsigned FuncReg;
5521   unsigned Save;
5522   bool SaveIsReg = true;
5523 
5524   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
5525   OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
5526   if (ResTy == MatchOperand_NoMatch) {
5527     reportParseError("expected register containing function address");
5528     return false;
5529   }
5530 
5531   MipsOperand &FuncRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
5532   if (!FuncRegOpnd.isGPRAsmReg()) {
5533     reportParseError(FuncRegOpnd.getStartLoc(), "invalid register");
5534     Parser.eatToEndOfStatement();
5535     return false;
5536   }
5537 
5538   FuncReg = FuncRegOpnd.getGPR32Reg();
5539   TmpReg.clear();
5540 
5541   if (!eatComma("unexpected token, expected comma"))
5542     return true;
5543 
5544   ResTy = parseAnyRegister(TmpReg);
5545   if (ResTy == MatchOperand_NoMatch) {
5546     const MCExpr *OffsetExpr;
5547     int64_t OffsetVal;
5548     SMLoc ExprLoc = getLexer().getLoc();
5549 
5550     if (Parser.parseExpression(OffsetExpr) ||
5551         !OffsetExpr->evaluateAsAbsolute(OffsetVal)) {
5552       reportParseError(ExprLoc, "expected save register or stack offset");
5553       Parser.eatToEndOfStatement();
5554       return false;
5555     }
5556 
5557     Save = OffsetVal;
5558     SaveIsReg = false;
5559   } else {
5560     MipsOperand &SaveOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
5561     if (!SaveOpnd.isGPRAsmReg()) {
5562       reportParseError(SaveOpnd.getStartLoc(), "invalid register");
5563       Parser.eatToEndOfStatement();
5564       return false;
5565     }
5566     Save = SaveOpnd.getGPR32Reg();
5567   }
5568 
5569   if (!eatComma("unexpected token, expected comma"))
5570     return true;
5571 
5572   const MCExpr *Expr;
5573   if (Parser.parseExpression(Expr)) {
5574     reportParseError("expected expression");
5575     return false;
5576   }
5577 
5578   if (Expr->getKind() != MCExpr::SymbolRef) {
5579     reportParseError("expected symbol");
5580     return false;
5581   }
5582   const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
5583 
5584   CpSaveLocation = Save;
5585   CpSaveLocationIsRegister = SaveIsReg;
5586 
5587   getTargetStreamer().emitDirectiveCpsetup(FuncReg, Save, Ref->getSymbol(),
5588                                            SaveIsReg);
5589   return false;
5590 }
5591 
5592 bool MipsAsmParser::parseDirectiveCPReturn() {
5593   getTargetStreamer().emitDirectiveCpreturn(CpSaveLocation,
5594                                             CpSaveLocationIsRegister);
5595   return false;
5596 }
5597 
5598 bool MipsAsmParser::parseDirectiveNaN() {
5599   MCAsmParser &Parser = getParser();
5600   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5601     const AsmToken &Tok = Parser.getTok();
5602 
5603     if (Tok.getString() == "2008") {
5604       Parser.Lex();
5605       getTargetStreamer().emitDirectiveNaN2008();
5606       return false;
5607     } else if (Tok.getString() == "legacy") {
5608       Parser.Lex();
5609       getTargetStreamer().emitDirectiveNaNLegacy();
5610       return false;
5611     }
5612   }
5613   // If we don't recognize the option passed to the .nan
5614   // directive (e.g. no option or unknown option), emit an error.
5615   reportParseError("invalid option in .nan directive");
5616   return false;
5617 }
5618 
5619 bool MipsAsmParser::parseDirectiveSet() {
5620   MCAsmParser &Parser = getParser();
5621   // Get the next token.
5622   const AsmToken &Tok = Parser.getTok();
5623 
5624   if (Tok.getString() == "noat") {
5625     return parseSetNoAtDirective();
5626   } else if (Tok.getString() == "at") {
5627     return parseSetAtDirective();
5628   } else if (Tok.getString() == "arch") {
5629     return parseSetArchDirective();
5630   } else if (Tok.getString() == "fp") {
5631     return parseSetFpDirective();
5632   } else if (Tok.getString() == "oddspreg") {
5633     return parseSetOddSPRegDirective();
5634   } else if (Tok.getString() == "nooddspreg") {
5635     return parseSetNoOddSPRegDirective();
5636   } else if (Tok.getString() == "pop") {
5637     return parseSetPopDirective();
5638   } else if (Tok.getString() == "push") {
5639     return parseSetPushDirective();
5640   } else if (Tok.getString() == "reorder") {
5641     return parseSetReorderDirective();
5642   } else if (Tok.getString() == "noreorder") {
5643     return parseSetNoReorderDirective();
5644   } else if (Tok.getString() == "macro") {
5645     return parseSetMacroDirective();
5646   } else if (Tok.getString() == "nomacro") {
5647     return parseSetNoMacroDirective();
5648   } else if (Tok.getString() == "mips16") {
5649     return parseSetMips16Directive();
5650   } else if (Tok.getString() == "nomips16") {
5651     return parseSetNoMips16Directive();
5652   } else if (Tok.getString() == "nomicromips") {
5653     clearFeatureBits(Mips::FeatureMicroMips, "micromips");
5654     getTargetStreamer().emitDirectiveSetNoMicroMips();
5655     Parser.eatToEndOfStatement();
5656     return false;
5657   } else if (Tok.getString() == "micromips") {
5658     return parseSetFeature(Mips::FeatureMicroMips);
5659   } else if (Tok.getString() == "mips0") {
5660     return parseSetMips0Directive();
5661   } else if (Tok.getString() == "mips1") {
5662     return parseSetFeature(Mips::FeatureMips1);
5663   } else if (Tok.getString() == "mips2") {
5664     return parseSetFeature(Mips::FeatureMips2);
5665   } else if (Tok.getString() == "mips3") {
5666     return parseSetFeature(Mips::FeatureMips3);
5667   } else if (Tok.getString() == "mips4") {
5668     return parseSetFeature(Mips::FeatureMips4);
5669   } else if (Tok.getString() == "mips5") {
5670     return parseSetFeature(Mips::FeatureMips5);
5671   } else if (Tok.getString() == "mips32") {
5672     return parseSetFeature(Mips::FeatureMips32);
5673   } else if (Tok.getString() == "mips32r2") {
5674     return parseSetFeature(Mips::FeatureMips32r2);
5675   } else if (Tok.getString() == "mips32r3") {
5676     return parseSetFeature(Mips::FeatureMips32r3);
5677   } else if (Tok.getString() == "mips32r5") {
5678     return parseSetFeature(Mips::FeatureMips32r5);
5679   } else if (Tok.getString() == "mips32r6") {
5680     return parseSetFeature(Mips::FeatureMips32r6);
5681   } else if (Tok.getString() == "mips64") {
5682     return parseSetFeature(Mips::FeatureMips64);
5683   } else if (Tok.getString() == "mips64r2") {
5684     return parseSetFeature(Mips::FeatureMips64r2);
5685   } else if (Tok.getString() == "mips64r3") {
5686     return parseSetFeature(Mips::FeatureMips64r3);
5687   } else if (Tok.getString() == "mips64r5") {
5688     return parseSetFeature(Mips::FeatureMips64r5);
5689   } else if (Tok.getString() == "mips64r6") {
5690     return parseSetFeature(Mips::FeatureMips64r6);
5691   } else if (Tok.getString() == "dsp") {
5692     return parseSetFeature(Mips::FeatureDSP);
5693   } else if (Tok.getString() == "nodsp") {
5694     return parseSetNoDspDirective();
5695   } else if (Tok.getString() == "msa") {
5696     return parseSetMsaDirective();
5697   } else if (Tok.getString() == "nomsa") {
5698     return parseSetNoMsaDirective();
5699   } else if (Tok.getString() == "softfloat") {
5700     return parseSetSoftFloatDirective();
5701   } else if (Tok.getString() == "hardfloat") {
5702     return parseSetHardFloatDirective();
5703   } else {
5704     // It is just an identifier, look for an assignment.
5705     parseSetAssignment();
5706     return false;
5707   }
5708 
5709   return true;
5710 }
5711 
5712 /// parseDataDirective
5713 ///  ::= .word [ expression (, expression)* ]
5714 bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) {
5715   MCAsmParser &Parser = getParser();
5716   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5717     for (;;) {
5718       const MCExpr *Value;
5719       if (getParser().parseExpression(Value))
5720         return true;
5721 
5722       getParser().getStreamer().EmitValue(Value, Size);
5723 
5724       if (getLexer().is(AsmToken::EndOfStatement))
5725         break;
5726 
5727       if (getLexer().isNot(AsmToken::Comma))
5728         return Error(L, "unexpected token, expected comma");
5729       Parser.Lex();
5730     }
5731   }
5732 
5733   Parser.Lex();
5734   return false;
5735 }
5736 
5737 /// parseDirectiveGpWord
5738 ///  ::= .gpword local_sym
5739 bool MipsAsmParser::parseDirectiveGpWord() {
5740   MCAsmParser &Parser = getParser();
5741   const MCExpr *Value;
5742   // EmitGPRel32Value requires an expression, so we are using base class
5743   // method to evaluate the expression.
5744   if (getParser().parseExpression(Value))
5745     return true;
5746   getParser().getStreamer().EmitGPRel32Value(Value);
5747 
5748   if (getLexer().isNot(AsmToken::EndOfStatement))
5749     return Error(getLexer().getLoc(),
5750                 "unexpected token, expected end of statement");
5751   Parser.Lex(); // Eat EndOfStatement token.
5752   return false;
5753 }
5754 
5755 /// parseDirectiveGpDWord
5756 ///  ::= .gpdword local_sym
5757 bool MipsAsmParser::parseDirectiveGpDWord() {
5758   MCAsmParser &Parser = getParser();
5759   const MCExpr *Value;
5760   // EmitGPRel64Value requires an expression, so we are using base class
5761   // method to evaluate the expression.
5762   if (getParser().parseExpression(Value))
5763     return true;
5764   getParser().getStreamer().EmitGPRel64Value(Value);
5765 
5766   if (getLexer().isNot(AsmToken::EndOfStatement))
5767     return Error(getLexer().getLoc(),
5768                 "unexpected token, expected end of statement");
5769   Parser.Lex(); // Eat EndOfStatement token.
5770   return false;
5771 }
5772 
5773 /// parseDirectiveDtpRelWord
5774 ///  ::= .dtprelword tls_sym
5775 bool MipsAsmParser::parseDirectiveDtpRelWord() {
5776   MCAsmParser &Parser = getParser();
5777   const MCExpr *Value;
5778   // EmitDTPRel32Value requires an expression, so we are using base class
5779   // method to evaluate the expression.
5780   if (getParser().parseExpression(Value))
5781     return true;
5782   getParser().getStreamer().EmitDTPRel32Value(Value);
5783 
5784   if (getLexer().isNot(AsmToken::EndOfStatement))
5785     return Error(getLexer().getLoc(),
5786                 "unexpected token, expected end of statement");
5787   Parser.Lex(); // Eat EndOfStatement token.
5788   return false;
5789 }
5790 
5791 /// parseDirectiveDtpRelDWord
5792 ///  ::= .dtpreldword tls_sym
5793 bool MipsAsmParser::parseDirectiveDtpRelDWord() {
5794   MCAsmParser &Parser = getParser();
5795   const MCExpr *Value;
5796   // EmitDTPRel64Value requires an expression, so we are using base class
5797   // method to evaluate the expression.
5798   if (getParser().parseExpression(Value))
5799     return true;
5800   getParser().getStreamer().EmitDTPRel64Value(Value);
5801 
5802   if (getLexer().isNot(AsmToken::EndOfStatement))
5803     return Error(getLexer().getLoc(),
5804                 "unexpected token, expected end of statement");
5805   Parser.Lex(); // Eat EndOfStatement token.
5806   return false;
5807 }
5808 
5809 /// parseDirectiveTpRelWord
5810 ///  ::= .tprelword tls_sym
5811 bool MipsAsmParser::parseDirectiveTpRelWord() {
5812   MCAsmParser &Parser = getParser();
5813   const MCExpr *Value;
5814   // EmitTPRel32Value requires an expression, so we are using base class
5815   // method to evaluate the expression.
5816   if (getParser().parseExpression(Value))
5817     return true;
5818   getParser().getStreamer().EmitTPRel32Value(Value);
5819 
5820   if (getLexer().isNot(AsmToken::EndOfStatement))
5821     return Error(getLexer().getLoc(),
5822                 "unexpected token, expected end of statement");
5823   Parser.Lex(); // Eat EndOfStatement token.
5824   return false;
5825 }
5826 
5827 /// parseDirectiveTpRelDWord
5828 ///  ::= .tpreldword tls_sym
5829 bool MipsAsmParser::parseDirectiveTpRelDWord() {
5830   MCAsmParser &Parser = getParser();
5831   const MCExpr *Value;
5832   // EmitTPRel64Value requires an expression, so we are using base class
5833   // method to evaluate the expression.
5834   if (getParser().parseExpression(Value))
5835     return true;
5836   getParser().getStreamer().EmitTPRel64Value(Value);
5837 
5838   if (getLexer().isNot(AsmToken::EndOfStatement))
5839     return Error(getLexer().getLoc(),
5840                 "unexpected token, expected end of statement");
5841   Parser.Lex(); // Eat EndOfStatement token.
5842   return false;
5843 }
5844 
5845 bool MipsAsmParser::parseDirectiveOption() {
5846   MCAsmParser &Parser = getParser();
5847   // Get the option token.
5848   AsmToken Tok = Parser.getTok();
5849   // At the moment only identifiers are supported.
5850   if (Tok.isNot(AsmToken::Identifier)) {
5851     Error(Parser.getTok().getLoc(), "unexpected token, expected identifier");
5852     Parser.eatToEndOfStatement();
5853     return false;
5854   }
5855 
5856   StringRef Option = Tok.getIdentifier();
5857 
5858   if (Option == "pic0") {
5859     // MipsAsmParser needs to know if the current PIC mode changes.
5860     IsPicEnabled = false;
5861 
5862     getTargetStreamer().emitDirectiveOptionPic0();
5863     Parser.Lex();
5864     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
5865       Error(Parser.getTok().getLoc(),
5866             "unexpected token, expected end of statement");
5867       Parser.eatToEndOfStatement();
5868     }
5869     return false;
5870   }
5871 
5872   if (Option == "pic2") {
5873     // MipsAsmParser needs to know if the current PIC mode changes.
5874     IsPicEnabled = true;
5875 
5876     getTargetStreamer().emitDirectiveOptionPic2();
5877     Parser.Lex();
5878     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
5879       Error(Parser.getTok().getLoc(),
5880             "unexpected token, expected end of statement");
5881       Parser.eatToEndOfStatement();
5882     }
5883     return false;
5884   }
5885 
5886   // Unknown option.
5887   Warning(Parser.getTok().getLoc(),
5888           "unknown option, expected 'pic0' or 'pic2'");
5889   Parser.eatToEndOfStatement();
5890   return false;
5891 }
5892 
5893 /// parseInsnDirective
5894 ///  ::= .insn
5895 bool MipsAsmParser::parseInsnDirective() {
5896   // If this is not the end of the statement, report an error.
5897   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5898     reportParseError("unexpected token, expected end of statement");
5899     return false;
5900   }
5901 
5902   // The actual label marking happens in
5903   // MipsELFStreamer::createPendingLabelRelocs().
5904   getTargetStreamer().emitDirectiveInsn();
5905 
5906   getParser().Lex(); // Eat EndOfStatement token.
5907   return false;
5908 }
5909 
5910 /// parseSSectionDirective
5911 ///  ::= .sbss
5912 ///  ::= .sdata
5913 bool MipsAsmParser::parseSSectionDirective(StringRef Section, unsigned Type) {
5914   // If this is not the end of the statement, report an error.
5915   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5916     reportParseError("unexpected token, expected end of statement");
5917     return false;
5918   }
5919 
5920   MCSection *ELFSection = getContext().getELFSection(
5921       Section, Type, ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_MIPS_GPREL);
5922   getParser().getStreamer().SwitchSection(ELFSection);
5923 
5924   getParser().Lex(); // Eat EndOfStatement token.
5925   return false;
5926 }
5927 
5928 /// parseDirectiveModule
5929 ///  ::= .module oddspreg
5930 ///  ::= .module nooddspreg
5931 ///  ::= .module fp=value
5932 ///  ::= .module softfloat
5933 ///  ::= .module hardfloat
5934 bool MipsAsmParser::parseDirectiveModule() {
5935   MCAsmParser &Parser = getParser();
5936   MCAsmLexer &Lexer = getLexer();
5937   SMLoc L = Lexer.getLoc();
5938 
5939   if (!getTargetStreamer().isModuleDirectiveAllowed()) {
5940     // TODO : get a better message.
5941     reportParseError(".module directive must appear before any code");
5942     return false;
5943   }
5944 
5945   StringRef Option;
5946   if (Parser.parseIdentifier(Option)) {
5947     reportParseError("expected .module option identifier");
5948     return false;
5949   }
5950 
5951   if (Option == "oddspreg") {
5952     clearModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5953 
5954     // Synchronize the abiflags information with the FeatureBits information we
5955     // changed above.
5956     getTargetStreamer().updateABIInfo(*this);
5957 
5958     // If printing assembly, use the recently updated abiflags information.
5959     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5960     // emitted at the end).
5961     getTargetStreamer().emitDirectiveModuleOddSPReg();
5962 
5963     // If this is not the end of the statement, report an error.
5964     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5965       reportParseError("unexpected token, expected end of statement");
5966       return false;
5967     }
5968 
5969     return false; // parseDirectiveModule has finished successfully.
5970   } else if (Option == "nooddspreg") {
5971     if (!isABI_O32()) {
5972       Error(L, "'.module nooddspreg' requires the O32 ABI");
5973       return false;
5974     }
5975 
5976     setModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5977 
5978     // Synchronize the abiflags information with the FeatureBits information we
5979     // changed above.
5980     getTargetStreamer().updateABIInfo(*this);
5981 
5982     // If printing assembly, use the recently updated abiflags information.
5983     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5984     // emitted at the end).
5985     getTargetStreamer().emitDirectiveModuleOddSPReg();
5986 
5987     // If this is not the end of the statement, report an error.
5988     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5989       reportParseError("unexpected token, expected end of statement");
5990       return false;
5991     }
5992 
5993     return false; // parseDirectiveModule has finished successfully.
5994   } else if (Option == "fp") {
5995     return parseDirectiveModuleFP();
5996   } else if (Option == "softfloat") {
5997     setModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5998 
5999     // Synchronize the ABI Flags information with the FeatureBits information we
6000     // updated above.
6001     getTargetStreamer().updateABIInfo(*this);
6002 
6003     // If printing assembly, use the recently updated ABI Flags information.
6004     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
6005     // emitted later).
6006     getTargetStreamer().emitDirectiveModuleSoftFloat();
6007 
6008     // If this is not the end of the statement, report an error.
6009     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6010       reportParseError("unexpected token, expected end of statement");
6011       return false;
6012     }
6013 
6014     return false; // parseDirectiveModule has finished successfully.
6015   } else if (Option == "hardfloat") {
6016     clearModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float");
6017 
6018     // Synchronize the ABI Flags information with the FeatureBits information we
6019     // updated above.
6020     getTargetStreamer().updateABIInfo(*this);
6021 
6022     // If printing assembly, use the recently updated ABI Flags information.
6023     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
6024     // emitted later).
6025     getTargetStreamer().emitDirectiveModuleHardFloat();
6026 
6027     // If this is not the end of the statement, report an error.
6028     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6029       reportParseError("unexpected token, expected end of statement");
6030       return false;
6031     }
6032 
6033     return false; // parseDirectiveModule has finished successfully.
6034   } else {
6035     return Error(L, "'" + Twine(Option) + "' is not a valid .module option.");
6036   }
6037 }
6038 
6039 /// parseDirectiveModuleFP
6040 ///  ::= =32
6041 ///  ::= =xx
6042 ///  ::= =64
6043 bool MipsAsmParser::parseDirectiveModuleFP() {
6044   MCAsmParser &Parser = getParser();
6045   MCAsmLexer &Lexer = getLexer();
6046 
6047   if (Lexer.isNot(AsmToken::Equal)) {
6048     reportParseError("unexpected token, expected equals sign '='");
6049     return false;
6050   }
6051   Parser.Lex(); // Eat '=' token.
6052 
6053   MipsABIFlagsSection::FpABIKind FpABI;
6054   if (!parseFpABIValue(FpABI, ".module"))
6055     return false;
6056 
6057   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6058     reportParseError("unexpected token, expected end of statement");
6059     return false;
6060   }
6061 
6062   // Synchronize the abiflags information with the FeatureBits information we
6063   // changed above.
6064   getTargetStreamer().updateABIInfo(*this);
6065 
6066   // If printing assembly, use the recently updated abiflags information.
6067   // If generating ELF, don't do anything (the .MIPS.abiflags section gets
6068   // emitted at the end).
6069   getTargetStreamer().emitDirectiveModuleFP();
6070 
6071   Parser.Lex(); // Consume the EndOfStatement.
6072   return false;
6073 }
6074 
6075 bool MipsAsmParser::parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
6076                                     StringRef Directive) {
6077   MCAsmParser &Parser = getParser();
6078   MCAsmLexer &Lexer = getLexer();
6079   bool ModuleLevelOptions = Directive == ".module";
6080 
6081   if (Lexer.is(AsmToken::Identifier)) {
6082     StringRef Value = Parser.getTok().getString();
6083     Parser.Lex();
6084 
6085     if (Value != "xx") {
6086       reportParseError("unsupported value, expected 'xx', '32' or '64'");
6087       return false;
6088     }
6089 
6090     if (!isABI_O32()) {
6091       reportParseError("'" + Directive + " fp=xx' requires the O32 ABI");
6092       return false;
6093     }
6094 
6095     FpABI = MipsABIFlagsSection::FpABIKind::XX;
6096     if (ModuleLevelOptions) {
6097       setModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
6098       clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
6099     } else {
6100       setFeatureBits(Mips::FeatureFPXX, "fpxx");
6101       clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
6102     }
6103     return true;
6104   }
6105 
6106   if (Lexer.is(AsmToken::Integer)) {
6107     unsigned Value = Parser.getTok().getIntVal();
6108     Parser.Lex();
6109 
6110     if (Value != 32 && Value != 64) {
6111       reportParseError("unsupported value, expected 'xx', '32' or '64'");
6112       return false;
6113     }
6114 
6115     if (Value == 32) {
6116       if (!isABI_O32()) {
6117         reportParseError("'" + Directive + " fp=32' requires the O32 ABI");
6118         return false;
6119       }
6120 
6121       FpABI = MipsABIFlagsSection::FpABIKind::S32;
6122       if (ModuleLevelOptions) {
6123         clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
6124         clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
6125       } else {
6126         clearFeatureBits(Mips::FeatureFPXX, "fpxx");
6127         clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
6128       }
6129     } else {
6130       FpABI = MipsABIFlagsSection::FpABIKind::S64;
6131       if (ModuleLevelOptions) {
6132         clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
6133         setModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
6134       } else {
6135         clearFeatureBits(Mips::FeatureFPXX, "fpxx");
6136         setFeatureBits(Mips::FeatureFP64Bit, "fp64");
6137       }
6138     }
6139 
6140     return true;
6141   }
6142 
6143   return false;
6144 }
6145 
6146 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
6147   // This returns false if this function recognizes the directive
6148   // regardless of whether it is successfully handles or reports an
6149   // error. Otherwise it returns true to give the generic parser a
6150   // chance at recognizing it.
6151 
6152   MCAsmParser &Parser = getParser();
6153   StringRef IDVal = DirectiveID.getString();
6154 
6155   if (IDVal == ".cpload") {
6156     parseDirectiveCpLoad(DirectiveID.getLoc());
6157     return false;
6158   }
6159   if (IDVal == ".cprestore") {
6160     parseDirectiveCpRestore(DirectiveID.getLoc());
6161     return false;
6162   }
6163   if (IDVal == ".dword") {
6164     parseDataDirective(8, DirectiveID.getLoc());
6165     return false;
6166   }
6167   if (IDVal == ".ent") {
6168     StringRef SymbolName;
6169 
6170     if (Parser.parseIdentifier(SymbolName)) {
6171       reportParseError("expected identifier after .ent");
6172       return false;
6173     }
6174 
6175     // There's an undocumented extension that allows an integer to
6176     // follow the name of the procedure which AFAICS is ignored by GAS.
6177     // Example: .ent foo,2
6178     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6179       if (getLexer().isNot(AsmToken::Comma)) {
6180         // Even though we accept this undocumented extension for compatibility
6181         // reasons, the additional integer argument does not actually change
6182         // the behaviour of the '.ent' directive, so we would like to discourage
6183         // its use. We do this by not referring to the extended version in
6184         // error messages which are not directly related to its use.
6185         reportParseError("unexpected token, expected end of statement");
6186         return false;
6187       }
6188       Parser.Lex(); // Eat the comma.
6189       const MCExpr *DummyNumber;
6190       int64_t DummyNumberVal;
6191       // If the user was explicitly trying to use the extended version,
6192       // we still give helpful extension-related error messages.
6193       if (Parser.parseExpression(DummyNumber)) {
6194         reportParseError("expected number after comma");
6195         return false;
6196       }
6197       if (!DummyNumber->evaluateAsAbsolute(DummyNumberVal)) {
6198         reportParseError("expected an absolute expression after comma");
6199         return false;
6200       }
6201     }
6202 
6203     // If this is not the end of the statement, report an error.
6204     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6205       reportParseError("unexpected token, expected end of statement");
6206       return false;
6207     }
6208 
6209     MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
6210 
6211     getTargetStreamer().emitDirectiveEnt(*Sym);
6212     CurrentFn = Sym;
6213     IsCpRestoreSet = false;
6214     return false;
6215   }
6216 
6217   if (IDVal == ".end") {
6218     StringRef SymbolName;
6219 
6220     if (Parser.parseIdentifier(SymbolName)) {
6221       reportParseError("expected identifier after .end");
6222       return false;
6223     }
6224 
6225     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6226       reportParseError("unexpected token, expected end of statement");
6227       return false;
6228     }
6229 
6230     if (CurrentFn == nullptr) {
6231       reportParseError(".end used without .ent");
6232       return false;
6233     }
6234 
6235     if ((SymbolName != CurrentFn->getName())) {
6236       reportParseError(".end symbol does not match .ent symbol");
6237       return false;
6238     }
6239 
6240     getTargetStreamer().emitDirectiveEnd(SymbolName);
6241     CurrentFn = nullptr;
6242     IsCpRestoreSet = false;
6243     return false;
6244   }
6245 
6246   if (IDVal == ".frame") {
6247     // .frame $stack_reg, frame_size_in_bytes, $return_reg
6248     SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
6249     OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
6250     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
6251       reportParseError("expected stack register");
6252       return false;
6253     }
6254 
6255     MipsOperand &StackRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
6256     if (!StackRegOpnd.isGPRAsmReg()) {
6257       reportParseError(StackRegOpnd.getStartLoc(),
6258                        "expected general purpose register");
6259       return false;
6260     }
6261     unsigned StackReg = StackRegOpnd.getGPR32Reg();
6262 
6263     if (Parser.getTok().is(AsmToken::Comma))
6264       Parser.Lex();
6265     else {
6266       reportParseError("unexpected token, expected comma");
6267       return false;
6268     }
6269 
6270     // Parse the frame size.
6271     const MCExpr *FrameSize;
6272     int64_t FrameSizeVal;
6273 
6274     if (Parser.parseExpression(FrameSize)) {
6275       reportParseError("expected frame size value");
6276       return false;
6277     }
6278 
6279     if (!FrameSize->evaluateAsAbsolute(FrameSizeVal)) {
6280       reportParseError("frame size not an absolute expression");
6281       return false;
6282     }
6283 
6284     if (Parser.getTok().is(AsmToken::Comma))
6285       Parser.Lex();
6286     else {
6287       reportParseError("unexpected token, expected comma");
6288       return false;
6289     }
6290 
6291     // Parse the return register.
6292     TmpReg.clear();
6293     ResTy = parseAnyRegister(TmpReg);
6294     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
6295       reportParseError("expected return register");
6296       return false;
6297     }
6298 
6299     MipsOperand &ReturnRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
6300     if (!ReturnRegOpnd.isGPRAsmReg()) {
6301       reportParseError(ReturnRegOpnd.getStartLoc(),
6302                        "expected general purpose register");
6303       return false;
6304     }
6305 
6306     // If this is not the end of the statement, report an error.
6307     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6308       reportParseError("unexpected token, expected end of statement");
6309       return false;
6310     }
6311 
6312     getTargetStreamer().emitFrame(StackReg, FrameSizeVal,
6313                                   ReturnRegOpnd.getGPR32Reg());
6314     IsCpRestoreSet = false;
6315     return false;
6316   }
6317 
6318   if (IDVal == ".set") {
6319     parseDirectiveSet();
6320     return false;
6321   }
6322 
6323   if (IDVal == ".mask" || IDVal == ".fmask") {
6324     // .mask bitmask, frame_offset
6325     // bitmask: One bit for each register used.
6326     // frame_offset: Offset from Canonical Frame Address ($sp on entry) where
6327     //               first register is expected to be saved.
6328     // Examples:
6329     //   .mask 0x80000000, -4
6330     //   .fmask 0x80000000, -4
6331     //
6332 
6333     // Parse the bitmask
6334     const MCExpr *BitMask;
6335     int64_t BitMaskVal;
6336 
6337     if (Parser.parseExpression(BitMask)) {
6338       reportParseError("expected bitmask value");
6339       return false;
6340     }
6341 
6342     if (!BitMask->evaluateAsAbsolute(BitMaskVal)) {
6343       reportParseError("bitmask not an absolute expression");
6344       return false;
6345     }
6346 
6347     if (Parser.getTok().is(AsmToken::Comma))
6348       Parser.Lex();
6349     else {
6350       reportParseError("unexpected token, expected comma");
6351       return false;
6352     }
6353 
6354     // Parse the frame_offset
6355     const MCExpr *FrameOffset;
6356     int64_t FrameOffsetVal;
6357 
6358     if (Parser.parseExpression(FrameOffset)) {
6359       reportParseError("expected frame offset value");
6360       return false;
6361     }
6362 
6363     if (!FrameOffset->evaluateAsAbsolute(FrameOffsetVal)) {
6364       reportParseError("frame offset not an absolute expression");
6365       return false;
6366     }
6367 
6368     // If this is not the end of the statement, report an error.
6369     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6370       reportParseError("unexpected token, expected end of statement");
6371       return false;
6372     }
6373 
6374     if (IDVal == ".mask")
6375       getTargetStreamer().emitMask(BitMaskVal, FrameOffsetVal);
6376     else
6377       getTargetStreamer().emitFMask(BitMaskVal, FrameOffsetVal);
6378     return false;
6379   }
6380 
6381   if (IDVal == ".nan")
6382     return parseDirectiveNaN();
6383 
6384   if (IDVal == ".gpword") {
6385     parseDirectiveGpWord();
6386     return false;
6387   }
6388 
6389   if (IDVal == ".gpdword") {
6390     parseDirectiveGpDWord();
6391     return false;
6392   }
6393 
6394   if (IDVal == ".dtprelword") {
6395     parseDirectiveDtpRelWord();
6396     return false;
6397   }
6398 
6399   if (IDVal == ".dtpreldword") {
6400     parseDirectiveDtpRelDWord();
6401     return false;
6402   }
6403 
6404   if (IDVal == ".tprelword") {
6405     parseDirectiveTpRelWord();
6406     return false;
6407   }
6408 
6409   if (IDVal == ".tpreldword") {
6410     parseDirectiveTpRelDWord();
6411     return false;
6412   }
6413 
6414   if (IDVal == ".word") {
6415     parseDataDirective(4, DirectiveID.getLoc());
6416     return false;
6417   }
6418 
6419   if (IDVal == ".hword") {
6420     parseDataDirective(2, DirectiveID.getLoc());
6421     return false;
6422   }
6423 
6424   if (IDVal == ".option") {
6425     parseDirectiveOption();
6426     return false;
6427   }
6428 
6429   if (IDVal == ".abicalls") {
6430     getTargetStreamer().emitDirectiveAbiCalls();
6431     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
6432       Error(Parser.getTok().getLoc(),
6433             "unexpected token, expected end of statement");
6434       // Clear line
6435       Parser.eatToEndOfStatement();
6436     }
6437     return false;
6438   }
6439 
6440   if (IDVal == ".cpsetup") {
6441     parseDirectiveCPSetup();
6442     return false;
6443   }
6444   if (IDVal == ".cpreturn") {
6445     parseDirectiveCPReturn();
6446     return false;
6447   }
6448   if (IDVal == ".module") {
6449     parseDirectiveModule();
6450     return false;
6451   }
6452   if (IDVal == ".llvm_internal_mips_reallow_module_directive") {
6453     parseInternalDirectiveReallowModule();
6454     return false;
6455   }
6456   if (IDVal == ".insn") {
6457     parseInsnDirective();
6458     return false;
6459   }
6460   if (IDVal == ".sbss") {
6461     parseSSectionDirective(IDVal, ELF::SHT_NOBITS);
6462     return false;
6463   }
6464   if (IDVal == ".sdata") {
6465     parseSSectionDirective(IDVal, ELF::SHT_PROGBITS);
6466     return false;
6467   }
6468 
6469   return true;
6470 }
6471 
6472 bool MipsAsmParser::parseInternalDirectiveReallowModule() {
6473   // If this is not the end of the statement, report an error.
6474   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6475     reportParseError("unexpected token, expected end of statement");
6476     return false;
6477   }
6478 
6479   getTargetStreamer().reallowModuleDirective();
6480 
6481   getParser().Lex(); // Eat EndOfStatement token.
6482   return false;
6483 }
6484 
6485 extern "C" void LLVMInitializeMipsAsmParser() {
6486   RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
6487   RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
6488   RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
6489   RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
6490 }
6491 
6492 #define GET_REGISTER_MATCHER
6493 #define GET_MATCHER_IMPLEMENTATION
6494 #include "MipsGenAsmMatcher.inc"
6495