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