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