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