xref: /freebsd/contrib/llvm-project/llvm/lib/Target/Mips/AsmParser/MipsAsmParser.cpp (revision 85868e8a1daeaae7a0e48effb2ea2310ae3b02c6)
1 //===-- MipsAsmParser.cpp - Parse Mips assembly to MCInst instructions ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "MCTargetDesc/MipsABIFlagsSection.h"
10 #include "MCTargetDesc/MipsABIInfo.h"
11 #include "MCTargetDesc/MipsBaseInfo.h"
12 #include "MCTargetDesc/MipsMCExpr.h"
13 #include "MCTargetDesc/MipsMCTargetDesc.h"
14 #include "MipsTargetStreamer.h"
15 #include "TargetInfo/MipsTargetInfo.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/BinaryFormat/ELF.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstrDesc.h"
28 #include "llvm/MC/MCObjectFileInfo.h"
29 #include "llvm/MC/MCParser/MCAsmLexer.h"
30 #include "llvm/MC/MCParser/MCAsmParser.h"
31 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
32 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
33 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
34 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
35 #include "llvm/MC/MCSectionELF.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSubtargetInfo.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/MC/MCSymbolELF.h"
40 #include "llvm/MC/MCValue.h"
41 #include "llvm/MC/SubtargetFeature.h"
42 #include "llvm/Support/Alignment.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/SMLoc.h"
50 #include "llvm/Support/SourceMgr.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include <algorithm>
54 #include <cassert>
55 #include <cstdint>
56 #include <memory>
57 #include <string>
58 #include <utility>
59 
60 using namespace llvm;
61 
62 #define DEBUG_TYPE "mips-asm-parser"
63 
64 namespace llvm {
65 
66 class MCInstrInfo;
67 
68 } // end namespace llvm
69 
70 extern cl::opt<bool> EmitJalrReloc;
71 
72 namespace {
73 
74 class MipsAssemblerOptions {
75 public:
76   MipsAssemblerOptions(const FeatureBitset &Features_) : Features(Features_) {}
77 
78   MipsAssemblerOptions(const MipsAssemblerOptions *Opts) {
79     ATReg = Opts->getATRegIndex();
80     Reorder = Opts->isReorder();
81     Macro = Opts->isMacro();
82     Features = Opts->getFeatures();
83   }
84 
85   unsigned getATRegIndex() const { return ATReg; }
86   bool setATRegIndex(unsigned Reg) {
87     if (Reg > 31)
88       return false;
89 
90     ATReg = Reg;
91     return true;
92   }
93 
94   bool isReorder() const { return Reorder; }
95   void setReorder() { Reorder = true; }
96   void setNoReorder() { Reorder = false; }
97 
98   bool isMacro() const { return Macro; }
99   void setMacro() { Macro = true; }
100   void setNoMacro() { Macro = false; }
101 
102   const FeatureBitset &getFeatures() const { return Features; }
103   void setFeatures(const FeatureBitset &Features_) { Features = Features_; }
104 
105   // Set of features that are either architecture features or referenced
106   // by them (e.g.: FeatureNaN2008 implied by FeatureMips32r6).
107   // The full table can be found in MipsGenSubtargetInfo.inc (MipsFeatureKV[]).
108   // The reason we need this mask is explained in the selectArch function.
109   // FIXME: Ideally we would like TableGen to generate this information.
110   static const FeatureBitset AllArchRelatedMask;
111 
112 private:
113   unsigned ATReg = 1;
114   bool Reorder = true;
115   bool Macro = true;
116   FeatureBitset Features;
117 };
118 
119 } // end anonymous namespace
120 
121 const FeatureBitset MipsAssemblerOptions::AllArchRelatedMask = {
122     Mips::FeatureMips1, Mips::FeatureMips2, Mips::FeatureMips3,
123     Mips::FeatureMips3_32, Mips::FeatureMips3_32r2, Mips::FeatureMips4,
124     Mips::FeatureMips4_32, Mips::FeatureMips4_32r2, Mips::FeatureMips5,
125     Mips::FeatureMips5_32r2, Mips::FeatureMips32, Mips::FeatureMips32r2,
126     Mips::FeatureMips32r3, Mips::FeatureMips32r5, Mips::FeatureMips32r6,
127     Mips::FeatureMips64, Mips::FeatureMips64r2, Mips::FeatureMips64r3,
128     Mips::FeatureMips64r5, Mips::FeatureMips64r6, Mips::FeatureCnMips,
129     Mips::FeatureCnMipsP, Mips::FeatureFP64Bit, Mips::FeatureGP64Bit,
130     Mips::FeatureNaN2008
131 };
132 
133 namespace {
134 
135 class MipsAsmParser : public MCTargetAsmParser {
136   MipsTargetStreamer &getTargetStreamer() {
137     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
138     return static_cast<MipsTargetStreamer &>(TS);
139   }
140 
141   MipsABIInfo ABI;
142   SmallVector<std::unique_ptr<MipsAssemblerOptions>, 2> AssemblerOptions;
143   MCSymbol *CurrentFn; // Pointer to the function being parsed. It may be a
144                        // nullptr, which indicates that no function is currently
145                        // selected. This usually happens after an '.end func'
146                        // directive.
147   bool IsLittleEndian;
148   bool IsPicEnabled;
149   bool IsCpRestoreSet;
150   int CpRestoreOffset;
151   unsigned GPReg;
152   unsigned CpSaveLocation;
153   /// If true, then CpSaveLocation is a register, otherwise it's an offset.
154   bool     CpSaveLocationIsRegister;
155 
156   // Map of register aliases created via the .set directive.
157   StringMap<AsmToken> RegisterSets;
158 
159   // Print a warning along with its fix-it message at the given range.
160   void printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
161                              SMRange Range, bool ShowColors = true);
162 
163   void ConvertXWPOperands(MCInst &Inst, const OperandVector &Operands);
164 
165 #define GET_ASSEMBLER_HEADER
166 #include "MipsGenAsmMatcher.inc"
167 
168   unsigned
169   checkEarlyTargetMatchPredicate(MCInst &Inst,
170                                  const OperandVector &Operands) override;
171   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
172 
173   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
174                                OperandVector &Operands, MCStreamer &Out,
175                                uint64_t &ErrorInfo,
176                                bool MatchingInlineAsm) override;
177 
178   /// Parse a register as used in CFI directives
179   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
180 
181   bool parseParenSuffix(StringRef Name, OperandVector &Operands);
182 
183   bool parseBracketSuffix(StringRef Name, OperandVector &Operands);
184 
185   bool mnemonicIsValid(StringRef Mnemonic, unsigned VariantID);
186 
187   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
188                         SMLoc NameLoc, OperandVector &Operands) override;
189 
190   bool ParseDirective(AsmToken DirectiveID) override;
191 
192   OperandMatchResultTy parseMemOperand(OperandVector &Operands);
193   OperandMatchResultTy
194   matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
195                                     StringRef Identifier, SMLoc S);
196   OperandMatchResultTy matchAnyRegisterWithoutDollar(OperandVector &Operands,
197                                                      const AsmToken &Token,
198                                                      SMLoc S);
199   OperandMatchResultTy matchAnyRegisterWithoutDollar(OperandVector &Operands,
200                                                      SMLoc S);
201   OperandMatchResultTy parseAnyRegister(OperandVector &Operands);
202   OperandMatchResultTy parseImm(OperandVector &Operands);
203   OperandMatchResultTy parseJumpTarget(OperandVector &Operands);
204   OperandMatchResultTy parseInvNum(OperandVector &Operands);
205   OperandMatchResultTy parseRegisterList(OperandVector &Operands);
206 
207   bool searchSymbolAlias(OperandVector &Operands);
208 
209   bool parseOperand(OperandVector &, StringRef Mnemonic);
210 
211   enum MacroExpanderResultTy {
212     MER_NotAMacro,
213     MER_Success,
214     MER_Fail,
215   };
216 
217   // Expands assembly pseudo instructions.
218   MacroExpanderResultTy tryExpandInstruction(MCInst &Inst, SMLoc IDLoc,
219                                              MCStreamer &Out,
220                                              const MCSubtargetInfo *STI);
221 
222   bool expandJalWithRegs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
223                          const MCSubtargetInfo *STI);
224 
225   bool loadImmediate(int64_t ImmValue, unsigned DstReg, unsigned SrcReg,
226                      bool Is32BitImm, bool IsAddress, SMLoc IDLoc,
227                      MCStreamer &Out, const MCSubtargetInfo *STI);
228 
229   bool loadAndAddSymbolAddress(const MCExpr *SymExpr, unsigned DstReg,
230                                unsigned SrcReg, bool Is32BitSym, SMLoc IDLoc,
231                                MCStreamer &Out, const MCSubtargetInfo *STI);
232 
233   bool emitPartialAddress(MipsTargetStreamer &TOut, SMLoc IDLoc, MCSymbol *Sym);
234 
235   bool expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
236                      MCStreamer &Out, const MCSubtargetInfo *STI);
237 
238   bool expandLoadSingleImmToGPR(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
239                                 const MCSubtargetInfo *STI);
240   bool expandLoadSingleImmToFPR(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
241                                 const MCSubtargetInfo *STI);
242   bool expandLoadDoubleImmToGPR(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
243                                 const MCSubtargetInfo *STI);
244   bool expandLoadDoubleImmToFPR(MCInst &Inst, bool Is64FPU, SMLoc IDLoc,
245                                 MCStreamer &Out, const MCSubtargetInfo *STI);
246 
247   bool expandLoadAddress(unsigned DstReg, unsigned BaseReg,
248                          const MCOperand &Offset, bool Is32BitAddress,
249                          SMLoc IDLoc, MCStreamer &Out,
250                          const MCSubtargetInfo *STI);
251 
252   bool expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
253                                   const MCSubtargetInfo *STI);
254 
255   void expandMemInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
256                      const MCSubtargetInfo *STI, bool IsLoad);
257 
258   bool expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
259                                const MCSubtargetInfo *STI);
260 
261   bool expandAliasImmediate(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
262                             const MCSubtargetInfo *STI);
263 
264   bool expandBranchImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
265                        const MCSubtargetInfo *STI);
266 
267   bool expandCondBranches(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
268                           const MCSubtargetInfo *STI);
269 
270   bool expandDivRem(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
271                     const MCSubtargetInfo *STI, const bool IsMips64,
272                     const bool Signed);
273 
274   bool expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU, SMLoc IDLoc,
275                    MCStreamer &Out, const MCSubtargetInfo *STI);
276 
277   bool expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc, MCStreamer &Out,
278                  const MCSubtargetInfo *STI);
279 
280   bool expandUsh(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
281                  const MCSubtargetInfo *STI);
282 
283   bool expandUxw(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
284                  const MCSubtargetInfo *STI);
285 
286   bool expandSge(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
287                  const MCSubtargetInfo *STI);
288 
289   bool expandSgeImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
290                     const MCSubtargetInfo *STI);
291 
292   bool expandSgtImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
293                     const MCSubtargetInfo *STI);
294 
295   bool expandRotation(MCInst &Inst, SMLoc IDLoc,
296                       MCStreamer &Out, const MCSubtargetInfo *STI);
297   bool expandRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
298                          const MCSubtargetInfo *STI);
299   bool expandDRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
300                        const MCSubtargetInfo *STI);
301   bool expandDRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
302                           const MCSubtargetInfo *STI);
303 
304   bool expandAbs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
305                  const MCSubtargetInfo *STI);
306 
307   bool expandMulImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
308                     const MCSubtargetInfo *STI);
309 
310   bool expandMulO(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
311                   const MCSubtargetInfo *STI);
312 
313   bool expandMulOU(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
314                    const MCSubtargetInfo *STI);
315 
316   bool expandDMULMacro(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
317                        const MCSubtargetInfo *STI);
318 
319   bool expandLoadStoreDMacro(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
320                              const MCSubtargetInfo *STI, bool IsLoad);
321 
322   bool expandStoreDM1Macro(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
323                            const MCSubtargetInfo *STI);
324 
325   bool expandSeq(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
326                  const MCSubtargetInfo *STI);
327 
328   bool expandSeqI(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
329                   const MCSubtargetInfo *STI);
330 
331   bool expandMXTRAlias(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
332                        const MCSubtargetInfo *STI);
333 
334   bool expandSaaAddr(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
335                      const MCSubtargetInfo *STI);
336 
337   bool reportParseError(Twine ErrorMsg);
338   bool reportParseError(SMLoc Loc, Twine ErrorMsg);
339 
340   bool parseMemOffset(const MCExpr *&Res, bool isParenExpr);
341 
342   bool isEvaluated(const MCExpr *Expr);
343   bool parseSetMips0Directive();
344   bool parseSetArchDirective();
345   bool parseSetFeature(uint64_t Feature);
346   bool isPicAndNotNxxAbi(); // Used by .cpload, .cprestore, and .cpsetup.
347   bool parseDirectiveCpLoad(SMLoc Loc);
348   bool parseDirectiveCpLocal(SMLoc Loc);
349   bool parseDirectiveCpRestore(SMLoc Loc);
350   bool parseDirectiveCPSetup();
351   bool parseDirectiveCPReturn();
352   bool parseDirectiveNaN();
353   bool parseDirectiveSet();
354   bool parseDirectiveOption();
355   bool parseInsnDirective();
356   bool parseRSectionDirective(StringRef Section);
357   bool parseSSectionDirective(StringRef Section, unsigned Type);
358 
359   bool parseSetAtDirective();
360   bool parseSetNoAtDirective();
361   bool parseSetMacroDirective();
362   bool parseSetNoMacroDirective();
363   bool parseSetMsaDirective();
364   bool parseSetNoMsaDirective();
365   bool parseSetNoDspDirective();
366   bool parseSetReorderDirective();
367   bool parseSetNoReorderDirective();
368   bool parseSetMips16Directive();
369   bool parseSetNoMips16Directive();
370   bool parseSetFpDirective();
371   bool parseSetOddSPRegDirective();
372   bool parseSetNoOddSPRegDirective();
373   bool parseSetPopDirective();
374   bool parseSetPushDirective();
375   bool parseSetSoftFloatDirective();
376   bool parseSetHardFloatDirective();
377   bool parseSetMtDirective();
378   bool parseSetNoMtDirective();
379   bool parseSetNoCRCDirective();
380   bool parseSetNoVirtDirective();
381   bool parseSetNoGINVDirective();
382 
383   bool parseSetAssignment();
384 
385   bool parseDirectiveGpWord();
386   bool parseDirectiveGpDWord();
387   bool parseDirectiveDtpRelWord();
388   bool parseDirectiveDtpRelDWord();
389   bool parseDirectiveTpRelWord();
390   bool parseDirectiveTpRelDWord();
391   bool parseDirectiveModule();
392   bool parseDirectiveModuleFP();
393   bool parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
394                        StringRef Directive);
395 
396   bool parseInternalDirectiveReallowModule();
397 
398   bool eatComma(StringRef ErrorStr);
399 
400   int matchCPURegisterName(StringRef Symbol);
401 
402   int matchHWRegsRegisterName(StringRef Symbol);
403 
404   int matchFPURegisterName(StringRef Name);
405 
406   int matchFCCRegisterName(StringRef Name);
407 
408   int matchACRegisterName(StringRef Name);
409 
410   int matchMSA128RegisterName(StringRef Name);
411 
412   int matchMSA128CtrlRegisterName(StringRef Name);
413 
414   unsigned getReg(int RC, int RegNo);
415 
416   /// Returns the internal register number for the current AT. Also checks if
417   /// the current AT is unavailable (set to $0) and gives an error if it is.
418   /// This should be used in pseudo-instruction expansions which need AT.
419   unsigned getATReg(SMLoc Loc);
420 
421   bool canUseATReg();
422 
423   bool processInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
424                           const MCSubtargetInfo *STI);
425 
426   // Helper function that checks if the value of a vector index is within the
427   // boundaries of accepted values for each RegisterKind
428   // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
429   bool validateMSAIndex(int Val, int RegKind);
430 
431   // Selects a new architecture by updating the FeatureBits with the necessary
432   // info including implied dependencies.
433   // Internally, it clears all the feature bits related to *any* architecture
434   // and selects the new one using the ToggleFeature functionality of the
435   // MCSubtargetInfo object that handles implied dependencies. The reason we
436   // clear all the arch related bits manually is because ToggleFeature only
437   // clears the features that imply the feature being cleared and not the
438   // features implied by the feature being cleared. This is easier to see
439   // with an example:
440   //  --------------------------------------------------
441   // | Feature         | Implies                        |
442   // | -------------------------------------------------|
443   // | FeatureMips1    | None                           |
444   // | FeatureMips2    | FeatureMips1                   |
445   // | FeatureMips3    | FeatureMips2 | FeatureMipsGP64 |
446   // | FeatureMips4    | FeatureMips3                   |
447   // | ...             |                                |
448   //  --------------------------------------------------
449   //
450   // Setting Mips3 is equivalent to set: (FeatureMips3 | FeatureMips2 |
451   // FeatureMipsGP64 | FeatureMips1)
452   // Clearing Mips3 is equivalent to clear (FeatureMips3 | FeatureMips4).
453   void selectArch(StringRef ArchFeature) {
454     MCSubtargetInfo &STI = copySTI();
455     FeatureBitset FeatureBits = STI.getFeatureBits();
456     FeatureBits &= ~MipsAssemblerOptions::AllArchRelatedMask;
457     STI.setFeatureBits(FeatureBits);
458     setAvailableFeatures(
459         ComputeAvailableFeatures(STI.ToggleFeature(ArchFeature)));
460     AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
461   }
462 
463   void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
464     if (!(getSTI().getFeatureBits()[Feature])) {
465       MCSubtargetInfo &STI = copySTI();
466       setAvailableFeatures(
467           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
468       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
469     }
470   }
471 
472   void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
473     if (getSTI().getFeatureBits()[Feature]) {
474       MCSubtargetInfo &STI = copySTI();
475       setAvailableFeatures(
476           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
477       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
478     }
479   }
480 
481   void setModuleFeatureBits(uint64_t Feature, StringRef FeatureString) {
482     setFeatureBits(Feature, FeatureString);
483     AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits());
484   }
485 
486   void clearModuleFeatureBits(uint64_t Feature, StringRef FeatureString) {
487     clearFeatureBits(Feature, FeatureString);
488     AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits());
489   }
490 
491 public:
492   enum MipsMatchResultTy {
493     Match_RequiresDifferentSrcAndDst = FIRST_TARGET_MATCH_RESULT_TY,
494     Match_RequiresDifferentOperands,
495     Match_RequiresNoZeroRegister,
496     Match_RequiresSameSrcAndDst,
497     Match_NoFCCRegisterForCurrentISA,
498     Match_NonZeroOperandForSync,
499     Match_NonZeroOperandForMTCX,
500     Match_RequiresPosSizeRange0_32,
501     Match_RequiresPosSizeRange33_64,
502     Match_RequiresPosSizeUImm6,
503 #define GET_OPERAND_DIAGNOSTIC_TYPES
504 #include "MipsGenAsmMatcher.inc"
505 #undef GET_OPERAND_DIAGNOSTIC_TYPES
506   };
507 
508   MipsAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser,
509                 const MCInstrInfo &MII, const MCTargetOptions &Options)
510     : MCTargetAsmParser(Options, sti, MII),
511         ABI(MipsABIInfo::computeTargetABI(Triple(sti.getTargetTriple()),
512                                           sti.getCPU(), Options)) {
513     MCAsmParserExtension::Initialize(parser);
514 
515     parser.addAliasForDirective(".asciiz", ".asciz");
516     parser.addAliasForDirective(".hword", ".2byte");
517     parser.addAliasForDirective(".word", ".4byte");
518     parser.addAliasForDirective(".dword", ".8byte");
519 
520     // Initialize the set of available features.
521     setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
522 
523     // Remember the initial assembler options. The user can not modify these.
524     AssemblerOptions.push_back(
525         std::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits()));
526 
527     // Create an assembler options environment for the user to modify.
528     AssemblerOptions.push_back(
529         std::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits()));
530 
531     getTargetStreamer().updateABIInfo(*this);
532 
533     if (!isABI_O32() && !useOddSPReg() != 0)
534       report_fatal_error("-mno-odd-spreg requires the O32 ABI");
535 
536     CurrentFn = nullptr;
537 
538     IsPicEnabled = getContext().getObjectFileInfo()->isPositionIndependent();
539 
540     IsCpRestoreSet = false;
541     CpRestoreOffset = -1;
542     GPReg = ABI.GetGlobalPtr();
543 
544     const Triple &TheTriple = sti.getTargetTriple();
545     IsLittleEndian = TheTriple.isLittleEndian();
546 
547     if (getSTI().getCPU() == "mips64r6" && inMicroMipsMode())
548       report_fatal_error("microMIPS64R6 is not supported", false);
549 
550     if (!isABI_O32() && inMicroMipsMode())
551       report_fatal_error("microMIPS64 is not supported", false);
552   }
553 
554   /// True if all of $fcc0 - $fcc7 exist for the current ISA.
555   bool hasEightFccRegisters() const { return hasMips4() || hasMips32(); }
556 
557   bool isGP64bit() const {
558     return getSTI().getFeatureBits()[Mips::FeatureGP64Bit];
559   }
560 
561   bool isFP64bit() const {
562     return getSTI().getFeatureBits()[Mips::FeatureFP64Bit];
563   }
564 
565   const MipsABIInfo &getABI() const { return ABI; }
566   bool isABI_N32() const { return ABI.IsN32(); }
567   bool isABI_N64() const { return ABI.IsN64(); }
568   bool isABI_O32() const { return ABI.IsO32(); }
569   bool isABI_FPXX() const {
570     return getSTI().getFeatureBits()[Mips::FeatureFPXX];
571   }
572 
573   bool useOddSPReg() const {
574     return !(getSTI().getFeatureBits()[Mips::FeatureNoOddSPReg]);
575   }
576 
577   bool inMicroMipsMode() const {
578     return getSTI().getFeatureBits()[Mips::FeatureMicroMips];
579   }
580 
581   bool hasMips1() const {
582     return getSTI().getFeatureBits()[Mips::FeatureMips1];
583   }
584 
585   bool hasMips2() const {
586     return getSTI().getFeatureBits()[Mips::FeatureMips2];
587   }
588 
589   bool hasMips3() const {
590     return getSTI().getFeatureBits()[Mips::FeatureMips3];
591   }
592 
593   bool hasMips4() const {
594     return getSTI().getFeatureBits()[Mips::FeatureMips4];
595   }
596 
597   bool hasMips5() const {
598     return getSTI().getFeatureBits()[Mips::FeatureMips5];
599   }
600 
601   bool hasMips32() const {
602     return getSTI().getFeatureBits()[Mips::FeatureMips32];
603   }
604 
605   bool hasMips64() const {
606     return getSTI().getFeatureBits()[Mips::FeatureMips64];
607   }
608 
609   bool hasMips32r2() const {
610     return getSTI().getFeatureBits()[Mips::FeatureMips32r2];
611   }
612 
613   bool hasMips64r2() const {
614     return getSTI().getFeatureBits()[Mips::FeatureMips64r2];
615   }
616 
617   bool hasMips32r3() const {
618     return (getSTI().getFeatureBits()[Mips::FeatureMips32r3]);
619   }
620 
621   bool hasMips64r3() const {
622     return (getSTI().getFeatureBits()[Mips::FeatureMips64r3]);
623   }
624 
625   bool hasMips32r5() const {
626     return (getSTI().getFeatureBits()[Mips::FeatureMips32r5]);
627   }
628 
629   bool hasMips64r5() const {
630     return (getSTI().getFeatureBits()[Mips::FeatureMips64r5]);
631   }
632 
633   bool hasMips32r6() const {
634     return getSTI().getFeatureBits()[Mips::FeatureMips32r6];
635   }
636 
637   bool hasMips64r6() const {
638     return getSTI().getFeatureBits()[Mips::FeatureMips64r6];
639   }
640 
641   bool hasDSP() const {
642     return getSTI().getFeatureBits()[Mips::FeatureDSP];
643   }
644 
645   bool hasDSPR2() const {
646     return getSTI().getFeatureBits()[Mips::FeatureDSPR2];
647   }
648 
649   bool hasDSPR3() const {
650     return getSTI().getFeatureBits()[Mips::FeatureDSPR3];
651   }
652 
653   bool hasMSA() const {
654     return getSTI().getFeatureBits()[Mips::FeatureMSA];
655   }
656 
657   bool hasCnMips() const {
658     return (getSTI().getFeatureBits()[Mips::FeatureCnMips]);
659   }
660 
661   bool hasCnMipsP() const {
662     return (getSTI().getFeatureBits()[Mips::FeatureCnMipsP]);
663   }
664 
665   bool inPicMode() {
666     return IsPicEnabled;
667   }
668 
669   bool inMips16Mode() const {
670     return getSTI().getFeatureBits()[Mips::FeatureMips16];
671   }
672 
673   bool useTraps() const {
674     return getSTI().getFeatureBits()[Mips::FeatureUseTCCInDIV];
675   }
676 
677   bool useSoftFloat() const {
678     return getSTI().getFeatureBits()[Mips::FeatureSoftFloat];
679   }
680   bool hasMT() const {
681     return getSTI().getFeatureBits()[Mips::FeatureMT];
682   }
683 
684   bool hasCRC() const {
685     return getSTI().getFeatureBits()[Mips::FeatureCRC];
686   }
687 
688   bool hasVirt() const {
689     return getSTI().getFeatureBits()[Mips::FeatureVirt];
690   }
691 
692   bool hasGINV() const {
693     return getSTI().getFeatureBits()[Mips::FeatureGINV];
694   }
695 
696   /// Warn if RegIndex is the same as the current AT.
697   void warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc);
698 
699   void warnIfNoMacro(SMLoc Loc);
700 
701   bool isLittle() const { return IsLittleEndian; }
702 
703   const MCExpr *createTargetUnaryExpr(const MCExpr *E,
704                                       AsmToken::TokenKind OperatorToken,
705                                       MCContext &Ctx) override {
706     switch(OperatorToken) {
707     default:
708       llvm_unreachable("Unknown token");
709       return nullptr;
710     case AsmToken::PercentCall16:
711       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, E, Ctx);
712     case AsmToken::PercentCall_Hi:
713       return MipsMCExpr::create(MipsMCExpr::MEK_CALL_HI16, E, Ctx);
714     case AsmToken::PercentCall_Lo:
715       return MipsMCExpr::create(MipsMCExpr::MEK_CALL_LO16, E, Ctx);
716     case AsmToken::PercentDtprel_Hi:
717       return MipsMCExpr::create(MipsMCExpr::MEK_DTPREL_HI, E, Ctx);
718     case AsmToken::PercentDtprel_Lo:
719       return MipsMCExpr::create(MipsMCExpr::MEK_DTPREL_LO, E, Ctx);
720     case AsmToken::PercentGot:
721       return MipsMCExpr::create(MipsMCExpr::MEK_GOT, E, Ctx);
722     case AsmToken::PercentGot_Disp:
723       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_DISP, E, Ctx);
724     case AsmToken::PercentGot_Hi:
725       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_HI16, E, Ctx);
726     case AsmToken::PercentGot_Lo:
727       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_LO16, E, Ctx);
728     case AsmToken::PercentGot_Ofst:
729       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_OFST, E, Ctx);
730     case AsmToken::PercentGot_Page:
731       return MipsMCExpr::create(MipsMCExpr::MEK_GOT_PAGE, E, Ctx);
732     case AsmToken::PercentGottprel:
733       return MipsMCExpr::create(MipsMCExpr::MEK_GOTTPREL, E, Ctx);
734     case AsmToken::PercentGp_Rel:
735       return MipsMCExpr::create(MipsMCExpr::MEK_GPREL, E, Ctx);
736     case AsmToken::PercentHi:
737       return MipsMCExpr::create(MipsMCExpr::MEK_HI, E, Ctx);
738     case AsmToken::PercentHigher:
739       return MipsMCExpr::create(MipsMCExpr::MEK_HIGHER, E, Ctx);
740     case AsmToken::PercentHighest:
741       return MipsMCExpr::create(MipsMCExpr::MEK_HIGHEST, E, Ctx);
742     case AsmToken::PercentLo:
743       return MipsMCExpr::create(MipsMCExpr::MEK_LO, E, Ctx);
744     case AsmToken::PercentNeg:
745       return MipsMCExpr::create(MipsMCExpr::MEK_NEG, E, Ctx);
746     case AsmToken::PercentPcrel_Hi:
747       return MipsMCExpr::create(MipsMCExpr::MEK_PCREL_HI16, E, Ctx);
748     case AsmToken::PercentPcrel_Lo:
749       return MipsMCExpr::create(MipsMCExpr::MEK_PCREL_LO16, E, Ctx);
750     case AsmToken::PercentTlsgd:
751       return MipsMCExpr::create(MipsMCExpr::MEK_TLSGD, E, Ctx);
752     case AsmToken::PercentTlsldm:
753       return MipsMCExpr::create(MipsMCExpr::MEK_TLSLDM, E, Ctx);
754     case AsmToken::PercentTprel_Hi:
755       return MipsMCExpr::create(MipsMCExpr::MEK_TPREL_HI, E, Ctx);
756     case AsmToken::PercentTprel_Lo:
757       return MipsMCExpr::create(MipsMCExpr::MEK_TPREL_LO, E, Ctx);
758     }
759   }
760 };
761 
762 /// MipsOperand - Instances of this class represent a parsed Mips machine
763 /// instruction.
764 class MipsOperand : public MCParsedAsmOperand {
765 public:
766   /// Broad categories of register classes
767   /// The exact class is finalized by the render method.
768   enum RegKind {
769     RegKind_GPR = 1,      /// GPR32 and GPR64 (depending on isGP64bit())
770     RegKind_FGR = 2,      /// FGR32, FGR64, AFGR64 (depending on context and
771                           /// isFP64bit())
772     RegKind_FCC = 4,      /// FCC
773     RegKind_MSA128 = 8,   /// MSA128[BHWD] (makes no difference which)
774     RegKind_MSACtrl = 16, /// MSA control registers
775     RegKind_COP2 = 32,    /// COP2
776     RegKind_ACC = 64,     /// HI32DSP, LO32DSP, and ACC64DSP (depending on
777                           /// context).
778     RegKind_CCR = 128,    /// CCR
779     RegKind_HWRegs = 256, /// HWRegs
780     RegKind_COP3 = 512,   /// COP3
781     RegKind_COP0 = 1024,  /// COP0
782     /// Potentially any (e.g. $1)
783     RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 |
784                       RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC |
785                       RegKind_CCR | RegKind_HWRegs | RegKind_COP3 | RegKind_COP0
786   };
787 
788 private:
789   enum KindTy {
790     k_Immediate,     /// An immediate (possibly involving symbol references)
791     k_Memory,        /// Base + Offset Memory Address
792     k_RegisterIndex, /// A register index in one or more RegKind.
793     k_Token,         /// A simple token
794     k_RegList,       /// A physical register list
795   } Kind;
796 
797 public:
798   MipsOperand(KindTy K, MipsAsmParser &Parser)
799       : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {}
800 
801   ~MipsOperand() override {
802     switch (Kind) {
803     case k_Memory:
804       delete Mem.Base;
805       break;
806     case k_RegList:
807       delete RegList.List;
808       break;
809     case k_Immediate:
810     case k_RegisterIndex:
811     case k_Token:
812       break;
813     }
814   }
815 
816 private:
817   /// For diagnostics, and checking the assembler temporary
818   MipsAsmParser &AsmParser;
819 
820   struct Token {
821     const char *Data;
822     unsigned Length;
823   };
824 
825   struct RegIdxOp {
826     unsigned Index; /// Index into the register class
827     RegKind Kind;   /// Bitfield of the kinds it could possibly be
828     struct Token Tok; /// The input token this operand originated from.
829     const MCRegisterInfo *RegInfo;
830   };
831 
832   struct ImmOp {
833     const MCExpr *Val;
834   };
835 
836   struct MemOp {
837     MipsOperand *Base;
838     const MCExpr *Off;
839   };
840 
841   struct RegListOp {
842     SmallVector<unsigned, 10> *List;
843   };
844 
845   union {
846     struct Token Tok;
847     struct RegIdxOp RegIdx;
848     struct ImmOp Imm;
849     struct MemOp Mem;
850     struct RegListOp RegList;
851   };
852 
853   SMLoc StartLoc, EndLoc;
854 
855   /// Internal constructor for register kinds
856   static std::unique_ptr<MipsOperand> CreateReg(unsigned Index, StringRef Str,
857                                                 RegKind RegKind,
858                                                 const MCRegisterInfo *RegInfo,
859                                                 SMLoc S, SMLoc E,
860                                                 MipsAsmParser &Parser) {
861     auto Op = std::make_unique<MipsOperand>(k_RegisterIndex, Parser);
862     Op->RegIdx.Index = Index;
863     Op->RegIdx.RegInfo = RegInfo;
864     Op->RegIdx.Kind = RegKind;
865     Op->RegIdx.Tok.Data = Str.data();
866     Op->RegIdx.Tok.Length = Str.size();
867     Op->StartLoc = S;
868     Op->EndLoc = E;
869     return Op;
870   }
871 
872 public:
873   /// Coerce the register to GPR32 and return the real register for the current
874   /// target.
875   unsigned getGPR32Reg() const {
876     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
877     AsmParser.warnIfRegIndexIsAT(RegIdx.Index, StartLoc);
878     unsigned ClassID = Mips::GPR32RegClassID;
879     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
880   }
881 
882   /// Coerce the register to GPR32 and return the real register for the current
883   /// target.
884   unsigned getGPRMM16Reg() const {
885     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
886     unsigned ClassID = Mips::GPR32RegClassID;
887     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
888   }
889 
890   /// Coerce the register to GPR64 and return the real register for the current
891   /// target.
892   unsigned getGPR64Reg() const {
893     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
894     unsigned ClassID = Mips::GPR64RegClassID;
895     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
896   }
897 
898 private:
899   /// Coerce the register to AFGR64 and return the real register for the current
900   /// target.
901   unsigned getAFGR64Reg() const {
902     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
903     if (RegIdx.Index % 2 != 0)
904       AsmParser.Warning(StartLoc, "Float register should be even.");
905     return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID)
906         .getRegister(RegIdx.Index / 2);
907   }
908 
909   /// Coerce the register to FGR64 and return the real register for the current
910   /// target.
911   unsigned getFGR64Reg() const {
912     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
913     return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID)
914         .getRegister(RegIdx.Index);
915   }
916 
917   /// Coerce the register to FGR32 and return the real register for the current
918   /// target.
919   unsigned getFGR32Reg() const {
920     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
921     return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID)
922         .getRegister(RegIdx.Index);
923   }
924 
925   /// Coerce the register to FCC and return the real register for the current
926   /// target.
927   unsigned getFCCReg() const {
928     assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!");
929     return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID)
930         .getRegister(RegIdx.Index);
931   }
932 
933   /// Coerce the register to MSA128 and return the real register for the current
934   /// target.
935   unsigned getMSA128Reg() const {
936     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!");
937     // It doesn't matter which of the MSA128[BHWD] classes we use. They are all
938     // identical
939     unsigned ClassID = Mips::MSA128BRegClassID;
940     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
941   }
942 
943   /// Coerce the register to MSACtrl and return the real register for the
944   /// current target.
945   unsigned getMSACtrlReg() const {
946     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!");
947     unsigned ClassID = Mips::MSACtrlRegClassID;
948     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
949   }
950 
951   /// Coerce the register to COP0 and return the real register for the
952   /// current target.
953   unsigned getCOP0Reg() const {
954     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP0) && "Invalid access!");
955     unsigned ClassID = Mips::COP0RegClassID;
956     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
957   }
958 
959   /// Coerce the register to COP2 and return the real register for the
960   /// current target.
961   unsigned getCOP2Reg() const {
962     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!");
963     unsigned ClassID = Mips::COP2RegClassID;
964     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
965   }
966 
967   /// Coerce the register to COP3 and return the real register for the
968   /// current target.
969   unsigned getCOP3Reg() const {
970     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP3) && "Invalid access!");
971     unsigned ClassID = Mips::COP3RegClassID;
972     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
973   }
974 
975   /// Coerce the register to ACC64DSP and return the real register for the
976   /// current target.
977   unsigned getACC64DSPReg() const {
978     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
979     unsigned ClassID = Mips::ACC64DSPRegClassID;
980     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
981   }
982 
983   /// Coerce the register to HI32DSP and return the real register for the
984   /// current target.
985   unsigned getHI32DSPReg() const {
986     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
987     unsigned ClassID = Mips::HI32DSPRegClassID;
988     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
989   }
990 
991   /// Coerce the register to LO32DSP and return the real register for the
992   /// current target.
993   unsigned getLO32DSPReg() const {
994     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
995     unsigned ClassID = Mips::LO32DSPRegClassID;
996     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
997   }
998 
999   /// Coerce the register to CCR and return the real register for the
1000   /// current target.
1001   unsigned getCCRReg() const {
1002     assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!");
1003     unsigned ClassID = Mips::CCRRegClassID;
1004     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
1005   }
1006 
1007   /// Coerce the register to HWRegs and return the real register for the
1008   /// current target.
1009   unsigned getHWRegsReg() const {
1010     assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!");
1011     unsigned ClassID = Mips::HWRegsRegClassID;
1012     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
1013   }
1014 
1015 public:
1016   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1017     // Add as immediate when possible.  Null MCExpr = 0.
1018     if (!Expr)
1019       Inst.addOperand(MCOperand::createImm(0));
1020     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1021       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1022     else
1023       Inst.addOperand(MCOperand::createExpr(Expr));
1024   }
1025 
1026   void addRegOperands(MCInst &Inst, unsigned N) const {
1027     llvm_unreachable("Use a custom parser instead");
1028   }
1029 
1030   /// Render the operand to an MCInst as a GPR32
1031   /// Asserts if the wrong number of operands are requested, or the operand
1032   /// is not a k_RegisterIndex compatible with RegKind_GPR
1033   void addGPR32ZeroAsmRegOperands(MCInst &Inst, unsigned N) const {
1034     assert(N == 1 && "Invalid number of operands!");
1035     Inst.addOperand(MCOperand::createReg(getGPR32Reg()));
1036   }
1037 
1038   void addGPR32NonZeroAsmRegOperands(MCInst &Inst, unsigned N) const {
1039     assert(N == 1 && "Invalid number of operands!");
1040     Inst.addOperand(MCOperand::createReg(getGPR32Reg()));
1041   }
1042 
1043   void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const {
1044     assert(N == 1 && "Invalid number of operands!");
1045     Inst.addOperand(MCOperand::createReg(getGPR32Reg()));
1046   }
1047 
1048   void addGPRMM16AsmRegOperands(MCInst &Inst, unsigned N) const {
1049     assert(N == 1 && "Invalid number of operands!");
1050     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
1051   }
1052 
1053   void addGPRMM16AsmRegZeroOperands(MCInst &Inst, unsigned N) const {
1054     assert(N == 1 && "Invalid number of operands!");
1055     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
1056   }
1057 
1058   void addGPRMM16AsmRegMovePOperands(MCInst &Inst, unsigned N) const {
1059     assert(N == 1 && "Invalid number of operands!");
1060     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
1061   }
1062 
1063   void addGPRMM16AsmRegMovePPairFirstOperands(MCInst &Inst, unsigned N) const {
1064     assert(N == 1 && "Invalid number of operands!");
1065     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
1066   }
1067 
1068   void addGPRMM16AsmRegMovePPairSecondOperands(MCInst &Inst,
1069                                                unsigned N) const {
1070     assert(N == 1 && "Invalid number of operands!");
1071     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
1072   }
1073 
1074   /// Render the operand to an MCInst as a GPR64
1075   /// Asserts if the wrong number of operands are requested, or the operand
1076   /// is not a k_RegisterIndex compatible with RegKind_GPR
1077   void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const {
1078     assert(N == 1 && "Invalid number of operands!");
1079     Inst.addOperand(MCOperand::createReg(getGPR64Reg()));
1080   }
1081 
1082   void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
1083     assert(N == 1 && "Invalid number of operands!");
1084     Inst.addOperand(MCOperand::createReg(getAFGR64Reg()));
1085   }
1086 
1087   void addStrictlyAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
1088     assert(N == 1 && "Invalid number of operands!");
1089     Inst.addOperand(MCOperand::createReg(getAFGR64Reg()));
1090   }
1091 
1092   void addStrictlyFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
1093     assert(N == 1 && "Invalid number of operands!");
1094     Inst.addOperand(MCOperand::createReg(getFGR64Reg()));
1095   }
1096 
1097   void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
1098     assert(N == 1 && "Invalid number of operands!");
1099     Inst.addOperand(MCOperand::createReg(getFGR64Reg()));
1100   }
1101 
1102   void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
1103     assert(N == 1 && "Invalid number of operands!");
1104     Inst.addOperand(MCOperand::createReg(getFGR32Reg()));
1105     // FIXME: We ought to do this for -integrated-as without -via-file-asm too.
1106     // FIXME: This should propagate failure up to parseStatement.
1107     if (!AsmParser.useOddSPReg() && RegIdx.Index & 1)
1108       AsmParser.getParser().printError(
1109           StartLoc, "-mno-odd-spreg prohibits the use of odd FPU "
1110                     "registers");
1111   }
1112 
1113   void addStrictlyFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
1114     assert(N == 1 && "Invalid number of operands!");
1115     Inst.addOperand(MCOperand::createReg(getFGR32Reg()));
1116     // FIXME: We ought to do this for -integrated-as without -via-file-asm too.
1117     if (!AsmParser.useOddSPReg() && RegIdx.Index & 1)
1118       AsmParser.Error(StartLoc, "-mno-odd-spreg prohibits the use of odd FPU "
1119                                 "registers");
1120   }
1121 
1122   void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const {
1123     assert(N == 1 && "Invalid number of operands!");
1124     Inst.addOperand(MCOperand::createReg(getFCCReg()));
1125   }
1126 
1127   void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const {
1128     assert(N == 1 && "Invalid number of operands!");
1129     Inst.addOperand(MCOperand::createReg(getMSA128Reg()));
1130   }
1131 
1132   void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const {
1133     assert(N == 1 && "Invalid number of operands!");
1134     Inst.addOperand(MCOperand::createReg(getMSACtrlReg()));
1135   }
1136 
1137   void addCOP0AsmRegOperands(MCInst &Inst, unsigned N) const {
1138     assert(N == 1 && "Invalid number of operands!");
1139     Inst.addOperand(MCOperand::createReg(getCOP0Reg()));
1140   }
1141 
1142   void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const {
1143     assert(N == 1 && "Invalid number of operands!");
1144     Inst.addOperand(MCOperand::createReg(getCOP2Reg()));
1145   }
1146 
1147   void addCOP3AsmRegOperands(MCInst &Inst, unsigned N) const {
1148     assert(N == 1 && "Invalid number of operands!");
1149     Inst.addOperand(MCOperand::createReg(getCOP3Reg()));
1150   }
1151 
1152   void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
1153     assert(N == 1 && "Invalid number of operands!");
1154     Inst.addOperand(MCOperand::createReg(getACC64DSPReg()));
1155   }
1156 
1157   void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
1158     assert(N == 1 && "Invalid number of operands!");
1159     Inst.addOperand(MCOperand::createReg(getHI32DSPReg()));
1160   }
1161 
1162   void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
1163     assert(N == 1 && "Invalid number of operands!");
1164     Inst.addOperand(MCOperand::createReg(getLO32DSPReg()));
1165   }
1166 
1167   void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const {
1168     assert(N == 1 && "Invalid number of operands!");
1169     Inst.addOperand(MCOperand::createReg(getCCRReg()));
1170   }
1171 
1172   void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const {
1173     assert(N == 1 && "Invalid number of operands!");
1174     Inst.addOperand(MCOperand::createReg(getHWRegsReg()));
1175   }
1176 
1177   template <unsigned Bits, int Offset = 0, int AdjustOffset = 0>
1178   void addConstantUImmOperands(MCInst &Inst, unsigned N) const {
1179     assert(N == 1 && "Invalid number of operands!");
1180     uint64_t Imm = getConstantImm() - Offset;
1181     Imm &= (1ULL << Bits) - 1;
1182     Imm += Offset;
1183     Imm += AdjustOffset;
1184     Inst.addOperand(MCOperand::createImm(Imm));
1185   }
1186 
1187   template <unsigned Bits>
1188   void addSImmOperands(MCInst &Inst, unsigned N) const {
1189     if (isImm() && !isConstantImm()) {
1190       addExpr(Inst, getImm());
1191       return;
1192     }
1193     addConstantSImmOperands<Bits, 0, 0>(Inst, N);
1194   }
1195 
1196   template <unsigned Bits>
1197   void addUImmOperands(MCInst &Inst, unsigned N) const {
1198     if (isImm() && !isConstantImm()) {
1199       addExpr(Inst, getImm());
1200       return;
1201     }
1202     addConstantUImmOperands<Bits, 0, 0>(Inst, N);
1203   }
1204 
1205   template <unsigned Bits, int Offset = 0, int AdjustOffset = 0>
1206   void addConstantSImmOperands(MCInst &Inst, unsigned N) const {
1207     assert(N == 1 && "Invalid number of operands!");
1208     int64_t Imm = getConstantImm() - Offset;
1209     Imm = SignExtend64<Bits>(Imm);
1210     Imm += Offset;
1211     Imm += AdjustOffset;
1212     Inst.addOperand(MCOperand::createImm(Imm));
1213   }
1214 
1215   void addImmOperands(MCInst &Inst, unsigned N) const {
1216     assert(N == 1 && "Invalid number of operands!");
1217     const MCExpr *Expr = getImm();
1218     addExpr(Inst, Expr);
1219   }
1220 
1221   void addMemOperands(MCInst &Inst, unsigned N) const {
1222     assert(N == 2 && "Invalid number of operands!");
1223 
1224     Inst.addOperand(MCOperand::createReg(AsmParser.getABI().ArePtrs64bit()
1225                                              ? getMemBase()->getGPR64Reg()
1226                                              : getMemBase()->getGPR32Reg()));
1227 
1228     const MCExpr *Expr = getMemOff();
1229     addExpr(Inst, Expr);
1230   }
1231 
1232   void addMicroMipsMemOperands(MCInst &Inst, unsigned N) const {
1233     assert(N == 2 && "Invalid number of operands!");
1234 
1235     Inst.addOperand(MCOperand::createReg(getMemBase()->getGPRMM16Reg()));
1236 
1237     const MCExpr *Expr = getMemOff();
1238     addExpr(Inst, Expr);
1239   }
1240 
1241   void addRegListOperands(MCInst &Inst, unsigned N) const {
1242     assert(N == 1 && "Invalid number of operands!");
1243 
1244     for (auto RegNo : getRegList())
1245       Inst.addOperand(MCOperand::createReg(RegNo));
1246   }
1247 
1248   bool isReg() const override {
1249     // As a special case until we sort out the definition of div/divu, accept
1250     // $0/$zero here so that MCK_ZERO works correctly.
1251     return isGPRAsmReg() && RegIdx.Index == 0;
1252   }
1253 
1254   bool isRegIdx() const { return Kind == k_RegisterIndex; }
1255   bool isImm() const override { return Kind == k_Immediate; }
1256 
1257   bool isConstantImm() const {
1258     int64_t Res;
1259     return isImm() && getImm()->evaluateAsAbsolute(Res);
1260   }
1261 
1262   bool isConstantImmz() const {
1263     return isConstantImm() && getConstantImm() == 0;
1264   }
1265 
1266   template <unsigned Bits, int Offset = 0> bool isConstantUImm() const {
1267     return isConstantImm() && isUInt<Bits>(getConstantImm() - Offset);
1268   }
1269 
1270   template <unsigned Bits> bool isSImm() const {
1271     return isConstantImm() ? isInt<Bits>(getConstantImm()) : isImm();
1272   }
1273 
1274   template <unsigned Bits> bool isUImm() const {
1275     return isConstantImm() ? isUInt<Bits>(getConstantImm()) : isImm();
1276   }
1277 
1278   template <unsigned Bits> bool isAnyImm() const {
1279     return isConstantImm() ? (isInt<Bits>(getConstantImm()) ||
1280                               isUInt<Bits>(getConstantImm()))
1281                            : isImm();
1282   }
1283 
1284   template <unsigned Bits, int Offset = 0> bool isConstantSImm() const {
1285     return isConstantImm() && isInt<Bits>(getConstantImm() - Offset);
1286   }
1287 
1288   template <unsigned Bottom, unsigned Top> bool isConstantUImmRange() const {
1289     return isConstantImm() && getConstantImm() >= Bottom &&
1290            getConstantImm() <= Top;
1291   }
1292 
1293   bool isToken() const override {
1294     // Note: It's not possible to pretend that other operand kinds are tokens.
1295     // The matcher emitter checks tokens first.
1296     return Kind == k_Token;
1297   }
1298 
1299   bool isMem() const override { return Kind == k_Memory; }
1300 
1301   bool isConstantMemOff() const {
1302     return isMem() && isa<MCConstantExpr>(getMemOff());
1303   }
1304 
1305   // Allow relocation operators.
1306   // FIXME: This predicate and others need to look through binary expressions
1307   //        and determine whether a Value is a constant or not.
1308   template <unsigned Bits, unsigned ShiftAmount = 0>
1309   bool isMemWithSimmOffset() const {
1310     if (!isMem())
1311       return false;
1312     if (!getMemBase()->isGPRAsmReg())
1313       return false;
1314     if (isa<MCTargetExpr>(getMemOff()) ||
1315         (isConstantMemOff() &&
1316          isShiftedInt<Bits, ShiftAmount>(getConstantMemOff())))
1317       return true;
1318     MCValue Res;
1319     bool IsReloc = getMemOff()->evaluateAsRelocatable(Res, nullptr, nullptr);
1320     return IsReloc && isShiftedInt<Bits, ShiftAmount>(Res.getConstant());
1321   }
1322 
1323   bool isMemWithPtrSizeOffset() const {
1324     if (!isMem())
1325       return false;
1326     if (!getMemBase()->isGPRAsmReg())
1327       return false;
1328     const unsigned PtrBits = AsmParser.getABI().ArePtrs64bit() ? 64 : 32;
1329     if (isa<MCTargetExpr>(getMemOff()) ||
1330         (isConstantMemOff() && isIntN(PtrBits, getConstantMemOff())))
1331       return true;
1332     MCValue Res;
1333     bool IsReloc = getMemOff()->evaluateAsRelocatable(Res, nullptr, nullptr);
1334     return IsReloc && isIntN(PtrBits, Res.getConstant());
1335   }
1336 
1337   bool isMemWithGRPMM16Base() const {
1338     return isMem() && getMemBase()->isMM16AsmReg();
1339   }
1340 
1341   template <unsigned Bits> bool isMemWithUimmOffsetSP() const {
1342     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
1343       && getMemBase()->isRegIdx() && (getMemBase()->getGPR32Reg() == Mips::SP);
1344   }
1345 
1346   template <unsigned Bits> bool isMemWithUimmWordAlignedOffsetSP() const {
1347     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
1348       && (getConstantMemOff() % 4 == 0) && getMemBase()->isRegIdx()
1349       && (getMemBase()->getGPR32Reg() == Mips::SP);
1350   }
1351 
1352   template <unsigned Bits> bool isMemWithSimmWordAlignedOffsetGP() const {
1353     return isMem() && isConstantMemOff() && isInt<Bits>(getConstantMemOff())
1354       && (getConstantMemOff() % 4 == 0) && getMemBase()->isRegIdx()
1355       && (getMemBase()->getGPR32Reg() == Mips::GP);
1356   }
1357 
1358   template <unsigned Bits, unsigned ShiftLeftAmount>
1359   bool isScaledUImm() const {
1360     return isConstantImm() &&
1361            isShiftedUInt<Bits, ShiftLeftAmount>(getConstantImm());
1362   }
1363 
1364   template <unsigned Bits, unsigned ShiftLeftAmount>
1365   bool isScaledSImm() const {
1366     if (isConstantImm() &&
1367         isShiftedInt<Bits, ShiftLeftAmount>(getConstantImm()))
1368       return true;
1369     // Operand can also be a symbol or symbol plus
1370     // offset in case of relocations.
1371     if (Kind != k_Immediate)
1372       return false;
1373     MCValue Res;
1374     bool Success = getImm()->evaluateAsRelocatable(Res, nullptr, nullptr);
1375     return Success && isShiftedInt<Bits, ShiftLeftAmount>(Res.getConstant());
1376   }
1377 
1378   bool isRegList16() const {
1379     if (!isRegList())
1380       return false;
1381 
1382     int Size = RegList.List->size();
1383     if (Size < 2 || Size > 5)
1384       return false;
1385 
1386     unsigned R0 = RegList.List->front();
1387     unsigned R1 = RegList.List->back();
1388     if (!((R0 == Mips::S0 && R1 == Mips::RA) ||
1389           (R0 == Mips::S0_64 && R1 == Mips::RA_64)))
1390       return false;
1391 
1392     int PrevReg = *RegList.List->begin();
1393     for (int i = 1; i < Size - 1; i++) {
1394       int Reg = (*(RegList.List))[i];
1395       if ( Reg != PrevReg + 1)
1396         return false;
1397       PrevReg = Reg;
1398     }
1399 
1400     return true;
1401   }
1402 
1403   bool isInvNum() const { return Kind == k_Immediate; }
1404 
1405   bool isLSAImm() const {
1406     if (!isConstantImm())
1407       return false;
1408     int64_t Val = getConstantImm();
1409     return 1 <= Val && Val <= 4;
1410   }
1411 
1412   bool isRegList() const { return Kind == k_RegList; }
1413 
1414   StringRef getToken() const {
1415     assert(Kind == k_Token && "Invalid access!");
1416     return StringRef(Tok.Data, Tok.Length);
1417   }
1418 
1419   unsigned getReg() const override {
1420     // As a special case until we sort out the definition of div/divu, accept
1421     // $0/$zero here so that MCK_ZERO works correctly.
1422     if (Kind == k_RegisterIndex && RegIdx.Index == 0 &&
1423         RegIdx.Kind & RegKind_GPR)
1424       return getGPR32Reg(); // FIXME: GPR64 too
1425 
1426     llvm_unreachable("Invalid access!");
1427     return 0;
1428   }
1429 
1430   const MCExpr *getImm() const {
1431     assert((Kind == k_Immediate) && "Invalid access!");
1432     return Imm.Val;
1433   }
1434 
1435   int64_t getConstantImm() const {
1436     const MCExpr *Val = getImm();
1437     int64_t Value = 0;
1438     (void)Val->evaluateAsAbsolute(Value);
1439     return Value;
1440   }
1441 
1442   MipsOperand *getMemBase() const {
1443     assert((Kind == k_Memory) && "Invalid access!");
1444     return Mem.Base;
1445   }
1446 
1447   const MCExpr *getMemOff() const {
1448     assert((Kind == k_Memory) && "Invalid access!");
1449     return Mem.Off;
1450   }
1451 
1452   int64_t getConstantMemOff() const {
1453     return static_cast<const MCConstantExpr *>(getMemOff())->getValue();
1454   }
1455 
1456   const SmallVectorImpl<unsigned> &getRegList() const {
1457     assert((Kind == k_RegList) && "Invalid access!");
1458     return *(RegList.List);
1459   }
1460 
1461   static std::unique_ptr<MipsOperand> CreateToken(StringRef Str, SMLoc S,
1462                                                   MipsAsmParser &Parser) {
1463     auto Op = std::make_unique<MipsOperand>(k_Token, Parser);
1464     Op->Tok.Data = Str.data();
1465     Op->Tok.Length = Str.size();
1466     Op->StartLoc = S;
1467     Op->EndLoc = S;
1468     return Op;
1469   }
1470 
1471   /// Create a numeric register (e.g. $1). The exact register remains
1472   /// unresolved until an instruction successfully matches
1473   static std::unique_ptr<MipsOperand>
1474   createNumericReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1475                    SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1476     LLVM_DEBUG(dbgs() << "createNumericReg(" << Index << ", ...)\n");
1477     return CreateReg(Index, Str, RegKind_Numeric, RegInfo, S, E, Parser);
1478   }
1479 
1480   /// Create a register that is definitely a GPR.
1481   /// This is typically only used for named registers such as $gp.
1482   static std::unique_ptr<MipsOperand>
1483   createGPRReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1484                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1485     return CreateReg(Index, Str, RegKind_GPR, RegInfo, S, E, Parser);
1486   }
1487 
1488   /// Create a register that is definitely a FGR.
1489   /// This is typically only used for named registers such as $f0.
1490   static std::unique_ptr<MipsOperand>
1491   createFGRReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1492                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1493     return CreateReg(Index, Str, RegKind_FGR, RegInfo, S, E, Parser);
1494   }
1495 
1496   /// Create a register that is definitely a HWReg.
1497   /// This is typically only used for named registers such as $hwr_cpunum.
1498   static std::unique_ptr<MipsOperand>
1499   createHWRegsReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1500                   SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1501     return CreateReg(Index, Str, RegKind_HWRegs, RegInfo, S, E, Parser);
1502   }
1503 
1504   /// Create a register that is definitely an FCC.
1505   /// This is typically only used for named registers such as $fcc0.
1506   static std::unique_ptr<MipsOperand>
1507   createFCCReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1508                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1509     return CreateReg(Index, Str, RegKind_FCC, RegInfo, S, E, Parser);
1510   }
1511 
1512   /// Create a register that is definitely an ACC.
1513   /// This is typically only used for named registers such as $ac0.
1514   static std::unique_ptr<MipsOperand>
1515   createACCReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1516                SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1517     return CreateReg(Index, Str, RegKind_ACC, RegInfo, S, E, Parser);
1518   }
1519 
1520   /// Create a register that is definitely an MSA128.
1521   /// This is typically only used for named registers such as $w0.
1522   static std::unique_ptr<MipsOperand>
1523   createMSA128Reg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1524                   SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1525     return CreateReg(Index, Str, RegKind_MSA128, RegInfo, S, E, Parser);
1526   }
1527 
1528   /// Create a register that is definitely an MSACtrl.
1529   /// This is typically only used for named registers such as $msaaccess.
1530   static std::unique_ptr<MipsOperand>
1531   createMSACtrlReg(unsigned Index, StringRef Str, const MCRegisterInfo *RegInfo,
1532                    SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1533     return CreateReg(Index, Str, RegKind_MSACtrl, RegInfo, S, E, Parser);
1534   }
1535 
1536   static std::unique_ptr<MipsOperand>
1537   CreateImm(const MCExpr *Val, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1538     auto Op = std::make_unique<MipsOperand>(k_Immediate, Parser);
1539     Op->Imm.Val = Val;
1540     Op->StartLoc = S;
1541     Op->EndLoc = E;
1542     return Op;
1543   }
1544 
1545   static std::unique_ptr<MipsOperand>
1546   CreateMem(std::unique_ptr<MipsOperand> Base, const MCExpr *Off, SMLoc S,
1547             SMLoc E, MipsAsmParser &Parser) {
1548     auto Op = std::make_unique<MipsOperand>(k_Memory, Parser);
1549     Op->Mem.Base = Base.release();
1550     Op->Mem.Off = Off;
1551     Op->StartLoc = S;
1552     Op->EndLoc = E;
1553     return Op;
1554   }
1555 
1556   static std::unique_ptr<MipsOperand>
1557   CreateRegList(SmallVectorImpl<unsigned> &Regs, SMLoc StartLoc, SMLoc EndLoc,
1558                 MipsAsmParser &Parser) {
1559     assert(Regs.size() > 0 && "Empty list not allowed");
1560 
1561     auto Op = std::make_unique<MipsOperand>(k_RegList, Parser);
1562     Op->RegList.List = new SmallVector<unsigned, 10>(Regs.begin(), Regs.end());
1563     Op->StartLoc = StartLoc;
1564     Op->EndLoc = EndLoc;
1565     return Op;
1566   }
1567 
1568  bool isGPRZeroAsmReg() const {
1569     return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index == 0;
1570   }
1571 
1572  bool isGPRNonZeroAsmReg() const {
1573    return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index > 0 &&
1574           RegIdx.Index <= 31;
1575   }
1576 
1577   bool isGPRAsmReg() const {
1578     return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31;
1579   }
1580 
1581   bool isMM16AsmReg() const {
1582     if (!(isRegIdx() && RegIdx.Kind))
1583       return false;
1584     return ((RegIdx.Index >= 2 && RegIdx.Index <= 7)
1585             || RegIdx.Index == 16 || RegIdx.Index == 17);
1586 
1587   }
1588   bool isMM16AsmRegZero() const {
1589     if (!(isRegIdx() && RegIdx.Kind))
1590       return false;
1591     return (RegIdx.Index == 0 ||
1592             (RegIdx.Index >= 2 && RegIdx.Index <= 7) ||
1593             RegIdx.Index == 17);
1594   }
1595 
1596   bool isMM16AsmRegMoveP() const {
1597     if (!(isRegIdx() && RegIdx.Kind))
1598       return false;
1599     return (RegIdx.Index == 0 || (RegIdx.Index >= 2 && RegIdx.Index <= 3) ||
1600       (RegIdx.Index >= 16 && RegIdx.Index <= 20));
1601   }
1602 
1603   bool isMM16AsmRegMovePPairFirst() const {
1604     if (!(isRegIdx() && RegIdx.Kind))
1605       return false;
1606     return RegIdx.Index >= 4 && RegIdx.Index <= 6;
1607   }
1608 
1609   bool isMM16AsmRegMovePPairSecond() const {
1610     if (!(isRegIdx() && RegIdx.Kind))
1611       return false;
1612     return (RegIdx.Index == 21 || RegIdx.Index == 22 ||
1613       (RegIdx.Index >= 5 && RegIdx.Index <= 7));
1614   }
1615 
1616   bool isFGRAsmReg() const {
1617     // AFGR64 is $0-$15 but we handle this in getAFGR64()
1618     return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31;
1619   }
1620 
1621   bool isStrictlyFGRAsmReg() const {
1622     // AFGR64 is $0-$15 but we handle this in getAFGR64()
1623     return isRegIdx() && RegIdx.Kind == RegKind_FGR && RegIdx.Index <= 31;
1624   }
1625 
1626   bool isHWRegsAsmReg() const {
1627     return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31;
1628   }
1629 
1630   bool isCCRAsmReg() const {
1631     return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31;
1632   }
1633 
1634   bool isFCCAsmReg() const {
1635     if (!(isRegIdx() && RegIdx.Kind & RegKind_FCC))
1636       return false;
1637     return RegIdx.Index <= 7;
1638   }
1639 
1640   bool isACCAsmReg() const {
1641     return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3;
1642   }
1643 
1644   bool isCOP0AsmReg() const {
1645     return isRegIdx() && RegIdx.Kind & RegKind_COP0 && RegIdx.Index <= 31;
1646   }
1647 
1648   bool isCOP2AsmReg() const {
1649     return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31;
1650   }
1651 
1652   bool isCOP3AsmReg() const {
1653     return isRegIdx() && RegIdx.Kind & RegKind_COP3 && RegIdx.Index <= 31;
1654   }
1655 
1656   bool isMSA128AsmReg() const {
1657     return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31;
1658   }
1659 
1660   bool isMSACtrlAsmReg() const {
1661     return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7;
1662   }
1663 
1664   /// getStartLoc - Get the location of the first token of this operand.
1665   SMLoc getStartLoc() const override { return StartLoc; }
1666   /// getEndLoc - Get the location of the last token of this operand.
1667   SMLoc getEndLoc() const override { return EndLoc; }
1668 
1669   void print(raw_ostream &OS) const override {
1670     switch (Kind) {
1671     case k_Immediate:
1672       OS << "Imm<";
1673       OS << *Imm.Val;
1674       OS << ">";
1675       break;
1676     case k_Memory:
1677       OS << "Mem<";
1678       Mem.Base->print(OS);
1679       OS << ", ";
1680       OS << *Mem.Off;
1681       OS << ">";
1682       break;
1683     case k_RegisterIndex:
1684       OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ", "
1685          << StringRef(RegIdx.Tok.Data, RegIdx.Tok.Length) << ">";
1686       break;
1687     case k_Token:
1688       OS << getToken();
1689       break;
1690     case k_RegList:
1691       OS << "RegList< ";
1692       for (auto Reg : (*RegList.List))
1693         OS << Reg << " ";
1694       OS <<  ">";
1695       break;
1696     }
1697   }
1698 
1699   bool isValidForTie(const MipsOperand &Other) const {
1700     if (Kind != Other.Kind)
1701       return false;
1702 
1703     switch (Kind) {
1704     default:
1705       llvm_unreachable("Unexpected kind");
1706       return false;
1707     case k_RegisterIndex: {
1708       StringRef Token(RegIdx.Tok.Data, RegIdx.Tok.Length);
1709       StringRef OtherToken(Other.RegIdx.Tok.Data, Other.RegIdx.Tok.Length);
1710       return Token == OtherToken;
1711     }
1712     }
1713   }
1714 }; // class MipsOperand
1715 
1716 } // end anonymous namespace
1717 
1718 namespace llvm {
1719 
1720 extern const MCInstrDesc MipsInsts[];
1721 
1722 } // end namespace llvm
1723 
1724 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
1725   return MipsInsts[Opcode];
1726 }
1727 
1728 static bool hasShortDelaySlot(MCInst &Inst) {
1729   switch (Inst.getOpcode()) {
1730     case Mips::BEQ_MM:
1731     case Mips::BNE_MM:
1732     case Mips::BLTZ_MM:
1733     case Mips::BGEZ_MM:
1734     case Mips::BLEZ_MM:
1735     case Mips::BGTZ_MM:
1736     case Mips::JRC16_MM:
1737     case Mips::JALS_MM:
1738     case Mips::JALRS_MM:
1739     case Mips::JALRS16_MM:
1740     case Mips::BGEZALS_MM:
1741     case Mips::BLTZALS_MM:
1742       return true;
1743     case Mips::J_MM:
1744       return !Inst.getOperand(0).isReg();
1745     default:
1746       return false;
1747   }
1748 }
1749 
1750 static const MCSymbol *getSingleMCSymbol(const MCExpr *Expr) {
1751   if (const MCSymbolRefExpr *SRExpr = dyn_cast<MCSymbolRefExpr>(Expr)) {
1752     return &SRExpr->getSymbol();
1753   }
1754 
1755   if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr)) {
1756     const MCSymbol *LHSSym = getSingleMCSymbol(BExpr->getLHS());
1757     const MCSymbol *RHSSym = getSingleMCSymbol(BExpr->getRHS());
1758 
1759     if (LHSSym)
1760       return LHSSym;
1761 
1762     if (RHSSym)
1763       return RHSSym;
1764 
1765     return nullptr;
1766   }
1767 
1768   if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr))
1769     return getSingleMCSymbol(UExpr->getSubExpr());
1770 
1771   return nullptr;
1772 }
1773 
1774 static unsigned countMCSymbolRefExpr(const MCExpr *Expr) {
1775   if (isa<MCSymbolRefExpr>(Expr))
1776     return 1;
1777 
1778   if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr))
1779     return countMCSymbolRefExpr(BExpr->getLHS()) +
1780            countMCSymbolRefExpr(BExpr->getRHS());
1781 
1782   if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr))
1783     return countMCSymbolRefExpr(UExpr->getSubExpr());
1784 
1785   return 0;
1786 }
1787 
1788 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
1789                                        MCStreamer &Out,
1790                                        const MCSubtargetInfo *STI) {
1791   MipsTargetStreamer &TOut = getTargetStreamer();
1792   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
1793   bool ExpandedJalSym = false;
1794 
1795   Inst.setLoc(IDLoc);
1796 
1797   if (MCID.isBranch() || MCID.isCall()) {
1798     const unsigned Opcode = Inst.getOpcode();
1799     MCOperand Offset;
1800 
1801     switch (Opcode) {
1802     default:
1803       break;
1804     case Mips::BBIT0:
1805     case Mips::BBIT032:
1806     case Mips::BBIT1:
1807     case Mips::BBIT132:
1808       assert(hasCnMips() && "instruction only valid for octeon cpus");
1809       LLVM_FALLTHROUGH;
1810 
1811     case Mips::BEQ:
1812     case Mips::BNE:
1813     case Mips::BEQ_MM:
1814     case Mips::BNE_MM:
1815       assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1816       Offset = Inst.getOperand(2);
1817       if (!Offset.isImm())
1818         break; // We'll deal with this situation later on when applying fixups.
1819       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1820         return Error(IDLoc, "branch target out of range");
1821       if (offsetToAlignment(Offset.getImm(),
1822                             (inMicroMipsMode() ? Align(2) : Align(4))))
1823         return Error(IDLoc, "branch to misaligned address");
1824       break;
1825     case Mips::BGEZ:
1826     case Mips::BGTZ:
1827     case Mips::BLEZ:
1828     case Mips::BLTZ:
1829     case Mips::BGEZAL:
1830     case Mips::BLTZAL:
1831     case Mips::BC1F:
1832     case Mips::BC1T:
1833     case Mips::BGEZ_MM:
1834     case Mips::BGTZ_MM:
1835     case Mips::BLEZ_MM:
1836     case Mips::BLTZ_MM:
1837     case Mips::BGEZAL_MM:
1838     case Mips::BLTZAL_MM:
1839     case Mips::BC1F_MM:
1840     case Mips::BC1T_MM:
1841     case Mips::BC1EQZC_MMR6:
1842     case Mips::BC1NEZC_MMR6:
1843     case Mips::BC2EQZC_MMR6:
1844     case Mips::BC2NEZC_MMR6:
1845       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1846       Offset = Inst.getOperand(1);
1847       if (!Offset.isImm())
1848         break; // We'll deal with this situation later on when applying fixups.
1849       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1850         return Error(IDLoc, "branch target out of range");
1851       if (offsetToAlignment(Offset.getImm(),
1852                             (inMicroMipsMode() ? Align(2) : Align(4))))
1853         return Error(IDLoc, "branch to misaligned address");
1854       break;
1855     case Mips::BGEC:    case Mips::BGEC_MMR6:
1856     case Mips::BLTC:    case Mips::BLTC_MMR6:
1857     case Mips::BGEUC:   case Mips::BGEUC_MMR6:
1858     case Mips::BLTUC:   case Mips::BLTUC_MMR6:
1859     case Mips::BEQC:    case Mips::BEQC_MMR6:
1860     case Mips::BNEC:    case Mips::BNEC_MMR6:
1861       assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1862       Offset = Inst.getOperand(2);
1863       if (!Offset.isImm())
1864         break; // We'll deal with this situation later on when applying fixups.
1865       if (!isIntN(18, Offset.getImm()))
1866         return Error(IDLoc, "branch target out of range");
1867       if (offsetToAlignment(Offset.getImm(), Align(4)))
1868         return Error(IDLoc, "branch to misaligned address");
1869       break;
1870     case Mips::BLEZC:   case Mips::BLEZC_MMR6:
1871     case Mips::BGEZC:   case Mips::BGEZC_MMR6:
1872     case Mips::BGTZC:   case Mips::BGTZC_MMR6:
1873     case Mips::BLTZC:   case Mips::BLTZC_MMR6:
1874       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1875       Offset = Inst.getOperand(1);
1876       if (!Offset.isImm())
1877         break; // We'll deal with this situation later on when applying fixups.
1878       if (!isIntN(18, Offset.getImm()))
1879         return Error(IDLoc, "branch target out of range");
1880       if (offsetToAlignment(Offset.getImm(), Align(4)))
1881         return Error(IDLoc, "branch to misaligned address");
1882       break;
1883     case Mips::BEQZC:   case Mips::BEQZC_MMR6:
1884     case Mips::BNEZC:   case Mips::BNEZC_MMR6:
1885       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1886       Offset = Inst.getOperand(1);
1887       if (!Offset.isImm())
1888         break; // We'll deal with this situation later on when applying fixups.
1889       if (!isIntN(23, Offset.getImm()))
1890         return Error(IDLoc, "branch target out of range");
1891       if (offsetToAlignment(Offset.getImm(), Align(4)))
1892         return Error(IDLoc, "branch to misaligned address");
1893       break;
1894     case Mips::BEQZ16_MM:
1895     case Mips::BEQZC16_MMR6:
1896     case Mips::BNEZ16_MM:
1897     case Mips::BNEZC16_MMR6:
1898       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1899       Offset = Inst.getOperand(1);
1900       if (!Offset.isImm())
1901         break; // We'll deal with this situation later on when applying fixups.
1902       if (!isInt<8>(Offset.getImm()))
1903         return Error(IDLoc, "branch target out of range");
1904       if (offsetToAlignment(Offset.getImm(), Align(2)))
1905         return Error(IDLoc, "branch to misaligned address");
1906       break;
1907     }
1908   }
1909 
1910   // SSNOP is deprecated on MIPS32r6/MIPS64r6
1911   // We still accept it but it is a normal nop.
1912   if (hasMips32r6() && Inst.getOpcode() == Mips::SSNOP) {
1913     std::string ISA = hasMips64r6() ? "MIPS64r6" : "MIPS32r6";
1914     Warning(IDLoc, "ssnop is deprecated for " + ISA + " and is equivalent to a "
1915                                                       "nop instruction");
1916   }
1917 
1918   if (hasCnMips()) {
1919     const unsigned Opcode = Inst.getOpcode();
1920     MCOperand Opnd;
1921     int Imm;
1922 
1923     switch (Opcode) {
1924       default:
1925         break;
1926 
1927       case Mips::BBIT0:
1928       case Mips::BBIT032:
1929       case Mips::BBIT1:
1930       case Mips::BBIT132:
1931         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1932         // The offset is handled above
1933         Opnd = Inst.getOperand(1);
1934         if (!Opnd.isImm())
1935           return Error(IDLoc, "expected immediate operand kind");
1936         Imm = Opnd.getImm();
1937         if (Imm < 0 || Imm > (Opcode == Mips::BBIT0 ||
1938                               Opcode == Mips::BBIT1 ? 63 : 31))
1939           return Error(IDLoc, "immediate operand value out of range");
1940         if (Imm > 31) {
1941           Inst.setOpcode(Opcode == Mips::BBIT0 ? Mips::BBIT032
1942                                                : Mips::BBIT132);
1943           Inst.getOperand(1).setImm(Imm - 32);
1944         }
1945         break;
1946 
1947       case Mips::SEQi:
1948       case Mips::SNEi:
1949         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1950         Opnd = Inst.getOperand(2);
1951         if (!Opnd.isImm())
1952           return Error(IDLoc, "expected immediate operand kind");
1953         Imm = Opnd.getImm();
1954         if (!isInt<10>(Imm))
1955           return Error(IDLoc, "immediate operand value out of range");
1956         break;
1957     }
1958   }
1959 
1960   // Warn on division by zero. We're checking here as all instructions get
1961   // processed here, not just the macros that need expansion.
1962   //
1963   // The MIPS backend models most of the divison instructions and macros as
1964   // three operand instructions. The pre-R6 divide instructions however have
1965   // two operands and explicitly define HI/LO as part of the instruction,
1966   // not in the operands.
1967   unsigned FirstOp = 1;
1968   unsigned SecondOp = 2;
1969   switch (Inst.getOpcode()) {
1970   default:
1971     break;
1972   case Mips::SDivIMacro:
1973   case Mips::UDivIMacro:
1974   case Mips::DSDivIMacro:
1975   case Mips::DUDivIMacro:
1976     if (Inst.getOperand(2).getImm() == 0) {
1977       if (Inst.getOperand(1).getReg() == Mips::ZERO ||
1978           Inst.getOperand(1).getReg() == Mips::ZERO_64)
1979         Warning(IDLoc, "dividing zero by zero");
1980       else
1981         Warning(IDLoc, "division by zero");
1982     }
1983     break;
1984   case Mips::DSDIV:
1985   case Mips::SDIV:
1986   case Mips::UDIV:
1987   case Mips::DUDIV:
1988   case Mips::UDIV_MM:
1989   case Mips::SDIV_MM:
1990     FirstOp = 0;
1991     SecondOp = 1;
1992     LLVM_FALLTHROUGH;
1993   case Mips::SDivMacro:
1994   case Mips::DSDivMacro:
1995   case Mips::UDivMacro:
1996   case Mips::DUDivMacro:
1997   case Mips::DIV:
1998   case Mips::DIVU:
1999   case Mips::DDIV:
2000   case Mips::DDIVU:
2001   case Mips::DIVU_MMR6:
2002   case Mips::DIV_MMR6:
2003     if (Inst.getOperand(SecondOp).getReg() == Mips::ZERO ||
2004         Inst.getOperand(SecondOp).getReg() == Mips::ZERO_64) {
2005       if (Inst.getOperand(FirstOp).getReg() == Mips::ZERO ||
2006           Inst.getOperand(FirstOp).getReg() == Mips::ZERO_64)
2007         Warning(IDLoc, "dividing zero by zero");
2008       else
2009         Warning(IDLoc, "division by zero");
2010     }
2011     break;
2012   }
2013 
2014   // For PIC code convert unconditional jump to unconditional branch.
2015   if ((Inst.getOpcode() == Mips::J || Inst.getOpcode() == Mips::J_MM) &&
2016       inPicMode()) {
2017     MCInst BInst;
2018     BInst.setOpcode(inMicroMipsMode() ? Mips::BEQ_MM : Mips::BEQ);
2019     BInst.addOperand(MCOperand::createReg(Mips::ZERO));
2020     BInst.addOperand(MCOperand::createReg(Mips::ZERO));
2021     BInst.addOperand(Inst.getOperand(0));
2022     Inst = BInst;
2023   }
2024 
2025   // This expansion is not in a function called by tryExpandInstruction()
2026   // because the pseudo-instruction doesn't have a distinct opcode.
2027   if ((Inst.getOpcode() == Mips::JAL || Inst.getOpcode() == Mips::JAL_MM) &&
2028       inPicMode()) {
2029     warnIfNoMacro(IDLoc);
2030 
2031     const MCExpr *JalExpr = Inst.getOperand(0).getExpr();
2032 
2033     // We can do this expansion if there's only 1 symbol in the argument
2034     // expression.
2035     if (countMCSymbolRefExpr(JalExpr) > 1)
2036       return Error(IDLoc, "jal doesn't support multiple symbols in PIC mode");
2037 
2038     // FIXME: This is checking the expression can be handled by the later stages
2039     //        of the assembler. We ought to leave it to those later stages.
2040     const MCSymbol *JalSym = getSingleMCSymbol(JalExpr);
2041 
2042     // FIXME: Add support for label+offset operands (currently causes an error).
2043     // FIXME: Add support for forward-declared local symbols.
2044     // FIXME: Add expansion for when the LargeGOT option is enabled.
2045     if (JalSym->isInSection() || JalSym->isTemporary() ||
2046         (JalSym->isELF() &&
2047          cast<MCSymbolELF>(JalSym)->getBinding() == ELF::STB_LOCAL)) {
2048       if (isABI_O32()) {
2049         // If it's a local symbol and the O32 ABI is being used, we expand to:
2050         //  lw $25, 0($gp)
2051         //    R_(MICRO)MIPS_GOT16  label
2052         //  addiu $25, $25, 0
2053         //    R_(MICRO)MIPS_LO16   label
2054         //  jalr  $25
2055         const MCExpr *Got16RelocExpr =
2056             MipsMCExpr::create(MipsMCExpr::MEK_GOT, JalExpr, getContext());
2057         const MCExpr *Lo16RelocExpr =
2058             MipsMCExpr::create(MipsMCExpr::MEK_LO, JalExpr, getContext());
2059 
2060         TOut.emitRRX(Mips::LW, Mips::T9, GPReg,
2061                      MCOperand::createExpr(Got16RelocExpr), IDLoc, STI);
2062         TOut.emitRRX(Mips::ADDiu, Mips::T9, Mips::T9,
2063                      MCOperand::createExpr(Lo16RelocExpr), IDLoc, STI);
2064       } else if (isABI_N32() || isABI_N64()) {
2065         // If it's a local symbol and the N32/N64 ABIs are being used,
2066         // we expand to:
2067         //  lw/ld $25, 0($gp)
2068         //    R_(MICRO)MIPS_GOT_DISP  label
2069         //  jalr  $25
2070         const MCExpr *GotDispRelocExpr =
2071             MipsMCExpr::create(MipsMCExpr::MEK_GOT_DISP, JalExpr, getContext());
2072 
2073         TOut.emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9,
2074                      GPReg, MCOperand::createExpr(GotDispRelocExpr), IDLoc,
2075                      STI);
2076       }
2077     } else {
2078       // If it's an external/weak symbol, we expand to:
2079       //  lw/ld    $25, 0($gp)
2080       //    R_(MICRO)MIPS_CALL16  label
2081       //  jalr  $25
2082       const MCExpr *Call16RelocExpr =
2083           MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, JalExpr, getContext());
2084 
2085       TOut.emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9, GPReg,
2086                    MCOperand::createExpr(Call16RelocExpr), IDLoc, STI);
2087     }
2088 
2089     MCInst JalrInst;
2090     if (IsCpRestoreSet && inMicroMipsMode())
2091       JalrInst.setOpcode(Mips::JALRS_MM);
2092     else
2093       JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR);
2094     JalrInst.addOperand(MCOperand::createReg(Mips::RA));
2095     JalrInst.addOperand(MCOperand::createReg(Mips::T9));
2096 
2097     if (EmitJalrReloc) {
2098       // As an optimization hint for the linker, before the JALR we add:
2099       // .reloc tmplabel, R_{MICRO}MIPS_JALR, symbol
2100       // tmplabel:
2101       MCSymbol *TmpLabel = getContext().createTempSymbol();
2102       const MCExpr *TmpExpr = MCSymbolRefExpr::create(TmpLabel, getContext());
2103       const MCExpr *RelocJalrExpr =
2104           MCSymbolRefExpr::create(JalSym, MCSymbolRefExpr::VK_None,
2105                                   getContext(), IDLoc);
2106 
2107       TOut.getStreamer().EmitRelocDirective(*TmpExpr,
2108           inMicroMipsMode() ? "R_MICROMIPS_JALR" : "R_MIPS_JALR",
2109           RelocJalrExpr, IDLoc, *STI);
2110       TOut.getStreamer().EmitLabel(TmpLabel);
2111     }
2112 
2113     Inst = JalrInst;
2114     ExpandedJalSym = true;
2115   }
2116 
2117   bool IsPCRelativeLoad = (MCID.TSFlags & MipsII::IsPCRelativeLoad) != 0;
2118   if ((MCID.mayLoad() || MCID.mayStore()) && !IsPCRelativeLoad) {
2119     // Check the offset of memory operand, if it is a symbol
2120     // reference or immediate we may have to expand instructions.
2121     for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
2122       const MCOperandInfo &OpInfo = MCID.OpInfo[i];
2123       if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
2124           (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
2125         MCOperand &Op = Inst.getOperand(i);
2126         if (Op.isImm()) {
2127           int64_t MemOffset = Op.getImm();
2128           if (MemOffset < -32768 || MemOffset > 32767) {
2129             // Offset can't exceed 16bit value.
2130             expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad());
2131             return getParser().hasPendingError();
2132           }
2133         } else if (Op.isExpr()) {
2134           const MCExpr *Expr = Op.getExpr();
2135           if (Expr->getKind() == MCExpr::SymbolRef) {
2136             const MCSymbolRefExpr *SR =
2137                 static_cast<const MCSymbolRefExpr *>(Expr);
2138             if (SR->getKind() == MCSymbolRefExpr::VK_None) {
2139               // Expand symbol.
2140               expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad());
2141               return getParser().hasPendingError();
2142             }
2143           } else if (!isEvaluated(Expr)) {
2144             expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad());
2145             return getParser().hasPendingError();
2146           }
2147         }
2148       }
2149     } // for
2150   }   // if load/store
2151 
2152   if (inMicroMipsMode()) {
2153     if (MCID.mayLoad() && Inst.getOpcode() != Mips::LWP_MM) {
2154       // Try to create 16-bit GP relative load instruction.
2155       for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
2156         const MCOperandInfo &OpInfo = MCID.OpInfo[i];
2157         if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
2158             (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
2159           MCOperand &Op = Inst.getOperand(i);
2160           if (Op.isImm()) {
2161             int MemOffset = Op.getImm();
2162             MCOperand &DstReg = Inst.getOperand(0);
2163             MCOperand &BaseReg = Inst.getOperand(1);
2164             if (isInt<9>(MemOffset) && (MemOffset % 4 == 0) &&
2165                 getContext().getRegisterInfo()->getRegClass(
2166                   Mips::GPRMM16RegClassID).contains(DstReg.getReg()) &&
2167                 (BaseReg.getReg() == Mips::GP ||
2168                 BaseReg.getReg() == Mips::GP_64)) {
2169 
2170               TOut.emitRRI(Mips::LWGP_MM, DstReg.getReg(), Mips::GP, MemOffset,
2171                            IDLoc, STI);
2172               return false;
2173             }
2174           }
2175         }
2176       } // for
2177     }   // if load
2178 
2179     // TODO: Handle this with the AsmOperandClass.PredicateMethod.
2180 
2181     MCOperand Opnd;
2182     int Imm;
2183 
2184     switch (Inst.getOpcode()) {
2185       default:
2186         break;
2187       case Mips::ADDIUSP_MM:
2188         Opnd = Inst.getOperand(0);
2189         if (!Opnd.isImm())
2190           return Error(IDLoc, "expected immediate operand kind");
2191         Imm = Opnd.getImm();
2192         if (Imm < -1032 || Imm > 1028 || (Imm < 8 && Imm > -12) ||
2193             Imm % 4 != 0)
2194           return Error(IDLoc, "immediate operand value out of range");
2195         break;
2196       case Mips::SLL16_MM:
2197       case Mips::SRL16_MM:
2198         Opnd = Inst.getOperand(2);
2199         if (!Opnd.isImm())
2200           return Error(IDLoc, "expected immediate operand kind");
2201         Imm = Opnd.getImm();
2202         if (Imm < 1 || Imm > 8)
2203           return Error(IDLoc, "immediate operand value out of range");
2204         break;
2205       case Mips::LI16_MM:
2206         Opnd = Inst.getOperand(1);
2207         if (!Opnd.isImm())
2208           return Error(IDLoc, "expected immediate operand kind");
2209         Imm = Opnd.getImm();
2210         if (Imm < -1 || Imm > 126)
2211           return Error(IDLoc, "immediate operand value out of range");
2212         break;
2213       case Mips::ADDIUR2_MM:
2214         Opnd = Inst.getOperand(2);
2215         if (!Opnd.isImm())
2216           return Error(IDLoc, "expected immediate operand kind");
2217         Imm = Opnd.getImm();
2218         if (!(Imm == 1 || Imm == -1 ||
2219               ((Imm % 4 == 0) && Imm < 28 && Imm > 0)))
2220           return Error(IDLoc, "immediate operand value out of range");
2221         break;
2222       case Mips::ANDI16_MM:
2223         Opnd = Inst.getOperand(2);
2224         if (!Opnd.isImm())
2225           return Error(IDLoc, "expected immediate operand kind");
2226         Imm = Opnd.getImm();
2227         if (!(Imm == 128 || (Imm >= 1 && Imm <= 4) || Imm == 7 || Imm == 8 ||
2228               Imm == 15 || Imm == 16 || Imm == 31 || Imm == 32 || Imm == 63 ||
2229               Imm == 64 || Imm == 255 || Imm == 32768 || Imm == 65535))
2230           return Error(IDLoc, "immediate operand value out of range");
2231         break;
2232       case Mips::LBU16_MM:
2233         Opnd = Inst.getOperand(2);
2234         if (!Opnd.isImm())
2235           return Error(IDLoc, "expected immediate operand kind");
2236         Imm = Opnd.getImm();
2237         if (Imm < -1 || Imm > 14)
2238           return Error(IDLoc, "immediate operand value out of range");
2239         break;
2240       case Mips::SB16_MM:
2241       case Mips::SB16_MMR6:
2242         Opnd = Inst.getOperand(2);
2243         if (!Opnd.isImm())
2244           return Error(IDLoc, "expected immediate operand kind");
2245         Imm = Opnd.getImm();
2246         if (Imm < 0 || Imm > 15)
2247           return Error(IDLoc, "immediate operand value out of range");
2248         break;
2249       case Mips::LHU16_MM:
2250       case Mips::SH16_MM:
2251       case Mips::SH16_MMR6:
2252         Opnd = Inst.getOperand(2);
2253         if (!Opnd.isImm())
2254           return Error(IDLoc, "expected immediate operand kind");
2255         Imm = Opnd.getImm();
2256         if (Imm < 0 || Imm > 30 || (Imm % 2 != 0))
2257           return Error(IDLoc, "immediate operand value out of range");
2258         break;
2259       case Mips::LW16_MM:
2260       case Mips::SW16_MM:
2261       case Mips::SW16_MMR6:
2262         Opnd = Inst.getOperand(2);
2263         if (!Opnd.isImm())
2264           return Error(IDLoc, "expected immediate operand kind");
2265         Imm = Opnd.getImm();
2266         if (Imm < 0 || Imm > 60 || (Imm % 4 != 0))
2267           return Error(IDLoc, "immediate operand value out of range");
2268         break;
2269       case Mips::ADDIUPC_MM:
2270         Opnd = Inst.getOperand(1);
2271         if (!Opnd.isImm())
2272           return Error(IDLoc, "expected immediate operand kind");
2273         Imm = Opnd.getImm();
2274         if ((Imm % 4 != 0) || !isInt<25>(Imm))
2275           return Error(IDLoc, "immediate operand value out of range");
2276         break;
2277       case Mips::LWP_MM:
2278       case Mips::SWP_MM:
2279         if (Inst.getOperand(0).getReg() == Mips::RA)
2280           return Error(IDLoc, "invalid operand for instruction");
2281         break;
2282       case Mips::MOVEP_MM:
2283       case Mips::MOVEP_MMR6: {
2284         unsigned R0 = Inst.getOperand(0).getReg();
2285         unsigned R1 = Inst.getOperand(1).getReg();
2286         bool RegPair = ((R0 == Mips::A1 && R1 == Mips::A2) ||
2287                         (R0 == Mips::A1 && R1 == Mips::A3) ||
2288                         (R0 == Mips::A2 && R1 == Mips::A3) ||
2289                         (R0 == Mips::A0 && R1 == Mips::S5) ||
2290                         (R0 == Mips::A0 && R1 == Mips::S6) ||
2291                         (R0 == Mips::A0 && R1 == Mips::A1) ||
2292                         (R0 == Mips::A0 && R1 == Mips::A2) ||
2293                         (R0 == Mips::A0 && R1 == Mips::A3));
2294         if (!RegPair)
2295           return Error(IDLoc, "invalid operand for instruction");
2296         break;
2297       }
2298     }
2299   }
2300 
2301   bool FillDelaySlot =
2302       MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder();
2303   if (FillDelaySlot)
2304     TOut.emitDirectiveSetNoReorder();
2305 
2306   MacroExpanderResultTy ExpandResult =
2307       tryExpandInstruction(Inst, IDLoc, Out, STI);
2308   switch (ExpandResult) {
2309   case MER_NotAMacro:
2310     Out.EmitInstruction(Inst, *STI);
2311     break;
2312   case MER_Success:
2313     break;
2314   case MER_Fail:
2315     return true;
2316   }
2317 
2318   // We know we emitted an instruction on the MER_NotAMacro or MER_Success path.
2319   // If we're in microMIPS mode then we must also set EF_MIPS_MICROMIPS.
2320   if (inMicroMipsMode()) {
2321     TOut.setUsesMicroMips();
2322     TOut.updateABIInfo(*this);
2323   }
2324 
2325   // If this instruction has a delay slot and .set reorder is active,
2326   // emit a NOP after it.
2327   if (FillDelaySlot) {
2328     TOut.emitEmptyDelaySlot(hasShortDelaySlot(Inst), IDLoc, STI);
2329     TOut.emitDirectiveSetReorder();
2330   }
2331 
2332   if ((Inst.getOpcode() == Mips::JalOneReg ||
2333        Inst.getOpcode() == Mips::JalTwoReg || ExpandedJalSym) &&
2334       isPicAndNotNxxAbi()) {
2335     if (IsCpRestoreSet) {
2336       // We need a NOP between the JALR and the LW:
2337       // If .set reorder has been used, we've already emitted a NOP.
2338       // If .set noreorder has been used, we need to emit a NOP at this point.
2339       if (!AssemblerOptions.back()->isReorder())
2340         TOut.emitEmptyDelaySlot(hasShortDelaySlot(Inst), IDLoc,
2341                                 STI);
2342 
2343       // Load the $gp from the stack.
2344       TOut.emitGPRestore(CpRestoreOffset, IDLoc, STI);
2345     } else
2346       Warning(IDLoc, "no .cprestore used in PIC mode");
2347   }
2348 
2349   return false;
2350 }
2351 
2352 MipsAsmParser::MacroExpanderResultTy
2353 MipsAsmParser::tryExpandInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
2354                                     const MCSubtargetInfo *STI) {
2355   switch (Inst.getOpcode()) {
2356   default:
2357     return MER_NotAMacro;
2358   case Mips::LoadImm32:
2359     return expandLoadImm(Inst, true, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2360   case Mips::LoadImm64:
2361     return expandLoadImm(Inst, false, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2362   case Mips::LoadAddrImm32:
2363   case Mips::LoadAddrImm64:
2364     assert(Inst.getOperand(0).isReg() && "expected register operand kind");
2365     assert((Inst.getOperand(1).isImm() || Inst.getOperand(1).isExpr()) &&
2366            "expected immediate operand kind");
2367 
2368     return expandLoadAddress(Inst.getOperand(0).getReg(), Mips::NoRegister,
2369                              Inst.getOperand(1),
2370                              Inst.getOpcode() == Mips::LoadAddrImm32, IDLoc,
2371                              Out, STI)
2372                ? MER_Fail
2373                : MER_Success;
2374   case Mips::LoadAddrReg32:
2375   case Mips::LoadAddrReg64:
2376     assert(Inst.getOperand(0).isReg() && "expected register operand kind");
2377     assert(Inst.getOperand(1).isReg() && "expected register operand kind");
2378     assert((Inst.getOperand(2).isImm() || Inst.getOperand(2).isExpr()) &&
2379            "expected immediate operand kind");
2380 
2381     return expandLoadAddress(Inst.getOperand(0).getReg(),
2382                              Inst.getOperand(1).getReg(), Inst.getOperand(2),
2383                              Inst.getOpcode() == Mips::LoadAddrReg32, IDLoc,
2384                              Out, STI)
2385                ? MER_Fail
2386                : MER_Success;
2387   case Mips::B_MM_Pseudo:
2388   case Mips::B_MMR6_Pseudo:
2389     return expandUncondBranchMMPseudo(Inst, IDLoc, Out, STI) ? MER_Fail
2390                                                              : MER_Success;
2391   case Mips::SWM_MM:
2392   case Mips::LWM_MM:
2393     return expandLoadStoreMultiple(Inst, IDLoc, Out, STI) ? MER_Fail
2394                                                           : MER_Success;
2395   case Mips::JalOneReg:
2396   case Mips::JalTwoReg:
2397     return expandJalWithRegs(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2398   case Mips::BneImm:
2399   case Mips::BeqImm:
2400   case Mips::BEQLImmMacro:
2401   case Mips::BNELImmMacro:
2402     return expandBranchImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2403   case Mips::BLT:
2404   case Mips::BLE:
2405   case Mips::BGE:
2406   case Mips::BGT:
2407   case Mips::BLTU:
2408   case Mips::BLEU:
2409   case Mips::BGEU:
2410   case Mips::BGTU:
2411   case Mips::BLTL:
2412   case Mips::BLEL:
2413   case Mips::BGEL:
2414   case Mips::BGTL:
2415   case Mips::BLTUL:
2416   case Mips::BLEUL:
2417   case Mips::BGEUL:
2418   case Mips::BGTUL:
2419   case Mips::BLTImmMacro:
2420   case Mips::BLEImmMacro:
2421   case Mips::BGEImmMacro:
2422   case Mips::BGTImmMacro:
2423   case Mips::BLTUImmMacro:
2424   case Mips::BLEUImmMacro:
2425   case Mips::BGEUImmMacro:
2426   case Mips::BGTUImmMacro:
2427   case Mips::BLTLImmMacro:
2428   case Mips::BLELImmMacro:
2429   case Mips::BGELImmMacro:
2430   case Mips::BGTLImmMacro:
2431   case Mips::BLTULImmMacro:
2432   case Mips::BLEULImmMacro:
2433   case Mips::BGEULImmMacro:
2434   case Mips::BGTULImmMacro:
2435     return expandCondBranches(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2436   case Mips::SDivMacro:
2437   case Mips::SDivIMacro:
2438   case Mips::SRemMacro:
2439   case Mips::SRemIMacro:
2440     return expandDivRem(Inst, IDLoc, Out, STI, false, true) ? MER_Fail
2441                                                             : MER_Success;
2442   case Mips::DSDivMacro:
2443   case Mips::DSDivIMacro:
2444   case Mips::DSRemMacro:
2445   case Mips::DSRemIMacro:
2446     return expandDivRem(Inst, IDLoc, Out, STI, true, true) ? MER_Fail
2447                                                            : MER_Success;
2448   case Mips::UDivMacro:
2449   case Mips::UDivIMacro:
2450   case Mips::URemMacro:
2451   case Mips::URemIMacro:
2452     return expandDivRem(Inst, IDLoc, Out, STI, false, false) ? MER_Fail
2453                                                              : MER_Success;
2454   case Mips::DUDivMacro:
2455   case Mips::DUDivIMacro:
2456   case Mips::DURemMacro:
2457   case Mips::DURemIMacro:
2458     return expandDivRem(Inst, IDLoc, Out, STI, true, false) ? MER_Fail
2459                                                             : MER_Success;
2460   case Mips::PseudoTRUNC_W_S:
2461     return expandTrunc(Inst, false, false, IDLoc, Out, STI) ? MER_Fail
2462                                                             : MER_Success;
2463   case Mips::PseudoTRUNC_W_D32:
2464     return expandTrunc(Inst, true, false, IDLoc, Out, STI) ? MER_Fail
2465                                                            : MER_Success;
2466   case Mips::PseudoTRUNC_W_D:
2467     return expandTrunc(Inst, true, true, IDLoc, Out, STI) ? MER_Fail
2468                                                           : MER_Success;
2469 
2470   case Mips::LoadImmSingleGPR:
2471     return expandLoadSingleImmToGPR(Inst, IDLoc, Out, STI) ? MER_Fail
2472                                                            : MER_Success;
2473   case Mips::LoadImmSingleFGR:
2474     return expandLoadSingleImmToFPR(Inst, IDLoc, Out, STI) ? MER_Fail
2475                                                            : MER_Success;
2476   case Mips::LoadImmDoubleGPR:
2477     return expandLoadDoubleImmToGPR(Inst, IDLoc, Out, STI) ? MER_Fail
2478                                                            : MER_Success;
2479   case Mips::LoadImmDoubleFGR:
2480     return expandLoadDoubleImmToFPR(Inst, true, IDLoc, Out, STI) ? MER_Fail
2481                                                                  : MER_Success;
2482   case Mips::LoadImmDoubleFGR_32:
2483     return expandLoadDoubleImmToFPR(Inst, false, IDLoc, Out, STI) ? MER_Fail
2484                                                                   : MER_Success;
2485 
2486   case Mips::Ulh:
2487     return expandUlh(Inst, true, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2488   case Mips::Ulhu:
2489     return expandUlh(Inst, false, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2490   case Mips::Ush:
2491     return expandUsh(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2492   case Mips::Ulw:
2493   case Mips::Usw:
2494     return expandUxw(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2495   case Mips::NORImm:
2496   case Mips::NORImm64:
2497     return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2498   case Mips::SGE:
2499   case Mips::SGEU:
2500     return expandSge(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2501   case Mips::SGEImm:
2502   case Mips::SGEUImm:
2503   case Mips::SGEImm64:
2504   case Mips::SGEUImm64:
2505     return expandSgeImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2506   case Mips::SGTImm:
2507   case Mips::SGTUImm:
2508   case Mips::SGTImm64:
2509   case Mips::SGTUImm64:
2510     return expandSgtImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2511   case Mips::SLTImm64:
2512     if (isInt<16>(Inst.getOperand(2).getImm())) {
2513       Inst.setOpcode(Mips::SLTi64);
2514       return MER_NotAMacro;
2515     }
2516     return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2517   case Mips::SLTUImm64:
2518     if (isInt<16>(Inst.getOperand(2).getImm())) {
2519       Inst.setOpcode(Mips::SLTiu64);
2520       return MER_NotAMacro;
2521     }
2522     return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2523   case Mips::ADDi:   case Mips::ADDi_MM:
2524   case Mips::ADDiu:  case Mips::ADDiu_MM:
2525   case Mips::SLTi:   case Mips::SLTi_MM:
2526   case Mips::SLTiu:  case Mips::SLTiu_MM:
2527     if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() &&
2528         Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) {
2529       int64_t ImmValue = Inst.getOperand(2).getImm();
2530       if (isInt<16>(ImmValue))
2531         return MER_NotAMacro;
2532       return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail
2533                                                          : MER_Success;
2534     }
2535     return MER_NotAMacro;
2536   case Mips::ANDi:  case Mips::ANDi_MM:  case Mips::ANDi64:
2537   case Mips::ORi:   case Mips::ORi_MM:   case Mips::ORi64:
2538   case Mips::XORi:  case Mips::XORi_MM:  case Mips::XORi64:
2539     if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() &&
2540         Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) {
2541       int64_t ImmValue = Inst.getOperand(2).getImm();
2542       if (isUInt<16>(ImmValue))
2543         return MER_NotAMacro;
2544       return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail
2545                                                          : MER_Success;
2546     }
2547     return MER_NotAMacro;
2548   case Mips::ROL:
2549   case Mips::ROR:
2550     return expandRotation(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2551   case Mips::ROLImm:
2552   case Mips::RORImm:
2553     return expandRotationImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2554   case Mips::DROL:
2555   case Mips::DROR:
2556     return expandDRotation(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2557   case Mips::DROLImm:
2558   case Mips::DRORImm:
2559     return expandDRotationImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2560   case Mips::ABSMacro:
2561     return expandAbs(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2562   case Mips::MULImmMacro:
2563   case Mips::DMULImmMacro:
2564     return expandMulImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2565   case Mips::MULOMacro:
2566   case Mips::DMULOMacro:
2567     return expandMulO(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2568   case Mips::MULOUMacro:
2569   case Mips::DMULOUMacro:
2570     return expandMulOU(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2571   case Mips::DMULMacro:
2572     return expandDMULMacro(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2573   case Mips::LDMacro:
2574   case Mips::SDMacro:
2575     return expandLoadStoreDMacro(Inst, IDLoc, Out, STI,
2576                                  Inst.getOpcode() == Mips::LDMacro)
2577                ? MER_Fail
2578                : MER_Success;
2579   case Mips::SDC1_M1:
2580     return expandStoreDM1Macro(Inst, IDLoc, Out, STI)
2581                ? MER_Fail
2582                : MER_Success;
2583   case Mips::SEQMacro:
2584     return expandSeq(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2585   case Mips::SEQIMacro:
2586     return expandSeqI(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2587   case Mips::MFTC0:   case Mips::MTTC0:
2588   case Mips::MFTGPR:  case Mips::MTTGPR:
2589   case Mips::MFTLO:   case Mips::MTTLO:
2590   case Mips::MFTHI:   case Mips::MTTHI:
2591   case Mips::MFTACX:  case Mips::MTTACX:
2592   case Mips::MFTDSP:  case Mips::MTTDSP:
2593   case Mips::MFTC1:   case Mips::MTTC1:
2594   case Mips::MFTHC1:  case Mips::MTTHC1:
2595   case Mips::CFTC1:   case Mips::CTTC1:
2596     return expandMXTRAlias(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2597   case Mips::SaaAddr:
2598   case Mips::SaadAddr:
2599     return expandSaaAddr(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success;
2600   }
2601 }
2602 
2603 bool MipsAsmParser::expandJalWithRegs(MCInst &Inst, SMLoc IDLoc,
2604                                       MCStreamer &Out,
2605                                       const MCSubtargetInfo *STI) {
2606   MipsTargetStreamer &TOut = getTargetStreamer();
2607 
2608   // Create a JALR instruction which is going to replace the pseudo-JAL.
2609   MCInst JalrInst;
2610   JalrInst.setLoc(IDLoc);
2611   const MCOperand FirstRegOp = Inst.getOperand(0);
2612   const unsigned Opcode = Inst.getOpcode();
2613 
2614   if (Opcode == Mips::JalOneReg) {
2615     // jal $rs => jalr $rs
2616     if (IsCpRestoreSet && inMicroMipsMode()) {
2617       JalrInst.setOpcode(Mips::JALRS16_MM);
2618       JalrInst.addOperand(FirstRegOp);
2619     } else if (inMicroMipsMode()) {
2620       JalrInst.setOpcode(hasMips32r6() ? Mips::JALRC16_MMR6 : Mips::JALR16_MM);
2621       JalrInst.addOperand(FirstRegOp);
2622     } else {
2623       JalrInst.setOpcode(Mips::JALR);
2624       JalrInst.addOperand(MCOperand::createReg(Mips::RA));
2625       JalrInst.addOperand(FirstRegOp);
2626     }
2627   } else if (Opcode == Mips::JalTwoReg) {
2628     // jal $rd, $rs => jalr $rd, $rs
2629     if (IsCpRestoreSet && inMicroMipsMode())
2630       JalrInst.setOpcode(Mips::JALRS_MM);
2631     else
2632       JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR);
2633     JalrInst.addOperand(FirstRegOp);
2634     const MCOperand SecondRegOp = Inst.getOperand(1);
2635     JalrInst.addOperand(SecondRegOp);
2636   }
2637   Out.EmitInstruction(JalrInst, *STI);
2638 
2639   // If .set reorder is active and branch instruction has a delay slot,
2640   // emit a NOP after it.
2641   const MCInstrDesc &MCID = getInstDesc(JalrInst.getOpcode());
2642   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder())
2643     TOut.emitEmptyDelaySlot(hasShortDelaySlot(JalrInst), IDLoc,
2644                             STI);
2645 
2646   return false;
2647 }
2648 
2649 /// Can the value be represented by a unsigned N-bit value and a shift left?
2650 template <unsigned N> static bool isShiftedUIntAtAnyPosition(uint64_t x) {
2651   unsigned BitNum = findFirstSet(x);
2652 
2653   return (x == x >> BitNum << BitNum) && isUInt<N>(x >> BitNum);
2654 }
2655 
2656 /// Load (or add) an immediate into a register.
2657 ///
2658 /// @param ImmValue     The immediate to load.
2659 /// @param DstReg       The register that will hold the immediate.
2660 /// @param SrcReg       A register to add to the immediate or Mips::NoRegister
2661 ///                     for a simple initialization.
2662 /// @param Is32BitImm   Is ImmValue 32-bit or 64-bit?
2663 /// @param IsAddress    True if the immediate represents an address. False if it
2664 ///                     is an integer.
2665 /// @param IDLoc        Location of the immediate in the source file.
2666 bool MipsAsmParser::loadImmediate(int64_t ImmValue, unsigned DstReg,
2667                                   unsigned SrcReg, bool Is32BitImm,
2668                                   bool IsAddress, SMLoc IDLoc, MCStreamer &Out,
2669                                   const MCSubtargetInfo *STI) {
2670   MipsTargetStreamer &TOut = getTargetStreamer();
2671 
2672   if (!Is32BitImm && !isGP64bit()) {
2673     Error(IDLoc, "instruction requires a 64-bit architecture");
2674     return true;
2675   }
2676 
2677   if (Is32BitImm) {
2678     if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) {
2679       // Sign extend up to 64-bit so that the predicates match the hardware
2680       // behaviour. In particular, isInt<16>(0xffff8000) and similar should be
2681       // true.
2682       ImmValue = SignExtend64<32>(ImmValue);
2683     } else {
2684       Error(IDLoc, "instruction requires a 32-bit immediate");
2685       return true;
2686     }
2687   }
2688 
2689   unsigned ZeroReg = IsAddress ? ABI.GetNullPtr() : ABI.GetZeroReg();
2690   unsigned AdduOp = !Is32BitImm ? Mips::DADDu : Mips::ADDu;
2691 
2692   bool UseSrcReg = false;
2693   if (SrcReg != Mips::NoRegister)
2694     UseSrcReg = true;
2695 
2696   unsigned TmpReg = DstReg;
2697   if (UseSrcReg &&
2698       getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) {
2699     // At this point we need AT to perform the expansions and we exit if it is
2700     // not available.
2701     unsigned ATReg = getATReg(IDLoc);
2702     if (!ATReg)
2703       return true;
2704     TmpReg = ATReg;
2705   }
2706 
2707   if (isInt<16>(ImmValue)) {
2708     if (!UseSrcReg)
2709       SrcReg = ZeroReg;
2710 
2711     // This doesn't quite follow the usual ABI expectations for N32 but matches
2712     // traditional assembler behaviour. N32 would normally use addiu for both
2713     // integers and addresses.
2714     if (IsAddress && !Is32BitImm) {
2715       TOut.emitRRI(Mips::DADDiu, DstReg, SrcReg, ImmValue, IDLoc, STI);
2716       return false;
2717     }
2718 
2719     TOut.emitRRI(Mips::ADDiu, DstReg, SrcReg, ImmValue, IDLoc, STI);
2720     return false;
2721   }
2722 
2723   if (isUInt<16>(ImmValue)) {
2724     unsigned TmpReg = DstReg;
2725     if (SrcReg == DstReg) {
2726       TmpReg = getATReg(IDLoc);
2727       if (!TmpReg)
2728         return true;
2729     }
2730 
2731     TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, ImmValue, IDLoc, STI);
2732     if (UseSrcReg)
2733       TOut.emitRRR(ABI.GetPtrAdduOp(), DstReg, TmpReg, SrcReg, IDLoc, STI);
2734     return false;
2735   }
2736 
2737   if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) {
2738     warnIfNoMacro(IDLoc);
2739 
2740     uint16_t Bits31To16 = (ImmValue >> 16) & 0xffff;
2741     uint16_t Bits15To0 = ImmValue & 0xffff;
2742     if (!Is32BitImm && !isInt<32>(ImmValue)) {
2743       // Traditional behaviour seems to special case this particular value. It's
2744       // not clear why other masks are handled differently.
2745       if (ImmValue == 0xffffffff) {
2746         TOut.emitRI(Mips::LUi, TmpReg, 0xffff, IDLoc, STI);
2747         TOut.emitRRI(Mips::DSRL32, TmpReg, TmpReg, 0, IDLoc, STI);
2748         if (UseSrcReg)
2749           TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2750         return false;
2751       }
2752 
2753       // Expand to an ORi instead of a LUi to avoid sign-extending into the
2754       // upper 32 bits.
2755       TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits31To16, IDLoc, STI);
2756       TOut.emitRRI(Mips::DSLL, TmpReg, TmpReg, 16, IDLoc, STI);
2757       if (Bits15To0)
2758         TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, STI);
2759       if (UseSrcReg)
2760         TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2761       return false;
2762     }
2763 
2764     TOut.emitRI(Mips::LUi, TmpReg, Bits31To16, IDLoc, STI);
2765     if (Bits15To0)
2766       TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, STI);
2767     if (UseSrcReg)
2768       TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2769     return false;
2770   }
2771 
2772   if (isShiftedUIntAtAnyPosition<16>(ImmValue)) {
2773     if (Is32BitImm) {
2774       Error(IDLoc, "instruction requires a 32-bit immediate");
2775       return true;
2776     }
2777 
2778     // Traditionally, these immediates are shifted as little as possible and as
2779     // such we align the most significant bit to bit 15 of our temporary.
2780     unsigned FirstSet = findFirstSet((uint64_t)ImmValue);
2781     unsigned LastSet = findLastSet((uint64_t)ImmValue);
2782     unsigned ShiftAmount = FirstSet - (15 - (LastSet - FirstSet));
2783     uint16_t Bits = (ImmValue >> ShiftAmount) & 0xffff;
2784     TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits, IDLoc, STI);
2785     TOut.emitRRI(Mips::DSLL, TmpReg, TmpReg, ShiftAmount, IDLoc, STI);
2786 
2787     if (UseSrcReg)
2788       TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2789 
2790     return false;
2791   }
2792 
2793   warnIfNoMacro(IDLoc);
2794 
2795   // The remaining case is packed with a sequence of dsll and ori with zeros
2796   // being omitted and any neighbouring dsll's being coalesced.
2797   // The highest 32-bit's are equivalent to a 32-bit immediate load.
2798 
2799   // Load bits 32-63 of ImmValue into bits 0-31 of the temporary register.
2800   if (loadImmediate(ImmValue >> 32, TmpReg, Mips::NoRegister, true, false,
2801                     IDLoc, Out, STI))
2802     return false;
2803 
2804   // Shift and accumulate into the register. If a 16-bit chunk is zero, then
2805   // skip it and defer the shift to the next chunk.
2806   unsigned ShiftCarriedForwards = 16;
2807   for (int BitNum = 16; BitNum >= 0; BitNum -= 16) {
2808     uint16_t ImmChunk = (ImmValue >> BitNum) & 0xffff;
2809 
2810     if (ImmChunk != 0) {
2811       TOut.emitDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc, STI);
2812       TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, ImmChunk, IDLoc, STI);
2813       ShiftCarriedForwards = 0;
2814     }
2815 
2816     ShiftCarriedForwards += 16;
2817   }
2818   ShiftCarriedForwards -= 16;
2819 
2820   // Finish any remaining shifts left by trailing zeros.
2821   if (ShiftCarriedForwards)
2822     TOut.emitDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc, STI);
2823 
2824   if (UseSrcReg)
2825     TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI);
2826 
2827   return false;
2828 }
2829 
2830 bool MipsAsmParser::expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
2831                                   MCStreamer &Out, const MCSubtargetInfo *STI) {
2832   const MCOperand &ImmOp = Inst.getOperand(1);
2833   assert(ImmOp.isImm() && "expected immediate operand kind");
2834   const MCOperand &DstRegOp = Inst.getOperand(0);
2835   assert(DstRegOp.isReg() && "expected register operand kind");
2836 
2837   if (loadImmediate(ImmOp.getImm(), DstRegOp.getReg(), Mips::NoRegister,
2838                     Is32BitImm, false, IDLoc, Out, STI))
2839     return true;
2840 
2841   return false;
2842 }
2843 
2844 bool MipsAsmParser::expandLoadAddress(unsigned DstReg, unsigned BaseReg,
2845                                       const MCOperand &Offset,
2846                                       bool Is32BitAddress, SMLoc IDLoc,
2847                                       MCStreamer &Out,
2848                                       const MCSubtargetInfo *STI) {
2849   // la can't produce a usable address when addresses are 64-bit.
2850   if (Is32BitAddress && ABI.ArePtrs64bit()) {
2851     // FIXME: Demote this to a warning and continue as if we had 'dla' instead.
2852     //        We currently can't do this because we depend on the equality
2853     //        operator and N64 can end up with a GPR32/GPR64 mismatch.
2854     Error(IDLoc, "la used to load 64-bit address");
2855     // Continue as if we had 'dla' instead.
2856     Is32BitAddress = false;
2857     return true;
2858   }
2859 
2860   // dla requires 64-bit addresses.
2861   if (!Is32BitAddress && !hasMips3()) {
2862     Error(IDLoc, "instruction requires a 64-bit architecture");
2863     return true;
2864   }
2865 
2866   if (!Offset.isImm())
2867     return loadAndAddSymbolAddress(Offset.getExpr(), DstReg, BaseReg,
2868                                    Is32BitAddress, IDLoc, Out, STI);
2869 
2870   if (!ABI.ArePtrs64bit()) {
2871     // Continue as if we had 'la' whether we had 'la' or 'dla'.
2872     Is32BitAddress = true;
2873   }
2874 
2875   return loadImmediate(Offset.getImm(), DstReg, BaseReg, Is32BitAddress, true,
2876                        IDLoc, Out, STI);
2877 }
2878 
2879 bool MipsAsmParser::loadAndAddSymbolAddress(const MCExpr *SymExpr,
2880                                             unsigned DstReg, unsigned SrcReg,
2881                                             bool Is32BitSym, SMLoc IDLoc,
2882                                             MCStreamer &Out,
2883                                             const MCSubtargetInfo *STI) {
2884   MipsTargetStreamer &TOut = getTargetStreamer();
2885   bool UseSrcReg = SrcReg != Mips::NoRegister && SrcReg != Mips::ZERO &&
2886                    SrcReg != Mips::ZERO_64;
2887   warnIfNoMacro(IDLoc);
2888 
2889   if (inPicMode()) {
2890     MCValue Res;
2891     if (!SymExpr->evaluateAsRelocatable(Res, nullptr, nullptr)) {
2892       Error(IDLoc, "expected relocatable expression");
2893       return true;
2894     }
2895     if (Res.getSymB() != nullptr) {
2896       Error(IDLoc, "expected relocatable expression with only one symbol");
2897       return true;
2898     }
2899 
2900     bool IsPtr64 = ABI.ArePtrs64bit();
2901     bool IsLocalSym =
2902         Res.getSymA()->getSymbol().isInSection() ||
2903         Res.getSymA()->getSymbol().isTemporary() ||
2904         (Res.getSymA()->getSymbol().isELF() &&
2905          cast<MCSymbolELF>(Res.getSymA()->getSymbol()).getBinding() ==
2906              ELF::STB_LOCAL);
2907     bool UseXGOT = STI->getFeatureBits()[Mips::FeatureXGOT] && !IsLocalSym;
2908 
2909     // The case where the result register is $25 is somewhat special. If the
2910     // symbol in the final relocation is external and not modified with a
2911     // constant then we must use R_MIPS_CALL16 instead of R_MIPS_GOT16
2912     // or R_MIPS_CALL16 instead of R_MIPS_GOT_DISP in 64-bit case.
2913     if ((DstReg == Mips::T9 || DstReg == Mips::T9_64) && !UseSrcReg &&
2914         Res.getConstant() == 0 && !IsLocalSym) {
2915       if (UseXGOT) {
2916         const MCExpr *CallHiExpr = MipsMCExpr::create(MipsMCExpr::MEK_CALL_HI16,
2917                                                       SymExpr, getContext());
2918         const MCExpr *CallLoExpr = MipsMCExpr::create(MipsMCExpr::MEK_CALL_LO16,
2919                                                       SymExpr, getContext());
2920         TOut.emitRX(Mips::LUi, DstReg, MCOperand::createExpr(CallHiExpr), IDLoc,
2921                     STI);
2922         TOut.emitRRR(IsPtr64 ? Mips::DADDu : Mips::ADDu, DstReg, DstReg, GPReg,
2923                      IDLoc, STI);
2924         TOut.emitRRX(IsPtr64 ? Mips::LD : Mips::LW, DstReg, DstReg,
2925                      MCOperand::createExpr(CallLoExpr), IDLoc, STI);
2926       } else {
2927         const MCExpr *CallExpr =
2928             MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, SymExpr, getContext());
2929         TOut.emitRRX(IsPtr64 ? Mips::LD : Mips::LW, DstReg, GPReg,
2930                      MCOperand::createExpr(CallExpr), IDLoc, STI);
2931       }
2932       return false;
2933     }
2934 
2935     unsigned TmpReg = DstReg;
2936     if (UseSrcReg &&
2937         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg,
2938                                                                SrcReg)) {
2939       // If $rs is the same as $rd, we need to use AT.
2940       // If it is not available we exit.
2941       unsigned ATReg = getATReg(IDLoc);
2942       if (!ATReg)
2943         return true;
2944       TmpReg = ATReg;
2945     }
2946 
2947     if (UseXGOT) {
2948       // Loading address from XGOT
2949       //   External GOT: lui $tmp, %got_hi(symbol)($gp)
2950       //                 addu $tmp, $tmp, $gp
2951       //                 lw $tmp, %got_lo(symbol)($tmp)
2952       //                >addiu $tmp, $tmp, offset
2953       //                >addiu $rd, $tmp, $rs
2954       // The addiu's marked with a '>' may be omitted if they are redundant. If
2955       // this happens then the last instruction must use $rd as the result
2956       // register.
2957       const MCExpr *CallHiExpr =
2958           MipsMCExpr::create(MipsMCExpr::MEK_GOT_HI16, SymExpr, getContext());
2959       const MCExpr *CallLoExpr = MipsMCExpr::create(
2960           MipsMCExpr::MEK_GOT_LO16, Res.getSymA(), getContext());
2961 
2962       TOut.emitRX(Mips::LUi, TmpReg, MCOperand::createExpr(CallHiExpr), IDLoc,
2963                   STI);
2964       TOut.emitRRR(IsPtr64 ? Mips::DADDu : Mips::ADDu, TmpReg, TmpReg, GPReg,
2965                    IDLoc, STI);
2966       TOut.emitRRX(IsPtr64 ? Mips::LD : Mips::LW, TmpReg, TmpReg,
2967                    MCOperand::createExpr(CallLoExpr), IDLoc, STI);
2968 
2969       if (Res.getConstant() != 0)
2970         TOut.emitRRX(IsPtr64 ? Mips::DADDiu : Mips::ADDiu, TmpReg, TmpReg,
2971                      MCOperand::createExpr(MCConstantExpr::create(
2972                          Res.getConstant(), getContext())),
2973                      IDLoc, STI);
2974 
2975       if (UseSrcReg)
2976         TOut.emitRRR(IsPtr64 ? Mips::DADDu : Mips::ADDu, DstReg, TmpReg, SrcReg,
2977                      IDLoc, STI);
2978       return false;
2979     }
2980 
2981     const MipsMCExpr *GotExpr = nullptr;
2982     const MCExpr *LoExpr = nullptr;
2983     if (IsPtr64) {
2984       // The remaining cases are:
2985       //   Small offset: ld $tmp, %got_disp(symbol)($gp)
2986       //                >daddiu $tmp, $tmp, offset
2987       //                >daddu $rd, $tmp, $rs
2988       // The daddiu's marked with a '>' may be omitted if they are redundant. If
2989       // this happens then the last instruction must use $rd as the result
2990       // register.
2991       GotExpr = MipsMCExpr::create(MipsMCExpr::MEK_GOT_DISP, Res.getSymA(),
2992                                    getContext());
2993       if (Res.getConstant() != 0) {
2994         // Symbols fully resolve with just the %got_disp(symbol) but we
2995         // must still account for any offset to the symbol for
2996         // expressions like symbol+8.
2997         LoExpr = MCConstantExpr::create(Res.getConstant(), getContext());
2998 
2999         // FIXME: Offsets greater than 16 bits are not yet implemented.
3000         // FIXME: The correct range is a 32-bit sign-extended number.
3001         if (Res.getConstant() < -0x8000 || Res.getConstant() > 0x7fff) {
3002           Error(IDLoc, "macro instruction uses large offset, which is not "
3003                        "currently supported");
3004           return true;
3005         }
3006       }
3007     } else {
3008       // The remaining cases are:
3009       //   External GOT: lw $tmp, %got(symbol)($gp)
3010       //                >addiu $tmp, $tmp, offset
3011       //                >addiu $rd, $tmp, $rs
3012       //   Local GOT:    lw $tmp, %got(symbol+offset)($gp)
3013       //                 addiu $tmp, $tmp, %lo(symbol+offset)($gp)
3014       //                >addiu $rd, $tmp, $rs
3015       // The addiu's marked with a '>' may be omitted if they are redundant. If
3016       // this happens then the last instruction must use $rd as the result
3017       // register.
3018       if (IsLocalSym) {
3019         GotExpr =
3020             MipsMCExpr::create(MipsMCExpr::MEK_GOT, SymExpr, getContext());
3021         LoExpr = MipsMCExpr::create(MipsMCExpr::MEK_LO, SymExpr, getContext());
3022       } else {
3023         // External symbols fully resolve the symbol with just the %got(symbol)
3024         // but we must still account for any offset to the symbol for
3025         // expressions like symbol+8.
3026         GotExpr = MipsMCExpr::create(MipsMCExpr::MEK_GOT, Res.getSymA(),
3027                                      getContext());
3028         if (Res.getConstant() != 0)
3029           LoExpr = MCConstantExpr::create(Res.getConstant(), getContext());
3030       }
3031     }
3032 
3033     TOut.emitRRX(IsPtr64 ? Mips::LD : Mips::LW, TmpReg, GPReg,
3034                  MCOperand::createExpr(GotExpr), IDLoc, STI);
3035 
3036     if (LoExpr)
3037       TOut.emitRRX(IsPtr64 ? Mips::DADDiu : Mips::ADDiu, TmpReg, TmpReg,
3038                    MCOperand::createExpr(LoExpr), IDLoc, STI);
3039 
3040     if (UseSrcReg)
3041       TOut.emitRRR(IsPtr64 ? Mips::DADDu : Mips::ADDu, DstReg, TmpReg, SrcReg,
3042                    IDLoc, STI);
3043 
3044     return false;
3045   }
3046 
3047   const MipsMCExpr *HiExpr =
3048       MipsMCExpr::create(MipsMCExpr::MEK_HI, SymExpr, getContext());
3049   const MipsMCExpr *LoExpr =
3050       MipsMCExpr::create(MipsMCExpr::MEK_LO, SymExpr, getContext());
3051 
3052   // This is the 64-bit symbol address expansion.
3053   if (ABI.ArePtrs64bit() && isGP64bit()) {
3054     // We need AT for the 64-bit expansion in the cases where the optional
3055     // source register is the destination register and for the superscalar
3056     // scheduled form.
3057     //
3058     // If it is not available we exit if the destination is the same as the
3059     // source register.
3060 
3061     const MipsMCExpr *HighestExpr =
3062         MipsMCExpr::create(MipsMCExpr::MEK_HIGHEST, SymExpr, getContext());
3063     const MipsMCExpr *HigherExpr =
3064         MipsMCExpr::create(MipsMCExpr::MEK_HIGHER, SymExpr, getContext());
3065 
3066     bool RdRegIsRsReg =
3067         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg);
3068 
3069     if (canUseATReg() && UseSrcReg && RdRegIsRsReg) {
3070       unsigned ATReg = getATReg(IDLoc);
3071 
3072       // If $rs is the same as $rd:
3073       // (d)la $rd, sym($rd) => lui    $at, %highest(sym)
3074       //                        daddiu $at, $at, %higher(sym)
3075       //                        dsll   $at, $at, 16
3076       //                        daddiu $at, $at, %hi(sym)
3077       //                        dsll   $at, $at, 16
3078       //                        daddiu $at, $at, %lo(sym)
3079       //                        daddu  $rd, $at, $rd
3080       TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HighestExpr), IDLoc,
3081                   STI);
3082       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg,
3083                    MCOperand::createExpr(HigherExpr), IDLoc, STI);
3084       TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI);
3085       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(HiExpr),
3086                    IDLoc, STI);
3087       TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI);
3088       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr),
3089                    IDLoc, STI);
3090       TOut.emitRRR(Mips::DADDu, DstReg, ATReg, SrcReg, IDLoc, STI);
3091 
3092       return false;
3093     } else if (canUseATReg() && !RdRegIsRsReg && DstReg != getATReg(IDLoc)) {
3094       unsigned ATReg = getATReg(IDLoc);
3095 
3096       // If the $rs is different from $rd or if $rs isn't specified and we
3097       // have $at available:
3098       // (d)la $rd, sym/sym($rs) => lui    $rd, %highest(sym)
3099       //                            lui    $at, %hi(sym)
3100       //                            daddiu $rd, $rd, %higher(sym)
3101       //                            daddiu $at, $at, %lo(sym)
3102       //                            dsll32 $rd, $rd, 0
3103       //                            daddu  $rd, $rd, $at
3104       //                            (daddu  $rd, $rd, $rs)
3105       //
3106       // Which is preferred for superscalar issue.
3107       TOut.emitRX(Mips::LUi, DstReg, MCOperand::createExpr(HighestExpr), IDLoc,
3108                   STI);
3109       TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HiExpr), IDLoc, STI);
3110       TOut.emitRRX(Mips::DADDiu, DstReg, DstReg,
3111                    MCOperand::createExpr(HigherExpr), IDLoc, STI);
3112       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr),
3113                    IDLoc, STI);
3114       TOut.emitRRI(Mips::DSLL32, DstReg, DstReg, 0, IDLoc, STI);
3115       TOut.emitRRR(Mips::DADDu, DstReg, DstReg, ATReg, IDLoc, STI);
3116       if (UseSrcReg)
3117         TOut.emitRRR(Mips::DADDu, DstReg, DstReg, SrcReg, IDLoc, STI);
3118 
3119       return false;
3120     } else if ((!canUseATReg() && !RdRegIsRsReg) ||
3121                (canUseATReg() && DstReg == getATReg(IDLoc))) {
3122       // Otherwise, synthesize the address in the destination register
3123       // serially:
3124       // (d)la $rd, sym/sym($rs) => lui    $rd, %highest(sym)
3125       //                            daddiu $rd, $rd, %higher(sym)
3126       //                            dsll   $rd, $rd, 16
3127       //                            daddiu $rd, $rd, %hi(sym)
3128       //                            dsll   $rd, $rd, 16
3129       //                            daddiu $rd, $rd, %lo(sym)
3130       TOut.emitRX(Mips::LUi, DstReg, MCOperand::createExpr(HighestExpr), IDLoc,
3131                   STI);
3132       TOut.emitRRX(Mips::DADDiu, DstReg, DstReg,
3133                    MCOperand::createExpr(HigherExpr), IDLoc, STI);
3134       TOut.emitRRI(Mips::DSLL, DstReg, DstReg, 16, IDLoc, STI);
3135       TOut.emitRRX(Mips::DADDiu, DstReg, DstReg,
3136                    MCOperand::createExpr(HiExpr), IDLoc, STI);
3137       TOut.emitRRI(Mips::DSLL, DstReg, DstReg, 16, IDLoc, STI);
3138       TOut.emitRRX(Mips::DADDiu, DstReg, DstReg,
3139                    MCOperand::createExpr(LoExpr), IDLoc, STI);
3140       if (UseSrcReg)
3141         TOut.emitRRR(Mips::DADDu, DstReg, DstReg, SrcReg, IDLoc, STI);
3142 
3143       return false;
3144     } else {
3145       // We have a case where SrcReg == DstReg and we don't have $at
3146       // available. We can't expand this case, so error out appropriately.
3147       assert(SrcReg == DstReg && !canUseATReg() &&
3148              "Could have expanded dla but didn't?");
3149       reportParseError(IDLoc,
3150                      "pseudo-instruction requires $at, which is not available");
3151       return true;
3152     }
3153   }
3154 
3155   // And now, the 32-bit symbol address expansion:
3156   // If $rs is the same as $rd:
3157   // (d)la $rd, sym($rd)     => lui   $at, %hi(sym)
3158   //                            ori   $at, $at, %lo(sym)
3159   //                            addu  $rd, $at, $rd
3160   // Otherwise, if the $rs is different from $rd or if $rs isn't specified:
3161   // (d)la $rd, sym/sym($rs) => lui   $rd, %hi(sym)
3162   //                            ori   $rd, $rd, %lo(sym)
3163   //                            (addu $rd, $rd, $rs)
3164   unsigned TmpReg = DstReg;
3165   if (UseSrcReg &&
3166       getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) {
3167     // If $rs is the same as $rd, we need to use AT.
3168     // If it is not available we exit.
3169     unsigned ATReg = getATReg(IDLoc);
3170     if (!ATReg)
3171       return true;
3172     TmpReg = ATReg;
3173   }
3174 
3175   TOut.emitRX(Mips::LUi, TmpReg, MCOperand::createExpr(HiExpr), IDLoc, STI);
3176   TOut.emitRRX(Mips::ADDiu, TmpReg, TmpReg, MCOperand::createExpr(LoExpr),
3177                IDLoc, STI);
3178 
3179   if (UseSrcReg)
3180     TOut.emitRRR(Mips::ADDu, DstReg, TmpReg, SrcReg, IDLoc, STI);
3181   else
3182     assert(
3183         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, TmpReg));
3184 
3185   return false;
3186 }
3187 
3188 // Each double-precision register DO-D15 overlaps with two of the single
3189 // precision registers F0-F31. As an example, all of the following hold true:
3190 // D0 + 1 == F1, F1 + 1 == D1, F1 + 1 == F2, depending on the context.
3191 static unsigned nextReg(unsigned Reg) {
3192   if (MipsMCRegisterClasses[Mips::FGR32RegClassID].contains(Reg))
3193     return Reg == (unsigned)Mips::F31 ? (unsigned)Mips::F0 : Reg + 1;
3194   switch (Reg) {
3195   default: llvm_unreachable("Unknown register in assembly macro expansion!");
3196   case Mips::ZERO: return Mips::AT;
3197   case Mips::AT:   return Mips::V0;
3198   case Mips::V0:   return Mips::V1;
3199   case Mips::V1:   return Mips::A0;
3200   case Mips::A0:   return Mips::A1;
3201   case Mips::A1:   return Mips::A2;
3202   case Mips::A2:   return Mips::A3;
3203   case Mips::A3:   return Mips::T0;
3204   case Mips::T0:   return Mips::T1;
3205   case Mips::T1:   return Mips::T2;
3206   case Mips::T2:   return Mips::T3;
3207   case Mips::T3:   return Mips::T4;
3208   case Mips::T4:   return Mips::T5;
3209   case Mips::T5:   return Mips::T6;
3210   case Mips::T6:   return Mips::T7;
3211   case Mips::T7:   return Mips::S0;
3212   case Mips::S0:   return Mips::S1;
3213   case Mips::S1:   return Mips::S2;
3214   case Mips::S2:   return Mips::S3;
3215   case Mips::S3:   return Mips::S4;
3216   case Mips::S4:   return Mips::S5;
3217   case Mips::S5:   return Mips::S6;
3218   case Mips::S6:   return Mips::S7;
3219   case Mips::S7:   return Mips::T8;
3220   case Mips::T8:   return Mips::T9;
3221   case Mips::T9:   return Mips::K0;
3222   case Mips::K0:   return Mips::K1;
3223   case Mips::K1:   return Mips::GP;
3224   case Mips::GP:   return Mips::SP;
3225   case Mips::SP:   return Mips::FP;
3226   case Mips::FP:   return Mips::RA;
3227   case Mips::RA:   return Mips::ZERO;
3228   case Mips::D0:   return Mips::F1;
3229   case Mips::D1:   return Mips::F3;
3230   case Mips::D2:   return Mips::F5;
3231   case Mips::D3:   return Mips::F7;
3232   case Mips::D4:   return Mips::F9;
3233   case Mips::D5:   return Mips::F11;
3234   case Mips::D6:   return Mips::F13;
3235   case Mips::D7:   return Mips::F15;
3236   case Mips::D8:   return Mips::F17;
3237   case Mips::D9:   return Mips::F19;
3238   case Mips::D10:   return Mips::F21;
3239   case Mips::D11:   return Mips::F23;
3240   case Mips::D12:   return Mips::F25;
3241   case Mips::D13:   return Mips::F27;
3242   case Mips::D14:   return Mips::F29;
3243   case Mips::D15:   return Mips::F31;
3244   }
3245 }
3246 
3247 // FIXME: This method is too general. In principle we should compute the number
3248 // of instructions required to synthesize the immediate inline compared to
3249 // synthesizing the address inline and relying on non .text sections.
3250 // For static O32 and N32 this may yield a small benefit, for static N64 this is
3251 // likely to yield a much larger benefit as we have to synthesize a 64bit
3252 // address to load a 64 bit value.
3253 bool MipsAsmParser::emitPartialAddress(MipsTargetStreamer &TOut, SMLoc IDLoc,
3254                                        MCSymbol *Sym) {
3255   unsigned ATReg = getATReg(IDLoc);
3256   if (!ATReg)
3257     return true;
3258 
3259   if(IsPicEnabled) {
3260     const MCExpr *GotSym =
3261         MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3262     const MipsMCExpr *GotExpr =
3263         MipsMCExpr::create(MipsMCExpr::MEK_GOT, GotSym, getContext());
3264 
3265     if(isABI_O32() || isABI_N32()) {
3266       TOut.emitRRX(Mips::LW, ATReg, GPReg, MCOperand::createExpr(GotExpr),
3267                    IDLoc, STI);
3268     } else { //isABI_N64()
3269       TOut.emitRRX(Mips::LD, ATReg, GPReg, MCOperand::createExpr(GotExpr),
3270                    IDLoc, STI);
3271     }
3272   } else { //!IsPicEnabled
3273     const MCExpr *HiSym =
3274         MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3275     const MipsMCExpr *HiExpr =
3276         MipsMCExpr::create(MipsMCExpr::MEK_HI, HiSym, getContext());
3277 
3278     // FIXME: This is technically correct but gives a different result to gas,
3279     // but gas is incomplete there (it has a fixme noting it doesn't work with
3280     // 64-bit addresses).
3281     // FIXME: With -msym32 option, the address expansion for N64 should probably
3282     // use the O32 / N32 case. It's safe to use the 64 address expansion as the
3283     // symbol's value is considered sign extended.
3284     if(isABI_O32() || isABI_N32()) {
3285       TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HiExpr), IDLoc, STI);
3286     } else { //isABI_N64()
3287       const MCExpr *HighestSym =
3288           MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3289       const MipsMCExpr *HighestExpr =
3290           MipsMCExpr::create(MipsMCExpr::MEK_HIGHEST, HighestSym, getContext());
3291       const MCExpr *HigherSym =
3292           MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3293       const MipsMCExpr *HigherExpr =
3294           MipsMCExpr::create(MipsMCExpr::MEK_HIGHER, HigherSym, getContext());
3295 
3296       TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HighestExpr), IDLoc,
3297                   STI);
3298       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg,
3299                    MCOperand::createExpr(HigherExpr), IDLoc, STI);
3300       TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI);
3301       TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(HiExpr),
3302                    IDLoc, STI);
3303       TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI);
3304     }
3305   }
3306   return false;
3307 }
3308 
3309 static uint64_t convertIntToDoubleImm(uint64_t ImmOp64) {
3310   // If ImmOp64 is AsmToken::Integer type (all bits set to zero in the
3311   // exponent field), convert it to double (e.g. 1 to 1.0)
3312   if ((Hi_32(ImmOp64) & 0x7ff00000) == 0) {
3313     APFloat RealVal(APFloat::IEEEdouble(), ImmOp64);
3314     ImmOp64 = RealVal.bitcastToAPInt().getZExtValue();
3315   }
3316   return ImmOp64;
3317 }
3318 
3319 static uint32_t covertDoubleImmToSingleImm(uint64_t ImmOp64) {
3320   // Conversion of a double in an uint64_t to a float in a uint32_t,
3321   // retaining the bit pattern of a float.
3322   double DoubleImm = BitsToDouble(ImmOp64);
3323   float TmpFloat = static_cast<float>(DoubleImm);
3324   return FloatToBits(TmpFloat);
3325 }
3326 
3327 bool MipsAsmParser::expandLoadSingleImmToGPR(MCInst &Inst, SMLoc IDLoc,
3328                                              MCStreamer &Out,
3329                                              const MCSubtargetInfo *STI) {
3330   assert(Inst.getNumOperands() == 2 && "Invalid operand count");
3331   assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isImm() &&
3332          "Invalid instruction operand.");
3333 
3334   unsigned FirstReg = Inst.getOperand(0).getReg();
3335   uint64_t ImmOp64 = Inst.getOperand(1).getImm();
3336 
3337   uint32_t ImmOp32 = covertDoubleImmToSingleImm(convertIntToDoubleImm(ImmOp64));
3338 
3339   return loadImmediate(ImmOp32, FirstReg, Mips::NoRegister, true, false, IDLoc,
3340                        Out, STI);
3341 }
3342 
3343 bool MipsAsmParser::expandLoadSingleImmToFPR(MCInst &Inst, SMLoc IDLoc,
3344                                              MCStreamer &Out,
3345                                              const MCSubtargetInfo *STI) {
3346   MipsTargetStreamer &TOut = getTargetStreamer();
3347   assert(Inst.getNumOperands() == 2 && "Invalid operand count");
3348   assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isImm() &&
3349          "Invalid instruction operand.");
3350 
3351   unsigned FirstReg = Inst.getOperand(0).getReg();
3352   uint64_t ImmOp64 = Inst.getOperand(1).getImm();
3353 
3354   ImmOp64 = convertIntToDoubleImm(ImmOp64);
3355 
3356   uint32_t ImmOp32 = covertDoubleImmToSingleImm(ImmOp64);
3357 
3358   unsigned TmpReg = Mips::ZERO;
3359   if (ImmOp32 != 0) {
3360     TmpReg = getATReg(IDLoc);
3361     if (!TmpReg)
3362       return true;
3363   }
3364 
3365   if (Lo_32(ImmOp64) == 0) {
3366     if (TmpReg != Mips::ZERO && loadImmediate(ImmOp32, TmpReg, Mips::NoRegister,
3367                                               true, false, IDLoc, Out, STI))
3368       return true;
3369     TOut.emitRR(Mips::MTC1, FirstReg, TmpReg, IDLoc, STI);
3370     return false;
3371   }
3372 
3373   MCSection *CS = getStreamer().getCurrentSectionOnly();
3374   // FIXME: Enhance this expansion to use the .lit4 & .lit8 sections
3375   // where appropriate.
3376   MCSection *ReadOnlySection =
3377       getContext().getELFSection(".rodata", ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
3378 
3379   MCSymbol *Sym = getContext().createTempSymbol();
3380   const MCExpr *LoSym =
3381       MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3382   const MipsMCExpr *LoExpr =
3383       MipsMCExpr::create(MipsMCExpr::MEK_LO, LoSym, getContext());
3384 
3385   getStreamer().SwitchSection(ReadOnlySection);
3386   getStreamer().EmitLabel(Sym, IDLoc);
3387   getStreamer().EmitIntValue(ImmOp32, 4);
3388   getStreamer().SwitchSection(CS);
3389 
3390   if (emitPartialAddress(TOut, IDLoc, Sym))
3391     return true;
3392   TOut.emitRRX(Mips::LWC1, FirstReg, TmpReg, MCOperand::createExpr(LoExpr),
3393                IDLoc, STI);
3394   return false;
3395 }
3396 
3397 bool MipsAsmParser::expandLoadDoubleImmToGPR(MCInst &Inst, SMLoc IDLoc,
3398                                              MCStreamer &Out,
3399                                              const MCSubtargetInfo *STI) {
3400   MipsTargetStreamer &TOut = getTargetStreamer();
3401   assert(Inst.getNumOperands() == 2 && "Invalid operand count");
3402   assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isImm() &&
3403          "Invalid instruction operand.");
3404 
3405   unsigned FirstReg = Inst.getOperand(0).getReg();
3406   uint64_t ImmOp64 = Inst.getOperand(1).getImm();
3407 
3408   ImmOp64 = convertIntToDoubleImm(ImmOp64);
3409 
3410   if (Lo_32(ImmOp64) == 0) {
3411     if (isGP64bit()) {
3412       if (loadImmediate(ImmOp64, FirstReg, Mips::NoRegister, false, false,
3413                         IDLoc, Out, STI))
3414         return true;
3415     } else {
3416       if (loadImmediate(Hi_32(ImmOp64), FirstReg, Mips::NoRegister, true, false,
3417                         IDLoc, Out, STI))
3418         return true;
3419 
3420       if (loadImmediate(0, nextReg(FirstReg), Mips::NoRegister, true, false,
3421                         IDLoc, Out, STI))
3422         return true;
3423     }
3424     return false;
3425   }
3426 
3427   MCSection *CS = getStreamer().getCurrentSectionOnly();
3428   MCSection *ReadOnlySection =
3429       getContext().getELFSection(".rodata", ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
3430 
3431   MCSymbol *Sym = getContext().createTempSymbol();
3432   const MCExpr *LoSym =
3433       MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3434   const MipsMCExpr *LoExpr =
3435       MipsMCExpr::create(MipsMCExpr::MEK_LO, LoSym, getContext());
3436 
3437   getStreamer().SwitchSection(ReadOnlySection);
3438   getStreamer().EmitLabel(Sym, IDLoc);
3439   getStreamer().EmitValueToAlignment(8);
3440   getStreamer().EmitIntValue(ImmOp64, 8);
3441   getStreamer().SwitchSection(CS);
3442 
3443   unsigned TmpReg = getATReg(IDLoc);
3444   if (!TmpReg)
3445     return true;
3446 
3447   if (emitPartialAddress(TOut, IDLoc, Sym))
3448     return true;
3449 
3450   TOut.emitRRX(isABI_N64() ? Mips::DADDiu : Mips::ADDiu, TmpReg, TmpReg,
3451                MCOperand::createExpr(LoExpr), IDLoc, STI);
3452 
3453   if (isGP64bit())
3454     TOut.emitRRI(Mips::LD, FirstReg, TmpReg, 0, IDLoc, STI);
3455   else {
3456     TOut.emitRRI(Mips::LW, FirstReg, TmpReg, 0, IDLoc, STI);
3457     TOut.emitRRI(Mips::LW, nextReg(FirstReg), TmpReg, 4, IDLoc, STI);
3458   }
3459   return false;
3460 }
3461 
3462 bool MipsAsmParser::expandLoadDoubleImmToFPR(MCInst &Inst, bool Is64FPU,
3463                                              SMLoc IDLoc, MCStreamer &Out,
3464                                              const MCSubtargetInfo *STI) {
3465   MipsTargetStreamer &TOut = getTargetStreamer();
3466   assert(Inst.getNumOperands() == 2 && "Invalid operand count");
3467   assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isImm() &&
3468          "Invalid instruction operand.");
3469 
3470   unsigned FirstReg = Inst.getOperand(0).getReg();
3471   uint64_t ImmOp64 = Inst.getOperand(1).getImm();
3472 
3473   ImmOp64 = convertIntToDoubleImm(ImmOp64);
3474 
3475   unsigned TmpReg = Mips::ZERO;
3476   if (ImmOp64 != 0) {
3477     TmpReg = getATReg(IDLoc);
3478     if (!TmpReg)
3479       return true;
3480   }
3481 
3482   if ((Lo_32(ImmOp64) == 0) &&
3483       !((Hi_32(ImmOp64) & 0xffff0000) && (Hi_32(ImmOp64) & 0x0000ffff))) {
3484     if (isGP64bit()) {
3485       if (TmpReg != Mips::ZERO &&
3486           loadImmediate(ImmOp64, TmpReg, Mips::NoRegister, false, false, IDLoc,
3487                         Out, STI))
3488         return true;
3489       TOut.emitRR(Mips::DMTC1, FirstReg, TmpReg, IDLoc, STI);
3490       return false;
3491     }
3492 
3493     if (TmpReg != Mips::ZERO &&
3494         loadImmediate(Hi_32(ImmOp64), TmpReg, Mips::NoRegister, true, false,
3495                       IDLoc, Out, STI))
3496       return true;
3497 
3498     if (hasMips32r2()) {
3499       TOut.emitRR(Mips::MTC1, FirstReg, Mips::ZERO, IDLoc, STI);
3500       TOut.emitRRR(Mips::MTHC1_D32, FirstReg, FirstReg, TmpReg, IDLoc, STI);
3501     } else {
3502       TOut.emitRR(Mips::MTC1, nextReg(FirstReg), TmpReg, IDLoc, STI);
3503       TOut.emitRR(Mips::MTC1, FirstReg, Mips::ZERO, IDLoc, STI);
3504     }
3505     return false;
3506   }
3507 
3508   MCSection *CS = getStreamer().getCurrentSectionOnly();
3509   // FIXME: Enhance this expansion to use the .lit4 & .lit8 sections
3510   // where appropriate.
3511   MCSection *ReadOnlySection =
3512       getContext().getELFSection(".rodata", ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
3513 
3514   MCSymbol *Sym = getContext().createTempSymbol();
3515   const MCExpr *LoSym =
3516       MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
3517   const MipsMCExpr *LoExpr =
3518       MipsMCExpr::create(MipsMCExpr::MEK_LO, LoSym, getContext());
3519 
3520   getStreamer().SwitchSection(ReadOnlySection);
3521   getStreamer().EmitLabel(Sym, IDLoc);
3522   getStreamer().EmitValueToAlignment(8);
3523   getStreamer().EmitIntValue(ImmOp64, 8);
3524   getStreamer().SwitchSection(CS);
3525 
3526   if (emitPartialAddress(TOut, IDLoc, Sym))
3527     return true;
3528 
3529   TOut.emitRRX(Is64FPU ? Mips::LDC164 : Mips::LDC1, FirstReg, TmpReg,
3530                MCOperand::createExpr(LoExpr), IDLoc, STI);
3531 
3532   return false;
3533 }
3534 
3535 bool MipsAsmParser::expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc,
3536                                                MCStreamer &Out,
3537                                                const MCSubtargetInfo *STI) {
3538   MipsTargetStreamer &TOut = getTargetStreamer();
3539 
3540   assert(getInstDesc(Inst.getOpcode()).getNumOperands() == 1 &&
3541          "unexpected number of operands");
3542 
3543   MCOperand Offset = Inst.getOperand(0);
3544   if (Offset.isExpr()) {
3545     Inst.clear();
3546     Inst.setOpcode(Mips::BEQ_MM);
3547     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
3548     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
3549     Inst.addOperand(MCOperand::createExpr(Offset.getExpr()));
3550   } else {
3551     assert(Offset.isImm() && "expected immediate operand kind");
3552     if (isInt<11>(Offset.getImm())) {
3553       // If offset fits into 11 bits then this instruction becomes microMIPS
3554       // 16-bit unconditional branch instruction.
3555       if (inMicroMipsMode())
3556         Inst.setOpcode(hasMips32r6() ? Mips::BC16_MMR6 : Mips::B16_MM);
3557     } else {
3558       if (!isInt<17>(Offset.getImm()))
3559         return Error(IDLoc, "branch target out of range");
3560       if (offsetToAlignment(Offset.getImm(), Align(2)))
3561         return Error(IDLoc, "branch to misaligned address");
3562       Inst.clear();
3563       Inst.setOpcode(Mips::BEQ_MM);
3564       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
3565       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
3566       Inst.addOperand(MCOperand::createImm(Offset.getImm()));
3567     }
3568   }
3569   Out.EmitInstruction(Inst, *STI);
3570 
3571   // If .set reorder is active and branch instruction has a delay slot,
3572   // emit a NOP after it.
3573   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
3574   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder())
3575     TOut.emitEmptyDelaySlot(true, IDLoc, STI);
3576 
3577   return false;
3578 }
3579 
3580 bool MipsAsmParser::expandBranchImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3581                                     const MCSubtargetInfo *STI) {
3582   MipsTargetStreamer &TOut = getTargetStreamer();
3583   const MCOperand &DstRegOp = Inst.getOperand(0);
3584   assert(DstRegOp.isReg() && "expected register operand kind");
3585 
3586   const MCOperand &ImmOp = Inst.getOperand(1);
3587   assert(ImmOp.isImm() && "expected immediate operand kind");
3588 
3589   const MCOperand &MemOffsetOp = Inst.getOperand(2);
3590   assert((MemOffsetOp.isImm() || MemOffsetOp.isExpr()) &&
3591          "expected immediate or expression operand");
3592 
3593   bool IsLikely = false;
3594 
3595   unsigned OpCode = 0;
3596   switch(Inst.getOpcode()) {
3597     case Mips::BneImm:
3598       OpCode = Mips::BNE;
3599       break;
3600     case Mips::BeqImm:
3601       OpCode = Mips::BEQ;
3602       break;
3603     case Mips::BEQLImmMacro:
3604       OpCode = Mips::BEQL;
3605       IsLikely = true;
3606       break;
3607     case Mips::BNELImmMacro:
3608       OpCode = Mips::BNEL;
3609       IsLikely = true;
3610       break;
3611     default:
3612       llvm_unreachable("Unknown immediate branch pseudo-instruction.");
3613       break;
3614   }
3615 
3616   int64_t ImmValue = ImmOp.getImm();
3617   if (ImmValue == 0) {
3618     if (IsLikely) {
3619       TOut.emitRRX(OpCode, DstRegOp.getReg(), Mips::ZERO,
3620                    MCOperand::createExpr(MemOffsetOp.getExpr()), IDLoc, STI);
3621       TOut.emitRRI(Mips::SLL, Mips::ZERO, Mips::ZERO, 0, IDLoc, STI);
3622     } else
3623       TOut.emitRRX(OpCode, DstRegOp.getReg(), Mips::ZERO, MemOffsetOp, IDLoc,
3624               STI);
3625   } else {
3626     warnIfNoMacro(IDLoc);
3627 
3628     unsigned ATReg = getATReg(IDLoc);
3629     if (!ATReg)
3630       return true;
3631 
3632     if (loadImmediate(ImmValue, ATReg, Mips::NoRegister, !isGP64bit(), true,
3633                       IDLoc, Out, STI))
3634       return true;
3635 
3636     if (IsLikely) {
3637       TOut.emitRRX(OpCode, DstRegOp.getReg(), ATReg,
3638               MCOperand::createExpr(MemOffsetOp.getExpr()), IDLoc, STI);
3639       TOut.emitRRI(Mips::SLL, Mips::ZERO, Mips::ZERO, 0, IDLoc, STI);
3640     } else
3641       TOut.emitRRX(OpCode, DstRegOp.getReg(), ATReg, MemOffsetOp, IDLoc, STI);
3642   }
3643   return false;
3644 }
3645 
3646 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
3647                                   const MCSubtargetInfo *STI, bool IsLoad) {
3648   const MCOperand &DstRegOp = Inst.getOperand(0);
3649   assert(DstRegOp.isReg() && "expected register operand kind");
3650   const MCOperand &BaseRegOp = Inst.getOperand(1);
3651   assert(BaseRegOp.isReg() && "expected register operand kind");
3652 
3653   MipsTargetStreamer &TOut = getTargetStreamer();
3654   unsigned DstReg = DstRegOp.getReg();
3655   unsigned BaseReg = BaseRegOp.getReg();
3656   unsigned TmpReg = DstReg;
3657 
3658   const MCInstrDesc &Desc = getInstDesc(Inst.getOpcode());
3659   int16_t DstRegClass = Desc.OpInfo[0].RegClass;
3660   unsigned DstRegClassID =
3661       getContext().getRegisterInfo()->getRegClass(DstRegClass).getID();
3662   bool IsGPR = (DstRegClassID == Mips::GPR32RegClassID) ||
3663                (DstRegClassID == Mips::GPR64RegClassID);
3664 
3665   if (!IsLoad || !IsGPR || (BaseReg == DstReg)) {
3666     // At this point we need AT to perform the expansions
3667     // and we exit if it is not available.
3668     TmpReg = getATReg(IDLoc);
3669     if (!TmpReg)
3670       return;
3671   }
3672 
3673   if (Inst.getNumOperands() > 3) {
3674     const MCOperand &BaseRegOp = Inst.getOperand(2);
3675     assert(BaseRegOp.isReg() && "expected register operand kind");
3676     const MCOperand &ExprOp = Inst.getOperand(3);
3677     assert(ExprOp.isExpr() && "expected expression oprand kind");
3678 
3679     unsigned BaseReg = BaseRegOp.getReg();
3680     const MCExpr *ExprOffset = ExprOp.getExpr();
3681 
3682     MCOperand LoOperand = MCOperand::createExpr(
3683         MipsMCExpr::create(MipsMCExpr::MEK_LO, ExprOffset, getContext()));
3684     MCOperand HiOperand = MCOperand::createExpr(
3685         MipsMCExpr::create(MipsMCExpr::MEK_HI, ExprOffset, getContext()));
3686     TOut.emitSCWithSymOffset(Inst.getOpcode(), DstReg, BaseReg, HiOperand,
3687                              LoOperand, TmpReg, IDLoc, STI);
3688     return;
3689   }
3690 
3691   const MCOperand &OffsetOp = Inst.getOperand(2);
3692 
3693   if (OffsetOp.isImm()) {
3694     int64_t LoOffset = OffsetOp.getImm() & 0xffff;
3695     int64_t HiOffset = OffsetOp.getImm() & ~0xffff;
3696 
3697     // If msb of LoOffset is 1(negative number) we must increment
3698     // HiOffset to account for the sign-extension of the low part.
3699     if (LoOffset & 0x8000)
3700       HiOffset += 0x10000;
3701 
3702     bool IsLargeOffset = HiOffset != 0;
3703 
3704     if (IsLargeOffset) {
3705       bool Is32BitImm = (HiOffset >> 32) == 0;
3706       if (loadImmediate(HiOffset, TmpReg, Mips::NoRegister, Is32BitImm, true,
3707                         IDLoc, Out, STI))
3708         return;
3709     }
3710 
3711     if (BaseReg != Mips::ZERO && BaseReg != Mips::ZERO_64)
3712       TOut.emitRRR(isGP64bit() ? Mips::DADDu : Mips::ADDu, TmpReg, TmpReg,
3713                    BaseReg, IDLoc, STI);
3714     TOut.emitRRI(Inst.getOpcode(), DstReg, TmpReg, LoOffset, IDLoc, STI);
3715     return;
3716   }
3717 
3718   if (OffsetOp.isExpr()) {
3719     if (inPicMode()) {
3720       // FIXME:
3721       // c) Check that immediates of R_MIPS_GOT16/R_MIPS_LO16 relocations
3722       //    do not exceed 16-bit.
3723       // d) Use R_MIPS_GOT_PAGE/R_MIPS_GOT_OFST relocations instead
3724       //    of R_MIPS_GOT_DISP in appropriate cases to reduce number
3725       //    of GOT entries.
3726       MCValue Res;
3727       if (!OffsetOp.getExpr()->evaluateAsRelocatable(Res, nullptr, nullptr)) {
3728         Error(IDLoc, "expected relocatable expression");
3729         return;
3730       }
3731       if (Res.getSymB() != nullptr) {
3732         Error(IDLoc, "expected relocatable expression with only one symbol");
3733         return;
3734       }
3735 
3736       loadAndAddSymbolAddress(Res.getSymA(), TmpReg, BaseReg,
3737                               !ABI.ArePtrs64bit(), IDLoc, Out, STI);
3738       TOut.emitRRI(Inst.getOpcode(), DstReg, TmpReg, Res.getConstant(), IDLoc,
3739                    STI);
3740     } else {
3741       // FIXME: Implement 64-bit case.
3742       // 1) lw $8, sym => lui $8,  %hi(sym)
3743       //                  lw  $8,  %lo(sym)($8)
3744       // 2) sw $8, sym => lui $at, %hi(sym)
3745       //                  sw  $8,  %lo(sym)($at)
3746       const MCExpr *ExprOffset = OffsetOp.getExpr();
3747       MCOperand LoOperand = MCOperand::createExpr(
3748           MipsMCExpr::create(MipsMCExpr::MEK_LO, ExprOffset, getContext()));
3749       MCOperand HiOperand = MCOperand::createExpr(
3750           MipsMCExpr::create(MipsMCExpr::MEK_HI, ExprOffset, getContext()));
3751 
3752       // Generate the base address in TmpReg.
3753       TOut.emitRX(Mips::LUi, TmpReg, HiOperand, IDLoc, STI);
3754       if (BaseReg != Mips::ZERO)
3755         TOut.emitRRR(Mips::ADDu, TmpReg, TmpReg, BaseReg, IDLoc, STI);
3756       // Emit the load or store with the adjusted base and offset.
3757       TOut.emitRRX(Inst.getOpcode(), DstReg, TmpReg, LoOperand, IDLoc, STI);
3758     }
3759     return;
3760   }
3761 
3762   llvm_unreachable("unexpected operand type");
3763 }
3764 
3765 bool MipsAsmParser::expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc,
3766                                             MCStreamer &Out,
3767                                             const MCSubtargetInfo *STI) {
3768   unsigned OpNum = Inst.getNumOperands();
3769   unsigned Opcode = Inst.getOpcode();
3770   unsigned NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM32_MM : Mips::LWM32_MM;
3771 
3772   assert(Inst.getOperand(OpNum - 1).isImm() &&
3773          Inst.getOperand(OpNum - 2).isReg() &&
3774          Inst.getOperand(OpNum - 3).isReg() && "Invalid instruction operand.");
3775 
3776   if (OpNum < 8 && Inst.getOperand(OpNum - 1).getImm() <= 60 &&
3777       Inst.getOperand(OpNum - 1).getImm() >= 0 &&
3778       (Inst.getOperand(OpNum - 2).getReg() == Mips::SP ||
3779        Inst.getOperand(OpNum - 2).getReg() == Mips::SP_64) &&
3780       (Inst.getOperand(OpNum - 3).getReg() == Mips::RA ||
3781        Inst.getOperand(OpNum - 3).getReg() == Mips::RA_64)) {
3782     // It can be implemented as SWM16 or LWM16 instruction.
3783     if (inMicroMipsMode() && hasMips32r6())
3784       NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MMR6 : Mips::LWM16_MMR6;
3785     else
3786       NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MM : Mips::LWM16_MM;
3787   }
3788 
3789   Inst.setOpcode(NewOpcode);
3790   Out.EmitInstruction(Inst, *STI);
3791   return false;
3792 }
3793 
3794 bool MipsAsmParser::expandCondBranches(MCInst &Inst, SMLoc IDLoc,
3795                                        MCStreamer &Out,
3796                                        const MCSubtargetInfo *STI) {
3797   MipsTargetStreamer &TOut = getTargetStreamer();
3798   bool EmittedNoMacroWarning = false;
3799   unsigned PseudoOpcode = Inst.getOpcode();
3800   unsigned SrcReg = Inst.getOperand(0).getReg();
3801   const MCOperand &TrgOp = Inst.getOperand(1);
3802   const MCExpr *OffsetExpr = Inst.getOperand(2).getExpr();
3803 
3804   unsigned ZeroSrcOpcode, ZeroTrgOpcode;
3805   bool ReverseOrderSLT, IsUnsigned, IsLikely, AcceptsEquality;
3806 
3807   unsigned TrgReg;
3808   if (TrgOp.isReg())
3809     TrgReg = TrgOp.getReg();
3810   else if (TrgOp.isImm()) {
3811     warnIfNoMacro(IDLoc);
3812     EmittedNoMacroWarning = true;
3813 
3814     TrgReg = getATReg(IDLoc);
3815     if (!TrgReg)
3816       return true;
3817 
3818     switch(PseudoOpcode) {
3819     default:
3820       llvm_unreachable("unknown opcode for branch pseudo-instruction");
3821     case Mips::BLTImmMacro:
3822       PseudoOpcode = Mips::BLT;
3823       break;
3824     case Mips::BLEImmMacro:
3825       PseudoOpcode = Mips::BLE;
3826       break;
3827     case Mips::BGEImmMacro:
3828       PseudoOpcode = Mips::BGE;
3829       break;
3830     case Mips::BGTImmMacro:
3831       PseudoOpcode = Mips::BGT;
3832       break;
3833     case Mips::BLTUImmMacro:
3834       PseudoOpcode = Mips::BLTU;
3835       break;
3836     case Mips::BLEUImmMacro:
3837       PseudoOpcode = Mips::BLEU;
3838       break;
3839     case Mips::BGEUImmMacro:
3840       PseudoOpcode = Mips::BGEU;
3841       break;
3842     case Mips::BGTUImmMacro:
3843       PseudoOpcode = Mips::BGTU;
3844       break;
3845     case Mips::BLTLImmMacro:
3846       PseudoOpcode = Mips::BLTL;
3847       break;
3848     case Mips::BLELImmMacro:
3849       PseudoOpcode = Mips::BLEL;
3850       break;
3851     case Mips::BGELImmMacro:
3852       PseudoOpcode = Mips::BGEL;
3853       break;
3854     case Mips::BGTLImmMacro:
3855       PseudoOpcode = Mips::BGTL;
3856       break;
3857     case Mips::BLTULImmMacro:
3858       PseudoOpcode = Mips::BLTUL;
3859       break;
3860     case Mips::BLEULImmMacro:
3861       PseudoOpcode = Mips::BLEUL;
3862       break;
3863     case Mips::BGEULImmMacro:
3864       PseudoOpcode = Mips::BGEUL;
3865       break;
3866     case Mips::BGTULImmMacro:
3867       PseudoOpcode = Mips::BGTUL;
3868       break;
3869     }
3870 
3871     if (loadImmediate(TrgOp.getImm(), TrgReg, Mips::NoRegister, !isGP64bit(),
3872                       false, IDLoc, Out, STI))
3873       return true;
3874   }
3875 
3876   switch (PseudoOpcode) {
3877   case Mips::BLT:
3878   case Mips::BLTU:
3879   case Mips::BLTL:
3880   case Mips::BLTUL:
3881     AcceptsEquality = false;
3882     ReverseOrderSLT = false;
3883     IsUnsigned =
3884         ((PseudoOpcode == Mips::BLTU) || (PseudoOpcode == Mips::BLTUL));
3885     IsLikely = ((PseudoOpcode == Mips::BLTL) || (PseudoOpcode == Mips::BLTUL));
3886     ZeroSrcOpcode = Mips::BGTZ;
3887     ZeroTrgOpcode = Mips::BLTZ;
3888     break;
3889   case Mips::BLE:
3890   case Mips::BLEU:
3891   case Mips::BLEL:
3892   case Mips::BLEUL:
3893     AcceptsEquality = true;
3894     ReverseOrderSLT = true;
3895     IsUnsigned =
3896         ((PseudoOpcode == Mips::BLEU) || (PseudoOpcode == Mips::BLEUL));
3897     IsLikely = ((PseudoOpcode == Mips::BLEL) || (PseudoOpcode == Mips::BLEUL));
3898     ZeroSrcOpcode = Mips::BGEZ;
3899     ZeroTrgOpcode = Mips::BLEZ;
3900     break;
3901   case Mips::BGE:
3902   case Mips::BGEU:
3903   case Mips::BGEL:
3904   case Mips::BGEUL:
3905     AcceptsEquality = true;
3906     ReverseOrderSLT = false;
3907     IsUnsigned =
3908         ((PseudoOpcode == Mips::BGEU) || (PseudoOpcode == Mips::BGEUL));
3909     IsLikely = ((PseudoOpcode == Mips::BGEL) || (PseudoOpcode == Mips::BGEUL));
3910     ZeroSrcOpcode = Mips::BLEZ;
3911     ZeroTrgOpcode = Mips::BGEZ;
3912     break;
3913   case Mips::BGT:
3914   case Mips::BGTU:
3915   case Mips::BGTL:
3916   case Mips::BGTUL:
3917     AcceptsEquality = false;
3918     ReverseOrderSLT = true;
3919     IsUnsigned =
3920         ((PseudoOpcode == Mips::BGTU) || (PseudoOpcode == Mips::BGTUL));
3921     IsLikely = ((PseudoOpcode == Mips::BGTL) || (PseudoOpcode == Mips::BGTUL));
3922     ZeroSrcOpcode = Mips::BLTZ;
3923     ZeroTrgOpcode = Mips::BGTZ;
3924     break;
3925   default:
3926     llvm_unreachable("unknown opcode for branch pseudo-instruction");
3927   }
3928 
3929   bool IsTrgRegZero = (TrgReg == Mips::ZERO);
3930   bool IsSrcRegZero = (SrcReg == Mips::ZERO);
3931   if (IsSrcRegZero && IsTrgRegZero) {
3932     // FIXME: All of these Opcode-specific if's are needed for compatibility
3933     // with GAS' behaviour. However, they may not generate the most efficient
3934     // code in some circumstances.
3935     if (PseudoOpcode == Mips::BLT) {
3936       TOut.emitRX(Mips::BLTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
3937                   IDLoc, STI);
3938       return false;
3939     }
3940     if (PseudoOpcode == Mips::BLE) {
3941       TOut.emitRX(Mips::BLEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
3942                   IDLoc, STI);
3943       Warning(IDLoc, "branch is always taken");
3944       return false;
3945     }
3946     if (PseudoOpcode == Mips::BGE) {
3947       TOut.emitRX(Mips::BGEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
3948                   IDLoc, STI);
3949       Warning(IDLoc, "branch is always taken");
3950       return false;
3951     }
3952     if (PseudoOpcode == Mips::BGT) {
3953       TOut.emitRX(Mips::BGTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr),
3954                   IDLoc, STI);
3955       return false;
3956     }
3957     if (PseudoOpcode == Mips::BGTU) {
3958       TOut.emitRRX(Mips::BNE, Mips::ZERO, Mips::ZERO,
3959                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3960       return false;
3961     }
3962     if (AcceptsEquality) {
3963       // If both registers are $0 and the pseudo-branch accepts equality, it
3964       // will always be taken, so we emit an unconditional branch.
3965       TOut.emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO,
3966                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3967       Warning(IDLoc, "branch is always taken");
3968       return false;
3969     }
3970     // If both registers are $0 and the pseudo-branch does not accept
3971     // equality, it will never be taken, so we don't have to emit anything.
3972     return false;
3973   }
3974   if (IsSrcRegZero || IsTrgRegZero) {
3975     if ((IsSrcRegZero && PseudoOpcode == Mips::BGTU) ||
3976         (IsTrgRegZero && PseudoOpcode == Mips::BLTU)) {
3977       // If the $rs is $0 and the pseudo-branch is BGTU (0 > x) or
3978       // if the $rt is $0 and the pseudo-branch is BLTU (x < 0),
3979       // the pseudo-branch will never be taken, so we don't emit anything.
3980       // This only applies to unsigned pseudo-branches.
3981       return false;
3982     }
3983     if ((IsSrcRegZero && PseudoOpcode == Mips::BLEU) ||
3984         (IsTrgRegZero && PseudoOpcode == Mips::BGEU)) {
3985       // If the $rs is $0 and the pseudo-branch is BLEU (0 <= x) or
3986       // if the $rt is $0 and the pseudo-branch is BGEU (x >= 0),
3987       // the pseudo-branch will always be taken, so we emit an unconditional
3988       // branch.
3989       // This only applies to unsigned pseudo-branches.
3990       TOut.emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO,
3991                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
3992       Warning(IDLoc, "branch is always taken");
3993       return false;
3994     }
3995     if (IsUnsigned) {
3996       // If the $rs is $0 and the pseudo-branch is BLTU (0 < x) or
3997       // if the $rt is $0 and the pseudo-branch is BGTU (x > 0),
3998       // the pseudo-branch will be taken only when the non-zero register is
3999       // different from 0, so we emit a BNEZ.
4000       //
4001       // If the $rs is $0 and the pseudo-branch is BGEU (0 >= x) or
4002       // if the $rt is $0 and the pseudo-branch is BLEU (x <= 0),
4003       // the pseudo-branch will be taken only when the non-zero register is
4004       // equal to 0, so we emit a BEQZ.
4005       //
4006       // Because only BLEU and BGEU branch on equality, we can use the
4007       // AcceptsEquality variable to decide when to emit the BEQZ.
4008       TOut.emitRRX(AcceptsEquality ? Mips::BEQ : Mips::BNE,
4009                    IsSrcRegZero ? TrgReg : SrcReg, Mips::ZERO,
4010                    MCOperand::createExpr(OffsetExpr), IDLoc, STI);
4011       return false;
4012     }
4013     // If we have a signed pseudo-branch and one of the registers is $0,
4014     // we can use an appropriate compare-to-zero branch. We select which one
4015     // to use in the switch statement above.
4016     TOut.emitRX(IsSrcRegZero ? ZeroSrcOpcode : ZeroTrgOpcode,
4017                 IsSrcRegZero ? TrgReg : SrcReg,
4018                 MCOperand::createExpr(OffsetExpr), IDLoc, STI);
4019     return false;
4020   }
4021 
4022   // If neither the SrcReg nor the TrgReg are $0, we need AT to perform the
4023   // expansions. If it is not available, we return.
4024   unsigned ATRegNum = getATReg(IDLoc);
4025   if (!ATRegNum)
4026     return true;
4027 
4028   if (!EmittedNoMacroWarning)
4029     warnIfNoMacro(IDLoc);
4030 
4031   // SLT fits well with 2 of our 4 pseudo-branches:
4032   //   BLT, where $rs < $rt, translates into "slt $at, $rs, $rt" and
4033   //   BGT, where $rs > $rt, translates into "slt $at, $rt, $rs".
4034   // If the result of the SLT is 1, we branch, and if it's 0, we don't.
4035   // This is accomplished by using a BNEZ with the result of the SLT.
4036   //
4037   // The other 2 pseudo-branches are opposites of the above 2 (BGE with BLT
4038   // and BLE with BGT), so we change the BNEZ into a BEQZ.
4039   // Because only BGE and BLE branch on equality, we can use the
4040   // AcceptsEquality variable to decide when to emit the BEQZ.
4041   // Note that the order of the SLT arguments doesn't change between
4042   // opposites.
4043   //
4044   // The same applies to the unsigned variants, except that SLTu is used
4045   // instead of SLT.
4046   TOut.emitRRR(IsUnsigned ? Mips::SLTu : Mips::SLT, ATRegNum,
4047                ReverseOrderSLT ? TrgReg : SrcReg,
4048                ReverseOrderSLT ? SrcReg : TrgReg, IDLoc, STI);
4049 
4050   TOut.emitRRX(IsLikely ? (AcceptsEquality ? Mips::BEQL : Mips::BNEL)
4051                         : (AcceptsEquality ? Mips::BEQ : Mips::BNE),
4052                ATRegNum, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
4053                STI);
4054   return false;
4055 }
4056 
4057 // Expand a integer division macro.
4058 //
4059 // Notably we don't have to emit a warning when encountering $rt as the $zero
4060 // register, or 0 as an immediate. processInstruction() has already done that.
4061 //
4062 // The destination register can only be $zero when expanding (S)DivIMacro or
4063 // D(S)DivMacro.
4064 
4065 bool MipsAsmParser::expandDivRem(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4066                                  const MCSubtargetInfo *STI, const bool IsMips64,
4067                                  const bool Signed) {
4068   MipsTargetStreamer &TOut = getTargetStreamer();
4069 
4070   warnIfNoMacro(IDLoc);
4071 
4072   const MCOperand &RdRegOp = Inst.getOperand(0);
4073   assert(RdRegOp.isReg() && "expected register operand kind");
4074   unsigned RdReg = RdRegOp.getReg();
4075 
4076   const MCOperand &RsRegOp = Inst.getOperand(1);
4077   assert(RsRegOp.isReg() && "expected register operand kind");
4078   unsigned RsReg = RsRegOp.getReg();
4079 
4080   unsigned RtReg;
4081   int64_t ImmValue;
4082 
4083   const MCOperand &RtOp = Inst.getOperand(2);
4084   assert((RtOp.isReg() || RtOp.isImm()) &&
4085          "expected register or immediate operand kind");
4086   if (RtOp.isReg())
4087     RtReg = RtOp.getReg();
4088   else
4089     ImmValue = RtOp.getImm();
4090 
4091   unsigned DivOp;
4092   unsigned ZeroReg;
4093   unsigned SubOp;
4094 
4095   if (IsMips64) {
4096     DivOp = Signed ? Mips::DSDIV : Mips::DUDIV;
4097     ZeroReg = Mips::ZERO_64;
4098     SubOp = Mips::DSUB;
4099   } else {
4100     DivOp = Signed ? Mips::SDIV : Mips::UDIV;
4101     ZeroReg = Mips::ZERO;
4102     SubOp = Mips::SUB;
4103   }
4104 
4105   bool UseTraps = useTraps();
4106 
4107   unsigned Opcode = Inst.getOpcode();
4108   bool isDiv = Opcode == Mips::SDivMacro || Opcode == Mips::SDivIMacro ||
4109                Opcode == Mips::UDivMacro || Opcode == Mips::UDivIMacro ||
4110                Opcode == Mips::DSDivMacro || Opcode == Mips::DSDivIMacro ||
4111                Opcode == Mips::DUDivMacro || Opcode == Mips::DUDivIMacro;
4112 
4113   bool isRem = Opcode == Mips::SRemMacro || Opcode == Mips::SRemIMacro ||
4114                Opcode == Mips::URemMacro || Opcode == Mips::URemIMacro ||
4115                Opcode == Mips::DSRemMacro || Opcode == Mips::DSRemIMacro ||
4116                Opcode == Mips::DURemMacro || Opcode == Mips::DURemIMacro;
4117 
4118   if (RtOp.isImm()) {
4119     unsigned ATReg = getATReg(IDLoc);
4120     if (!ATReg)
4121       return true;
4122 
4123     if (ImmValue == 0) {
4124       if (UseTraps)
4125         TOut.emitRRI(Mips::TEQ, ZeroReg, ZeroReg, 0x7, IDLoc, STI);
4126       else
4127         TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI);
4128       return false;
4129     }
4130 
4131     if (isRem && (ImmValue == 1 || (Signed && (ImmValue == -1)))) {
4132       TOut.emitRRR(Mips::OR, RdReg, ZeroReg, ZeroReg, IDLoc, STI);
4133       return false;
4134     } else if (isDiv && ImmValue == 1) {
4135       TOut.emitRRR(Mips::OR, RdReg, RsReg, Mips::ZERO, IDLoc, STI);
4136       return false;
4137     } else if (isDiv && Signed && ImmValue == -1) {
4138       TOut.emitRRR(SubOp, RdReg, ZeroReg, RsReg, IDLoc, STI);
4139       return false;
4140     } else {
4141       if (loadImmediate(ImmValue, ATReg, Mips::NoRegister, isInt<32>(ImmValue),
4142                         false, Inst.getLoc(), Out, STI))
4143         return true;
4144       TOut.emitRR(DivOp, RsReg, ATReg, IDLoc, STI);
4145       TOut.emitR(isDiv ? Mips::MFLO : Mips::MFHI, RdReg, IDLoc, STI);
4146       return false;
4147     }
4148     return true;
4149   }
4150 
4151   // If the macro expansion of (d)div(u) or (d)rem(u) would always trap or
4152   // break, insert the trap/break and exit. This gives a different result to
4153   // GAS. GAS has an inconsistency/missed optimization in that not all cases
4154   // are handled equivalently. As the observed behaviour is the same, we're ok.
4155   if (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64) {
4156     if (UseTraps) {
4157       TOut.emitRRI(Mips::TEQ, ZeroReg, ZeroReg, 0x7, IDLoc, STI);
4158       return false;
4159     }
4160     TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI);
4161     return false;
4162   }
4163 
4164   // (d)rem(u) $0, $X, $Y is a special case. Like div $zero, $X, $Y, it does
4165   // not expand to macro sequence.
4166   if (isRem && (RdReg == Mips::ZERO || RdReg == Mips::ZERO_64)) {
4167     TOut.emitRR(DivOp, RsReg, RtReg, IDLoc, STI);
4168     return false;
4169   }
4170 
4171   // Temporary label for first branch traget
4172   MCContext &Context = TOut.getStreamer().getContext();
4173   MCSymbol *BrTarget;
4174   MCOperand LabelOp;
4175 
4176   if (UseTraps) {
4177     TOut.emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, STI);
4178   } else {
4179     // Branch to the li instruction.
4180     BrTarget = Context.createTempSymbol();
4181     LabelOp = MCOperand::createExpr(MCSymbolRefExpr::create(BrTarget, Context));
4182     TOut.emitRRX(Mips::BNE, RtReg, ZeroReg, LabelOp, IDLoc, STI);
4183   }
4184 
4185   TOut.emitRR(DivOp, RsReg, RtReg, IDLoc, STI);
4186 
4187   if (!UseTraps)
4188     TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI);
4189 
4190   if (!Signed) {
4191     if (!UseTraps)
4192       TOut.getStreamer().EmitLabel(BrTarget);
4193 
4194     TOut.emitR(isDiv ? Mips::MFLO : Mips::MFHI, RdReg, IDLoc, STI);
4195     return false;
4196   }
4197 
4198   unsigned ATReg = getATReg(IDLoc);
4199   if (!ATReg)
4200     return true;
4201 
4202   if (!UseTraps)
4203     TOut.getStreamer().EmitLabel(BrTarget);
4204 
4205   TOut.emitRRI(Mips::ADDiu, ATReg, ZeroReg, -1, IDLoc, STI);
4206 
4207   // Temporary label for the second branch target.
4208   MCSymbol *BrTargetEnd = Context.createTempSymbol();
4209   MCOperand LabelOpEnd =
4210       MCOperand::createExpr(MCSymbolRefExpr::create(BrTargetEnd, Context));
4211 
4212   // Branch to the mflo instruction.
4213   TOut.emitRRX(Mips::BNE, RtReg, ATReg, LabelOpEnd, IDLoc, STI);
4214 
4215   if (IsMips64) {
4216     TOut.emitRRI(Mips::ADDiu, ATReg, ZeroReg, 1, IDLoc, STI);
4217     TOut.emitDSLL(ATReg, ATReg, 63, IDLoc, STI);
4218   } else {
4219     TOut.emitRI(Mips::LUi, ATReg, (uint16_t)0x8000, IDLoc, STI);
4220   }
4221 
4222   if (UseTraps)
4223     TOut.emitRRI(Mips::TEQ, RsReg, ATReg, 0x6, IDLoc, STI);
4224   else {
4225     // Branch to the mflo instruction.
4226     TOut.emitRRX(Mips::BNE, RsReg, ATReg, LabelOpEnd, IDLoc, STI);
4227     TOut.emitNop(IDLoc, STI);
4228     TOut.emitII(Mips::BREAK, 0x6, 0, IDLoc, STI);
4229   }
4230 
4231   TOut.getStreamer().EmitLabel(BrTargetEnd);
4232   TOut.emitR(isDiv ? Mips::MFLO : Mips::MFHI, RdReg, IDLoc, STI);
4233   return false;
4234 }
4235 
4236 bool MipsAsmParser::expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU,
4237                                 SMLoc IDLoc, MCStreamer &Out,
4238                                 const MCSubtargetInfo *STI) {
4239   MipsTargetStreamer &TOut = getTargetStreamer();
4240 
4241   assert(Inst.getNumOperands() == 3 && "Invalid operand count");
4242   assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg() &&
4243          Inst.getOperand(2).isReg() && "Invalid instruction operand.");
4244 
4245   unsigned FirstReg = Inst.getOperand(0).getReg();
4246   unsigned SecondReg = Inst.getOperand(1).getReg();
4247   unsigned ThirdReg = Inst.getOperand(2).getReg();
4248 
4249   if (hasMips1() && !hasMips2()) {
4250     unsigned ATReg = getATReg(IDLoc);
4251     if (!ATReg)
4252       return true;
4253     TOut.emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, STI);
4254     TOut.emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, STI);
4255     TOut.emitNop(IDLoc, STI);
4256     TOut.emitRRI(Mips::ORi, ATReg, ThirdReg, 0x3, IDLoc, STI);
4257     TOut.emitRRI(Mips::XORi, ATReg, ATReg, 0x2, IDLoc, STI);
4258     TOut.emitRR(Mips::CTC1, Mips::RA, ATReg, IDLoc, STI);
4259     TOut.emitNop(IDLoc, STI);
4260     TOut.emitRR(IsDouble ? (Is64FPU ? Mips::CVT_W_D64 : Mips::CVT_W_D32)
4261                          : Mips::CVT_W_S,
4262                 FirstReg, SecondReg, IDLoc, STI);
4263     TOut.emitRR(Mips::CTC1, Mips::RA, ThirdReg, IDLoc, STI);
4264     TOut.emitNop(IDLoc, STI);
4265     return false;
4266   }
4267 
4268   TOut.emitRR(IsDouble ? (Is64FPU ? Mips::TRUNC_W_D64 : Mips::TRUNC_W_D32)
4269                        : Mips::TRUNC_W_S,
4270               FirstReg, SecondReg, IDLoc, STI);
4271 
4272   return false;
4273 }
4274 
4275 bool MipsAsmParser::expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc,
4276                               MCStreamer &Out, const MCSubtargetInfo *STI) {
4277   if (hasMips32r6() || hasMips64r6()) {
4278     return Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
4279   }
4280 
4281   const MCOperand &DstRegOp = Inst.getOperand(0);
4282   assert(DstRegOp.isReg() && "expected register operand kind");
4283   const MCOperand &SrcRegOp = Inst.getOperand(1);
4284   assert(SrcRegOp.isReg() && "expected register operand kind");
4285   const MCOperand &OffsetImmOp = Inst.getOperand(2);
4286   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
4287 
4288   MipsTargetStreamer &TOut = getTargetStreamer();
4289   unsigned DstReg = DstRegOp.getReg();
4290   unsigned SrcReg = SrcRegOp.getReg();
4291   int64_t OffsetValue = OffsetImmOp.getImm();
4292 
4293   // NOTE: We always need AT for ULHU, as it is always used as the source
4294   // register for one of the LBu's.
4295   warnIfNoMacro(IDLoc);
4296   unsigned ATReg = getATReg(IDLoc);
4297   if (!ATReg)
4298     return true;
4299 
4300   bool IsLargeOffset = !(isInt<16>(OffsetValue + 1) && isInt<16>(OffsetValue));
4301   if (IsLargeOffset) {
4302     if (loadImmediate(OffsetValue, ATReg, SrcReg, !ABI.ArePtrs64bit(), true,
4303                       IDLoc, Out, STI))
4304       return true;
4305   }
4306 
4307   int64_t FirstOffset = IsLargeOffset ? 0 : OffsetValue;
4308   int64_t SecondOffset = IsLargeOffset ? 1 : (OffsetValue + 1);
4309   if (isLittle())
4310     std::swap(FirstOffset, SecondOffset);
4311 
4312   unsigned FirstLbuDstReg = IsLargeOffset ? DstReg : ATReg;
4313   unsigned SecondLbuDstReg = IsLargeOffset ? ATReg : DstReg;
4314 
4315   unsigned LbuSrcReg = IsLargeOffset ? ATReg : SrcReg;
4316   unsigned SllReg = IsLargeOffset ? DstReg : ATReg;
4317 
4318   TOut.emitRRI(Signed ? Mips::LB : Mips::LBu, FirstLbuDstReg, LbuSrcReg,
4319                FirstOffset, IDLoc, STI);
4320   TOut.emitRRI(Mips::LBu, SecondLbuDstReg, LbuSrcReg, SecondOffset, IDLoc, STI);
4321   TOut.emitRRI(Mips::SLL, SllReg, SllReg, 8, IDLoc, STI);
4322   TOut.emitRRR(Mips::OR, DstReg, DstReg, ATReg, IDLoc, STI);
4323 
4324   return false;
4325 }
4326 
4327 bool MipsAsmParser::expandUsh(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4328                               const MCSubtargetInfo *STI) {
4329   if (hasMips32r6() || hasMips64r6()) {
4330     return Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
4331   }
4332 
4333   const MCOperand &DstRegOp = Inst.getOperand(0);
4334   assert(DstRegOp.isReg() && "expected register operand kind");
4335   const MCOperand &SrcRegOp = Inst.getOperand(1);
4336   assert(SrcRegOp.isReg() && "expected register operand kind");
4337   const MCOperand &OffsetImmOp = Inst.getOperand(2);
4338   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
4339 
4340   MipsTargetStreamer &TOut = getTargetStreamer();
4341   unsigned DstReg = DstRegOp.getReg();
4342   unsigned SrcReg = SrcRegOp.getReg();
4343   int64_t OffsetValue = OffsetImmOp.getImm();
4344 
4345   warnIfNoMacro(IDLoc);
4346   unsigned ATReg = getATReg(IDLoc);
4347   if (!ATReg)
4348     return true;
4349 
4350   bool IsLargeOffset = !(isInt<16>(OffsetValue + 1) && isInt<16>(OffsetValue));
4351   if (IsLargeOffset) {
4352     if (loadImmediate(OffsetValue, ATReg, SrcReg, !ABI.ArePtrs64bit(), true,
4353                       IDLoc, Out, STI))
4354       return true;
4355   }
4356 
4357   int64_t FirstOffset = IsLargeOffset ? 1 : (OffsetValue + 1);
4358   int64_t SecondOffset = IsLargeOffset ? 0 : OffsetValue;
4359   if (isLittle())
4360     std::swap(FirstOffset, SecondOffset);
4361 
4362   if (IsLargeOffset) {
4363     TOut.emitRRI(Mips::SB, DstReg, ATReg, FirstOffset, IDLoc, STI);
4364     TOut.emitRRI(Mips::SRL, DstReg, DstReg, 8, IDLoc, STI);
4365     TOut.emitRRI(Mips::SB, DstReg, ATReg, SecondOffset, IDLoc, STI);
4366     TOut.emitRRI(Mips::LBu, ATReg, ATReg, 0, IDLoc, STI);
4367     TOut.emitRRI(Mips::SLL, DstReg, DstReg, 8, IDLoc, STI);
4368     TOut.emitRRR(Mips::OR, DstReg, DstReg, ATReg, IDLoc, STI);
4369   } else {
4370     TOut.emitRRI(Mips::SB, DstReg, SrcReg, FirstOffset, IDLoc, STI);
4371     TOut.emitRRI(Mips::SRL, ATReg, DstReg, 8, IDLoc, STI);
4372     TOut.emitRRI(Mips::SB, ATReg, SrcReg, SecondOffset, IDLoc, STI);
4373   }
4374 
4375   return false;
4376 }
4377 
4378 bool MipsAsmParser::expandUxw(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4379                               const MCSubtargetInfo *STI) {
4380   if (hasMips32r6() || hasMips64r6()) {
4381     return Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
4382   }
4383 
4384   const MCOperand &DstRegOp = Inst.getOperand(0);
4385   assert(DstRegOp.isReg() && "expected register operand kind");
4386   const MCOperand &SrcRegOp = Inst.getOperand(1);
4387   assert(SrcRegOp.isReg() && "expected register operand kind");
4388   const MCOperand &OffsetImmOp = Inst.getOperand(2);
4389   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
4390 
4391   MipsTargetStreamer &TOut = getTargetStreamer();
4392   unsigned DstReg = DstRegOp.getReg();
4393   unsigned SrcReg = SrcRegOp.getReg();
4394   int64_t OffsetValue = OffsetImmOp.getImm();
4395 
4396   // Compute left/right load/store offsets.
4397   bool IsLargeOffset = !(isInt<16>(OffsetValue + 3) && isInt<16>(OffsetValue));
4398   int64_t LxlOffset = IsLargeOffset ? 0 : OffsetValue;
4399   int64_t LxrOffset = IsLargeOffset ? 3 : (OffsetValue + 3);
4400   if (isLittle())
4401     std::swap(LxlOffset, LxrOffset);
4402 
4403   bool IsLoadInst = (Inst.getOpcode() == Mips::Ulw);
4404   bool DoMove = IsLoadInst && (SrcReg == DstReg) && !IsLargeOffset;
4405   unsigned TmpReg = SrcReg;
4406   if (IsLargeOffset || DoMove) {
4407     warnIfNoMacro(IDLoc);
4408     TmpReg = getATReg(IDLoc);
4409     if (!TmpReg)
4410       return true;
4411   }
4412 
4413   if (IsLargeOffset) {
4414     if (loadImmediate(OffsetValue, TmpReg, SrcReg, !ABI.ArePtrs64bit(), true,
4415                       IDLoc, Out, STI))
4416       return true;
4417   }
4418 
4419   if (DoMove)
4420     std::swap(DstReg, TmpReg);
4421 
4422   unsigned XWL = IsLoadInst ? Mips::LWL : Mips::SWL;
4423   unsigned XWR = IsLoadInst ? Mips::LWR : Mips::SWR;
4424   TOut.emitRRI(XWL, DstReg, TmpReg, LxlOffset, IDLoc, STI);
4425   TOut.emitRRI(XWR, DstReg, TmpReg, LxrOffset, IDLoc, STI);
4426 
4427   if (DoMove)
4428     TOut.emitRRR(Mips::OR, TmpReg, DstReg, Mips::ZERO, IDLoc, STI);
4429 
4430   return false;
4431 }
4432 
4433 bool MipsAsmParser::expandSge(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4434                               const MCSubtargetInfo *STI) {
4435   MipsTargetStreamer &TOut = getTargetStreamer();
4436 
4437   assert(Inst.getNumOperands() == 3 && "Invalid operand count");
4438   assert(Inst.getOperand(0).isReg() &&
4439          Inst.getOperand(1).isReg() &&
4440          Inst.getOperand(2).isReg() && "Invalid instruction operand.");
4441 
4442   unsigned DstReg = Inst.getOperand(0).getReg();
4443   unsigned SrcReg = Inst.getOperand(1).getReg();
4444   unsigned OpReg = Inst.getOperand(2).getReg();
4445   unsigned OpCode;
4446 
4447   warnIfNoMacro(IDLoc);
4448 
4449   switch (Inst.getOpcode()) {
4450   case Mips::SGE:
4451     OpCode = Mips::SLT;
4452     break;
4453   case Mips::SGEU:
4454     OpCode = Mips::SLTu;
4455     break;
4456   default:
4457     llvm_unreachable("unexpected 'sge' opcode");
4458   }
4459 
4460   // $SrcReg >= $OpReg is equal to (not ($SrcReg < $OpReg))
4461   TOut.emitRRR(OpCode, DstReg, SrcReg, OpReg, IDLoc, STI);
4462   TOut.emitRRI(Mips::XORi, DstReg, DstReg, 1, IDLoc, STI);
4463 
4464   return false;
4465 }
4466 
4467 bool MipsAsmParser::expandSgeImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4468                                  const MCSubtargetInfo *STI) {
4469   MipsTargetStreamer &TOut = getTargetStreamer();
4470 
4471   assert(Inst.getNumOperands() == 3 && "Invalid operand count");
4472   assert(Inst.getOperand(0).isReg() &&
4473          Inst.getOperand(1).isReg() &&
4474          Inst.getOperand(2).isImm() && "Invalid instruction operand.");
4475 
4476   unsigned DstReg = Inst.getOperand(0).getReg();
4477   unsigned SrcReg = Inst.getOperand(1).getReg();
4478   int64_t ImmValue = Inst.getOperand(2).getImm();
4479   unsigned OpRegCode, OpImmCode;
4480 
4481   warnIfNoMacro(IDLoc);
4482 
4483   switch (Inst.getOpcode()) {
4484   case Mips::SGEImm:
4485   case Mips::SGEImm64:
4486     OpRegCode = Mips::SLT;
4487     OpImmCode = Mips::SLTi;
4488     break;
4489   case Mips::SGEUImm:
4490   case Mips::SGEUImm64:
4491     OpRegCode = Mips::SLTu;
4492     OpImmCode = Mips::SLTiu;
4493     break;
4494   default:
4495     llvm_unreachable("unexpected 'sge' opcode with immediate");
4496   }
4497 
4498   // $SrcReg >= Imm is equal to (not ($SrcReg < Imm))
4499   if (isInt<16>(ImmValue)) {
4500     // Use immediate version of STL.
4501     TOut.emitRRI(OpImmCode, DstReg, SrcReg, ImmValue, IDLoc, STI);
4502     TOut.emitRRI(Mips::XORi, DstReg, DstReg, 1, IDLoc, STI);
4503   } else {
4504     unsigned ImmReg = DstReg;
4505     if (DstReg == SrcReg) {
4506       unsigned ATReg = getATReg(Inst.getLoc());
4507       if (!ATReg)
4508         return true;
4509       ImmReg = ATReg;
4510     }
4511 
4512     if (loadImmediate(ImmValue, ImmReg, Mips::NoRegister, isInt<32>(ImmValue),
4513                       false, IDLoc, Out, STI))
4514       return true;
4515 
4516     TOut.emitRRR(OpRegCode, DstReg, SrcReg, ImmReg, IDLoc, STI);
4517     TOut.emitRRI(Mips::XORi, DstReg, DstReg, 1, IDLoc, STI);
4518   }
4519 
4520   return false;
4521 }
4522 
4523 bool MipsAsmParser::expandSgtImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4524                                  const MCSubtargetInfo *STI) {
4525   MipsTargetStreamer &TOut = getTargetStreamer();
4526 
4527   assert(Inst.getNumOperands() == 3 && "Invalid operand count");
4528   assert(Inst.getOperand(0).isReg() &&
4529          Inst.getOperand(1).isReg() &&
4530          Inst.getOperand(2).isImm() && "Invalid instruction operand.");
4531 
4532   unsigned DstReg = Inst.getOperand(0).getReg();
4533   unsigned SrcReg = Inst.getOperand(1).getReg();
4534   unsigned ImmReg = DstReg;
4535   int64_t ImmValue = Inst.getOperand(2).getImm();
4536   unsigned OpCode;
4537 
4538   warnIfNoMacro(IDLoc);
4539 
4540   switch (Inst.getOpcode()) {
4541   case Mips::SGTImm:
4542   case Mips::SGTImm64:
4543     OpCode = Mips::SLT;
4544     break;
4545   case Mips::SGTUImm:
4546   case Mips::SGTUImm64:
4547     OpCode = Mips::SLTu;
4548     break;
4549   default:
4550     llvm_unreachable("unexpected 'sgt' opcode with immediate");
4551   }
4552 
4553   if (DstReg == SrcReg) {
4554     unsigned ATReg = getATReg(Inst.getLoc());
4555     if (!ATReg)
4556       return true;
4557     ImmReg = ATReg;
4558   }
4559 
4560   if (loadImmediate(ImmValue, ImmReg, Mips::NoRegister, isInt<32>(ImmValue),
4561                     false, IDLoc, Out, STI))
4562     return true;
4563 
4564   // $SrcReg > $ImmReg is equal to $ImmReg < $SrcReg
4565   TOut.emitRRR(OpCode, DstReg, ImmReg, SrcReg, IDLoc, STI);
4566 
4567   return false;
4568 }
4569 
4570 bool MipsAsmParser::expandAliasImmediate(MCInst &Inst, SMLoc IDLoc,
4571                                          MCStreamer &Out,
4572                                          const MCSubtargetInfo *STI) {
4573   MipsTargetStreamer &TOut = getTargetStreamer();
4574 
4575   assert(Inst.getNumOperands() == 3 && "Invalid operand count");
4576   assert(Inst.getOperand(0).isReg() &&
4577          Inst.getOperand(1).isReg() &&
4578          Inst.getOperand(2).isImm() && "Invalid instruction operand.");
4579 
4580   unsigned ATReg = Mips::NoRegister;
4581   unsigned FinalDstReg = Mips::NoRegister;
4582   unsigned DstReg = Inst.getOperand(0).getReg();
4583   unsigned SrcReg = Inst.getOperand(1).getReg();
4584   int64_t ImmValue = Inst.getOperand(2).getImm();
4585 
4586   bool Is32Bit = isInt<32>(ImmValue) || (!isGP64bit() && isUInt<32>(ImmValue));
4587 
4588   unsigned FinalOpcode = Inst.getOpcode();
4589 
4590   if (DstReg == SrcReg) {
4591     ATReg = getATReg(Inst.getLoc());
4592     if (!ATReg)
4593       return true;
4594     FinalDstReg = DstReg;
4595     DstReg = ATReg;
4596   }
4597 
4598   if (!loadImmediate(ImmValue, DstReg, Mips::NoRegister, Is32Bit, false,
4599                      Inst.getLoc(), Out, STI)) {
4600     switch (FinalOpcode) {
4601     default:
4602       llvm_unreachable("unimplemented expansion");
4603     case Mips::ADDi:
4604       FinalOpcode = Mips::ADD;
4605       break;
4606     case Mips::ADDiu:
4607       FinalOpcode = Mips::ADDu;
4608       break;
4609     case Mips::ANDi:
4610       FinalOpcode = Mips::AND;
4611       break;
4612     case Mips::NORImm:
4613       FinalOpcode = Mips::NOR;
4614       break;
4615     case Mips::ORi:
4616       FinalOpcode = Mips::OR;
4617       break;
4618     case Mips::SLTi:
4619       FinalOpcode = Mips::SLT;
4620       break;
4621     case Mips::SLTiu:
4622       FinalOpcode = Mips::SLTu;
4623       break;
4624     case Mips::XORi:
4625       FinalOpcode = Mips::XOR;
4626       break;
4627     case Mips::ADDi_MM:
4628       FinalOpcode = Mips::ADD_MM;
4629       break;
4630     case Mips::ADDiu_MM:
4631       FinalOpcode = Mips::ADDu_MM;
4632       break;
4633     case Mips::ANDi_MM:
4634       FinalOpcode = Mips::AND_MM;
4635       break;
4636     case Mips::ORi_MM:
4637       FinalOpcode = Mips::OR_MM;
4638       break;
4639     case Mips::SLTi_MM:
4640       FinalOpcode = Mips::SLT_MM;
4641       break;
4642     case Mips::SLTiu_MM:
4643       FinalOpcode = Mips::SLTu_MM;
4644       break;
4645     case Mips::XORi_MM:
4646       FinalOpcode = Mips::XOR_MM;
4647       break;
4648     case Mips::ANDi64:
4649       FinalOpcode = Mips::AND64;
4650       break;
4651     case Mips::NORImm64:
4652       FinalOpcode = Mips::NOR64;
4653       break;
4654     case Mips::ORi64:
4655       FinalOpcode = Mips::OR64;
4656       break;
4657     case Mips::SLTImm64:
4658       FinalOpcode = Mips::SLT64;
4659       break;
4660     case Mips::SLTUImm64:
4661       FinalOpcode = Mips::SLTu64;
4662       break;
4663     case Mips::XORi64:
4664       FinalOpcode = Mips::XOR64;
4665       break;
4666     }
4667 
4668     if (FinalDstReg == Mips::NoRegister)
4669       TOut.emitRRR(FinalOpcode, DstReg, DstReg, SrcReg, IDLoc, STI);
4670     else
4671       TOut.emitRRR(FinalOpcode, FinalDstReg, FinalDstReg, DstReg, IDLoc, STI);
4672     return false;
4673   }
4674   return true;
4675 }
4676 
4677 bool MipsAsmParser::expandRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4678                                    const MCSubtargetInfo *STI) {
4679   MipsTargetStreamer &TOut = getTargetStreamer();
4680   unsigned ATReg = Mips::NoRegister;
4681   unsigned DReg = Inst.getOperand(0).getReg();
4682   unsigned SReg = Inst.getOperand(1).getReg();
4683   unsigned TReg = Inst.getOperand(2).getReg();
4684   unsigned TmpReg = DReg;
4685 
4686   unsigned FirstShift = Mips::NOP;
4687   unsigned SecondShift = Mips::NOP;
4688 
4689   if (hasMips32r2()) {
4690     if (DReg == SReg) {
4691       TmpReg = getATReg(Inst.getLoc());
4692       if (!TmpReg)
4693         return true;
4694     }
4695 
4696     if (Inst.getOpcode() == Mips::ROL) {
4697       TOut.emitRRR(Mips::SUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
4698       TOut.emitRRR(Mips::ROTRV, DReg, SReg, TmpReg, Inst.getLoc(), STI);
4699       return false;
4700     }
4701 
4702     if (Inst.getOpcode() == Mips::ROR) {
4703       TOut.emitRRR(Mips::ROTRV, DReg, SReg, TReg, Inst.getLoc(), STI);
4704       return false;
4705     }
4706 
4707     return true;
4708   }
4709 
4710   if (hasMips32()) {
4711     switch (Inst.getOpcode()) {
4712     default:
4713       llvm_unreachable("unexpected instruction opcode");
4714     case Mips::ROL:
4715       FirstShift = Mips::SRLV;
4716       SecondShift = Mips::SLLV;
4717       break;
4718     case Mips::ROR:
4719       FirstShift = Mips::SLLV;
4720       SecondShift = Mips::SRLV;
4721       break;
4722     }
4723 
4724     ATReg = getATReg(Inst.getLoc());
4725     if (!ATReg)
4726       return true;
4727 
4728     TOut.emitRRR(Mips::SUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
4729     TOut.emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), STI);
4730     TOut.emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), STI);
4731     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
4732 
4733     return false;
4734   }
4735 
4736   return true;
4737 }
4738 
4739 bool MipsAsmParser::expandRotationImm(MCInst &Inst, SMLoc IDLoc,
4740                                       MCStreamer &Out,
4741                                       const MCSubtargetInfo *STI) {
4742   MipsTargetStreamer &TOut = getTargetStreamer();
4743   unsigned ATReg = Mips::NoRegister;
4744   unsigned DReg = Inst.getOperand(0).getReg();
4745   unsigned SReg = Inst.getOperand(1).getReg();
4746   int64_t ImmValue = Inst.getOperand(2).getImm();
4747 
4748   unsigned FirstShift = Mips::NOP;
4749   unsigned SecondShift = Mips::NOP;
4750 
4751   if (hasMips32r2()) {
4752     if (Inst.getOpcode() == Mips::ROLImm) {
4753       uint64_t MaxShift = 32;
4754       uint64_t ShiftValue = ImmValue;
4755       if (ImmValue != 0)
4756         ShiftValue = MaxShift - ImmValue;
4757       TOut.emitRRI(Mips::ROTR, DReg, SReg, ShiftValue, Inst.getLoc(), STI);
4758       return false;
4759     }
4760 
4761     if (Inst.getOpcode() == Mips::RORImm) {
4762       TOut.emitRRI(Mips::ROTR, DReg, SReg, ImmValue, Inst.getLoc(), STI);
4763       return false;
4764     }
4765 
4766     return true;
4767   }
4768 
4769   if (hasMips32()) {
4770     if (ImmValue == 0) {
4771       TOut.emitRRI(Mips::SRL, DReg, SReg, 0, Inst.getLoc(), STI);
4772       return false;
4773     }
4774 
4775     switch (Inst.getOpcode()) {
4776     default:
4777       llvm_unreachable("unexpected instruction opcode");
4778     case Mips::ROLImm:
4779       FirstShift = Mips::SLL;
4780       SecondShift = Mips::SRL;
4781       break;
4782     case Mips::RORImm:
4783       FirstShift = Mips::SRL;
4784       SecondShift = Mips::SLL;
4785       break;
4786     }
4787 
4788     ATReg = getATReg(Inst.getLoc());
4789     if (!ATReg)
4790       return true;
4791 
4792     TOut.emitRRI(FirstShift, ATReg, SReg, ImmValue, Inst.getLoc(), STI);
4793     TOut.emitRRI(SecondShift, DReg, SReg, 32 - ImmValue, Inst.getLoc(), STI);
4794     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
4795 
4796     return false;
4797   }
4798 
4799   return true;
4800 }
4801 
4802 bool MipsAsmParser::expandDRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4803                                     const MCSubtargetInfo *STI) {
4804   MipsTargetStreamer &TOut = getTargetStreamer();
4805   unsigned ATReg = Mips::NoRegister;
4806   unsigned DReg = Inst.getOperand(0).getReg();
4807   unsigned SReg = Inst.getOperand(1).getReg();
4808   unsigned TReg = Inst.getOperand(2).getReg();
4809   unsigned TmpReg = DReg;
4810 
4811   unsigned FirstShift = Mips::NOP;
4812   unsigned SecondShift = Mips::NOP;
4813 
4814   if (hasMips64r2()) {
4815     if (TmpReg == SReg) {
4816       TmpReg = getATReg(Inst.getLoc());
4817       if (!TmpReg)
4818         return true;
4819     }
4820 
4821     if (Inst.getOpcode() == Mips::DROL) {
4822       TOut.emitRRR(Mips::DSUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
4823       TOut.emitRRR(Mips::DROTRV, DReg, SReg, TmpReg, Inst.getLoc(), STI);
4824       return false;
4825     }
4826 
4827     if (Inst.getOpcode() == Mips::DROR) {
4828       TOut.emitRRR(Mips::DROTRV, DReg, SReg, TReg, Inst.getLoc(), STI);
4829       return false;
4830     }
4831 
4832     return true;
4833   }
4834 
4835   if (hasMips64()) {
4836     switch (Inst.getOpcode()) {
4837     default:
4838       llvm_unreachable("unexpected instruction opcode");
4839     case Mips::DROL:
4840       FirstShift = Mips::DSRLV;
4841       SecondShift = Mips::DSLLV;
4842       break;
4843     case Mips::DROR:
4844       FirstShift = Mips::DSLLV;
4845       SecondShift = Mips::DSRLV;
4846       break;
4847     }
4848 
4849     ATReg = getATReg(Inst.getLoc());
4850     if (!ATReg)
4851       return true;
4852 
4853     TOut.emitRRR(Mips::DSUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), STI);
4854     TOut.emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), STI);
4855     TOut.emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), STI);
4856     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
4857 
4858     return false;
4859   }
4860 
4861   return true;
4862 }
4863 
4864 bool MipsAsmParser::expandDRotationImm(MCInst &Inst, SMLoc IDLoc,
4865                                        MCStreamer &Out,
4866                                        const MCSubtargetInfo *STI) {
4867   MipsTargetStreamer &TOut = getTargetStreamer();
4868   unsigned ATReg = Mips::NoRegister;
4869   unsigned DReg = Inst.getOperand(0).getReg();
4870   unsigned SReg = Inst.getOperand(1).getReg();
4871   int64_t ImmValue = Inst.getOperand(2).getImm() % 64;
4872 
4873   unsigned FirstShift = Mips::NOP;
4874   unsigned SecondShift = Mips::NOP;
4875 
4876   MCInst TmpInst;
4877 
4878   if (hasMips64r2()) {
4879     unsigned FinalOpcode = Mips::NOP;
4880     if (ImmValue == 0)
4881       FinalOpcode = Mips::DROTR;
4882     else if (ImmValue % 32 == 0)
4883       FinalOpcode = Mips::DROTR32;
4884     else if ((ImmValue >= 1) && (ImmValue <= 32)) {
4885       if (Inst.getOpcode() == Mips::DROLImm)
4886         FinalOpcode = Mips::DROTR32;
4887       else
4888         FinalOpcode = Mips::DROTR;
4889     } else if (ImmValue >= 33) {
4890       if (Inst.getOpcode() == Mips::DROLImm)
4891         FinalOpcode = Mips::DROTR;
4892       else
4893         FinalOpcode = Mips::DROTR32;
4894     }
4895 
4896     uint64_t ShiftValue = ImmValue % 32;
4897     if (Inst.getOpcode() == Mips::DROLImm)
4898       ShiftValue = (32 - ImmValue % 32) % 32;
4899 
4900     TOut.emitRRI(FinalOpcode, DReg, SReg, ShiftValue, Inst.getLoc(), STI);
4901 
4902     return false;
4903   }
4904 
4905   if (hasMips64()) {
4906     if (ImmValue == 0) {
4907       TOut.emitRRI(Mips::DSRL, DReg, SReg, 0, Inst.getLoc(), STI);
4908       return false;
4909     }
4910 
4911     switch (Inst.getOpcode()) {
4912     default:
4913       llvm_unreachable("unexpected instruction opcode");
4914     case Mips::DROLImm:
4915       if ((ImmValue >= 1) && (ImmValue <= 31)) {
4916         FirstShift = Mips::DSLL;
4917         SecondShift = Mips::DSRL32;
4918       }
4919       if (ImmValue == 32) {
4920         FirstShift = Mips::DSLL32;
4921         SecondShift = Mips::DSRL32;
4922       }
4923       if ((ImmValue >= 33) && (ImmValue <= 63)) {
4924         FirstShift = Mips::DSLL32;
4925         SecondShift = Mips::DSRL;
4926       }
4927       break;
4928     case Mips::DRORImm:
4929       if ((ImmValue >= 1) && (ImmValue <= 31)) {
4930         FirstShift = Mips::DSRL;
4931         SecondShift = Mips::DSLL32;
4932       }
4933       if (ImmValue == 32) {
4934         FirstShift = Mips::DSRL32;
4935         SecondShift = Mips::DSLL32;
4936       }
4937       if ((ImmValue >= 33) && (ImmValue <= 63)) {
4938         FirstShift = Mips::DSRL32;
4939         SecondShift = Mips::DSLL;
4940       }
4941       break;
4942     }
4943 
4944     ATReg = getATReg(Inst.getLoc());
4945     if (!ATReg)
4946       return true;
4947 
4948     TOut.emitRRI(FirstShift, ATReg, SReg, ImmValue % 32, Inst.getLoc(), STI);
4949     TOut.emitRRI(SecondShift, DReg, SReg, (32 - ImmValue % 32) % 32,
4950                  Inst.getLoc(), STI);
4951     TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI);
4952 
4953     return false;
4954   }
4955 
4956   return true;
4957 }
4958 
4959 bool MipsAsmParser::expandAbs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4960                               const MCSubtargetInfo *STI) {
4961   MipsTargetStreamer &TOut = getTargetStreamer();
4962   unsigned FirstRegOp = Inst.getOperand(0).getReg();
4963   unsigned SecondRegOp = Inst.getOperand(1).getReg();
4964 
4965   TOut.emitRI(Mips::BGEZ, SecondRegOp, 8, IDLoc, STI);
4966   if (FirstRegOp != SecondRegOp)
4967     TOut.emitRRR(Mips::ADDu, FirstRegOp, SecondRegOp, Mips::ZERO, IDLoc, STI);
4968   else
4969     TOut.emitEmptyDelaySlot(false, IDLoc, STI);
4970   TOut.emitRRR(Mips::SUB, FirstRegOp, Mips::ZERO, SecondRegOp, IDLoc, STI);
4971 
4972   return false;
4973 }
4974 
4975 bool MipsAsmParser::expandMulImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4976                                  const MCSubtargetInfo *STI) {
4977   MipsTargetStreamer &TOut = getTargetStreamer();
4978   unsigned ATReg = Mips::NoRegister;
4979   unsigned DstReg = Inst.getOperand(0).getReg();
4980   unsigned SrcReg = Inst.getOperand(1).getReg();
4981   int32_t ImmValue = Inst.getOperand(2).getImm();
4982 
4983   ATReg = getATReg(IDLoc);
4984   if (!ATReg)
4985     return true;
4986 
4987   loadImmediate(ImmValue, ATReg, Mips::NoRegister, true, false, IDLoc, Out,
4988                 STI);
4989 
4990   TOut.emitRR(Inst.getOpcode() == Mips::MULImmMacro ? Mips::MULT : Mips::DMULT,
4991               SrcReg, ATReg, IDLoc, STI);
4992 
4993   TOut.emitR(Mips::MFLO, DstReg, IDLoc, STI);
4994 
4995   return false;
4996 }
4997 
4998 bool MipsAsmParser::expandMulO(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
4999                                const MCSubtargetInfo *STI) {
5000   MipsTargetStreamer &TOut = getTargetStreamer();
5001   unsigned ATReg = Mips::NoRegister;
5002   unsigned DstReg = Inst.getOperand(0).getReg();
5003   unsigned SrcReg = Inst.getOperand(1).getReg();
5004   unsigned TmpReg = Inst.getOperand(2).getReg();
5005 
5006   ATReg = getATReg(Inst.getLoc());
5007   if (!ATReg)
5008     return true;
5009 
5010   TOut.emitRR(Inst.getOpcode() == Mips::MULOMacro ? Mips::MULT : Mips::DMULT,
5011               SrcReg, TmpReg, IDLoc, STI);
5012 
5013   TOut.emitR(Mips::MFLO, DstReg, IDLoc, STI);
5014 
5015   TOut.emitRRI(Inst.getOpcode() == Mips::MULOMacro ? Mips::SRA : Mips::DSRA32,
5016                DstReg, DstReg, 0x1F, IDLoc, STI);
5017 
5018   TOut.emitR(Mips::MFHI, ATReg, IDLoc, STI);
5019 
5020   if (useTraps()) {
5021     TOut.emitRRI(Mips::TNE, DstReg, ATReg, 6, IDLoc, STI);
5022   } else {
5023     MCContext & Context = TOut.getStreamer().getContext();
5024     MCSymbol * BrTarget = Context.createTempSymbol();
5025     MCOperand LabelOp =
5026         MCOperand::createExpr(MCSymbolRefExpr::create(BrTarget, Context));
5027 
5028     TOut.emitRRX(Mips::BEQ, DstReg, ATReg, LabelOp, IDLoc, STI);
5029     if (AssemblerOptions.back()->isReorder())
5030       TOut.emitNop(IDLoc, STI);
5031     TOut.emitII(Mips::BREAK, 6, 0, IDLoc, STI);
5032 
5033     TOut.getStreamer().EmitLabel(BrTarget);
5034   }
5035   TOut.emitR(Mips::MFLO, DstReg, IDLoc, STI);
5036 
5037   return false;
5038 }
5039 
5040 bool MipsAsmParser::expandMulOU(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
5041                                 const MCSubtargetInfo *STI) {
5042   MipsTargetStreamer &TOut = getTargetStreamer();
5043   unsigned ATReg = Mips::NoRegister;
5044   unsigned DstReg = Inst.getOperand(0).getReg();
5045   unsigned SrcReg = Inst.getOperand(1).getReg();
5046   unsigned TmpReg = Inst.getOperand(2).getReg();
5047 
5048   ATReg = getATReg(IDLoc);
5049   if (!ATReg)
5050     return true;
5051 
5052   TOut.emitRR(Inst.getOpcode() == Mips::MULOUMacro ? Mips::MULTu : Mips::DMULTu,
5053               SrcReg, TmpReg, IDLoc, STI);
5054 
5055   TOut.emitR(Mips::MFHI, ATReg, IDLoc, STI);
5056   TOut.emitR(Mips::MFLO, DstReg, IDLoc, STI);
5057   if (useTraps()) {
5058     TOut.emitRRI(Mips::TNE, ATReg, Mips::ZERO, 6, IDLoc, STI);
5059   } else {
5060     MCContext & Context = TOut.getStreamer().getContext();
5061     MCSymbol * BrTarget = Context.createTempSymbol();
5062     MCOperand LabelOp =
5063         MCOperand::createExpr(MCSymbolRefExpr::create(BrTarget, Context));
5064 
5065     TOut.emitRRX(Mips::BEQ, ATReg, Mips::ZERO, LabelOp, IDLoc, STI);
5066     if (AssemblerOptions.back()->isReorder())
5067       TOut.emitNop(IDLoc, STI);
5068     TOut.emitII(Mips::BREAK, 6, 0, IDLoc, STI);
5069 
5070     TOut.getStreamer().EmitLabel(BrTarget);
5071   }
5072 
5073   return false;
5074 }
5075 
5076 bool MipsAsmParser::expandDMULMacro(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
5077                                     const MCSubtargetInfo *STI) {
5078   MipsTargetStreamer &TOut = getTargetStreamer();
5079   unsigned DstReg = Inst.getOperand(0).getReg();
5080   unsigned SrcReg = Inst.getOperand(1).getReg();
5081   unsigned TmpReg = Inst.getOperand(2).getReg();
5082 
5083   TOut.emitRR(Mips::DMULTu, SrcReg, TmpReg, IDLoc, STI);
5084   TOut.emitR(Mips::MFLO, DstReg, IDLoc, STI);
5085 
5086   return false;
5087 }
5088 
5089 // Expand 'ld $<reg> offset($reg2)' to 'lw $<reg>, offset($reg2);
5090 //                                      lw $<reg+1>>, offset+4($reg2)'
5091 // or expand 'sd $<reg> offset($reg2)' to 'sw $<reg>, offset($reg2);
5092 //                                         sw $<reg+1>>, offset+4($reg2)'
5093 // for O32.
5094 bool MipsAsmParser::expandLoadStoreDMacro(MCInst &Inst, SMLoc IDLoc,
5095                                           MCStreamer &Out,
5096                                           const MCSubtargetInfo *STI,
5097                                           bool IsLoad) {
5098   if (!isABI_O32())
5099     return true;
5100 
5101   warnIfNoMacro(IDLoc);
5102 
5103   MipsTargetStreamer &TOut = getTargetStreamer();
5104   unsigned Opcode = IsLoad ? Mips::LW : Mips::SW;
5105   unsigned FirstReg = Inst.getOperand(0).getReg();
5106   unsigned SecondReg = nextReg(FirstReg);
5107   unsigned BaseReg = Inst.getOperand(1).getReg();
5108   if (!SecondReg)
5109     return true;
5110 
5111   warnIfRegIndexIsAT(FirstReg, IDLoc);
5112 
5113   assert(Inst.getOperand(2).isImm() &&
5114          "Offset for load macro is not immediate!");
5115 
5116   MCOperand &FirstOffset = Inst.getOperand(2);
5117   signed NextOffset = FirstOffset.getImm() + 4;
5118   MCOperand SecondOffset = MCOperand::createImm(NextOffset);
5119 
5120   if (!isInt<16>(FirstOffset.getImm()) || !isInt<16>(NextOffset))
5121     return true;
5122 
5123   // For loads, clobber the base register with the second load instead of the
5124   // first if the BaseReg == FirstReg.
5125   if (FirstReg != BaseReg || !IsLoad) {
5126     TOut.emitRRX(Opcode, FirstReg, BaseReg, FirstOffset, IDLoc, STI);
5127     TOut.emitRRX(Opcode, SecondReg, BaseReg, SecondOffset, IDLoc, STI);
5128   } else {
5129     TOut.emitRRX(Opcode, SecondReg, BaseReg, SecondOffset, IDLoc, STI);
5130     TOut.emitRRX(Opcode, FirstReg, BaseReg, FirstOffset, IDLoc, STI);
5131   }
5132 
5133   return false;
5134 }
5135 
5136 
5137 // Expand 's.d $<reg> offset($reg2)' to 'swc1 $<reg+1>, offset($reg2);
5138 //                                       swc1 $<reg>, offset+4($reg2)'
5139 // or if little endian to 'swc1 $<reg>, offset($reg2);
5140 //                         swc1 $<reg+1>, offset+4($reg2)'
5141 // for Mips1.
5142 bool MipsAsmParser::expandStoreDM1Macro(MCInst &Inst, SMLoc IDLoc,
5143                                         MCStreamer &Out,
5144                                         const MCSubtargetInfo *STI) {
5145   if (!isABI_O32())
5146     return true;
5147 
5148   warnIfNoMacro(IDLoc);
5149 
5150   MipsTargetStreamer &TOut = getTargetStreamer();
5151   unsigned Opcode = Mips::SWC1;
5152   unsigned FirstReg = Inst.getOperand(0).getReg();
5153   unsigned SecondReg = nextReg(FirstReg);
5154   unsigned BaseReg = Inst.getOperand(1).getReg();
5155   if (!SecondReg)
5156     return true;
5157 
5158   warnIfRegIndexIsAT(FirstReg, IDLoc);
5159 
5160   assert(Inst.getOperand(2).isImm() &&
5161          "Offset for macro is not immediate!");
5162 
5163   MCOperand &FirstOffset = Inst.getOperand(2);
5164   signed NextOffset = FirstOffset.getImm() + 4;
5165   MCOperand SecondOffset = MCOperand::createImm(NextOffset);
5166 
5167   if (!isInt<16>(FirstOffset.getImm()) || !isInt<16>(NextOffset))
5168     return true;
5169 
5170   if (!IsLittleEndian)
5171     std::swap(FirstReg, SecondReg);
5172 
5173   TOut.emitRRX(Opcode, FirstReg, BaseReg, FirstOffset, IDLoc, STI);
5174   TOut.emitRRX(Opcode, SecondReg, BaseReg, SecondOffset, IDLoc, STI);
5175 
5176   return false;
5177 }
5178 
5179 bool MipsAsmParser::expandSeq(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
5180                               const MCSubtargetInfo *STI) {
5181   MipsTargetStreamer &TOut = getTargetStreamer();
5182 
5183   assert(Inst.getNumOperands() == 3 && "Invalid operand count");
5184   assert(Inst.getOperand(0).isReg() &&
5185          Inst.getOperand(1).isReg() &&
5186          Inst.getOperand(2).isReg() && "Invalid instruction operand.");
5187 
5188   unsigned DstReg = Inst.getOperand(0).getReg();
5189   unsigned SrcReg = Inst.getOperand(1).getReg();
5190   unsigned OpReg = Inst.getOperand(2).getReg();
5191 
5192   warnIfNoMacro(IDLoc);
5193 
5194   if (SrcReg != Mips::ZERO && OpReg != Mips::ZERO) {
5195     TOut.emitRRR(Mips::XOR, DstReg, SrcReg, OpReg, IDLoc, STI);
5196     TOut.emitRRI(Mips::SLTiu, DstReg, DstReg, 1, IDLoc, STI);
5197     return false;
5198   }
5199 
5200   unsigned Reg = SrcReg == Mips::ZERO ? OpReg : SrcReg;
5201   TOut.emitRRI(Mips::SLTiu, DstReg, Reg, 1, IDLoc, STI);
5202   return false;
5203 }
5204 
5205 bool MipsAsmParser::expandSeqI(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
5206                                const MCSubtargetInfo *STI) {
5207   MipsTargetStreamer &TOut = getTargetStreamer();
5208 
5209   assert(Inst.getNumOperands() == 3 && "Invalid operand count");
5210   assert(Inst.getOperand(0).isReg() &&
5211          Inst.getOperand(1).isReg() &&
5212          Inst.getOperand(2).isImm() && "Invalid instruction operand.");
5213 
5214   unsigned DstReg = Inst.getOperand(0).getReg();
5215   unsigned SrcReg = Inst.getOperand(1).getReg();
5216   int64_t Imm = Inst.getOperand(2).getImm();
5217 
5218   warnIfNoMacro(IDLoc);
5219 
5220   if (Imm == 0) {
5221     TOut.emitRRI(Mips::SLTiu, DstReg, SrcReg, 1, IDLoc, STI);
5222     return false;
5223   }
5224 
5225   if (SrcReg == Mips::ZERO) {
5226     Warning(IDLoc, "comparison is always false");
5227     TOut.emitRRR(isGP64bit() ? Mips::DADDu : Mips::ADDu,
5228                  DstReg, SrcReg, SrcReg, IDLoc, STI);
5229     return false;
5230   }
5231 
5232   unsigned Opc;
5233   if (Imm > -0x8000 && Imm < 0) {
5234     Imm = -Imm;
5235     Opc = isGP64bit() ? Mips::DADDiu : Mips::ADDiu;
5236   } else {
5237     Opc = Mips::XORi;
5238   }
5239 
5240   if (!isUInt<16>(Imm)) {
5241     unsigned ATReg = getATReg(IDLoc);
5242     if (!ATReg)
5243       return true;
5244 
5245     if (loadImmediate(Imm, ATReg, Mips::NoRegister, true, isGP64bit(), IDLoc,
5246                       Out, STI))
5247       return true;
5248 
5249     TOut.emitRRR(Mips::XOR, DstReg, SrcReg, ATReg, IDLoc, STI);
5250     TOut.emitRRI(Mips::SLTiu, DstReg, DstReg, 1, IDLoc, STI);
5251     return false;
5252   }
5253 
5254   TOut.emitRRI(Opc, DstReg, SrcReg, Imm, IDLoc, STI);
5255   TOut.emitRRI(Mips::SLTiu, DstReg, DstReg, 1, IDLoc, STI);
5256   return false;
5257 }
5258 
5259 // Map the DSP accumulator and control register to the corresponding gpr
5260 // operand. Unlike the other alias, the m(f|t)t(lo|hi|acx) instructions
5261 // do not map the DSP registers contigously to gpr registers.
5262 static unsigned getRegisterForMxtrDSP(MCInst &Inst, bool IsMFDSP) {
5263   switch (Inst.getOpcode()) {
5264     case Mips::MFTLO:
5265     case Mips::MTTLO:
5266       switch (Inst.getOperand(IsMFDSP ? 1 : 0).getReg()) {
5267         case Mips::AC0:
5268           return Mips::ZERO;
5269         case Mips::AC1:
5270           return Mips::A0;
5271         case Mips::AC2:
5272           return Mips::T0;
5273         case Mips::AC3:
5274           return Mips::T4;
5275         default:
5276           llvm_unreachable("Unknown register for 'mttr' alias!");
5277     }
5278     case Mips::MFTHI:
5279     case Mips::MTTHI:
5280       switch (Inst.getOperand(IsMFDSP ? 1 : 0).getReg()) {
5281         case Mips::AC0:
5282           return Mips::AT;
5283         case Mips::AC1:
5284           return Mips::A1;
5285         case Mips::AC2:
5286           return Mips::T1;
5287         case Mips::AC3:
5288           return Mips::T5;
5289         default:
5290           llvm_unreachable("Unknown register for 'mttr' alias!");
5291     }
5292     case Mips::MFTACX:
5293     case Mips::MTTACX:
5294       switch (Inst.getOperand(IsMFDSP ? 1 : 0).getReg()) {
5295         case Mips::AC0:
5296           return Mips::V0;
5297         case Mips::AC1:
5298           return Mips::A2;
5299         case Mips::AC2:
5300           return Mips::T2;
5301         case Mips::AC3:
5302           return Mips::T6;
5303         default:
5304           llvm_unreachable("Unknown register for 'mttr' alias!");
5305     }
5306     case Mips::MFTDSP:
5307     case Mips::MTTDSP:
5308       return Mips::S0;
5309     default:
5310       llvm_unreachable("Unknown instruction for 'mttr' dsp alias!");
5311   }
5312 }
5313 
5314 // Map the floating point register operand to the corresponding register
5315 // operand.
5316 static unsigned getRegisterForMxtrFP(MCInst &Inst, bool IsMFTC1) {
5317   switch (Inst.getOperand(IsMFTC1 ? 1 : 0).getReg()) {
5318     case Mips::F0:  return Mips::ZERO;
5319     case Mips::F1:  return Mips::AT;
5320     case Mips::F2:  return Mips::V0;
5321     case Mips::F3:  return Mips::V1;
5322     case Mips::F4:  return Mips::A0;
5323     case Mips::F5:  return Mips::A1;
5324     case Mips::F6:  return Mips::A2;
5325     case Mips::F7:  return Mips::A3;
5326     case Mips::F8:  return Mips::T0;
5327     case Mips::F9:  return Mips::T1;
5328     case Mips::F10: return Mips::T2;
5329     case Mips::F11: return Mips::T3;
5330     case Mips::F12: return Mips::T4;
5331     case Mips::F13: return Mips::T5;
5332     case Mips::F14: return Mips::T6;
5333     case Mips::F15: return Mips::T7;
5334     case Mips::F16: return Mips::S0;
5335     case Mips::F17: return Mips::S1;
5336     case Mips::F18: return Mips::S2;
5337     case Mips::F19: return Mips::S3;
5338     case Mips::F20: return Mips::S4;
5339     case Mips::F21: return Mips::S5;
5340     case Mips::F22: return Mips::S6;
5341     case Mips::F23: return Mips::S7;
5342     case Mips::F24: return Mips::T8;
5343     case Mips::F25: return Mips::T9;
5344     case Mips::F26: return Mips::K0;
5345     case Mips::F27: return Mips::K1;
5346     case Mips::F28: return Mips::GP;
5347     case Mips::F29: return Mips::SP;
5348     case Mips::F30: return Mips::FP;
5349     case Mips::F31: return Mips::RA;
5350     default: llvm_unreachable("Unknown register for mttc1 alias!");
5351   }
5352 }
5353 
5354 // Map the coprocessor operand the corresponding gpr register operand.
5355 static unsigned getRegisterForMxtrC0(MCInst &Inst, bool IsMFTC0) {
5356   switch (Inst.getOperand(IsMFTC0 ? 1 : 0).getReg()) {
5357     case Mips::COP00:  return Mips::ZERO;
5358     case Mips::COP01:  return Mips::AT;
5359     case Mips::COP02:  return Mips::V0;
5360     case Mips::COP03:  return Mips::V1;
5361     case Mips::COP04:  return Mips::A0;
5362     case Mips::COP05:  return Mips::A1;
5363     case Mips::COP06:  return Mips::A2;
5364     case Mips::COP07:  return Mips::A3;
5365     case Mips::COP08:  return Mips::T0;
5366     case Mips::COP09:  return Mips::T1;
5367     case Mips::COP010: return Mips::T2;
5368     case Mips::COP011: return Mips::T3;
5369     case Mips::COP012: return Mips::T4;
5370     case Mips::COP013: return Mips::T5;
5371     case Mips::COP014: return Mips::T6;
5372     case Mips::COP015: return Mips::T7;
5373     case Mips::COP016: return Mips::S0;
5374     case Mips::COP017: return Mips::S1;
5375     case Mips::COP018: return Mips::S2;
5376     case Mips::COP019: return Mips::S3;
5377     case Mips::COP020: return Mips::S4;
5378     case Mips::COP021: return Mips::S5;
5379     case Mips::COP022: return Mips::S6;
5380     case Mips::COP023: return Mips::S7;
5381     case Mips::COP024: return Mips::T8;
5382     case Mips::COP025: return Mips::T9;
5383     case Mips::COP026: return Mips::K0;
5384     case Mips::COP027: return Mips::K1;
5385     case Mips::COP028: return Mips::GP;
5386     case Mips::COP029: return Mips::SP;
5387     case Mips::COP030: return Mips::FP;
5388     case Mips::COP031: return Mips::RA;
5389     default: llvm_unreachable("Unknown register for mttc0 alias!");
5390   }
5391 }
5392 
5393 /// Expand an alias of 'mftr' or 'mttr' into the full instruction, by producing
5394 /// an mftr or mttr with the correctly mapped gpr register, u, sel and h bits.
5395 bool MipsAsmParser::expandMXTRAlias(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
5396                                     const MCSubtargetInfo *STI) {
5397   MipsTargetStreamer &TOut = getTargetStreamer();
5398   unsigned rd = 0;
5399   unsigned u = 1;
5400   unsigned sel = 0;
5401   unsigned h = 0;
5402   bool IsMFTR = false;
5403   switch (Inst.getOpcode()) {
5404     case Mips::MFTC0:
5405       IsMFTR = true;
5406       LLVM_FALLTHROUGH;
5407     case Mips::MTTC0:
5408       u = 0;
5409       rd = getRegisterForMxtrC0(Inst, IsMFTR);
5410       sel = Inst.getOperand(2).getImm();
5411       break;
5412     case Mips::MFTGPR:
5413       IsMFTR = true;
5414       LLVM_FALLTHROUGH;
5415     case Mips::MTTGPR:
5416       rd = Inst.getOperand(IsMFTR ? 1 : 0).getReg();
5417       break;
5418     case Mips::MFTLO:
5419     case Mips::MFTHI:
5420     case Mips::MFTACX:
5421     case Mips::MFTDSP:
5422       IsMFTR = true;
5423       LLVM_FALLTHROUGH;
5424     case Mips::MTTLO:
5425     case Mips::MTTHI:
5426     case Mips::MTTACX:
5427     case Mips::MTTDSP:
5428       rd = getRegisterForMxtrDSP(Inst, IsMFTR);
5429       sel = 1;
5430       break;
5431     case Mips::MFTHC1:
5432       h = 1;
5433       LLVM_FALLTHROUGH;
5434     case Mips::MFTC1:
5435       IsMFTR = true;
5436       rd = getRegisterForMxtrFP(Inst, IsMFTR);
5437       sel = 2;
5438       break;
5439     case Mips::MTTHC1:
5440       h = 1;
5441       LLVM_FALLTHROUGH;
5442     case Mips::MTTC1:
5443       rd = getRegisterForMxtrFP(Inst, IsMFTR);
5444       sel = 2;
5445       break;
5446     case Mips::CFTC1:
5447       IsMFTR = true;
5448       LLVM_FALLTHROUGH;
5449     case Mips::CTTC1:
5450       rd = getRegisterForMxtrFP(Inst, IsMFTR);
5451       sel = 3;
5452       break;
5453   }
5454   unsigned Op0 = IsMFTR ? Inst.getOperand(0).getReg() : rd;
5455   unsigned Op1 =
5456       IsMFTR ? rd
5457              : (Inst.getOpcode() != Mips::MTTDSP ? Inst.getOperand(1).getReg()
5458                                                  : Inst.getOperand(0).getReg());
5459 
5460   TOut.emitRRIII(IsMFTR ? Mips::MFTR : Mips::MTTR, Op0, Op1, u, sel, h, IDLoc,
5461                  STI);
5462   return false;
5463 }
5464 
5465 bool MipsAsmParser::expandSaaAddr(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
5466                                   const MCSubtargetInfo *STI) {
5467   assert(Inst.getNumOperands() == 3 && "expected three operands");
5468   assert(Inst.getOperand(0).isReg() && "expected register operand kind");
5469   assert(Inst.getOperand(1).isReg() && "expected register operand kind");
5470 
5471   warnIfNoMacro(IDLoc);
5472 
5473   MipsTargetStreamer &TOut = getTargetStreamer();
5474   unsigned Opcode = Inst.getOpcode() == Mips::SaaAddr ? Mips::SAA : Mips::SAAD;
5475   unsigned RtReg = Inst.getOperand(0).getReg();
5476   unsigned BaseReg = Inst.getOperand(1).getReg();
5477   const MCOperand &BaseOp = Inst.getOperand(2);
5478 
5479   if (BaseOp.isImm()) {
5480     int64_t ImmValue = BaseOp.getImm();
5481     if (ImmValue == 0) {
5482       TOut.emitRR(Opcode, RtReg, BaseReg, IDLoc, STI);
5483       return false;
5484     }
5485   }
5486 
5487   unsigned ATReg = getATReg(IDLoc);
5488   if (!ATReg)
5489     return true;
5490 
5491   if (expandLoadAddress(ATReg, BaseReg, BaseOp, !isGP64bit(), IDLoc, Out, STI))
5492     return true;
5493 
5494   TOut.emitRR(Opcode, RtReg, ATReg, IDLoc, STI);
5495   return false;
5496 }
5497 
5498 unsigned
5499 MipsAsmParser::checkEarlyTargetMatchPredicate(MCInst &Inst,
5500                                               const OperandVector &Operands) {
5501   switch (Inst.getOpcode()) {
5502   default:
5503     return Match_Success;
5504   case Mips::DATI:
5505   case Mips::DAHI:
5506     if (static_cast<MipsOperand &>(*Operands[1])
5507             .isValidForTie(static_cast<MipsOperand &>(*Operands[2])))
5508       return Match_Success;
5509     return Match_RequiresSameSrcAndDst;
5510   }
5511 }
5512 
5513 unsigned MipsAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
5514   switch (Inst.getOpcode()) {
5515   // As described by the MIPSR6 spec, daui must not use the zero operand for
5516   // its source operand.
5517   case Mips::DAUI:
5518     if (Inst.getOperand(1).getReg() == Mips::ZERO ||
5519         Inst.getOperand(1).getReg() == Mips::ZERO_64)
5520       return Match_RequiresNoZeroRegister;
5521     return Match_Success;
5522   // As described by the Mips32r2 spec, the registers Rd and Rs for
5523   // jalr.hb must be different.
5524   // It also applies for registers Rt and Rs of microMIPSr6 jalrc.hb instruction
5525   // and registers Rd and Base for microMIPS lwp instruction
5526   case Mips::JALR_HB:
5527   case Mips::JALR_HB64:
5528   case Mips::JALRC_HB_MMR6:
5529   case Mips::JALRC_MMR6:
5530     if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg())
5531       return Match_RequiresDifferentSrcAndDst;
5532     return Match_Success;
5533   case Mips::LWP_MM:
5534     if (Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg())
5535       return Match_RequiresDifferentSrcAndDst;
5536     return Match_Success;
5537   case Mips::SYNC:
5538     if (Inst.getOperand(0).getImm() != 0 && !hasMips32())
5539       return Match_NonZeroOperandForSync;
5540     return Match_Success;
5541   case Mips::MFC0:
5542   case Mips::MTC0:
5543   case Mips::MTC2:
5544   case Mips::MFC2:
5545     if (Inst.getOperand(2).getImm() != 0 && !hasMips32())
5546       return Match_NonZeroOperandForMTCX;
5547     return Match_Success;
5548   // As described the MIPSR6 spec, the compact branches that compare registers
5549   // must:
5550   // a) Not use the zero register.
5551   // b) Not use the same register twice.
5552   // c) rs < rt for bnec, beqc.
5553   //    NB: For this case, the encoding will swap the operands as their
5554   //    ordering doesn't matter. GAS performs this transformation  too.
5555   //    Hence, that constraint does not have to be enforced.
5556   //
5557   // The compact branches that branch iff the signed addition of two registers
5558   // would overflow must have rs >= rt. That can be handled like beqc/bnec with
5559   // operand swapping. They do not have restriction of using the zero register.
5560   case Mips::BLEZC:   case Mips::BLEZC_MMR6:
5561   case Mips::BGEZC:   case Mips::BGEZC_MMR6:
5562   case Mips::BGTZC:   case Mips::BGTZC_MMR6:
5563   case Mips::BLTZC:   case Mips::BLTZC_MMR6:
5564   case Mips::BEQZC:   case Mips::BEQZC_MMR6:
5565   case Mips::BNEZC:   case Mips::BNEZC_MMR6:
5566   case Mips::BLEZC64:
5567   case Mips::BGEZC64:
5568   case Mips::BGTZC64:
5569   case Mips::BLTZC64:
5570   case Mips::BEQZC64:
5571   case Mips::BNEZC64:
5572     if (Inst.getOperand(0).getReg() == Mips::ZERO ||
5573         Inst.getOperand(0).getReg() == Mips::ZERO_64)
5574       return Match_RequiresNoZeroRegister;
5575     return Match_Success;
5576   case Mips::BGEC:    case Mips::BGEC_MMR6:
5577   case Mips::BLTC:    case Mips::BLTC_MMR6:
5578   case Mips::BGEUC:   case Mips::BGEUC_MMR6:
5579   case Mips::BLTUC:   case Mips::BLTUC_MMR6:
5580   case Mips::BEQC:    case Mips::BEQC_MMR6:
5581   case Mips::BNEC:    case Mips::BNEC_MMR6:
5582   case Mips::BGEC64:
5583   case Mips::BLTC64:
5584   case Mips::BGEUC64:
5585   case Mips::BLTUC64:
5586   case Mips::BEQC64:
5587   case Mips::BNEC64:
5588     if (Inst.getOperand(0).getReg() == Mips::ZERO ||
5589         Inst.getOperand(0).getReg() == Mips::ZERO_64)
5590       return Match_RequiresNoZeroRegister;
5591     if (Inst.getOperand(1).getReg() == Mips::ZERO ||
5592         Inst.getOperand(1).getReg() == Mips::ZERO_64)
5593       return Match_RequiresNoZeroRegister;
5594     if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg())
5595       return Match_RequiresDifferentOperands;
5596     return Match_Success;
5597   case Mips::DINS: {
5598     assert(Inst.getOperand(2).isImm() && Inst.getOperand(3).isImm() &&
5599            "Operands must be immediates for dins!");
5600     const signed Pos = Inst.getOperand(2).getImm();
5601     const signed Size = Inst.getOperand(3).getImm();
5602     if ((0 > (Pos + Size)) || ((Pos + Size) > 32))
5603       return Match_RequiresPosSizeRange0_32;
5604     return Match_Success;
5605   }
5606   case Mips::DINSM:
5607   case Mips::DINSU: {
5608     assert(Inst.getOperand(2).isImm() && Inst.getOperand(3).isImm() &&
5609            "Operands must be immediates for dinsm/dinsu!");
5610     const signed Pos = Inst.getOperand(2).getImm();
5611     const signed Size = Inst.getOperand(3).getImm();
5612     if ((32 >= (Pos + Size)) || ((Pos + Size) > 64))
5613       return Match_RequiresPosSizeRange33_64;
5614     return Match_Success;
5615   }
5616   case Mips::DEXT: {
5617     assert(Inst.getOperand(2).isImm() && Inst.getOperand(3).isImm() &&
5618            "Operands must be immediates for DEXTM!");
5619     const signed Pos = Inst.getOperand(2).getImm();
5620     const signed Size = Inst.getOperand(3).getImm();
5621     if ((1 > (Pos + Size)) || ((Pos + Size) > 63))
5622       return Match_RequiresPosSizeUImm6;
5623     return Match_Success;
5624   }
5625   case Mips::DEXTM:
5626   case Mips::DEXTU: {
5627     assert(Inst.getOperand(2).isImm() && Inst.getOperand(3).isImm() &&
5628            "Operands must be immediates for dextm/dextu!");
5629     const signed Pos = Inst.getOperand(2).getImm();
5630     const signed Size = Inst.getOperand(3).getImm();
5631     if ((32 > (Pos + Size)) || ((Pos + Size) > 64))
5632       return Match_RequiresPosSizeRange33_64;
5633     return Match_Success;
5634   }
5635   case Mips::CRC32B: case Mips::CRC32CB:
5636   case Mips::CRC32H: case Mips::CRC32CH:
5637   case Mips::CRC32W: case Mips::CRC32CW:
5638   case Mips::CRC32D: case Mips::CRC32CD:
5639     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg())
5640       return Match_RequiresSameSrcAndDst;
5641     return Match_Success;
5642   }
5643 
5644   uint64_t TSFlags = getInstDesc(Inst.getOpcode()).TSFlags;
5645   if ((TSFlags & MipsII::HasFCCRegOperand) &&
5646       (Inst.getOperand(0).getReg() != Mips::FCC0) && !hasEightFccRegisters())
5647     return Match_NoFCCRegisterForCurrentISA;
5648 
5649   return Match_Success;
5650 
5651 }
5652 
5653 static SMLoc RefineErrorLoc(const SMLoc Loc, const OperandVector &Operands,
5654                             uint64_t ErrorInfo) {
5655   if (ErrorInfo != ~0ULL && ErrorInfo < Operands.size()) {
5656     SMLoc ErrorLoc = Operands[ErrorInfo]->getStartLoc();
5657     if (ErrorLoc == SMLoc())
5658       return Loc;
5659     return ErrorLoc;
5660   }
5661   return Loc;
5662 }
5663 
5664 bool MipsAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
5665                                             OperandVector &Operands,
5666                                             MCStreamer &Out,
5667                                             uint64_t &ErrorInfo,
5668                                             bool MatchingInlineAsm) {
5669   MCInst Inst;
5670   unsigned MatchResult =
5671       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
5672 
5673   switch (MatchResult) {
5674   case Match_Success:
5675     if (processInstruction(Inst, IDLoc, Out, STI))
5676       return true;
5677     return false;
5678   case Match_MissingFeature:
5679     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
5680     return true;
5681   case Match_InvalidOperand: {
5682     SMLoc ErrorLoc = IDLoc;
5683     if (ErrorInfo != ~0ULL) {
5684       if (ErrorInfo >= Operands.size())
5685         return Error(IDLoc, "too few operands for instruction");
5686 
5687       ErrorLoc = Operands[ErrorInfo]->getStartLoc();
5688       if (ErrorLoc == SMLoc())
5689         ErrorLoc = IDLoc;
5690     }
5691 
5692     return Error(ErrorLoc, "invalid operand for instruction");
5693   }
5694   case Match_NonZeroOperandForSync:
5695     return Error(IDLoc,
5696                  "s-type must be zero or unspecified for pre-MIPS32 ISAs");
5697   case Match_NonZeroOperandForMTCX:
5698     return Error(IDLoc, "selector must be zero for pre-MIPS32 ISAs");
5699   case Match_MnemonicFail:
5700     return Error(IDLoc, "invalid instruction");
5701   case Match_RequiresDifferentSrcAndDst:
5702     return Error(IDLoc, "source and destination must be different");
5703   case Match_RequiresDifferentOperands:
5704     return Error(IDLoc, "registers must be different");
5705   case Match_RequiresNoZeroRegister:
5706     return Error(IDLoc, "invalid operand ($zero) for instruction");
5707   case Match_RequiresSameSrcAndDst:
5708     return Error(IDLoc, "source and destination must match");
5709   case Match_NoFCCRegisterForCurrentISA:
5710     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5711                  "non-zero fcc register doesn't exist in current ISA level");
5712   case Match_Immz:
5713     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected '0'");
5714   case Match_UImm1_0:
5715     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5716                  "expected 1-bit unsigned immediate");
5717   case Match_UImm2_0:
5718     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5719                  "expected 2-bit unsigned immediate");
5720   case Match_UImm2_1:
5721     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5722                  "expected immediate in range 1 .. 4");
5723   case Match_UImm3_0:
5724     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5725                  "expected 3-bit unsigned immediate");
5726   case Match_UImm4_0:
5727     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5728                  "expected 4-bit unsigned immediate");
5729   case Match_SImm4_0:
5730     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5731                  "expected 4-bit signed immediate");
5732   case Match_UImm5_0:
5733     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5734                  "expected 5-bit unsigned immediate");
5735   case Match_SImm5_0:
5736     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5737                  "expected 5-bit signed immediate");
5738   case Match_UImm5_1:
5739     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5740                  "expected immediate in range 1 .. 32");
5741   case Match_UImm5_32:
5742     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5743                  "expected immediate in range 32 .. 63");
5744   case Match_UImm5_33:
5745     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5746                  "expected immediate in range 33 .. 64");
5747   case Match_UImm5_0_Report_UImm6:
5748     // This is used on UImm5 operands that have a corresponding UImm5_32
5749     // operand to avoid confusing the user.
5750     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5751                  "expected 6-bit unsigned immediate");
5752   case Match_UImm5_Lsl2:
5753     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5754                  "expected both 7-bit unsigned immediate and multiple of 4");
5755   case Match_UImmRange2_64:
5756     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5757                  "expected immediate in range 2 .. 64");
5758   case Match_UImm6_0:
5759     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5760                  "expected 6-bit unsigned immediate");
5761   case Match_UImm6_Lsl2:
5762     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5763                  "expected both 8-bit unsigned immediate and multiple of 4");
5764   case Match_SImm6_0:
5765     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5766                  "expected 6-bit signed immediate");
5767   case Match_UImm7_0:
5768     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5769                  "expected 7-bit unsigned immediate");
5770   case Match_UImm7_N1:
5771     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5772                  "expected immediate in range -1 .. 126");
5773   case Match_SImm7_Lsl2:
5774     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5775                  "expected both 9-bit signed immediate and multiple of 4");
5776   case Match_UImm8_0:
5777     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5778                  "expected 8-bit unsigned immediate");
5779   case Match_UImm10_0:
5780     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5781                  "expected 10-bit unsigned immediate");
5782   case Match_SImm10_0:
5783     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5784                  "expected 10-bit signed immediate");
5785   case Match_SImm11_0:
5786     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5787                  "expected 11-bit signed immediate");
5788   case Match_UImm16:
5789   case Match_UImm16_Relaxed:
5790   case Match_UImm16_AltRelaxed:
5791     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5792                  "expected 16-bit unsigned immediate");
5793   case Match_SImm16:
5794   case Match_SImm16_Relaxed:
5795     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5796                  "expected 16-bit signed immediate");
5797   case Match_SImm19_Lsl2:
5798     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5799                  "expected both 19-bit signed immediate and multiple of 4");
5800   case Match_UImm20_0:
5801     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5802                  "expected 20-bit unsigned immediate");
5803   case Match_UImm26_0:
5804     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5805                  "expected 26-bit unsigned immediate");
5806   case Match_SImm32:
5807   case Match_SImm32_Relaxed:
5808     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5809                  "expected 32-bit signed immediate");
5810   case Match_UImm32_Coerced:
5811     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5812                  "expected 32-bit immediate");
5813   case Match_MemSImm9:
5814     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5815                  "expected memory with 9-bit signed offset");
5816   case Match_MemSImm10:
5817     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5818                  "expected memory with 10-bit signed offset");
5819   case Match_MemSImm10Lsl1:
5820     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5821                  "expected memory with 11-bit signed offset and multiple of 2");
5822   case Match_MemSImm10Lsl2:
5823     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5824                  "expected memory with 12-bit signed offset and multiple of 4");
5825   case Match_MemSImm10Lsl3:
5826     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5827                  "expected memory with 13-bit signed offset and multiple of 8");
5828   case Match_MemSImm11:
5829     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5830                  "expected memory with 11-bit signed offset");
5831   case Match_MemSImm12:
5832     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5833                  "expected memory with 12-bit signed offset");
5834   case Match_MemSImm16:
5835     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5836                  "expected memory with 16-bit signed offset");
5837   case Match_MemSImmPtr:
5838     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
5839                  "expected memory with 32-bit signed offset");
5840   case Match_RequiresPosSizeRange0_32: {
5841     SMLoc ErrorStart = Operands[3]->getStartLoc();
5842     SMLoc ErrorEnd = Operands[4]->getEndLoc();
5843     return Error(ErrorStart, "size plus position are not in the range 0 .. 32",
5844                  SMRange(ErrorStart, ErrorEnd));
5845     }
5846   case Match_RequiresPosSizeUImm6: {
5847     SMLoc ErrorStart = Operands[3]->getStartLoc();
5848     SMLoc ErrorEnd = Operands[4]->getEndLoc();
5849     return Error(ErrorStart, "size plus position are not in the range 1 .. 63",
5850                  SMRange(ErrorStart, ErrorEnd));
5851     }
5852   case Match_RequiresPosSizeRange33_64: {
5853     SMLoc ErrorStart = Operands[3]->getStartLoc();
5854     SMLoc ErrorEnd = Operands[4]->getEndLoc();
5855     return Error(ErrorStart, "size plus position are not in the range 33 .. 64",
5856                  SMRange(ErrorStart, ErrorEnd));
5857     }
5858   }
5859 
5860   llvm_unreachable("Implement any new match types added!");
5861 }
5862 
5863 void MipsAsmParser::warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc) {
5864   if (RegIndex != 0 && AssemblerOptions.back()->getATRegIndex() == RegIndex)
5865     Warning(Loc, "used $at (currently $" + Twine(RegIndex) +
5866                      ") without \".set noat\"");
5867 }
5868 
5869 void MipsAsmParser::warnIfNoMacro(SMLoc Loc) {
5870   if (!AssemblerOptions.back()->isMacro())
5871     Warning(Loc, "macro instruction expanded into multiple instructions");
5872 }
5873 
5874 void MipsAsmParser::ConvertXWPOperands(MCInst &Inst,
5875                                        const OperandVector &Operands) {
5876   assert(
5877       (Inst.getOpcode() == Mips::LWP_MM || Inst.getOpcode() == Mips::SWP_MM) &&
5878       "Unexpected instruction!");
5879   ((MipsOperand &)*Operands[1]).addGPR32ZeroAsmRegOperands(Inst, 1);
5880   int NextReg = nextReg(((MipsOperand &)*Operands[1]).getGPR32Reg());
5881   Inst.addOperand(MCOperand::createReg(NextReg));
5882   ((MipsOperand &)*Operands[2]).addMemOperands(Inst, 2);
5883 }
5884 
5885 void
5886 MipsAsmParser::printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
5887                                      SMRange Range, bool ShowColors) {
5888   getSourceManager().PrintMessage(Range.Start, SourceMgr::DK_Warning, Msg,
5889                                   Range, SMFixIt(Range, FixMsg),
5890                                   ShowColors);
5891 }
5892 
5893 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
5894   int CC;
5895 
5896   CC = StringSwitch<unsigned>(Name)
5897            .Case("zero", 0)
5898            .Cases("at", "AT", 1)
5899            .Case("a0", 4)
5900            .Case("a1", 5)
5901            .Case("a2", 6)
5902            .Case("a3", 7)
5903            .Case("v0", 2)
5904            .Case("v1", 3)
5905            .Case("s0", 16)
5906            .Case("s1", 17)
5907            .Case("s2", 18)
5908            .Case("s3", 19)
5909            .Case("s4", 20)
5910            .Case("s5", 21)
5911            .Case("s6", 22)
5912            .Case("s7", 23)
5913            .Case("k0", 26)
5914            .Case("k1", 27)
5915            .Case("gp", 28)
5916            .Case("sp", 29)
5917            .Case("fp", 30)
5918            .Case("s8", 30)
5919            .Case("ra", 31)
5920            .Case("t0", 8)
5921            .Case("t1", 9)
5922            .Case("t2", 10)
5923            .Case("t3", 11)
5924            .Case("t4", 12)
5925            .Case("t5", 13)
5926            .Case("t6", 14)
5927            .Case("t7", 15)
5928            .Case("t8", 24)
5929            .Case("t9", 25)
5930            .Default(-1);
5931 
5932   if (!(isABI_N32() || isABI_N64()))
5933     return CC;
5934 
5935   if (12 <= CC && CC <= 15) {
5936     // Name is one of t4-t7
5937     AsmToken RegTok = getLexer().peekTok();
5938     SMRange RegRange = RegTok.getLocRange();
5939 
5940     StringRef FixedName = StringSwitch<StringRef>(Name)
5941                               .Case("t4", "t0")
5942                               .Case("t5", "t1")
5943                               .Case("t6", "t2")
5944                               .Case("t7", "t3")
5945                               .Default("");
5946     assert(FixedName != "" &&  "Register name is not one of t4-t7.");
5947 
5948     printWarningWithFixIt("register names $t4-$t7 are only available in O32.",
5949                           "Did you mean $" + FixedName + "?", RegRange);
5950   }
5951 
5952   // Although SGI documentation just cuts out t0-t3 for n32/n64,
5953   // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
5954   // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
5955   if (8 <= CC && CC <= 11)
5956     CC += 4;
5957 
5958   if (CC == -1)
5959     CC = StringSwitch<unsigned>(Name)
5960              .Case("a4", 8)
5961              .Case("a5", 9)
5962              .Case("a6", 10)
5963              .Case("a7", 11)
5964              .Case("kt0", 26)
5965              .Case("kt1", 27)
5966              .Default(-1);
5967 
5968   return CC;
5969 }
5970 
5971 int MipsAsmParser::matchHWRegsRegisterName(StringRef Name) {
5972   int CC;
5973 
5974   CC = StringSwitch<unsigned>(Name)
5975             .Case("hwr_cpunum", 0)
5976             .Case("hwr_synci_step", 1)
5977             .Case("hwr_cc", 2)
5978             .Case("hwr_ccres", 3)
5979             .Case("hwr_ulr", 29)
5980             .Default(-1);
5981 
5982   return CC;
5983 }
5984 
5985 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
5986   if (Name[0] == 'f') {
5987     StringRef NumString = Name.substr(1);
5988     unsigned IntVal;
5989     if (NumString.getAsInteger(10, IntVal))
5990       return -1;     // This is not an integer.
5991     if (IntVal > 31) // Maximum index for fpu register.
5992       return -1;
5993     return IntVal;
5994   }
5995   return -1;
5996 }
5997 
5998 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
5999   if (Name.startswith("fcc")) {
6000     StringRef NumString = Name.substr(3);
6001     unsigned IntVal;
6002     if (NumString.getAsInteger(10, IntVal))
6003       return -1;    // This is not an integer.
6004     if (IntVal > 7) // There are only 8 fcc registers.
6005       return -1;
6006     return IntVal;
6007   }
6008   return -1;
6009 }
6010 
6011 int MipsAsmParser::matchACRegisterName(StringRef Name) {
6012   if (Name.startswith("ac")) {
6013     StringRef NumString = Name.substr(2);
6014     unsigned IntVal;
6015     if (NumString.getAsInteger(10, IntVal))
6016       return -1;    // This is not an integer.
6017     if (IntVal > 3) // There are only 3 acc registers.
6018       return -1;
6019     return IntVal;
6020   }
6021   return -1;
6022 }
6023 
6024 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
6025   unsigned IntVal;
6026 
6027   if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
6028     return -1;
6029 
6030   if (IntVal > 31)
6031     return -1;
6032 
6033   return IntVal;
6034 }
6035 
6036 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
6037   int CC;
6038 
6039   CC = StringSwitch<unsigned>(Name)
6040            .Case("msair", 0)
6041            .Case("msacsr", 1)
6042            .Case("msaaccess", 2)
6043            .Case("msasave", 3)
6044            .Case("msamodify", 4)
6045            .Case("msarequest", 5)
6046            .Case("msamap", 6)
6047            .Case("msaunmap", 7)
6048            .Default(-1);
6049 
6050   return CC;
6051 }
6052 
6053 bool MipsAsmParser::canUseATReg() {
6054   return AssemblerOptions.back()->getATRegIndex() != 0;
6055 }
6056 
6057 unsigned MipsAsmParser::getATReg(SMLoc Loc) {
6058   unsigned ATIndex = AssemblerOptions.back()->getATRegIndex();
6059   if (ATIndex == 0) {
6060     reportParseError(Loc,
6061                      "pseudo-instruction requires $at, which is not available");
6062     return 0;
6063   }
6064   unsigned AT = getReg(
6065       (isGP64bit()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, ATIndex);
6066   return AT;
6067 }
6068 
6069 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
6070   return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
6071 }
6072 
6073 bool MipsAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
6074   MCAsmParser &Parser = getParser();
6075   LLVM_DEBUG(dbgs() << "parseOperand\n");
6076 
6077   // Check if the current operand has a custom associated parser, if so, try to
6078   // custom parse the operand, or fallback to the general approach.
6079   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
6080   if (ResTy == MatchOperand_Success)
6081     return false;
6082   // If there wasn't a custom match, try the generic matcher below. Otherwise,
6083   // there was a match, but an error occurred, in which case, just return that
6084   // the operand parsing failed.
6085   if (ResTy == MatchOperand_ParseFail)
6086     return true;
6087 
6088   LLVM_DEBUG(dbgs() << ".. Generic Parser\n");
6089 
6090   switch (getLexer().getKind()) {
6091   case AsmToken::Dollar: {
6092     // Parse the register.
6093     SMLoc S = Parser.getTok().getLoc();
6094 
6095     // Almost all registers have been parsed by custom parsers. There is only
6096     // one exception to this. $zero (and it's alias $0) will reach this point
6097     // for div, divu, and similar instructions because it is not an operand
6098     // to the instruction definition but an explicit register. Special case
6099     // this situation for now.
6100     if (parseAnyRegister(Operands) != MatchOperand_NoMatch)
6101       return false;
6102 
6103     // Maybe it is a symbol reference.
6104     StringRef Identifier;
6105     if (Parser.parseIdentifier(Identifier))
6106       return true;
6107 
6108     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6109     MCSymbol *Sym = getContext().getOrCreateSymbol("$" + Identifier);
6110     // Otherwise create a symbol reference.
6111     const MCExpr *Res =
6112         MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
6113 
6114     Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this));
6115     return false;
6116   }
6117   default: {
6118     LLVM_DEBUG(dbgs() << ".. generic integer expression\n");
6119 
6120     const MCExpr *Expr;
6121     SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
6122     if (getParser().parseExpression(Expr))
6123       return true;
6124 
6125     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6126 
6127     Operands.push_back(MipsOperand::CreateImm(Expr, S, E, *this));
6128     return false;
6129   }
6130   } // switch(getLexer().getKind())
6131   return true;
6132 }
6133 
6134 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
6135   switch (Expr->getKind()) {
6136   case MCExpr::Constant:
6137     return true;
6138   case MCExpr::SymbolRef:
6139     return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
6140   case MCExpr::Binary: {
6141     const MCBinaryExpr *BE = cast<MCBinaryExpr>(Expr);
6142     if (!isEvaluated(BE->getLHS()))
6143       return false;
6144     return isEvaluated(BE->getRHS());
6145   }
6146   case MCExpr::Unary:
6147     return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
6148   case MCExpr::Target:
6149     return true;
6150   }
6151   return false;
6152 }
6153 
6154 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
6155                                   SMLoc &EndLoc) {
6156   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
6157   OperandMatchResultTy ResTy = parseAnyRegister(Operands);
6158   if (ResTy == MatchOperand_Success) {
6159     assert(Operands.size() == 1);
6160     MipsOperand &Operand = static_cast<MipsOperand &>(*Operands.front());
6161     StartLoc = Operand.getStartLoc();
6162     EndLoc = Operand.getEndLoc();
6163 
6164     // AFAIK, we only support numeric registers and named GPR's in CFI
6165     // directives.
6166     // Don't worry about eating tokens before failing. Using an unrecognised
6167     // register is a parse error.
6168     if (Operand.isGPRAsmReg()) {
6169       // Resolve to GPR32 or GPR64 appropriately.
6170       RegNo = isGP64bit() ? Operand.getGPR64Reg() : Operand.getGPR32Reg();
6171     }
6172 
6173     return (RegNo == (unsigned)-1);
6174   }
6175 
6176   assert(Operands.size() == 0);
6177   return (RegNo == (unsigned)-1);
6178 }
6179 
6180 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
6181   SMLoc S;
6182 
6183   if (isParenExpr)
6184     return getParser().parseParenExprOfDepth(0, Res, S);
6185   return getParser().parseExpression(Res);
6186 }
6187 
6188 OperandMatchResultTy
6189 MipsAsmParser::parseMemOperand(OperandVector &Operands) {
6190   MCAsmParser &Parser = getParser();
6191   LLVM_DEBUG(dbgs() << "parseMemOperand\n");
6192   const MCExpr *IdVal = nullptr;
6193   SMLoc S;
6194   bool isParenExpr = false;
6195   OperandMatchResultTy Res = MatchOperand_NoMatch;
6196   // First operand is the offset.
6197   S = Parser.getTok().getLoc();
6198 
6199   if (getLexer().getKind() == AsmToken::LParen) {
6200     Parser.Lex();
6201     isParenExpr = true;
6202   }
6203 
6204   if (getLexer().getKind() != AsmToken::Dollar) {
6205     if (parseMemOffset(IdVal, isParenExpr))
6206       return MatchOperand_ParseFail;
6207 
6208     const AsmToken &Tok = Parser.getTok(); // Get the next token.
6209     if (Tok.isNot(AsmToken::LParen)) {
6210       MipsOperand &Mnemonic = static_cast<MipsOperand &>(*Operands[0]);
6211       if (Mnemonic.getToken() == "la" || Mnemonic.getToken() == "dla") {
6212         SMLoc E =
6213             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6214         Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
6215         return MatchOperand_Success;
6216       }
6217       if (Tok.is(AsmToken::EndOfStatement)) {
6218         SMLoc E =
6219             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6220 
6221         // Zero register assumed, add a memory operand with ZERO as its base.
6222         // "Base" will be managed by k_Memory.
6223         auto Base = MipsOperand::createGPRReg(
6224             0, "0", getContext().getRegisterInfo(), S, E, *this);
6225         Operands.push_back(
6226             MipsOperand::CreateMem(std::move(Base), IdVal, S, E, *this));
6227         return MatchOperand_Success;
6228       }
6229       MCBinaryExpr::Opcode Opcode;
6230       // GAS and LLVM treat comparison operators different. GAS will generate -1
6231       // or 0, while LLVM will generate 0 or 1. Since a comparsion operator is
6232       // highly unlikely to be found in a memory offset expression, we don't
6233       // handle them.
6234       switch (Tok.getKind()) {
6235       case AsmToken::Plus:
6236         Opcode = MCBinaryExpr::Add;
6237         Parser.Lex();
6238         break;
6239       case AsmToken::Minus:
6240         Opcode = MCBinaryExpr::Sub;
6241         Parser.Lex();
6242         break;
6243       case AsmToken::Star:
6244         Opcode = MCBinaryExpr::Mul;
6245         Parser.Lex();
6246         break;
6247       case AsmToken::Pipe:
6248         Opcode = MCBinaryExpr::Or;
6249         Parser.Lex();
6250         break;
6251       case AsmToken::Amp:
6252         Opcode = MCBinaryExpr::And;
6253         Parser.Lex();
6254         break;
6255       case AsmToken::LessLess:
6256         Opcode = MCBinaryExpr::Shl;
6257         Parser.Lex();
6258         break;
6259       case AsmToken::GreaterGreater:
6260         Opcode = MCBinaryExpr::LShr;
6261         Parser.Lex();
6262         break;
6263       case AsmToken::Caret:
6264         Opcode = MCBinaryExpr::Xor;
6265         Parser.Lex();
6266         break;
6267       case AsmToken::Slash:
6268         Opcode = MCBinaryExpr::Div;
6269         Parser.Lex();
6270         break;
6271       case AsmToken::Percent:
6272         Opcode = MCBinaryExpr::Mod;
6273         Parser.Lex();
6274         break;
6275       default:
6276         Error(Parser.getTok().getLoc(), "'(' or expression expected");
6277         return MatchOperand_ParseFail;
6278       }
6279       const MCExpr * NextExpr;
6280       if (getParser().parseExpression(NextExpr))
6281         return MatchOperand_ParseFail;
6282       IdVal = MCBinaryExpr::create(Opcode, IdVal, NextExpr, getContext());
6283     }
6284 
6285     Parser.Lex(); // Eat the '(' token.
6286   }
6287 
6288   Res = parseAnyRegister(Operands);
6289   if (Res != MatchOperand_Success)
6290     return Res;
6291 
6292   if (Parser.getTok().isNot(AsmToken::RParen)) {
6293     Error(Parser.getTok().getLoc(), "')' expected");
6294     return MatchOperand_ParseFail;
6295   }
6296 
6297   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6298 
6299   Parser.Lex(); // Eat the ')' token.
6300 
6301   if (!IdVal)
6302     IdVal = MCConstantExpr::create(0, getContext());
6303 
6304   // Replace the register operand with the memory operand.
6305   std::unique_ptr<MipsOperand> op(
6306       static_cast<MipsOperand *>(Operands.back().release()));
6307   // Remove the register from the operands.
6308   // "op" will be managed by k_Memory.
6309   Operands.pop_back();
6310   // Add the memory operand.
6311   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
6312     int64_t Imm;
6313     if (IdVal->evaluateAsAbsolute(Imm))
6314       IdVal = MCConstantExpr::create(Imm, getContext());
6315     else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
6316       IdVal = MCBinaryExpr::create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
6317                                    getContext());
6318   }
6319 
6320   Operands.push_back(MipsOperand::CreateMem(std::move(op), IdVal, S, E, *this));
6321   return MatchOperand_Success;
6322 }
6323 
6324 bool MipsAsmParser::searchSymbolAlias(OperandVector &Operands) {
6325   MCAsmParser &Parser = getParser();
6326   MCSymbol *Sym = getContext().lookupSymbol(Parser.getTok().getIdentifier());
6327   if (!Sym)
6328     return false;
6329 
6330   SMLoc S = Parser.getTok().getLoc();
6331   if (Sym->isVariable()) {
6332     const MCExpr *Expr = Sym->getVariableValue();
6333     if (Expr->getKind() == MCExpr::SymbolRef) {
6334       const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
6335       StringRef DefSymbol = Ref->getSymbol().getName();
6336       if (DefSymbol.startswith("$")) {
6337         OperandMatchResultTy ResTy =
6338             matchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S);
6339         if (ResTy == MatchOperand_Success) {
6340           Parser.Lex();
6341           return true;
6342         }
6343         if (ResTy == MatchOperand_ParseFail)
6344           llvm_unreachable("Should never ParseFail");
6345       }
6346     }
6347   } else if (Sym->isUnset()) {
6348     // If symbol is unset, it might be created in the `parseSetAssignment`
6349     // routine as an alias for a numeric register name.
6350     // Lookup in the aliases list.
6351     auto Entry = RegisterSets.find(Sym->getName());
6352     if (Entry != RegisterSets.end()) {
6353       OperandMatchResultTy ResTy =
6354           matchAnyRegisterWithoutDollar(Operands, Entry->getValue(), S);
6355       if (ResTy == MatchOperand_Success) {
6356         Parser.Lex();
6357         return true;
6358       }
6359     }
6360   }
6361 
6362   return false;
6363 }
6364 
6365 OperandMatchResultTy
6366 MipsAsmParser::matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
6367                                                  StringRef Identifier,
6368                                                  SMLoc S) {
6369   int Index = matchCPURegisterName(Identifier);
6370   if (Index != -1) {
6371     Operands.push_back(MipsOperand::createGPRReg(
6372         Index, Identifier, getContext().getRegisterInfo(), S,
6373         getLexer().getLoc(), *this));
6374     return MatchOperand_Success;
6375   }
6376 
6377   Index = matchHWRegsRegisterName(Identifier);
6378   if (Index != -1) {
6379     Operands.push_back(MipsOperand::createHWRegsReg(
6380         Index, Identifier, getContext().getRegisterInfo(), S,
6381         getLexer().getLoc(), *this));
6382     return MatchOperand_Success;
6383   }
6384 
6385   Index = matchFPURegisterName(Identifier);
6386   if (Index != -1) {
6387     Operands.push_back(MipsOperand::createFGRReg(
6388         Index, Identifier, getContext().getRegisterInfo(), S,
6389         getLexer().getLoc(), *this));
6390     return MatchOperand_Success;
6391   }
6392 
6393   Index = matchFCCRegisterName(Identifier);
6394   if (Index != -1) {
6395     Operands.push_back(MipsOperand::createFCCReg(
6396         Index, Identifier, getContext().getRegisterInfo(), S,
6397         getLexer().getLoc(), *this));
6398     return MatchOperand_Success;
6399   }
6400 
6401   Index = matchACRegisterName(Identifier);
6402   if (Index != -1) {
6403     Operands.push_back(MipsOperand::createACCReg(
6404         Index, Identifier, getContext().getRegisterInfo(), S,
6405         getLexer().getLoc(), *this));
6406     return MatchOperand_Success;
6407   }
6408 
6409   Index = matchMSA128RegisterName(Identifier);
6410   if (Index != -1) {
6411     Operands.push_back(MipsOperand::createMSA128Reg(
6412         Index, Identifier, getContext().getRegisterInfo(), S,
6413         getLexer().getLoc(), *this));
6414     return MatchOperand_Success;
6415   }
6416 
6417   Index = matchMSA128CtrlRegisterName(Identifier);
6418   if (Index != -1) {
6419     Operands.push_back(MipsOperand::createMSACtrlReg(
6420         Index, Identifier, getContext().getRegisterInfo(), S,
6421         getLexer().getLoc(), *this));
6422     return MatchOperand_Success;
6423   }
6424 
6425   return MatchOperand_NoMatch;
6426 }
6427 
6428 OperandMatchResultTy
6429 MipsAsmParser::matchAnyRegisterWithoutDollar(OperandVector &Operands,
6430                                              const AsmToken &Token, SMLoc S) {
6431   if (Token.is(AsmToken::Identifier)) {
6432     LLVM_DEBUG(dbgs() << ".. identifier\n");
6433     StringRef Identifier = Token.getIdentifier();
6434     OperandMatchResultTy ResTy =
6435         matchAnyRegisterNameWithoutDollar(Operands, Identifier, S);
6436     return ResTy;
6437   } else if (Token.is(AsmToken::Integer)) {
6438     LLVM_DEBUG(dbgs() << ".. integer\n");
6439     int64_t RegNum = Token.getIntVal();
6440     if (RegNum < 0 || RegNum > 31) {
6441       // Show the error, but treat invalid register
6442       // number as a normal one to continue parsing
6443       // and catch other possible errors.
6444       Error(getLexer().getLoc(), "invalid register number");
6445     }
6446     Operands.push_back(MipsOperand::createNumericReg(
6447         RegNum, Token.getString(), getContext().getRegisterInfo(), S,
6448         Token.getLoc(), *this));
6449     return MatchOperand_Success;
6450   }
6451 
6452   LLVM_DEBUG(dbgs() << Token.getKind() << "\n");
6453 
6454   return MatchOperand_NoMatch;
6455 }
6456 
6457 OperandMatchResultTy
6458 MipsAsmParser::matchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S) {
6459   auto Token = getLexer().peekTok(false);
6460   return matchAnyRegisterWithoutDollar(Operands, Token, S);
6461 }
6462 
6463 OperandMatchResultTy
6464 MipsAsmParser::parseAnyRegister(OperandVector &Operands) {
6465   MCAsmParser &Parser = getParser();
6466   LLVM_DEBUG(dbgs() << "parseAnyRegister\n");
6467 
6468   auto Token = Parser.getTok();
6469 
6470   SMLoc S = Token.getLoc();
6471 
6472   if (Token.isNot(AsmToken::Dollar)) {
6473     LLVM_DEBUG(dbgs() << ".. !$ -> try sym aliasing\n");
6474     if (Token.is(AsmToken::Identifier)) {
6475       if (searchSymbolAlias(Operands))
6476         return MatchOperand_Success;
6477     }
6478     LLVM_DEBUG(dbgs() << ".. !symalias -> NoMatch\n");
6479     return MatchOperand_NoMatch;
6480   }
6481   LLVM_DEBUG(dbgs() << ".. $\n");
6482 
6483   OperandMatchResultTy ResTy = matchAnyRegisterWithoutDollar(Operands, S);
6484   if (ResTy == MatchOperand_Success) {
6485     Parser.Lex(); // $
6486     Parser.Lex(); // identifier
6487   }
6488   return ResTy;
6489 }
6490 
6491 OperandMatchResultTy
6492 MipsAsmParser::parseJumpTarget(OperandVector &Operands) {
6493   MCAsmParser &Parser = getParser();
6494   LLVM_DEBUG(dbgs() << "parseJumpTarget\n");
6495 
6496   SMLoc S = getLexer().getLoc();
6497 
6498   // Registers are a valid target and have priority over symbols.
6499   OperandMatchResultTy ResTy = parseAnyRegister(Operands);
6500   if (ResTy != MatchOperand_NoMatch)
6501     return ResTy;
6502 
6503   // Integers and expressions are acceptable
6504   const MCExpr *Expr = nullptr;
6505   if (Parser.parseExpression(Expr)) {
6506     // We have no way of knowing if a symbol was consumed so we must ParseFail
6507     return MatchOperand_ParseFail;
6508   }
6509   Operands.push_back(
6510       MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this));
6511   return MatchOperand_Success;
6512 }
6513 
6514 OperandMatchResultTy
6515 MipsAsmParser::parseInvNum(OperandVector &Operands) {
6516   MCAsmParser &Parser = getParser();
6517   const MCExpr *IdVal;
6518   // If the first token is '$' we may have register operand. We have to reject
6519   // cases where it is not a register. Complicating the matter is that
6520   // register names are not reserved across all ABIs.
6521   // Peek past the dollar to see if it's a register name for this ABI.
6522   SMLoc S = Parser.getTok().getLoc();
6523   if (Parser.getTok().is(AsmToken::Dollar)) {
6524     return matchCPURegisterName(Parser.getLexer().peekTok().getString()) == -1
6525                ? MatchOperand_ParseFail
6526                : MatchOperand_NoMatch;
6527   }
6528   if (getParser().parseExpression(IdVal))
6529     return MatchOperand_ParseFail;
6530   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
6531   if (!MCE)
6532     return MatchOperand_NoMatch;
6533   int64_t Val = MCE->getValue();
6534   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6535   Operands.push_back(MipsOperand::CreateImm(
6536       MCConstantExpr::create(0 - Val, getContext()), S, E, *this));
6537   return MatchOperand_Success;
6538 }
6539 
6540 OperandMatchResultTy
6541 MipsAsmParser::parseRegisterList(OperandVector &Operands) {
6542   MCAsmParser &Parser = getParser();
6543   SmallVector<unsigned, 10> Regs;
6544   unsigned RegNo;
6545   unsigned PrevReg = Mips::NoRegister;
6546   bool RegRange = false;
6547   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands;
6548 
6549   if (Parser.getTok().isNot(AsmToken::Dollar))
6550     return MatchOperand_ParseFail;
6551 
6552   SMLoc S = Parser.getTok().getLoc();
6553   while (parseAnyRegister(TmpOperands) == MatchOperand_Success) {
6554     SMLoc E = getLexer().getLoc();
6555     MipsOperand &Reg = static_cast<MipsOperand &>(*TmpOperands.back());
6556     RegNo = isGP64bit() ? Reg.getGPR64Reg() : Reg.getGPR32Reg();
6557     if (RegRange) {
6558       // Remove last register operand because registers from register range
6559       // should be inserted first.
6560       if ((isGP64bit() && RegNo == Mips::RA_64) ||
6561           (!isGP64bit() && RegNo == Mips::RA)) {
6562         Regs.push_back(RegNo);
6563       } else {
6564         unsigned TmpReg = PrevReg + 1;
6565         while (TmpReg <= RegNo) {
6566           if ((((TmpReg < Mips::S0) || (TmpReg > Mips::S7)) && !isGP64bit()) ||
6567               (((TmpReg < Mips::S0_64) || (TmpReg > Mips::S7_64)) &&
6568                isGP64bit())) {
6569             Error(E, "invalid register operand");
6570             return MatchOperand_ParseFail;
6571           }
6572 
6573           PrevReg = TmpReg;
6574           Regs.push_back(TmpReg++);
6575         }
6576       }
6577 
6578       RegRange = false;
6579     } else {
6580       if ((PrevReg == Mips::NoRegister) &&
6581           ((isGP64bit() && (RegNo != Mips::S0_64) && (RegNo != Mips::RA_64)) ||
6582           (!isGP64bit() && (RegNo != Mips::S0) && (RegNo != Mips::RA)))) {
6583         Error(E, "$16 or $31 expected");
6584         return MatchOperand_ParseFail;
6585       } else if (!(((RegNo == Mips::FP || RegNo == Mips::RA ||
6586                     (RegNo >= Mips::S0 && RegNo <= Mips::S7)) &&
6587                     !isGP64bit()) ||
6588                    ((RegNo == Mips::FP_64 || RegNo == Mips::RA_64 ||
6589                     (RegNo >= Mips::S0_64 && RegNo <= Mips::S7_64)) &&
6590                     isGP64bit()))) {
6591         Error(E, "invalid register operand");
6592         return MatchOperand_ParseFail;
6593       } else if ((PrevReg != Mips::NoRegister) && (RegNo != PrevReg + 1) &&
6594                  ((RegNo != Mips::FP && RegNo != Mips::RA && !isGP64bit()) ||
6595                   (RegNo != Mips::FP_64 && RegNo != Mips::RA_64 &&
6596                    isGP64bit()))) {
6597         Error(E, "consecutive register numbers expected");
6598         return MatchOperand_ParseFail;
6599       }
6600 
6601       Regs.push_back(RegNo);
6602     }
6603 
6604     if (Parser.getTok().is(AsmToken::Minus))
6605       RegRange = true;
6606 
6607     if (!Parser.getTok().isNot(AsmToken::Minus) &&
6608         !Parser.getTok().isNot(AsmToken::Comma)) {
6609       Error(E, "',' or '-' expected");
6610       return MatchOperand_ParseFail;
6611     }
6612 
6613     Lex(); // Consume comma or minus
6614     if (Parser.getTok().isNot(AsmToken::Dollar))
6615       break;
6616 
6617     PrevReg = RegNo;
6618   }
6619 
6620   SMLoc E = Parser.getTok().getLoc();
6621   Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this));
6622   parseMemOperand(Operands);
6623   return MatchOperand_Success;
6624 }
6625 
6626 /// Sometimes (i.e. load/stores) the operand may be followed immediately by
6627 /// either this.
6628 /// ::= '(', register, ')'
6629 /// handle it before we iterate so we don't get tripped up by the lack of
6630 /// a comma.
6631 bool MipsAsmParser::parseParenSuffix(StringRef Name, OperandVector &Operands) {
6632   MCAsmParser &Parser = getParser();
6633   if (getLexer().is(AsmToken::LParen)) {
6634     Operands.push_back(
6635         MipsOperand::CreateToken("(", getLexer().getLoc(), *this));
6636     Parser.Lex();
6637     if (parseOperand(Operands, Name)) {
6638       SMLoc Loc = getLexer().getLoc();
6639       return Error(Loc, "unexpected token in argument list");
6640     }
6641     if (Parser.getTok().isNot(AsmToken::RParen)) {
6642       SMLoc Loc = getLexer().getLoc();
6643       return Error(Loc, "unexpected token, expected ')'");
6644     }
6645     Operands.push_back(
6646         MipsOperand::CreateToken(")", getLexer().getLoc(), *this));
6647     Parser.Lex();
6648   }
6649   return false;
6650 }
6651 
6652 /// Sometimes (i.e. in MSA) the operand may be followed immediately by
6653 /// either one of these.
6654 /// ::= '[', register, ']'
6655 /// ::= '[', integer, ']'
6656 /// handle it before we iterate so we don't get tripped up by the lack of
6657 /// a comma.
6658 bool MipsAsmParser::parseBracketSuffix(StringRef Name,
6659                                        OperandVector &Operands) {
6660   MCAsmParser &Parser = getParser();
6661   if (getLexer().is(AsmToken::LBrac)) {
6662     Operands.push_back(
6663         MipsOperand::CreateToken("[", getLexer().getLoc(), *this));
6664     Parser.Lex();
6665     if (parseOperand(Operands, Name)) {
6666       SMLoc Loc = getLexer().getLoc();
6667       return Error(Loc, "unexpected token in argument list");
6668     }
6669     if (Parser.getTok().isNot(AsmToken::RBrac)) {
6670       SMLoc Loc = getLexer().getLoc();
6671       return Error(Loc, "unexpected token, expected ']'");
6672     }
6673     Operands.push_back(
6674         MipsOperand::CreateToken("]", getLexer().getLoc(), *this));
6675     Parser.Lex();
6676   }
6677   return false;
6678 }
6679 
6680 static std::string MipsMnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,
6681                                           unsigned VariantID = 0);
6682 
6683 bool MipsAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
6684                                      SMLoc NameLoc, OperandVector &Operands) {
6685   MCAsmParser &Parser = getParser();
6686   LLVM_DEBUG(dbgs() << "ParseInstruction\n");
6687 
6688   // We have reached first instruction, module directive are now forbidden.
6689   getTargetStreamer().forbidModuleDirective();
6690 
6691   // Check if we have valid mnemonic
6692   if (!mnemonicIsValid(Name, 0)) {
6693     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
6694     std::string Suggestion = MipsMnemonicSpellCheck(Name, FBS);
6695     return Error(NameLoc, "unknown instruction" + Suggestion);
6696   }
6697   // First operand in MCInst is instruction mnemonic.
6698   Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this));
6699 
6700   // Read the remaining operands.
6701   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6702     // Read the first operand.
6703     if (parseOperand(Operands, Name)) {
6704       SMLoc Loc = getLexer().getLoc();
6705       return Error(Loc, "unexpected token in argument list");
6706     }
6707     if (getLexer().is(AsmToken::LBrac) && parseBracketSuffix(Name, Operands))
6708       return true;
6709     // AFAIK, parenthesis suffixes are never on the first operand
6710 
6711     while (getLexer().is(AsmToken::Comma)) {
6712       Parser.Lex(); // Eat the comma.
6713       // Parse and remember the operand.
6714       if (parseOperand(Operands, Name)) {
6715         SMLoc Loc = getLexer().getLoc();
6716         return Error(Loc, "unexpected token in argument list");
6717       }
6718       // Parse bracket and parenthesis suffixes before we iterate
6719       if (getLexer().is(AsmToken::LBrac)) {
6720         if (parseBracketSuffix(Name, Operands))
6721           return true;
6722       } else if (getLexer().is(AsmToken::LParen) &&
6723                  parseParenSuffix(Name, Operands))
6724         return true;
6725     }
6726   }
6727   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6728     SMLoc Loc = getLexer().getLoc();
6729     return Error(Loc, "unexpected token in argument list");
6730   }
6731   Parser.Lex(); // Consume the EndOfStatement.
6732   return false;
6733 }
6734 
6735 // FIXME: Given that these have the same name, these should both be
6736 // consistent on affecting the Parser.
6737 bool MipsAsmParser::reportParseError(Twine ErrorMsg) {
6738   SMLoc Loc = getLexer().getLoc();
6739   return Error(Loc, ErrorMsg);
6740 }
6741 
6742 bool MipsAsmParser::reportParseError(SMLoc Loc, Twine ErrorMsg) {
6743   return Error(Loc, ErrorMsg);
6744 }
6745 
6746 bool MipsAsmParser::parseSetNoAtDirective() {
6747   MCAsmParser &Parser = getParser();
6748   // Line should look like: ".set noat".
6749 
6750   // Set the $at register to $0.
6751   AssemblerOptions.back()->setATRegIndex(0);
6752 
6753   Parser.Lex(); // Eat "noat".
6754 
6755   // If this is not the end of the statement, report an error.
6756   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6757     reportParseError("unexpected token, expected end of statement");
6758     return false;
6759   }
6760 
6761   getTargetStreamer().emitDirectiveSetNoAt();
6762   Parser.Lex(); // Consume the EndOfStatement.
6763   return false;
6764 }
6765 
6766 bool MipsAsmParser::parseSetAtDirective() {
6767   // Line can be: ".set at", which sets $at to $1
6768   //          or  ".set at=$reg", which sets $at to $reg.
6769   MCAsmParser &Parser = getParser();
6770   Parser.Lex(); // Eat "at".
6771 
6772   if (getLexer().is(AsmToken::EndOfStatement)) {
6773     // No register was specified, so we set $at to $1.
6774     AssemblerOptions.back()->setATRegIndex(1);
6775 
6776     getTargetStreamer().emitDirectiveSetAt();
6777     Parser.Lex(); // Consume the EndOfStatement.
6778     return false;
6779   }
6780 
6781   if (getLexer().isNot(AsmToken::Equal)) {
6782     reportParseError("unexpected token, expected equals sign");
6783     return false;
6784   }
6785   Parser.Lex(); // Eat "=".
6786 
6787   if (getLexer().isNot(AsmToken::Dollar)) {
6788     if (getLexer().is(AsmToken::EndOfStatement)) {
6789       reportParseError("no register specified");
6790       return false;
6791     } else {
6792       reportParseError("unexpected token, expected dollar sign '$'");
6793       return false;
6794     }
6795   }
6796   Parser.Lex(); // Eat "$".
6797 
6798   // Find out what "reg" is.
6799   unsigned AtRegNo;
6800   const AsmToken &Reg = Parser.getTok();
6801   if (Reg.is(AsmToken::Identifier)) {
6802     AtRegNo = matchCPURegisterName(Reg.getIdentifier());
6803   } else if (Reg.is(AsmToken::Integer)) {
6804     AtRegNo = Reg.getIntVal();
6805   } else {
6806     reportParseError("unexpected token, expected identifier or integer");
6807     return false;
6808   }
6809 
6810   // Check if $reg is a valid register. If it is, set $at to $reg.
6811   if (!AssemblerOptions.back()->setATRegIndex(AtRegNo)) {
6812     reportParseError("invalid register");
6813     return false;
6814   }
6815   Parser.Lex(); // Eat "reg".
6816 
6817   // If this is not the end of the statement, report an error.
6818   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6819     reportParseError("unexpected token, expected end of statement");
6820     return false;
6821   }
6822 
6823   getTargetStreamer().emitDirectiveSetAtWithArg(AtRegNo);
6824 
6825   Parser.Lex(); // Consume the EndOfStatement.
6826   return false;
6827 }
6828 
6829 bool MipsAsmParser::parseSetReorderDirective() {
6830   MCAsmParser &Parser = getParser();
6831   Parser.Lex();
6832   // If this is not the end of the statement, report an error.
6833   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6834     reportParseError("unexpected token, expected end of statement");
6835     return false;
6836   }
6837   AssemblerOptions.back()->setReorder();
6838   getTargetStreamer().emitDirectiveSetReorder();
6839   Parser.Lex(); // Consume the EndOfStatement.
6840   return false;
6841 }
6842 
6843 bool MipsAsmParser::parseSetNoReorderDirective() {
6844   MCAsmParser &Parser = getParser();
6845   Parser.Lex();
6846   // If this is not the end of the statement, report an error.
6847   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6848     reportParseError("unexpected token, expected end of statement");
6849     return false;
6850   }
6851   AssemblerOptions.back()->setNoReorder();
6852   getTargetStreamer().emitDirectiveSetNoReorder();
6853   Parser.Lex(); // Consume the EndOfStatement.
6854   return false;
6855 }
6856 
6857 bool MipsAsmParser::parseSetMacroDirective() {
6858   MCAsmParser &Parser = getParser();
6859   Parser.Lex();
6860   // If this is not the end of the statement, report an error.
6861   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6862     reportParseError("unexpected token, expected end of statement");
6863     return false;
6864   }
6865   AssemblerOptions.back()->setMacro();
6866   getTargetStreamer().emitDirectiveSetMacro();
6867   Parser.Lex(); // Consume the EndOfStatement.
6868   return false;
6869 }
6870 
6871 bool MipsAsmParser::parseSetNoMacroDirective() {
6872   MCAsmParser &Parser = getParser();
6873   Parser.Lex();
6874   // If this is not the end of the statement, report an error.
6875   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6876     reportParseError("unexpected token, expected end of statement");
6877     return false;
6878   }
6879   if (AssemblerOptions.back()->isReorder()) {
6880     reportParseError("`noreorder' must be set before `nomacro'");
6881     return false;
6882   }
6883   AssemblerOptions.back()->setNoMacro();
6884   getTargetStreamer().emitDirectiveSetNoMacro();
6885   Parser.Lex(); // Consume the EndOfStatement.
6886   return false;
6887 }
6888 
6889 bool MipsAsmParser::parseSetMsaDirective() {
6890   MCAsmParser &Parser = getParser();
6891   Parser.Lex();
6892 
6893   // If this is not the end of the statement, report an error.
6894   if (getLexer().isNot(AsmToken::EndOfStatement))
6895     return reportParseError("unexpected token, expected end of statement");
6896 
6897   setFeatureBits(Mips::FeatureMSA, "msa");
6898   getTargetStreamer().emitDirectiveSetMsa();
6899   return false;
6900 }
6901 
6902 bool MipsAsmParser::parseSetNoMsaDirective() {
6903   MCAsmParser &Parser = getParser();
6904   Parser.Lex();
6905 
6906   // If this is not the end of the statement, report an error.
6907   if (getLexer().isNot(AsmToken::EndOfStatement))
6908     return reportParseError("unexpected token, expected end of statement");
6909 
6910   clearFeatureBits(Mips::FeatureMSA, "msa");
6911   getTargetStreamer().emitDirectiveSetNoMsa();
6912   return false;
6913 }
6914 
6915 bool MipsAsmParser::parseSetNoDspDirective() {
6916   MCAsmParser &Parser = getParser();
6917   Parser.Lex(); // Eat "nodsp".
6918 
6919   // If this is not the end of the statement, report an error.
6920   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6921     reportParseError("unexpected token, expected end of statement");
6922     return false;
6923   }
6924 
6925   clearFeatureBits(Mips::FeatureDSP, "dsp");
6926   getTargetStreamer().emitDirectiveSetNoDsp();
6927   return false;
6928 }
6929 
6930 bool MipsAsmParser::parseSetMips16Directive() {
6931   MCAsmParser &Parser = getParser();
6932   Parser.Lex(); // Eat "mips16".
6933 
6934   // If this is not the end of the statement, report an error.
6935   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6936     reportParseError("unexpected token, expected end of statement");
6937     return false;
6938   }
6939 
6940   setFeatureBits(Mips::FeatureMips16, "mips16");
6941   getTargetStreamer().emitDirectiveSetMips16();
6942   Parser.Lex(); // Consume the EndOfStatement.
6943   return false;
6944 }
6945 
6946 bool MipsAsmParser::parseSetNoMips16Directive() {
6947   MCAsmParser &Parser = getParser();
6948   Parser.Lex(); // Eat "nomips16".
6949 
6950   // If this is not the end of the statement, report an error.
6951   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6952     reportParseError("unexpected token, expected end of statement");
6953     return false;
6954   }
6955 
6956   clearFeatureBits(Mips::FeatureMips16, "mips16");
6957   getTargetStreamer().emitDirectiveSetNoMips16();
6958   Parser.Lex(); // Consume the EndOfStatement.
6959   return false;
6960 }
6961 
6962 bool MipsAsmParser::parseSetFpDirective() {
6963   MCAsmParser &Parser = getParser();
6964   MipsABIFlagsSection::FpABIKind FpAbiVal;
6965   // Line can be: .set fp=32
6966   //              .set fp=xx
6967   //              .set fp=64
6968   Parser.Lex(); // Eat fp token
6969   AsmToken Tok = Parser.getTok();
6970   if (Tok.isNot(AsmToken::Equal)) {
6971     reportParseError("unexpected token, expected equals sign '='");
6972     return false;
6973   }
6974   Parser.Lex(); // Eat '=' token.
6975   Tok = Parser.getTok();
6976 
6977   if (!parseFpABIValue(FpAbiVal, ".set"))
6978     return false;
6979 
6980   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6981     reportParseError("unexpected token, expected end of statement");
6982     return false;
6983   }
6984   getTargetStreamer().emitDirectiveSetFp(FpAbiVal);
6985   Parser.Lex(); // Consume the EndOfStatement.
6986   return false;
6987 }
6988 
6989 bool MipsAsmParser::parseSetOddSPRegDirective() {
6990   MCAsmParser &Parser = getParser();
6991 
6992   Parser.Lex(); // Eat "oddspreg".
6993   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6994     reportParseError("unexpected token, expected end of statement");
6995     return false;
6996   }
6997 
6998   clearFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
6999   getTargetStreamer().emitDirectiveSetOddSPReg();
7000   return false;
7001 }
7002 
7003 bool MipsAsmParser::parseSetNoOddSPRegDirective() {
7004   MCAsmParser &Parser = getParser();
7005 
7006   Parser.Lex(); // Eat "nooddspreg".
7007   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7008     reportParseError("unexpected token, expected end of statement");
7009     return false;
7010   }
7011 
7012   setFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
7013   getTargetStreamer().emitDirectiveSetNoOddSPReg();
7014   return false;
7015 }
7016 
7017 bool MipsAsmParser::parseSetMtDirective() {
7018   MCAsmParser &Parser = getParser();
7019   Parser.Lex(); // Eat "mt".
7020 
7021   // If this is not the end of the statement, report an error.
7022   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7023     reportParseError("unexpected token, expected end of statement");
7024     return false;
7025   }
7026 
7027   setFeatureBits(Mips::FeatureMT, "mt");
7028   getTargetStreamer().emitDirectiveSetMt();
7029   Parser.Lex(); // Consume the EndOfStatement.
7030   return false;
7031 }
7032 
7033 bool MipsAsmParser::parseSetNoMtDirective() {
7034   MCAsmParser &Parser = getParser();
7035   Parser.Lex(); // Eat "nomt".
7036 
7037   // If this is not the end of the statement, report an error.
7038   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7039     reportParseError("unexpected token, expected end of statement");
7040     return false;
7041   }
7042 
7043   clearFeatureBits(Mips::FeatureMT, "mt");
7044 
7045   getTargetStreamer().emitDirectiveSetNoMt();
7046   Parser.Lex(); // Consume the EndOfStatement.
7047   return false;
7048 }
7049 
7050 bool MipsAsmParser::parseSetNoCRCDirective() {
7051   MCAsmParser &Parser = getParser();
7052   Parser.Lex(); // Eat "nocrc".
7053 
7054   // If this is not the end of the statement, report an error.
7055   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7056     reportParseError("unexpected token, expected end of statement");
7057     return false;
7058   }
7059 
7060   clearFeatureBits(Mips::FeatureCRC, "crc");
7061 
7062   getTargetStreamer().emitDirectiveSetNoCRC();
7063   Parser.Lex(); // Consume the EndOfStatement.
7064   return false;
7065 }
7066 
7067 bool MipsAsmParser::parseSetNoVirtDirective() {
7068   MCAsmParser &Parser = getParser();
7069   Parser.Lex(); // Eat "novirt".
7070 
7071   // If this is not the end of the statement, report an error.
7072   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7073     reportParseError("unexpected token, expected end of statement");
7074     return false;
7075   }
7076 
7077   clearFeatureBits(Mips::FeatureVirt, "virt");
7078 
7079   getTargetStreamer().emitDirectiveSetNoVirt();
7080   Parser.Lex(); // Consume the EndOfStatement.
7081   return false;
7082 }
7083 
7084 bool MipsAsmParser::parseSetNoGINVDirective() {
7085   MCAsmParser &Parser = getParser();
7086   Parser.Lex(); // Eat "noginv".
7087 
7088   // If this is not the end of the statement, report an error.
7089   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7090     reportParseError("unexpected token, expected end of statement");
7091     return false;
7092   }
7093 
7094   clearFeatureBits(Mips::FeatureGINV, "ginv");
7095 
7096   getTargetStreamer().emitDirectiveSetNoGINV();
7097   Parser.Lex(); // Consume the EndOfStatement.
7098   return false;
7099 }
7100 
7101 bool MipsAsmParser::parseSetPopDirective() {
7102   MCAsmParser &Parser = getParser();
7103   SMLoc Loc = getLexer().getLoc();
7104 
7105   Parser.Lex();
7106   if (getLexer().isNot(AsmToken::EndOfStatement))
7107     return reportParseError("unexpected token, expected end of statement");
7108 
7109   // Always keep an element on the options "stack" to prevent the user
7110   // from changing the initial options. This is how we remember them.
7111   if (AssemblerOptions.size() == 2)
7112     return reportParseError(Loc, ".set pop with no .set push");
7113 
7114   MCSubtargetInfo &STI = copySTI();
7115   AssemblerOptions.pop_back();
7116   setAvailableFeatures(
7117       ComputeAvailableFeatures(AssemblerOptions.back()->getFeatures()));
7118   STI.setFeatureBits(AssemblerOptions.back()->getFeatures());
7119 
7120   getTargetStreamer().emitDirectiveSetPop();
7121   return false;
7122 }
7123 
7124 bool MipsAsmParser::parseSetPushDirective() {
7125   MCAsmParser &Parser = getParser();
7126   Parser.Lex();
7127   if (getLexer().isNot(AsmToken::EndOfStatement))
7128     return reportParseError("unexpected token, expected end of statement");
7129 
7130   // Create a copy of the current assembler options environment and push it.
7131   AssemblerOptions.push_back(
7132         std::make_unique<MipsAssemblerOptions>(AssemblerOptions.back().get()));
7133 
7134   getTargetStreamer().emitDirectiveSetPush();
7135   return false;
7136 }
7137 
7138 bool MipsAsmParser::parseSetSoftFloatDirective() {
7139   MCAsmParser &Parser = getParser();
7140   Parser.Lex();
7141   if (getLexer().isNot(AsmToken::EndOfStatement))
7142     return reportParseError("unexpected token, expected end of statement");
7143 
7144   setFeatureBits(Mips::FeatureSoftFloat, "soft-float");
7145   getTargetStreamer().emitDirectiveSetSoftFloat();
7146   return false;
7147 }
7148 
7149 bool MipsAsmParser::parseSetHardFloatDirective() {
7150   MCAsmParser &Parser = getParser();
7151   Parser.Lex();
7152   if (getLexer().isNot(AsmToken::EndOfStatement))
7153     return reportParseError("unexpected token, expected end of statement");
7154 
7155   clearFeatureBits(Mips::FeatureSoftFloat, "soft-float");
7156   getTargetStreamer().emitDirectiveSetHardFloat();
7157   return false;
7158 }
7159 
7160 bool MipsAsmParser::parseSetAssignment() {
7161   StringRef Name;
7162   MCAsmParser &Parser = getParser();
7163 
7164   if (Parser.parseIdentifier(Name))
7165     return reportParseError("expected identifier after .set");
7166 
7167   if (getLexer().isNot(AsmToken::Comma))
7168     return reportParseError("unexpected token, expected comma");
7169   Lex(); // Eat comma
7170 
7171   if (getLexer().is(AsmToken::Dollar) &&
7172       getLexer().peekTok().is(AsmToken::Integer)) {
7173     // Parse assignment of a numeric register:
7174     //   .set r1,$1
7175     Parser.Lex(); // Eat $.
7176     RegisterSets[Name] = Parser.getTok();
7177     Parser.Lex(); // Eat identifier.
7178     getContext().getOrCreateSymbol(Name);
7179     return false;
7180   }
7181 
7182   MCSymbol *Sym;
7183   const MCExpr *Value;
7184   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
7185                                                Parser, Sym, Value))
7186     return true;
7187   Sym->setVariableValue(Value);
7188 
7189   return false;
7190 }
7191 
7192 bool MipsAsmParser::parseSetMips0Directive() {
7193   MCAsmParser &Parser = getParser();
7194   Parser.Lex();
7195   if (getLexer().isNot(AsmToken::EndOfStatement))
7196     return reportParseError("unexpected token, expected end of statement");
7197 
7198   // Reset assembler options to their initial values.
7199   MCSubtargetInfo &STI = copySTI();
7200   setAvailableFeatures(
7201       ComputeAvailableFeatures(AssemblerOptions.front()->getFeatures()));
7202   STI.setFeatureBits(AssemblerOptions.front()->getFeatures());
7203   AssemblerOptions.back()->setFeatures(AssemblerOptions.front()->getFeatures());
7204 
7205   getTargetStreamer().emitDirectiveSetMips0();
7206   return false;
7207 }
7208 
7209 bool MipsAsmParser::parseSetArchDirective() {
7210   MCAsmParser &Parser = getParser();
7211   Parser.Lex();
7212   if (getLexer().isNot(AsmToken::Equal))
7213     return reportParseError("unexpected token, expected equals sign");
7214 
7215   Parser.Lex();
7216   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
7217   if (Arch.empty())
7218     return reportParseError("expected arch identifier");
7219 
7220   StringRef ArchFeatureName =
7221       StringSwitch<StringRef>(Arch)
7222           .Case("mips1", "mips1")
7223           .Case("mips2", "mips2")
7224           .Case("mips3", "mips3")
7225           .Case("mips4", "mips4")
7226           .Case("mips5", "mips5")
7227           .Case("mips32", "mips32")
7228           .Case("mips32r2", "mips32r2")
7229           .Case("mips32r3", "mips32r3")
7230           .Case("mips32r5", "mips32r5")
7231           .Case("mips32r6", "mips32r6")
7232           .Case("mips64", "mips64")
7233           .Case("mips64r2", "mips64r2")
7234           .Case("mips64r3", "mips64r3")
7235           .Case("mips64r5", "mips64r5")
7236           .Case("mips64r6", "mips64r6")
7237           .Case("octeon", "cnmips")
7238           .Case("octeon+", "cnmipsp")
7239           .Case("r4000", "mips3") // This is an implementation of Mips3.
7240           .Default("");
7241 
7242   if (ArchFeatureName.empty())
7243     return reportParseError("unsupported architecture");
7244 
7245   if (ArchFeatureName == "mips64r6" && inMicroMipsMode())
7246     return reportParseError("mips64r6 does not support microMIPS");
7247 
7248   selectArch(ArchFeatureName);
7249   getTargetStreamer().emitDirectiveSetArch(Arch);
7250   return false;
7251 }
7252 
7253 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
7254   MCAsmParser &Parser = getParser();
7255   Parser.Lex();
7256   if (getLexer().isNot(AsmToken::EndOfStatement))
7257     return reportParseError("unexpected token, expected end of statement");
7258 
7259   switch (Feature) {
7260   default:
7261     llvm_unreachable("Unimplemented feature");
7262   case Mips::FeatureDSP:
7263     setFeatureBits(Mips::FeatureDSP, "dsp");
7264     getTargetStreamer().emitDirectiveSetDsp();
7265     break;
7266   case Mips::FeatureDSPR2:
7267     setFeatureBits(Mips::FeatureDSPR2, "dspr2");
7268     getTargetStreamer().emitDirectiveSetDspr2();
7269     break;
7270   case Mips::FeatureMicroMips:
7271     setFeatureBits(Mips::FeatureMicroMips, "micromips");
7272     getTargetStreamer().emitDirectiveSetMicroMips();
7273     break;
7274   case Mips::FeatureMips1:
7275     selectArch("mips1");
7276     getTargetStreamer().emitDirectiveSetMips1();
7277     break;
7278   case Mips::FeatureMips2:
7279     selectArch("mips2");
7280     getTargetStreamer().emitDirectiveSetMips2();
7281     break;
7282   case Mips::FeatureMips3:
7283     selectArch("mips3");
7284     getTargetStreamer().emitDirectiveSetMips3();
7285     break;
7286   case Mips::FeatureMips4:
7287     selectArch("mips4");
7288     getTargetStreamer().emitDirectiveSetMips4();
7289     break;
7290   case Mips::FeatureMips5:
7291     selectArch("mips5");
7292     getTargetStreamer().emitDirectiveSetMips5();
7293     break;
7294   case Mips::FeatureMips32:
7295     selectArch("mips32");
7296     getTargetStreamer().emitDirectiveSetMips32();
7297     break;
7298   case Mips::FeatureMips32r2:
7299     selectArch("mips32r2");
7300     getTargetStreamer().emitDirectiveSetMips32R2();
7301     break;
7302   case Mips::FeatureMips32r3:
7303     selectArch("mips32r3");
7304     getTargetStreamer().emitDirectiveSetMips32R3();
7305     break;
7306   case Mips::FeatureMips32r5:
7307     selectArch("mips32r5");
7308     getTargetStreamer().emitDirectiveSetMips32R5();
7309     break;
7310   case Mips::FeatureMips32r6:
7311     selectArch("mips32r6");
7312     getTargetStreamer().emitDirectiveSetMips32R6();
7313     break;
7314   case Mips::FeatureMips64:
7315     selectArch("mips64");
7316     getTargetStreamer().emitDirectiveSetMips64();
7317     break;
7318   case Mips::FeatureMips64r2:
7319     selectArch("mips64r2");
7320     getTargetStreamer().emitDirectiveSetMips64R2();
7321     break;
7322   case Mips::FeatureMips64r3:
7323     selectArch("mips64r3");
7324     getTargetStreamer().emitDirectiveSetMips64R3();
7325     break;
7326   case Mips::FeatureMips64r5:
7327     selectArch("mips64r5");
7328     getTargetStreamer().emitDirectiveSetMips64R5();
7329     break;
7330   case Mips::FeatureMips64r6:
7331     selectArch("mips64r6");
7332     getTargetStreamer().emitDirectiveSetMips64R6();
7333     break;
7334   case Mips::FeatureCRC:
7335     setFeatureBits(Mips::FeatureCRC, "crc");
7336     getTargetStreamer().emitDirectiveSetCRC();
7337     break;
7338   case Mips::FeatureVirt:
7339     setFeatureBits(Mips::FeatureVirt, "virt");
7340     getTargetStreamer().emitDirectiveSetVirt();
7341     break;
7342   case Mips::FeatureGINV:
7343     setFeatureBits(Mips::FeatureGINV, "ginv");
7344     getTargetStreamer().emitDirectiveSetGINV();
7345     break;
7346   }
7347   return false;
7348 }
7349 
7350 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
7351   MCAsmParser &Parser = getParser();
7352   if (getLexer().isNot(AsmToken::Comma)) {
7353     SMLoc Loc = getLexer().getLoc();
7354     return Error(Loc, ErrorStr);
7355   }
7356 
7357   Parser.Lex(); // Eat the comma.
7358   return true;
7359 }
7360 
7361 // Used to determine if .cpload, .cprestore, and .cpsetup have any effect.
7362 // In this class, it is only used for .cprestore.
7363 // FIXME: Only keep track of IsPicEnabled in one place, instead of in both
7364 // MipsTargetELFStreamer and MipsAsmParser.
7365 bool MipsAsmParser::isPicAndNotNxxAbi() {
7366   return inPicMode() && !(isABI_N32() || isABI_N64());
7367 }
7368 
7369 bool MipsAsmParser::parseDirectiveCpLoad(SMLoc Loc) {
7370   if (AssemblerOptions.back()->isReorder())
7371     Warning(Loc, ".cpload should be inside a noreorder section");
7372 
7373   if (inMips16Mode()) {
7374     reportParseError(".cpload is not supported in Mips16 mode");
7375     return false;
7376   }
7377 
7378   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Reg;
7379   OperandMatchResultTy ResTy = parseAnyRegister(Reg);
7380   if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
7381     reportParseError("expected register containing function address");
7382     return false;
7383   }
7384 
7385   MipsOperand &RegOpnd = static_cast<MipsOperand &>(*Reg[0]);
7386   if (!RegOpnd.isGPRAsmReg()) {
7387     reportParseError(RegOpnd.getStartLoc(), "invalid register");
7388     return false;
7389   }
7390 
7391   // If this is not the end of the statement, report an error.
7392   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7393     reportParseError("unexpected token, expected end of statement");
7394     return false;
7395   }
7396 
7397   getTargetStreamer().emitDirectiveCpLoad(RegOpnd.getGPR32Reg());
7398   return false;
7399 }
7400 
7401 bool MipsAsmParser::parseDirectiveCpLocal(SMLoc Loc) {
7402   if (!isABI_N32() && !isABI_N64()) {
7403     reportParseError(".cplocal is allowed only in N32 or N64 mode");
7404     return false;
7405   }
7406 
7407   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Reg;
7408   OperandMatchResultTy ResTy = parseAnyRegister(Reg);
7409   if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
7410     reportParseError("expected register containing global pointer");
7411     return false;
7412   }
7413 
7414   MipsOperand &RegOpnd = static_cast<MipsOperand &>(*Reg[0]);
7415   if (!RegOpnd.isGPRAsmReg()) {
7416     reportParseError(RegOpnd.getStartLoc(), "invalid register");
7417     return false;
7418   }
7419 
7420   // If this is not the end of the statement, report an error.
7421   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7422     reportParseError("unexpected token, expected end of statement");
7423     return false;
7424   }
7425   getParser().Lex(); // Consume the EndOfStatement.
7426 
7427   unsigned NewReg = RegOpnd.getGPR32Reg();
7428   if (IsPicEnabled)
7429     GPReg = NewReg;
7430 
7431   getTargetStreamer().emitDirectiveCpLocal(NewReg);
7432   return false;
7433 }
7434 
7435 bool MipsAsmParser::parseDirectiveCpRestore(SMLoc Loc) {
7436   MCAsmParser &Parser = getParser();
7437 
7438   // Note that .cprestore is ignored if used with the N32 and N64 ABIs or if it
7439   // is used in non-PIC mode.
7440 
7441   if (inMips16Mode()) {
7442     reportParseError(".cprestore is not supported in Mips16 mode");
7443     return false;
7444   }
7445 
7446   // Get the stack offset value.
7447   const MCExpr *StackOffset;
7448   int64_t StackOffsetVal;
7449   if (Parser.parseExpression(StackOffset)) {
7450     reportParseError("expected stack offset value");
7451     return false;
7452   }
7453 
7454   if (!StackOffset->evaluateAsAbsolute(StackOffsetVal)) {
7455     reportParseError("stack offset is not an absolute expression");
7456     return false;
7457   }
7458 
7459   if (StackOffsetVal < 0) {
7460     Warning(Loc, ".cprestore with negative stack offset has no effect");
7461     IsCpRestoreSet = false;
7462   } else {
7463     IsCpRestoreSet = true;
7464     CpRestoreOffset = StackOffsetVal;
7465   }
7466 
7467   // If this is not the end of the statement, report an error.
7468   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7469     reportParseError("unexpected token, expected end of statement");
7470     return false;
7471   }
7472 
7473   if (!getTargetStreamer().emitDirectiveCpRestore(
7474           CpRestoreOffset, [&]() { return getATReg(Loc); }, Loc, STI))
7475     return true;
7476   Parser.Lex(); // Consume the EndOfStatement.
7477   return false;
7478 }
7479 
7480 bool MipsAsmParser::parseDirectiveCPSetup() {
7481   MCAsmParser &Parser = getParser();
7482   unsigned FuncReg;
7483   unsigned Save;
7484   bool SaveIsReg = true;
7485 
7486   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
7487   OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
7488   if (ResTy == MatchOperand_NoMatch) {
7489     reportParseError("expected register containing function address");
7490     return false;
7491   }
7492 
7493   MipsOperand &FuncRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
7494   if (!FuncRegOpnd.isGPRAsmReg()) {
7495     reportParseError(FuncRegOpnd.getStartLoc(), "invalid register");
7496     return false;
7497   }
7498 
7499   FuncReg = FuncRegOpnd.getGPR32Reg();
7500   TmpReg.clear();
7501 
7502   if (!eatComma("unexpected token, expected comma"))
7503     return true;
7504 
7505   ResTy = parseAnyRegister(TmpReg);
7506   if (ResTy == MatchOperand_NoMatch) {
7507     const MCExpr *OffsetExpr;
7508     int64_t OffsetVal;
7509     SMLoc ExprLoc = getLexer().getLoc();
7510 
7511     if (Parser.parseExpression(OffsetExpr) ||
7512         !OffsetExpr->evaluateAsAbsolute(OffsetVal)) {
7513       reportParseError(ExprLoc, "expected save register or stack offset");
7514       return false;
7515     }
7516 
7517     Save = OffsetVal;
7518     SaveIsReg = false;
7519   } else {
7520     MipsOperand &SaveOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
7521     if (!SaveOpnd.isGPRAsmReg()) {
7522       reportParseError(SaveOpnd.getStartLoc(), "invalid register");
7523       return false;
7524     }
7525     Save = SaveOpnd.getGPR32Reg();
7526   }
7527 
7528   if (!eatComma("unexpected token, expected comma"))
7529     return true;
7530 
7531   const MCExpr *Expr;
7532   if (Parser.parseExpression(Expr)) {
7533     reportParseError("expected expression");
7534     return false;
7535   }
7536 
7537   if (Expr->getKind() != MCExpr::SymbolRef) {
7538     reportParseError("expected symbol");
7539     return false;
7540   }
7541   const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
7542 
7543   CpSaveLocation = Save;
7544   CpSaveLocationIsRegister = SaveIsReg;
7545 
7546   getTargetStreamer().emitDirectiveCpsetup(FuncReg, Save, Ref->getSymbol(),
7547                                            SaveIsReg);
7548   return false;
7549 }
7550 
7551 bool MipsAsmParser::parseDirectiveCPReturn() {
7552   getTargetStreamer().emitDirectiveCpreturn(CpSaveLocation,
7553                                             CpSaveLocationIsRegister);
7554   return false;
7555 }
7556 
7557 bool MipsAsmParser::parseDirectiveNaN() {
7558   MCAsmParser &Parser = getParser();
7559   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7560     const AsmToken &Tok = Parser.getTok();
7561 
7562     if (Tok.getString() == "2008") {
7563       Parser.Lex();
7564       getTargetStreamer().emitDirectiveNaN2008();
7565       return false;
7566     } else if (Tok.getString() == "legacy") {
7567       Parser.Lex();
7568       getTargetStreamer().emitDirectiveNaNLegacy();
7569       return false;
7570     }
7571   }
7572   // If we don't recognize the option passed to the .nan
7573   // directive (e.g. no option or unknown option), emit an error.
7574   reportParseError("invalid option in .nan directive");
7575   return false;
7576 }
7577 
7578 bool MipsAsmParser::parseDirectiveSet() {
7579   const AsmToken &Tok = getParser().getTok();
7580   StringRef IdVal = Tok.getString();
7581   SMLoc Loc = Tok.getLoc();
7582 
7583   if (IdVal == "noat")
7584     return parseSetNoAtDirective();
7585   if (IdVal == "at")
7586     return parseSetAtDirective();
7587   if (IdVal == "arch")
7588     return parseSetArchDirective();
7589   if (IdVal == "bopt") {
7590     Warning(Loc, "'bopt' feature is unsupported");
7591     getParser().Lex();
7592     return false;
7593   }
7594   if (IdVal == "nobopt") {
7595     // We're already running in nobopt mode, so nothing to do.
7596     getParser().Lex();
7597     return false;
7598   }
7599   if (IdVal == "fp")
7600     return parseSetFpDirective();
7601   if (IdVal == "oddspreg")
7602     return parseSetOddSPRegDirective();
7603   if (IdVal == "nooddspreg")
7604     return parseSetNoOddSPRegDirective();
7605   if (IdVal == "pop")
7606     return parseSetPopDirective();
7607   if (IdVal == "push")
7608     return parseSetPushDirective();
7609   if (IdVal == "reorder")
7610     return parseSetReorderDirective();
7611   if (IdVal == "noreorder")
7612     return parseSetNoReorderDirective();
7613   if (IdVal == "macro")
7614     return parseSetMacroDirective();
7615   if (IdVal == "nomacro")
7616     return parseSetNoMacroDirective();
7617   if (IdVal == "mips16")
7618     return parseSetMips16Directive();
7619   if (IdVal == "nomips16")
7620     return parseSetNoMips16Directive();
7621   if (IdVal == "nomicromips") {
7622     clearFeatureBits(Mips::FeatureMicroMips, "micromips");
7623     getTargetStreamer().emitDirectiveSetNoMicroMips();
7624     getParser().eatToEndOfStatement();
7625     return false;
7626   }
7627   if (IdVal == "micromips") {
7628     if (hasMips64r6()) {
7629       Error(Loc, ".set micromips directive is not supported with MIPS64R6");
7630       return false;
7631     }
7632     return parseSetFeature(Mips::FeatureMicroMips);
7633   }
7634   if (IdVal == "mips0")
7635     return parseSetMips0Directive();
7636   if (IdVal == "mips1")
7637     return parseSetFeature(Mips::FeatureMips1);
7638   if (IdVal == "mips2")
7639     return parseSetFeature(Mips::FeatureMips2);
7640   if (IdVal == "mips3")
7641     return parseSetFeature(Mips::FeatureMips3);
7642   if (IdVal == "mips4")
7643     return parseSetFeature(Mips::FeatureMips4);
7644   if (IdVal == "mips5")
7645     return parseSetFeature(Mips::FeatureMips5);
7646   if (IdVal == "mips32")
7647     return parseSetFeature(Mips::FeatureMips32);
7648   if (IdVal == "mips32r2")
7649     return parseSetFeature(Mips::FeatureMips32r2);
7650   if (IdVal == "mips32r3")
7651     return parseSetFeature(Mips::FeatureMips32r3);
7652   if (IdVal == "mips32r5")
7653     return parseSetFeature(Mips::FeatureMips32r5);
7654   if (IdVal == "mips32r6")
7655     return parseSetFeature(Mips::FeatureMips32r6);
7656   if (IdVal == "mips64")
7657     return parseSetFeature(Mips::FeatureMips64);
7658   if (IdVal == "mips64r2")
7659     return parseSetFeature(Mips::FeatureMips64r2);
7660   if (IdVal == "mips64r3")
7661     return parseSetFeature(Mips::FeatureMips64r3);
7662   if (IdVal == "mips64r5")
7663     return parseSetFeature(Mips::FeatureMips64r5);
7664   if (IdVal == "mips64r6") {
7665     if (inMicroMipsMode()) {
7666       Error(Loc, "MIPS64R6 is not supported with microMIPS");
7667       return false;
7668     }
7669     return parseSetFeature(Mips::FeatureMips64r6);
7670   }
7671   if (IdVal == "dsp")
7672     return parseSetFeature(Mips::FeatureDSP);
7673   if (IdVal == "dspr2")
7674     return parseSetFeature(Mips::FeatureDSPR2);
7675   if (IdVal == "nodsp")
7676     return parseSetNoDspDirective();
7677   if (IdVal == "msa")
7678     return parseSetMsaDirective();
7679   if (IdVal == "nomsa")
7680     return parseSetNoMsaDirective();
7681   if (IdVal == "mt")
7682     return parseSetMtDirective();
7683   if (IdVal == "nomt")
7684     return parseSetNoMtDirective();
7685   if (IdVal == "softfloat")
7686     return parseSetSoftFloatDirective();
7687   if (IdVal == "hardfloat")
7688     return parseSetHardFloatDirective();
7689   if (IdVal == "crc")
7690     return parseSetFeature(Mips::FeatureCRC);
7691   if (IdVal == "nocrc")
7692     return parseSetNoCRCDirective();
7693   if (IdVal == "virt")
7694     return parseSetFeature(Mips::FeatureVirt);
7695   if (IdVal == "novirt")
7696     return parseSetNoVirtDirective();
7697   if (IdVal == "ginv")
7698     return parseSetFeature(Mips::FeatureGINV);
7699   if (IdVal == "noginv")
7700     return parseSetNoGINVDirective();
7701 
7702   // It is just an identifier, look for an assignment.
7703   return parseSetAssignment();
7704 }
7705 
7706 /// parseDirectiveGpWord
7707 ///  ::= .gpword local_sym
7708 bool MipsAsmParser::parseDirectiveGpWord() {
7709   MCAsmParser &Parser = getParser();
7710   const MCExpr *Value;
7711   // EmitGPRel32Value requires an expression, so we are using base class
7712   // method to evaluate the expression.
7713   if (getParser().parseExpression(Value))
7714     return true;
7715   getParser().getStreamer().EmitGPRel32Value(Value);
7716 
7717   if (getLexer().isNot(AsmToken::EndOfStatement))
7718     return Error(getLexer().getLoc(),
7719                 "unexpected token, expected end of statement");
7720   Parser.Lex(); // Eat EndOfStatement token.
7721   return false;
7722 }
7723 
7724 /// parseDirectiveGpDWord
7725 ///  ::= .gpdword local_sym
7726 bool MipsAsmParser::parseDirectiveGpDWord() {
7727   MCAsmParser &Parser = getParser();
7728   const MCExpr *Value;
7729   // EmitGPRel64Value requires an expression, so we are using base class
7730   // method to evaluate the expression.
7731   if (getParser().parseExpression(Value))
7732     return true;
7733   getParser().getStreamer().EmitGPRel64Value(Value);
7734 
7735   if (getLexer().isNot(AsmToken::EndOfStatement))
7736     return Error(getLexer().getLoc(),
7737                 "unexpected token, expected end of statement");
7738   Parser.Lex(); // Eat EndOfStatement token.
7739   return false;
7740 }
7741 
7742 /// parseDirectiveDtpRelWord
7743 ///  ::= .dtprelword tls_sym
7744 bool MipsAsmParser::parseDirectiveDtpRelWord() {
7745   MCAsmParser &Parser = getParser();
7746   const MCExpr *Value;
7747   // EmitDTPRel32Value requires an expression, so we are using base class
7748   // method to evaluate the expression.
7749   if (getParser().parseExpression(Value))
7750     return true;
7751   getParser().getStreamer().EmitDTPRel32Value(Value);
7752 
7753   if (getLexer().isNot(AsmToken::EndOfStatement))
7754     return Error(getLexer().getLoc(),
7755                 "unexpected token, expected end of statement");
7756   Parser.Lex(); // Eat EndOfStatement token.
7757   return false;
7758 }
7759 
7760 /// parseDirectiveDtpRelDWord
7761 ///  ::= .dtpreldword tls_sym
7762 bool MipsAsmParser::parseDirectiveDtpRelDWord() {
7763   MCAsmParser &Parser = getParser();
7764   const MCExpr *Value;
7765   // EmitDTPRel64Value requires an expression, so we are using base class
7766   // method to evaluate the expression.
7767   if (getParser().parseExpression(Value))
7768     return true;
7769   getParser().getStreamer().EmitDTPRel64Value(Value);
7770 
7771   if (getLexer().isNot(AsmToken::EndOfStatement))
7772     return Error(getLexer().getLoc(),
7773                 "unexpected token, expected end of statement");
7774   Parser.Lex(); // Eat EndOfStatement token.
7775   return false;
7776 }
7777 
7778 /// parseDirectiveTpRelWord
7779 ///  ::= .tprelword tls_sym
7780 bool MipsAsmParser::parseDirectiveTpRelWord() {
7781   MCAsmParser &Parser = getParser();
7782   const MCExpr *Value;
7783   // EmitTPRel32Value requires an expression, so we are using base class
7784   // method to evaluate the expression.
7785   if (getParser().parseExpression(Value))
7786     return true;
7787   getParser().getStreamer().EmitTPRel32Value(Value);
7788 
7789   if (getLexer().isNot(AsmToken::EndOfStatement))
7790     return Error(getLexer().getLoc(),
7791                 "unexpected token, expected end of statement");
7792   Parser.Lex(); // Eat EndOfStatement token.
7793   return false;
7794 }
7795 
7796 /// parseDirectiveTpRelDWord
7797 ///  ::= .tpreldword tls_sym
7798 bool MipsAsmParser::parseDirectiveTpRelDWord() {
7799   MCAsmParser &Parser = getParser();
7800   const MCExpr *Value;
7801   // EmitTPRel64Value requires an expression, so we are using base class
7802   // method to evaluate the expression.
7803   if (getParser().parseExpression(Value))
7804     return true;
7805   getParser().getStreamer().EmitTPRel64Value(Value);
7806 
7807   if (getLexer().isNot(AsmToken::EndOfStatement))
7808     return Error(getLexer().getLoc(),
7809                 "unexpected token, expected end of statement");
7810   Parser.Lex(); // Eat EndOfStatement token.
7811   return false;
7812 }
7813 
7814 bool MipsAsmParser::parseDirectiveOption() {
7815   MCAsmParser &Parser = getParser();
7816   // Get the option token.
7817   AsmToken Tok = Parser.getTok();
7818   // At the moment only identifiers are supported.
7819   if (Tok.isNot(AsmToken::Identifier)) {
7820     return Error(Parser.getTok().getLoc(),
7821                  "unexpected token, expected identifier");
7822   }
7823 
7824   StringRef Option = Tok.getIdentifier();
7825 
7826   if (Option == "pic0") {
7827     // MipsAsmParser needs to know if the current PIC mode changes.
7828     IsPicEnabled = false;
7829 
7830     getTargetStreamer().emitDirectiveOptionPic0();
7831     Parser.Lex();
7832     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
7833       return Error(Parser.getTok().getLoc(),
7834                    "unexpected token, expected end of statement");
7835     }
7836     return false;
7837   }
7838 
7839   if (Option == "pic2") {
7840     // MipsAsmParser needs to know if the current PIC mode changes.
7841     IsPicEnabled = true;
7842 
7843     getTargetStreamer().emitDirectiveOptionPic2();
7844     Parser.Lex();
7845     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
7846       return Error(Parser.getTok().getLoc(),
7847                    "unexpected token, expected end of statement");
7848     }
7849     return false;
7850   }
7851 
7852   // Unknown option.
7853   Warning(Parser.getTok().getLoc(),
7854           "unknown option, expected 'pic0' or 'pic2'");
7855   Parser.eatToEndOfStatement();
7856   return false;
7857 }
7858 
7859 /// parseInsnDirective
7860 ///  ::= .insn
7861 bool MipsAsmParser::parseInsnDirective() {
7862   // If this is not the end of the statement, report an error.
7863   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7864     reportParseError("unexpected token, expected end of statement");
7865     return false;
7866   }
7867 
7868   // The actual label marking happens in
7869   // MipsELFStreamer::createPendingLabelRelocs().
7870   getTargetStreamer().emitDirectiveInsn();
7871 
7872   getParser().Lex(); // Eat EndOfStatement token.
7873   return false;
7874 }
7875 
7876 /// parseRSectionDirective
7877 ///  ::= .rdata
7878 bool MipsAsmParser::parseRSectionDirective(StringRef Section) {
7879   // If this is not the end of the statement, report an error.
7880   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7881     reportParseError("unexpected token, expected end of statement");
7882     return false;
7883   }
7884 
7885   MCSection *ELFSection = getContext().getELFSection(
7886       Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
7887   getParser().getStreamer().SwitchSection(ELFSection);
7888 
7889   getParser().Lex(); // Eat EndOfStatement token.
7890   return false;
7891 }
7892 
7893 /// parseSSectionDirective
7894 ///  ::= .sbss
7895 ///  ::= .sdata
7896 bool MipsAsmParser::parseSSectionDirective(StringRef Section, unsigned Type) {
7897   // If this is not the end of the statement, report an error.
7898   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7899     reportParseError("unexpected token, expected end of statement");
7900     return false;
7901   }
7902 
7903   MCSection *ELFSection = getContext().getELFSection(
7904       Section, Type, ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_MIPS_GPREL);
7905   getParser().getStreamer().SwitchSection(ELFSection);
7906 
7907   getParser().Lex(); // Eat EndOfStatement token.
7908   return false;
7909 }
7910 
7911 /// parseDirectiveModule
7912 ///  ::= .module oddspreg
7913 ///  ::= .module nooddspreg
7914 ///  ::= .module fp=value
7915 ///  ::= .module softfloat
7916 ///  ::= .module hardfloat
7917 ///  ::= .module mt
7918 ///  ::= .module crc
7919 ///  ::= .module nocrc
7920 ///  ::= .module virt
7921 ///  ::= .module novirt
7922 ///  ::= .module ginv
7923 ///  ::= .module noginv
7924 bool MipsAsmParser::parseDirectiveModule() {
7925   MCAsmParser &Parser = getParser();
7926   MCAsmLexer &Lexer = getLexer();
7927   SMLoc L = Lexer.getLoc();
7928 
7929   if (!getTargetStreamer().isModuleDirectiveAllowed()) {
7930     // TODO : get a better message.
7931     reportParseError(".module directive must appear before any code");
7932     return false;
7933   }
7934 
7935   StringRef Option;
7936   if (Parser.parseIdentifier(Option)) {
7937     reportParseError("expected .module option identifier");
7938     return false;
7939   }
7940 
7941   if (Option == "oddspreg") {
7942     clearModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
7943 
7944     // Synchronize the abiflags information with the FeatureBits information we
7945     // changed above.
7946     getTargetStreamer().updateABIInfo(*this);
7947 
7948     // If printing assembly, use the recently updated abiflags information.
7949     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7950     // emitted at the end).
7951     getTargetStreamer().emitDirectiveModuleOddSPReg();
7952 
7953     // If this is not the end of the statement, report an error.
7954     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7955       reportParseError("unexpected token, expected end of statement");
7956       return false;
7957     }
7958 
7959     return false; // parseDirectiveModule has finished successfully.
7960   } else if (Option == "nooddspreg") {
7961     if (!isABI_O32()) {
7962       return Error(L, "'.module nooddspreg' requires the O32 ABI");
7963     }
7964 
7965     setModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
7966 
7967     // Synchronize the abiflags information with the FeatureBits information we
7968     // changed above.
7969     getTargetStreamer().updateABIInfo(*this);
7970 
7971     // If printing assembly, use the recently updated abiflags information.
7972     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7973     // emitted at the end).
7974     getTargetStreamer().emitDirectiveModuleOddSPReg();
7975 
7976     // If this is not the end of the statement, report an error.
7977     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7978       reportParseError("unexpected token, expected end of statement");
7979       return false;
7980     }
7981 
7982     return false; // parseDirectiveModule has finished successfully.
7983   } else if (Option == "fp") {
7984     return parseDirectiveModuleFP();
7985   } else if (Option == "softfloat") {
7986     setModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float");
7987 
7988     // Synchronize the ABI Flags information with the FeatureBits information we
7989     // updated above.
7990     getTargetStreamer().updateABIInfo(*this);
7991 
7992     // If printing assembly, use the recently updated ABI Flags information.
7993     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
7994     // emitted later).
7995     getTargetStreamer().emitDirectiveModuleSoftFloat();
7996 
7997     // If this is not the end of the statement, report an error.
7998     if (getLexer().isNot(AsmToken::EndOfStatement)) {
7999       reportParseError("unexpected token, expected end of statement");
8000       return false;
8001     }
8002 
8003     return false; // parseDirectiveModule has finished successfully.
8004   } else if (Option == "hardfloat") {
8005     clearModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float");
8006 
8007     // Synchronize the ABI Flags information with the FeatureBits information we
8008     // updated above.
8009     getTargetStreamer().updateABIInfo(*this);
8010 
8011     // If printing assembly, use the recently updated ABI Flags information.
8012     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
8013     // emitted later).
8014     getTargetStreamer().emitDirectiveModuleHardFloat();
8015 
8016     // If this is not the end of the statement, report an error.
8017     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8018       reportParseError("unexpected token, expected end of statement");
8019       return false;
8020     }
8021 
8022     return false; // parseDirectiveModule has finished successfully.
8023   } else if (Option == "mt") {
8024     setModuleFeatureBits(Mips::FeatureMT, "mt");
8025 
8026     // Synchronize the ABI Flags information with the FeatureBits information we
8027     // updated above.
8028     getTargetStreamer().updateABIInfo(*this);
8029 
8030     // If printing assembly, use the recently updated ABI Flags information.
8031     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
8032     // emitted later).
8033     getTargetStreamer().emitDirectiveModuleMT();
8034 
8035     // If this is not the end of the statement, report an error.
8036     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8037       reportParseError("unexpected token, expected end of statement");
8038       return false;
8039     }
8040 
8041     return false; // parseDirectiveModule has finished successfully.
8042   } else if (Option == "crc") {
8043     setModuleFeatureBits(Mips::FeatureCRC, "crc");
8044 
8045     // Synchronize the ABI Flags information with the FeatureBits information we
8046     // updated above.
8047     getTargetStreamer().updateABIInfo(*this);
8048 
8049     // If printing assembly, use the recently updated ABI Flags information.
8050     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
8051     // emitted later).
8052     getTargetStreamer().emitDirectiveModuleCRC();
8053 
8054     // If this is not the end of the statement, report an error.
8055     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8056       reportParseError("unexpected token, expected end of statement");
8057       return false;
8058     }
8059 
8060     return false; // parseDirectiveModule has finished successfully.
8061   } else if (Option == "nocrc") {
8062     clearModuleFeatureBits(Mips::FeatureCRC, "crc");
8063 
8064     // Synchronize the ABI Flags information with the FeatureBits information we
8065     // updated above.
8066     getTargetStreamer().updateABIInfo(*this);
8067 
8068     // If printing assembly, use the recently updated ABI Flags information.
8069     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
8070     // emitted later).
8071     getTargetStreamer().emitDirectiveModuleNoCRC();
8072 
8073     // If this is not the end of the statement, report an error.
8074     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8075       reportParseError("unexpected token, expected end of statement");
8076       return false;
8077     }
8078 
8079     return false; // parseDirectiveModule has finished successfully.
8080   } else if (Option == "virt") {
8081     setModuleFeatureBits(Mips::FeatureVirt, "virt");
8082 
8083     // Synchronize the ABI Flags information with the FeatureBits information we
8084     // updated above.
8085     getTargetStreamer().updateABIInfo(*this);
8086 
8087     // If printing assembly, use the recently updated ABI Flags information.
8088     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
8089     // emitted later).
8090     getTargetStreamer().emitDirectiveModuleVirt();
8091 
8092     // If this is not the end of the statement, report an error.
8093     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8094       reportParseError("unexpected token, expected end of statement");
8095       return false;
8096     }
8097 
8098     return false; // parseDirectiveModule has finished successfully.
8099   } else if (Option == "novirt") {
8100     clearModuleFeatureBits(Mips::FeatureVirt, "virt");
8101 
8102     // Synchronize the ABI Flags information with the FeatureBits information we
8103     // updated above.
8104     getTargetStreamer().updateABIInfo(*this);
8105 
8106     // If printing assembly, use the recently updated ABI Flags information.
8107     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
8108     // emitted later).
8109     getTargetStreamer().emitDirectiveModuleNoVirt();
8110 
8111     // If this is not the end of the statement, report an error.
8112     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8113       reportParseError("unexpected token, expected end of statement");
8114       return false;
8115     }
8116 
8117     return false; // parseDirectiveModule has finished successfully.
8118   } else if (Option == "ginv") {
8119     setModuleFeatureBits(Mips::FeatureGINV, "ginv");
8120 
8121     // Synchronize the ABI Flags information with the FeatureBits information we
8122     // updated above.
8123     getTargetStreamer().updateABIInfo(*this);
8124 
8125     // If printing assembly, use the recently updated ABI Flags information.
8126     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
8127     // emitted later).
8128     getTargetStreamer().emitDirectiveModuleGINV();
8129 
8130     // If this is not the end of the statement, report an error.
8131     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8132       reportParseError("unexpected token, expected end of statement");
8133       return false;
8134     }
8135 
8136     return false; // parseDirectiveModule has finished successfully.
8137   } else if (Option == "noginv") {
8138     clearModuleFeatureBits(Mips::FeatureGINV, "ginv");
8139 
8140     // Synchronize the ABI Flags information with the FeatureBits information we
8141     // updated above.
8142     getTargetStreamer().updateABIInfo(*this);
8143 
8144     // If printing assembly, use the recently updated ABI Flags information.
8145     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
8146     // emitted later).
8147     getTargetStreamer().emitDirectiveModuleNoGINV();
8148 
8149     // If this is not the end of the statement, report an error.
8150     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8151       reportParseError("unexpected token, expected end of statement");
8152       return false;
8153     }
8154 
8155     return false; // parseDirectiveModule has finished successfully.
8156   } else {
8157     return Error(L, "'" + Twine(Option) + "' is not a valid .module option.");
8158   }
8159 }
8160 
8161 /// parseDirectiveModuleFP
8162 ///  ::= =32
8163 ///  ::= =xx
8164 ///  ::= =64
8165 bool MipsAsmParser::parseDirectiveModuleFP() {
8166   MCAsmParser &Parser = getParser();
8167   MCAsmLexer &Lexer = getLexer();
8168 
8169   if (Lexer.isNot(AsmToken::Equal)) {
8170     reportParseError("unexpected token, expected equals sign '='");
8171     return false;
8172   }
8173   Parser.Lex(); // Eat '=' token.
8174 
8175   MipsABIFlagsSection::FpABIKind FpABI;
8176   if (!parseFpABIValue(FpABI, ".module"))
8177     return false;
8178 
8179   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8180     reportParseError("unexpected token, expected end of statement");
8181     return false;
8182   }
8183 
8184   // Synchronize the abiflags information with the FeatureBits information we
8185   // changed above.
8186   getTargetStreamer().updateABIInfo(*this);
8187 
8188   // If printing assembly, use the recently updated abiflags information.
8189   // If generating ELF, don't do anything (the .MIPS.abiflags section gets
8190   // emitted at the end).
8191   getTargetStreamer().emitDirectiveModuleFP();
8192 
8193   Parser.Lex(); // Consume the EndOfStatement.
8194   return false;
8195 }
8196 
8197 bool MipsAsmParser::parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
8198                                     StringRef Directive) {
8199   MCAsmParser &Parser = getParser();
8200   MCAsmLexer &Lexer = getLexer();
8201   bool ModuleLevelOptions = Directive == ".module";
8202 
8203   if (Lexer.is(AsmToken::Identifier)) {
8204     StringRef Value = Parser.getTok().getString();
8205     Parser.Lex();
8206 
8207     if (Value != "xx") {
8208       reportParseError("unsupported value, expected 'xx', '32' or '64'");
8209       return false;
8210     }
8211 
8212     if (!isABI_O32()) {
8213       reportParseError("'" + Directive + " fp=xx' requires the O32 ABI");
8214       return false;
8215     }
8216 
8217     FpABI = MipsABIFlagsSection::FpABIKind::XX;
8218     if (ModuleLevelOptions) {
8219       setModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
8220       clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
8221     } else {
8222       setFeatureBits(Mips::FeatureFPXX, "fpxx");
8223       clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
8224     }
8225     return true;
8226   }
8227 
8228   if (Lexer.is(AsmToken::Integer)) {
8229     unsigned Value = Parser.getTok().getIntVal();
8230     Parser.Lex();
8231 
8232     if (Value != 32 && Value != 64) {
8233       reportParseError("unsupported value, expected 'xx', '32' or '64'");
8234       return false;
8235     }
8236 
8237     if (Value == 32) {
8238       if (!isABI_O32()) {
8239         reportParseError("'" + Directive + " fp=32' requires the O32 ABI");
8240         return false;
8241       }
8242 
8243       FpABI = MipsABIFlagsSection::FpABIKind::S32;
8244       if (ModuleLevelOptions) {
8245         clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
8246         clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
8247       } else {
8248         clearFeatureBits(Mips::FeatureFPXX, "fpxx");
8249         clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
8250       }
8251     } else {
8252       FpABI = MipsABIFlagsSection::FpABIKind::S64;
8253       if (ModuleLevelOptions) {
8254         clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
8255         setModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
8256       } else {
8257         clearFeatureBits(Mips::FeatureFPXX, "fpxx");
8258         setFeatureBits(Mips::FeatureFP64Bit, "fp64");
8259       }
8260     }
8261 
8262     return true;
8263   }
8264 
8265   return false;
8266 }
8267 
8268 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
8269   // This returns false if this function recognizes the directive
8270   // regardless of whether it is successfully handles or reports an
8271   // error. Otherwise it returns true to give the generic parser a
8272   // chance at recognizing it.
8273 
8274   MCAsmParser &Parser = getParser();
8275   StringRef IDVal = DirectiveID.getString();
8276 
8277   if (IDVal == ".cpload") {
8278     parseDirectiveCpLoad(DirectiveID.getLoc());
8279     return false;
8280   }
8281   if (IDVal == ".cprestore") {
8282     parseDirectiveCpRestore(DirectiveID.getLoc());
8283     return false;
8284   }
8285   if (IDVal == ".cplocal") {
8286     parseDirectiveCpLocal(DirectiveID.getLoc());
8287     return false;
8288   }
8289   if (IDVal == ".ent") {
8290     StringRef SymbolName;
8291 
8292     if (Parser.parseIdentifier(SymbolName)) {
8293       reportParseError("expected identifier after .ent");
8294       return false;
8295     }
8296 
8297     // There's an undocumented extension that allows an integer to
8298     // follow the name of the procedure which AFAICS is ignored by GAS.
8299     // Example: .ent foo,2
8300     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8301       if (getLexer().isNot(AsmToken::Comma)) {
8302         // Even though we accept this undocumented extension for compatibility
8303         // reasons, the additional integer argument does not actually change
8304         // the behaviour of the '.ent' directive, so we would like to discourage
8305         // its use. We do this by not referring to the extended version in
8306         // error messages which are not directly related to its use.
8307         reportParseError("unexpected token, expected end of statement");
8308         return false;
8309       }
8310       Parser.Lex(); // Eat the comma.
8311       const MCExpr *DummyNumber;
8312       int64_t DummyNumberVal;
8313       // If the user was explicitly trying to use the extended version,
8314       // we still give helpful extension-related error messages.
8315       if (Parser.parseExpression(DummyNumber)) {
8316         reportParseError("expected number after comma");
8317         return false;
8318       }
8319       if (!DummyNumber->evaluateAsAbsolute(DummyNumberVal)) {
8320         reportParseError("expected an absolute expression after comma");
8321         return false;
8322       }
8323     }
8324 
8325     // If this is not the end of the statement, report an error.
8326     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8327       reportParseError("unexpected token, expected end of statement");
8328       return false;
8329     }
8330 
8331     MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
8332 
8333     getTargetStreamer().emitDirectiveEnt(*Sym);
8334     CurrentFn = Sym;
8335     IsCpRestoreSet = false;
8336     return false;
8337   }
8338 
8339   if (IDVal == ".end") {
8340     StringRef SymbolName;
8341 
8342     if (Parser.parseIdentifier(SymbolName)) {
8343       reportParseError("expected identifier after .end");
8344       return false;
8345     }
8346 
8347     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8348       reportParseError("unexpected token, expected end of statement");
8349       return false;
8350     }
8351 
8352     if (CurrentFn == nullptr) {
8353       reportParseError(".end used without .ent");
8354       return false;
8355     }
8356 
8357     if ((SymbolName != CurrentFn->getName())) {
8358       reportParseError(".end symbol does not match .ent symbol");
8359       return false;
8360     }
8361 
8362     getTargetStreamer().emitDirectiveEnd(SymbolName);
8363     CurrentFn = nullptr;
8364     IsCpRestoreSet = false;
8365     return false;
8366   }
8367 
8368   if (IDVal == ".frame") {
8369     // .frame $stack_reg, frame_size_in_bytes, $return_reg
8370     SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
8371     OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
8372     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
8373       reportParseError("expected stack register");
8374       return false;
8375     }
8376 
8377     MipsOperand &StackRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
8378     if (!StackRegOpnd.isGPRAsmReg()) {
8379       reportParseError(StackRegOpnd.getStartLoc(),
8380                        "expected general purpose register");
8381       return false;
8382     }
8383     unsigned StackReg = StackRegOpnd.getGPR32Reg();
8384 
8385     if (Parser.getTok().is(AsmToken::Comma))
8386       Parser.Lex();
8387     else {
8388       reportParseError("unexpected token, expected comma");
8389       return false;
8390     }
8391 
8392     // Parse the frame size.
8393     const MCExpr *FrameSize;
8394     int64_t FrameSizeVal;
8395 
8396     if (Parser.parseExpression(FrameSize)) {
8397       reportParseError("expected frame size value");
8398       return false;
8399     }
8400 
8401     if (!FrameSize->evaluateAsAbsolute(FrameSizeVal)) {
8402       reportParseError("frame size not an absolute expression");
8403       return false;
8404     }
8405 
8406     if (Parser.getTok().is(AsmToken::Comma))
8407       Parser.Lex();
8408     else {
8409       reportParseError("unexpected token, expected comma");
8410       return false;
8411     }
8412 
8413     // Parse the return register.
8414     TmpReg.clear();
8415     ResTy = parseAnyRegister(TmpReg);
8416     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
8417       reportParseError("expected return register");
8418       return false;
8419     }
8420 
8421     MipsOperand &ReturnRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
8422     if (!ReturnRegOpnd.isGPRAsmReg()) {
8423       reportParseError(ReturnRegOpnd.getStartLoc(),
8424                        "expected general purpose register");
8425       return false;
8426     }
8427 
8428     // If this is not the end of the statement, report an error.
8429     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8430       reportParseError("unexpected token, expected end of statement");
8431       return false;
8432     }
8433 
8434     getTargetStreamer().emitFrame(StackReg, FrameSizeVal,
8435                                   ReturnRegOpnd.getGPR32Reg());
8436     IsCpRestoreSet = false;
8437     return false;
8438   }
8439 
8440   if (IDVal == ".set") {
8441     parseDirectiveSet();
8442     return false;
8443   }
8444 
8445   if (IDVal == ".mask" || IDVal == ".fmask") {
8446     // .mask bitmask, frame_offset
8447     // bitmask: One bit for each register used.
8448     // frame_offset: Offset from Canonical Frame Address ($sp on entry) where
8449     //               first register is expected to be saved.
8450     // Examples:
8451     //   .mask 0x80000000, -4
8452     //   .fmask 0x80000000, -4
8453     //
8454 
8455     // Parse the bitmask
8456     const MCExpr *BitMask;
8457     int64_t BitMaskVal;
8458 
8459     if (Parser.parseExpression(BitMask)) {
8460       reportParseError("expected bitmask value");
8461       return false;
8462     }
8463 
8464     if (!BitMask->evaluateAsAbsolute(BitMaskVal)) {
8465       reportParseError("bitmask not an absolute expression");
8466       return false;
8467     }
8468 
8469     if (Parser.getTok().is(AsmToken::Comma))
8470       Parser.Lex();
8471     else {
8472       reportParseError("unexpected token, expected comma");
8473       return false;
8474     }
8475 
8476     // Parse the frame_offset
8477     const MCExpr *FrameOffset;
8478     int64_t FrameOffsetVal;
8479 
8480     if (Parser.parseExpression(FrameOffset)) {
8481       reportParseError("expected frame offset value");
8482       return false;
8483     }
8484 
8485     if (!FrameOffset->evaluateAsAbsolute(FrameOffsetVal)) {
8486       reportParseError("frame offset not an absolute expression");
8487       return false;
8488     }
8489 
8490     // If this is not the end of the statement, report an error.
8491     if (getLexer().isNot(AsmToken::EndOfStatement)) {
8492       reportParseError("unexpected token, expected end of statement");
8493       return false;
8494     }
8495 
8496     if (IDVal == ".mask")
8497       getTargetStreamer().emitMask(BitMaskVal, FrameOffsetVal);
8498     else
8499       getTargetStreamer().emitFMask(BitMaskVal, FrameOffsetVal);
8500     return false;
8501   }
8502 
8503   if (IDVal == ".nan")
8504     return parseDirectiveNaN();
8505 
8506   if (IDVal == ".gpword") {
8507     parseDirectiveGpWord();
8508     return false;
8509   }
8510 
8511   if (IDVal == ".gpdword") {
8512     parseDirectiveGpDWord();
8513     return false;
8514   }
8515 
8516   if (IDVal == ".dtprelword") {
8517     parseDirectiveDtpRelWord();
8518     return false;
8519   }
8520 
8521   if (IDVal == ".dtpreldword") {
8522     parseDirectiveDtpRelDWord();
8523     return false;
8524   }
8525 
8526   if (IDVal == ".tprelword") {
8527     parseDirectiveTpRelWord();
8528     return false;
8529   }
8530 
8531   if (IDVal == ".tpreldword") {
8532     parseDirectiveTpRelDWord();
8533     return false;
8534   }
8535 
8536   if (IDVal == ".option") {
8537     parseDirectiveOption();
8538     return false;
8539   }
8540 
8541   if (IDVal == ".abicalls") {
8542     getTargetStreamer().emitDirectiveAbiCalls();
8543     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
8544       Error(Parser.getTok().getLoc(),
8545             "unexpected token, expected end of statement");
8546     }
8547     return false;
8548   }
8549 
8550   if (IDVal == ".cpsetup") {
8551     parseDirectiveCPSetup();
8552     return false;
8553   }
8554   if (IDVal == ".cpreturn") {
8555     parseDirectiveCPReturn();
8556     return false;
8557   }
8558   if (IDVal == ".module") {
8559     parseDirectiveModule();
8560     return false;
8561   }
8562   if (IDVal == ".llvm_internal_mips_reallow_module_directive") {
8563     parseInternalDirectiveReallowModule();
8564     return false;
8565   }
8566   if (IDVal == ".insn") {
8567     parseInsnDirective();
8568     return false;
8569   }
8570   if (IDVal == ".rdata") {
8571     parseRSectionDirective(".rodata");
8572     return false;
8573   }
8574   if (IDVal == ".sbss") {
8575     parseSSectionDirective(IDVal, ELF::SHT_NOBITS);
8576     return false;
8577   }
8578   if (IDVal == ".sdata") {
8579     parseSSectionDirective(IDVal, ELF::SHT_PROGBITS);
8580     return false;
8581   }
8582 
8583   return true;
8584 }
8585 
8586 bool MipsAsmParser::parseInternalDirectiveReallowModule() {
8587   // If this is not the end of the statement, report an error.
8588   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8589     reportParseError("unexpected token, expected end of statement");
8590     return false;
8591   }
8592 
8593   getTargetStreamer().reallowModuleDirective();
8594 
8595   getParser().Lex(); // Eat EndOfStatement token.
8596   return false;
8597 }
8598 
8599 extern "C" void LLVMInitializeMipsAsmParser() {
8600   RegisterMCAsmParser<MipsAsmParser> X(getTheMipsTarget());
8601   RegisterMCAsmParser<MipsAsmParser> Y(getTheMipselTarget());
8602   RegisterMCAsmParser<MipsAsmParser> A(getTheMips64Target());
8603   RegisterMCAsmParser<MipsAsmParser> B(getTheMips64elTarget());
8604 }
8605 
8606 #define GET_REGISTER_MATCHER
8607 #define GET_MATCHER_IMPLEMENTATION
8608 #define GET_MNEMONIC_SPELL_CHECKER
8609 #include "MipsGenAsmMatcher.inc"
8610 
8611 bool MipsAsmParser::mnemonicIsValid(StringRef Mnemonic, unsigned VariantID) {
8612   // Find the appropriate table for this asm variant.
8613   const MatchEntry *Start, *End;
8614   switch (VariantID) {
8615   default: llvm_unreachable("invalid variant!");
8616   case 0: Start = std::begin(MatchTable0); End = std::end(MatchTable0); break;
8617   }
8618   // Search the table.
8619   auto MnemonicRange = std::equal_range(Start, End, Mnemonic, LessOpcode());
8620   return MnemonicRange.first != MnemonicRange.second;
8621 }
8622