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