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