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