1 //===-- MipsAsmParser.cpp - Parse Mips assembly to MCInst instructions ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "MCTargetDesc/MipsABIInfo.h"
11 #include "MCTargetDesc/MipsMCExpr.h"
12 #include "MCTargetDesc/MipsMCTargetDesc.h"
13 #include "MipsRegisterInfo.h"
14 #include "MipsTargetObjectFile.h"
15 #include "MipsTargetStreamer.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstBuilder.h"
23 #include "llvm/MC/MCParser/MCAsmLexer.h"
24 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
25 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
26 #include "llvm/MC/MCSectionELF.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ELF.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <memory>
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "mips-asm-parser"
41 
42 namespace llvm {
43 class MCInstrInfo;
44 }
45 
46 namespace {
47 class MipsAssemblerOptions {
48 public:
49   MipsAssemblerOptions(const FeatureBitset &Features_) :
50     ATReg(1), Reorder(true), Macro(true), Features(Features_) {}
51 
52   MipsAssemblerOptions(const MipsAssemblerOptions *Opts) {
53     ATReg = Opts->getATRegIndex();
54     Reorder = Opts->isReorder();
55     Macro = Opts->isMacro();
56     Features = Opts->getFeatures();
57   }
58 
59   unsigned getATRegIndex() const { return ATReg; }
60   bool setATRegIndex(unsigned Reg) {
61     if (Reg > 31)
62       return false;
63 
64     ATReg = Reg;
65     return true;
66   }
67 
68   bool isReorder() const { return Reorder; }
69   void setReorder() { Reorder = true; }
70   void setNoReorder() { Reorder = false; }
71 
72   bool isMacro() const { return Macro; }
73   void setMacro() { Macro = true; }
74   void setNoMacro() { Macro = false; }
75 
76   const FeatureBitset &getFeatures() const { return Features; }
77   void setFeatures(const FeatureBitset &Features_) { Features = Features_; }
78 
79   // Set of features that are either architecture features or referenced
80   // by them (e.g.: FeatureNaN2008 implied by FeatureMips32r6).
81   // The full table can be found in MipsGenSubtargetInfo.inc (MipsFeatureKV[]).
82   // The reason we need this mask is explained in the selectArch function.
83   // FIXME: Ideally we would like TableGen to generate this information.
84   static const FeatureBitset AllArchRelatedMask;
85 
86 private:
87   unsigned ATReg;
88   bool Reorder;
89   bool Macro;
90   FeatureBitset Features;
91 };
92 }
93 
94 const FeatureBitset MipsAssemblerOptions::AllArchRelatedMask = {
95     Mips::FeatureMips1, Mips::FeatureMips2, Mips::FeatureMips3,
96     Mips::FeatureMips3_32, Mips::FeatureMips3_32r2, Mips::FeatureMips4,
97     Mips::FeatureMips4_32, Mips::FeatureMips4_32r2, Mips::FeatureMips5,
98     Mips::FeatureMips5_32r2, Mips::FeatureMips32, Mips::FeatureMips32r2,
99     Mips::FeatureMips32r3, Mips::FeatureMips32r5, Mips::FeatureMips32r6,
100     Mips::FeatureMips64, Mips::FeatureMips64r2, Mips::FeatureMips64r3,
101     Mips::FeatureMips64r5, Mips::FeatureMips64r6, Mips::FeatureCnMips,
102     Mips::FeatureFP64Bit, Mips::FeatureGP64Bit, Mips::FeatureNaN2008
103 };
104 
105 namespace {
106 class MipsAsmParser : public MCTargetAsmParser {
107   MipsTargetStreamer &getTargetStreamer() {
108     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
109     return static_cast<MipsTargetStreamer &>(TS);
110   }
111 
112   MipsABIInfo ABI;
113   SmallVector<std::unique_ptr<MipsAssemblerOptions>, 2> AssemblerOptions;
114   MCSymbol *CurrentFn; // Pointer to the function being parsed. It may be a
115                        // nullptr, which indicates that no function is currently
116                        // selected. This usually happens after an '.end func'
117                        // directive.
118   bool IsLittleEndian;
119   bool IsPicEnabled;
120   bool IsCpRestoreSet;
121   int CpRestoreOffset;
122   unsigned CpSaveLocation;
123   /// If true, then CpSaveLocation is a register, otherwise it's an offset.
124   bool     CpSaveLocationIsRegister;
125 
126   // Print a warning along with its fix-it message at the given range.
127   void printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
128                              SMRange Range, bool ShowColors = true);
129 
130 #define GET_ASSEMBLER_HEADER
131 #include "MipsGenAsmMatcher.inc"
132 
133   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
134 
135   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
136                                OperandVector &Operands, MCStreamer &Out,
137                                uint64_t &ErrorInfo,
138                                bool MatchingInlineAsm) override;
139 
140   /// Parse a register as used in CFI directives
141   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
142 
143   bool parseParenSuffix(StringRef Name, OperandVector &Operands);
144 
145   bool parseBracketSuffix(StringRef Name, OperandVector &Operands);
146 
147   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
148                         SMLoc NameLoc, OperandVector &Operands) override;
149 
150   bool ParseDirective(AsmToken DirectiveID) override;
151 
152   OperandMatchResultTy parseMemOperand(OperandVector &Operands);
153   OperandMatchResultTy
154   matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
155                                     StringRef Identifier, SMLoc S);
156   OperandMatchResultTy matchAnyRegisterWithoutDollar(OperandVector &Operands,
157                                                      SMLoc S);
158   OperandMatchResultTy parseAnyRegister(OperandVector &Operands);
159   OperandMatchResultTy parseImm(OperandVector &Operands);
160   OperandMatchResultTy parseJumpTarget(OperandVector &Operands);
161   OperandMatchResultTy parseInvNum(OperandVector &Operands);
162   OperandMatchResultTy parseLSAImm(OperandVector &Operands);
163   OperandMatchResultTy parseRegisterPair(OperandVector &Operands);
164   OperandMatchResultTy parseMovePRegPair(OperandVector &Operands);
165   OperandMatchResultTy parseRegisterList(OperandVector &Operands);
166 
167   bool searchSymbolAlias(OperandVector &Operands);
168 
169   bool parseOperand(OperandVector &, StringRef Mnemonic);
170 
171   enum MacroExpanderResultTy {
172     MER_NotAMacro,
173     MER_Success,
174     MER_Fail,
175   };
176 
177   // Expands assembly pseudo instructions.
178   MacroExpanderResultTy
179   tryExpandInstruction(MCInst &Inst, SMLoc IDLoc,
180                        SmallVectorImpl<MCInst> &Instructions);
181 
182   bool expandJalWithRegs(MCInst &Inst, SMLoc IDLoc,
183                          SmallVectorImpl<MCInst> &Instructions);
184 
185   bool loadImmediate(int64_t ImmValue, unsigned DstReg, unsigned SrcReg,
186                      bool Is32BitImm, bool IsAddress, SMLoc IDLoc,
187                      SmallVectorImpl<MCInst> &Instructions);
188 
189   bool loadAndAddSymbolAddress(const MCExpr *SymExpr, unsigned DstReg,
190                                unsigned SrcReg, bool Is32BitSym, SMLoc IDLoc,
191                                SmallVectorImpl<MCInst> &Instructions);
192 
193   bool expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
194                      SmallVectorImpl<MCInst> &Instructions);
195 
196   bool expandLoadAddress(unsigned DstReg, unsigned BaseReg,
197                          const MCOperand &Offset, bool Is32BitAddress,
198                          SMLoc IDLoc, SmallVectorImpl<MCInst> &Instructions);
199 
200   bool expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc,
201                                   SmallVectorImpl<MCInst> &Instructions);
202 
203   void expandMemInst(MCInst &Inst, SMLoc IDLoc,
204                      SmallVectorImpl<MCInst> &Instructions, bool isLoad,
205                      bool isImmOpnd);
206 
207   bool expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc,
208                                SmallVectorImpl<MCInst> &Instructions);
209 
210   bool expandAliasImmediate(MCInst &Inst, SMLoc IDLoc,
211                           SmallVectorImpl<MCInst> &Instructions);
212 
213   bool expandBranchImm(MCInst &Inst, SMLoc IDLoc,
214                        SmallVectorImpl<MCInst> &Instructions);
215 
216   bool expandCondBranches(MCInst &Inst, SMLoc IDLoc,
217                           SmallVectorImpl<MCInst> &Instructions);
218 
219   bool expandDiv(MCInst &Inst, SMLoc IDLoc,
220                  SmallVectorImpl<MCInst> &Instructions, const bool IsMips64,
221                  const bool Signed);
222 
223   bool expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU, SMLoc IDLoc,
224                    SmallVectorImpl<MCInst> &Instructions);
225 
226   bool expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc,
227                  SmallVectorImpl<MCInst> &Instructions);
228 
229   bool expandUlw(MCInst &Inst, SMLoc IDLoc,
230                  SmallVectorImpl<MCInst> &Instructions);
231 
232   bool expandRotation(MCInst &Inst, SMLoc IDLoc,
233                       SmallVectorImpl<MCInst> &Instructions);
234   bool expandRotationImm(MCInst &Inst, SMLoc IDLoc,
235                          SmallVectorImpl<MCInst> &Instructions);
236   bool expandDRotation(MCInst &Inst, SMLoc IDLoc,
237                        SmallVectorImpl<MCInst> &Instructions);
238   bool expandDRotationImm(MCInst &Inst, SMLoc IDLoc,
239                           SmallVectorImpl<MCInst> &Instructions);
240 
241   bool expandAbs(MCInst &Inst, SMLoc IDLoc,
242                  SmallVectorImpl<MCInst> &Instructions);
243 
244   void createNop(bool hasShortDelaySlot, SMLoc IDLoc,
245                  SmallVectorImpl<MCInst> &Instructions);
246 
247   void createAddu(unsigned DstReg, unsigned SrcReg, unsigned TrgReg,
248                   bool Is64Bit, SmallVectorImpl<MCInst> &Instructions);
249 
250   void createCpRestoreMemOp(bool IsLoad, int StackOffset, SMLoc IDLoc,
251                             SmallVectorImpl<MCInst> &Instructions);
252 
253   bool reportParseError(Twine ErrorMsg);
254   bool reportParseError(SMLoc Loc, Twine ErrorMsg);
255 
256   bool parseMemOffset(const MCExpr *&Res, bool isParenExpr);
257   bool parseRelocOperand(const MCExpr *&Res);
258 
259   const MCExpr *evaluateRelocExpr(const MCExpr *Expr, StringRef RelocStr);
260 
261   bool isEvaluated(const MCExpr *Expr);
262   bool parseSetMips0Directive();
263   bool parseSetArchDirective();
264   bool parseSetFeature(uint64_t Feature);
265   bool isPicAndNotNxxAbi(); // Used by .cpload, .cprestore, and .cpsetup.
266   bool parseDirectiveCpLoad(SMLoc Loc);
267   bool parseDirectiveCpRestore(SMLoc Loc);
268   bool parseDirectiveCPSetup();
269   bool parseDirectiveCPReturn();
270   bool parseDirectiveNaN();
271   bool parseDirectiveSet();
272   bool parseDirectiveOption();
273   bool parseInsnDirective();
274   bool parseSSectionDirective(StringRef Section, unsigned Type);
275 
276   bool parseSetAtDirective();
277   bool parseSetNoAtDirective();
278   bool parseSetMacroDirective();
279   bool parseSetNoMacroDirective();
280   bool parseSetMsaDirective();
281   bool parseSetNoMsaDirective();
282   bool parseSetNoDspDirective();
283   bool parseSetReorderDirective();
284   bool parseSetNoReorderDirective();
285   bool parseSetMips16Directive();
286   bool parseSetNoMips16Directive();
287   bool parseSetFpDirective();
288   bool parseSetOddSPRegDirective();
289   bool parseSetNoOddSPRegDirective();
290   bool parseSetPopDirective();
291   bool parseSetPushDirective();
292   bool parseSetSoftFloatDirective();
293   bool parseSetHardFloatDirective();
294 
295   bool parseSetAssignment();
296 
297   bool parseDataDirective(unsigned Size, SMLoc L);
298   bool parseDirectiveGpWord();
299   bool parseDirectiveGpDWord();
300   bool parseDirectiveModule();
301   bool parseDirectiveModuleFP();
302   bool parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
303                        StringRef Directive);
304 
305   bool parseInternalDirectiveReallowModule();
306 
307   MCSymbolRefExpr::VariantKind getVariantKind(StringRef Symbol);
308 
309   bool eatComma(StringRef ErrorStr);
310 
311   int matchCPURegisterName(StringRef Symbol);
312 
313   int matchHWRegsRegisterName(StringRef Symbol);
314 
315   int matchRegisterByNumber(unsigned RegNum, unsigned RegClass);
316 
317   int matchFPURegisterName(StringRef Name);
318 
319   int matchFCCRegisterName(StringRef Name);
320 
321   int matchACRegisterName(StringRef Name);
322 
323   int matchMSA128RegisterName(StringRef Name);
324 
325   int matchMSA128CtrlRegisterName(StringRef Name);
326 
327   unsigned getReg(int RC, int RegNo);
328 
329   unsigned getGPR(int RegNo);
330 
331   /// Returns the internal register number for the current AT. Also checks if
332   /// the current AT is unavailable (set to $0) and gives an error if it is.
333   /// This should be used in pseudo-instruction expansions which need AT.
334   unsigned getATReg(SMLoc Loc);
335 
336   bool processInstruction(MCInst &Inst, SMLoc IDLoc,
337                           SmallVectorImpl<MCInst> &Instructions);
338 
339   // Helper function that checks if the value of a vector index is within the
340   // boundaries of accepted values for each RegisterKind
341   // Example: INSERT.B $w0[n], $1 => 16 > n >= 0
342   bool validateMSAIndex(int Val, int RegKind);
343 
344   // Selects a new architecture by updating the FeatureBits with the necessary
345   // info including implied dependencies.
346   // Internally, it clears all the feature bits related to *any* architecture
347   // and selects the new one using the ToggleFeature functionality of the
348   // MCSubtargetInfo object that handles implied dependencies. The reason we
349   // clear all the arch related bits manually is because ToggleFeature only
350   // clears the features that imply the feature being cleared and not the
351   // features implied by the feature being cleared. This is easier to see
352   // with an example:
353   //  --------------------------------------------------
354   // | Feature         | Implies                        |
355   // | -------------------------------------------------|
356   // | FeatureMips1    | None                           |
357   // | FeatureMips2    | FeatureMips1                   |
358   // | FeatureMips3    | FeatureMips2 | FeatureMipsGP64 |
359   // | FeatureMips4    | FeatureMips3                   |
360   // | ...             |                                |
361   //  --------------------------------------------------
362   //
363   // Setting Mips3 is equivalent to set: (FeatureMips3 | FeatureMips2 |
364   // FeatureMipsGP64 | FeatureMips1)
365   // Clearing Mips3 is equivalent to clear (FeatureMips3 | FeatureMips4).
366   void selectArch(StringRef ArchFeature) {
367     MCSubtargetInfo &STI = copySTI();
368     FeatureBitset FeatureBits = STI.getFeatureBits();
369     FeatureBits &= ~MipsAssemblerOptions::AllArchRelatedMask;
370     STI.setFeatureBits(FeatureBits);
371     setAvailableFeatures(
372         ComputeAvailableFeatures(STI.ToggleFeature(ArchFeature)));
373     AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
374   }
375 
376   void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
377     if (!(getSTI().getFeatureBits()[Feature])) {
378       MCSubtargetInfo &STI = copySTI();
379       setAvailableFeatures(
380           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
381       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
382     }
383   }
384 
385   void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
386     if (getSTI().getFeatureBits()[Feature]) {
387       MCSubtargetInfo &STI = copySTI();
388       setAvailableFeatures(
389           ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
390       AssemblerOptions.back()->setFeatures(STI.getFeatureBits());
391     }
392   }
393 
394   void setModuleFeatureBits(uint64_t Feature, StringRef FeatureString) {
395     setFeatureBits(Feature, FeatureString);
396     AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits());
397   }
398 
399   void clearModuleFeatureBits(uint64_t Feature, StringRef FeatureString) {
400     clearFeatureBits(Feature, FeatureString);
401     AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits());
402   }
403 
404 public:
405   enum MipsMatchResultTy {
406     Match_RequiresDifferentSrcAndDst = FIRST_TARGET_MATCH_RESULT_TY,
407 #define GET_OPERAND_DIAGNOSTIC_TYPES
408 #include "MipsGenAsmMatcher.inc"
409 #undef GET_OPERAND_DIAGNOSTIC_TYPES
410   };
411 
412   MipsAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser,
413                 const MCInstrInfo &MII, const MCTargetOptions &Options)
414     : MCTargetAsmParser(Options, sti),
415         ABI(MipsABIInfo::computeTargetABI(Triple(sti.getTargetTriple()),
416                                           sti.getCPU(), Options)) {
417     MCAsmParserExtension::Initialize(parser);
418 
419     parser.addAliasForDirective(".asciiz", ".asciz");
420 
421     // Initialize the set of available features.
422     setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
423 
424     // Remember the initial assembler options. The user can not modify these.
425     AssemblerOptions.push_back(
426         llvm::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits()));
427 
428     // Create an assembler options environment for the user to modify.
429     AssemblerOptions.push_back(
430         llvm::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits()));
431 
432     getTargetStreamer().updateABIInfo(*this);
433 
434     if (!isABI_O32() && !useOddSPReg() != 0)
435       report_fatal_error("-mno-odd-spreg requires the O32 ABI");
436 
437     CurrentFn = nullptr;
438 
439     IsPicEnabled =
440         (getContext().getObjectFileInfo()->getRelocM() == Reloc::PIC_);
441 
442     IsCpRestoreSet = false;
443     CpRestoreOffset = -1;
444 
445     Triple TheTriple(sti.getTargetTriple());
446     if ((TheTriple.getArch() == Triple::mips) ||
447         (TheTriple.getArch() == Triple::mips64))
448       IsLittleEndian = false;
449     else
450       IsLittleEndian = true;
451   }
452 
453   /// True if all of $fcc0 - $fcc7 exist for the current ISA.
454   bool hasEightFccRegisters() const { return hasMips4() || hasMips32(); }
455 
456   bool isGP64bit() const {
457     return getSTI().getFeatureBits()[Mips::FeatureGP64Bit];
458   }
459   bool isFP64bit() const {
460     return getSTI().getFeatureBits()[Mips::FeatureFP64Bit];
461   }
462   const MipsABIInfo &getABI() const { return ABI; }
463   bool isABI_N32() const { return ABI.IsN32(); }
464   bool isABI_N64() const { return ABI.IsN64(); }
465   bool isABI_O32() const { return ABI.IsO32(); }
466   bool isABI_FPXX() const {
467     return getSTI().getFeatureBits()[Mips::FeatureFPXX];
468   }
469 
470   bool useOddSPReg() const {
471     return !(getSTI().getFeatureBits()[Mips::FeatureNoOddSPReg]);
472   }
473 
474   bool inMicroMipsMode() const {
475     return getSTI().getFeatureBits()[Mips::FeatureMicroMips];
476   }
477   bool hasMips1() const {
478     return getSTI().getFeatureBits()[Mips::FeatureMips1];
479   }
480   bool hasMips2() const {
481     return getSTI().getFeatureBits()[Mips::FeatureMips2];
482   }
483   bool hasMips3() const {
484     return getSTI().getFeatureBits()[Mips::FeatureMips3];
485   }
486   bool hasMips4() const {
487     return getSTI().getFeatureBits()[Mips::FeatureMips4];
488   }
489   bool hasMips5() const {
490     return getSTI().getFeatureBits()[Mips::FeatureMips5];
491   }
492   bool hasMips32() const {
493     return getSTI().getFeatureBits()[Mips::FeatureMips32];
494   }
495   bool hasMips64() const {
496     return getSTI().getFeatureBits()[Mips::FeatureMips64];
497   }
498   bool hasMips32r2() const {
499     return getSTI().getFeatureBits()[Mips::FeatureMips32r2];
500   }
501   bool hasMips64r2() const {
502     return getSTI().getFeatureBits()[Mips::FeatureMips64r2];
503   }
504   bool hasMips32r3() const {
505     return (getSTI().getFeatureBits()[Mips::FeatureMips32r3]);
506   }
507   bool hasMips64r3() const {
508     return (getSTI().getFeatureBits()[Mips::FeatureMips64r3]);
509   }
510   bool hasMips32r5() const {
511     return (getSTI().getFeatureBits()[Mips::FeatureMips32r5]);
512   }
513   bool hasMips64r5() const {
514     return (getSTI().getFeatureBits()[Mips::FeatureMips64r5]);
515   }
516   bool hasMips32r6() const {
517     return getSTI().getFeatureBits()[Mips::FeatureMips32r6];
518   }
519   bool hasMips64r6() const {
520     return getSTI().getFeatureBits()[Mips::FeatureMips64r6];
521   }
522 
523   bool hasDSP() const {
524     return getSTI().getFeatureBits()[Mips::FeatureDSP];
525   }
526   bool hasDSPR2() const {
527     return getSTI().getFeatureBits()[Mips::FeatureDSPR2];
528   }
529   bool hasDSPR3() const {
530     return getSTI().getFeatureBits()[Mips::FeatureDSPR3];
531   }
532   bool hasMSA() const {
533     return getSTI().getFeatureBits()[Mips::FeatureMSA];
534   }
535   bool hasCnMips() const {
536     return (getSTI().getFeatureBits()[Mips::FeatureCnMips]);
537   }
538 
539   bool inPicMode() {
540     return IsPicEnabled;
541   }
542 
543   bool inMips16Mode() const {
544     return getSTI().getFeatureBits()[Mips::FeatureMips16];
545   }
546 
547   bool useTraps() const {
548     return getSTI().getFeatureBits()[Mips::FeatureUseTCCInDIV];
549   }
550 
551   bool useSoftFloat() const {
552     return getSTI().getFeatureBits()[Mips::FeatureSoftFloat];
553   }
554 
555   /// Warn if RegIndex is the same as the current AT.
556   void warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc);
557 
558   void warnIfNoMacro(SMLoc Loc);
559 
560   bool isLittle() const { return IsLittleEndian; }
561 };
562 }
563 
564 namespace {
565 
566 /// MipsOperand - Instances of this class represent a parsed Mips machine
567 /// instruction.
568 class MipsOperand : public MCParsedAsmOperand {
569 public:
570   /// Broad categories of register classes
571   /// The exact class is finalized by the render method.
572   enum RegKind {
573     RegKind_GPR = 1,      /// GPR32 and GPR64 (depending on isGP64bit())
574     RegKind_FGR = 2,      /// FGR32, FGR64, AFGR64 (depending on context and
575                           /// isFP64bit())
576     RegKind_FCC = 4,      /// FCC
577     RegKind_MSA128 = 8,   /// MSA128[BHWD] (makes no difference which)
578     RegKind_MSACtrl = 16, /// MSA control registers
579     RegKind_COP2 = 32,    /// COP2
580     RegKind_ACC = 64,     /// HI32DSP, LO32DSP, and ACC64DSP (depending on
581                           /// context).
582     RegKind_CCR = 128,    /// CCR
583     RegKind_HWRegs = 256, /// HWRegs
584     RegKind_COP3 = 512,   /// COP3
585     RegKind_COP0 = 1024,  /// COP0
586     /// Potentially any (e.g. $1)
587     RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 |
588                       RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC |
589                       RegKind_CCR | RegKind_HWRegs | RegKind_COP3 | RegKind_COP0
590   };
591 
592 private:
593   enum KindTy {
594     k_Immediate,     /// An immediate (possibly involving symbol references)
595     k_Memory,        /// Base + Offset Memory Address
596     k_PhysRegister,  /// A physical register from the Mips namespace
597     k_RegisterIndex, /// A register index in one or more RegKind.
598     k_Token,         /// A simple token
599     k_RegList,       /// A physical register list
600     k_RegPair        /// A pair of physical register
601   } Kind;
602 
603 public:
604   MipsOperand(KindTy K, MipsAsmParser &Parser)
605       : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {}
606 
607 private:
608   /// For diagnostics, and checking the assembler temporary
609   MipsAsmParser &AsmParser;
610 
611   struct Token {
612     const char *Data;
613     unsigned Length;
614   };
615 
616   struct PhysRegOp {
617     unsigned Num; /// Register Number
618   };
619 
620   struct RegIdxOp {
621     unsigned Index; /// Index into the register class
622     RegKind Kind;   /// Bitfield of the kinds it could possibly be
623     const MCRegisterInfo *RegInfo;
624   };
625 
626   struct ImmOp {
627     const MCExpr *Val;
628   };
629 
630   struct MemOp {
631     MipsOperand *Base;
632     const MCExpr *Off;
633   };
634 
635   struct RegListOp {
636     SmallVector<unsigned, 10> *List;
637   };
638 
639   union {
640     struct Token Tok;
641     struct PhysRegOp PhysReg;
642     struct RegIdxOp RegIdx;
643     struct ImmOp Imm;
644     struct MemOp Mem;
645     struct RegListOp RegList;
646   };
647 
648   SMLoc StartLoc, EndLoc;
649 
650   /// Internal constructor for register kinds
651   static std::unique_ptr<MipsOperand> CreateReg(unsigned Index, RegKind RegKind,
652                                                 const MCRegisterInfo *RegInfo,
653                                                 SMLoc S, SMLoc E,
654                                                 MipsAsmParser &Parser) {
655     auto Op = make_unique<MipsOperand>(k_RegisterIndex, Parser);
656     Op->RegIdx.Index = Index;
657     Op->RegIdx.RegInfo = RegInfo;
658     Op->RegIdx.Kind = RegKind;
659     Op->StartLoc = S;
660     Op->EndLoc = E;
661     return Op;
662   }
663 
664 public:
665   /// Coerce the register to GPR32 and return the real register for the current
666   /// target.
667   unsigned getGPR32Reg() const {
668     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
669     AsmParser.warnIfRegIndexIsAT(RegIdx.Index, StartLoc);
670     unsigned ClassID = Mips::GPR32RegClassID;
671     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
672   }
673 
674   /// Coerce the register to GPR32 and return the real register for the current
675   /// target.
676   unsigned getGPRMM16Reg() const {
677     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
678     unsigned ClassID = Mips::GPR32RegClassID;
679     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
680   }
681 
682   /// Coerce the register to GPR64 and return the real register for the current
683   /// target.
684   unsigned getGPR64Reg() const {
685     assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!");
686     unsigned ClassID = Mips::GPR64RegClassID;
687     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
688   }
689 
690 private:
691   /// Coerce the register to AFGR64 and return the real register for the current
692   /// target.
693   unsigned getAFGR64Reg() const {
694     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
695     if (RegIdx.Index % 2 != 0)
696       AsmParser.Warning(StartLoc, "Float register should be even.");
697     return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID)
698         .getRegister(RegIdx.Index / 2);
699   }
700 
701   /// Coerce the register to FGR64 and return the real register for the current
702   /// target.
703   unsigned getFGR64Reg() const {
704     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
705     return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID)
706         .getRegister(RegIdx.Index);
707   }
708 
709   /// Coerce the register to FGR32 and return the real register for the current
710   /// target.
711   unsigned getFGR32Reg() const {
712     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
713     return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID)
714         .getRegister(RegIdx.Index);
715   }
716 
717   /// Coerce the register to FGRH32 and return the real register for the current
718   /// target.
719   unsigned getFGRH32Reg() const {
720     assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!");
721     return RegIdx.RegInfo->getRegClass(Mips::FGRH32RegClassID)
722         .getRegister(RegIdx.Index);
723   }
724 
725   /// Coerce the register to FCC and return the real register for the current
726   /// target.
727   unsigned getFCCReg() const {
728     assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!");
729     return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID)
730         .getRegister(RegIdx.Index);
731   }
732 
733   /// Coerce the register to MSA128 and return the real register for the current
734   /// target.
735   unsigned getMSA128Reg() const {
736     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!");
737     // It doesn't matter which of the MSA128[BHWD] classes we use. They are all
738     // identical
739     unsigned ClassID = Mips::MSA128BRegClassID;
740     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
741   }
742 
743   /// Coerce the register to MSACtrl and return the real register for the
744   /// current target.
745   unsigned getMSACtrlReg() const {
746     assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!");
747     unsigned ClassID = Mips::MSACtrlRegClassID;
748     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
749   }
750 
751   /// Coerce the register to COP0 and return the real register for the
752   /// current target.
753   unsigned getCOP0Reg() const {
754     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP0) && "Invalid access!");
755     unsigned ClassID = Mips::COP0RegClassID;
756     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
757   }
758 
759   /// Coerce the register to COP2 and return the real register for the
760   /// current target.
761   unsigned getCOP2Reg() const {
762     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!");
763     unsigned ClassID = Mips::COP2RegClassID;
764     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
765   }
766 
767   /// Coerce the register to COP3 and return the real register for the
768   /// current target.
769   unsigned getCOP3Reg() const {
770     assert(isRegIdx() && (RegIdx.Kind & RegKind_COP3) && "Invalid access!");
771     unsigned ClassID = Mips::COP3RegClassID;
772     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
773   }
774 
775   /// Coerce the register to ACC64DSP and return the real register for the
776   /// current target.
777   unsigned getACC64DSPReg() const {
778     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
779     unsigned ClassID = Mips::ACC64DSPRegClassID;
780     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
781   }
782 
783   /// Coerce the register to HI32DSP and return the real register for the
784   /// current target.
785   unsigned getHI32DSPReg() const {
786     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
787     unsigned ClassID = Mips::HI32DSPRegClassID;
788     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
789   }
790 
791   /// Coerce the register to LO32DSP and return the real register for the
792   /// current target.
793   unsigned getLO32DSPReg() const {
794     assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!");
795     unsigned ClassID = Mips::LO32DSPRegClassID;
796     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
797   }
798 
799   /// Coerce the register to CCR and return the real register for the
800   /// current target.
801   unsigned getCCRReg() const {
802     assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!");
803     unsigned ClassID = Mips::CCRRegClassID;
804     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
805   }
806 
807   /// Coerce the register to HWRegs and return the real register for the
808   /// current target.
809   unsigned getHWRegsReg() const {
810     assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!");
811     unsigned ClassID = Mips::HWRegsRegClassID;
812     return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index);
813   }
814 
815 public:
816   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
817     // Add as immediate when possible.  Null MCExpr = 0.
818     if (!Expr)
819       Inst.addOperand(MCOperand::createImm(0));
820     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
821       Inst.addOperand(MCOperand::createImm(CE->getValue()));
822     else
823       Inst.addOperand(MCOperand::createExpr(Expr));
824   }
825 
826   void addRegOperands(MCInst &Inst, unsigned N) const {
827     llvm_unreachable("Use a custom parser instead");
828   }
829 
830   /// Render the operand to an MCInst as a GPR32
831   /// Asserts if the wrong number of operands are requested, or the operand
832   /// is not a k_RegisterIndex compatible with RegKind_GPR
833   void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const {
834     assert(N == 1 && "Invalid number of operands!");
835     Inst.addOperand(MCOperand::createReg(getGPR32Reg()));
836   }
837 
838   void addGPRMM16AsmRegOperands(MCInst &Inst, unsigned N) const {
839     assert(N == 1 && "Invalid number of operands!");
840     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
841   }
842 
843   void addGPRMM16AsmRegZeroOperands(MCInst &Inst, unsigned N) const {
844     assert(N == 1 && "Invalid number of operands!");
845     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
846   }
847 
848   void addGPRMM16AsmRegMovePOperands(MCInst &Inst, unsigned N) const {
849     assert(N == 1 && "Invalid number of operands!");
850     Inst.addOperand(MCOperand::createReg(getGPRMM16Reg()));
851   }
852 
853   /// Render the operand to an MCInst as a GPR64
854   /// Asserts if the wrong number of operands are requested, or the operand
855   /// is not a k_RegisterIndex compatible with RegKind_GPR
856   void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const {
857     assert(N == 1 && "Invalid number of operands!");
858     Inst.addOperand(MCOperand::createReg(getGPR64Reg()));
859   }
860 
861   void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
862     assert(N == 1 && "Invalid number of operands!");
863     Inst.addOperand(MCOperand::createReg(getAFGR64Reg()));
864   }
865 
866   void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const {
867     assert(N == 1 && "Invalid number of operands!");
868     Inst.addOperand(MCOperand::createReg(getFGR64Reg()));
869   }
870 
871   void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const {
872     assert(N == 1 && "Invalid number of operands!");
873     Inst.addOperand(MCOperand::createReg(getFGR32Reg()));
874     // FIXME: We ought to do this for -integrated-as without -via-file-asm too.
875     if (!AsmParser.useOddSPReg() && RegIdx.Index & 1)
876       AsmParser.Error(StartLoc, "-mno-odd-spreg prohibits the use of odd FPU "
877                                 "registers");
878   }
879 
880   void addFGRH32AsmRegOperands(MCInst &Inst, unsigned N) const {
881     assert(N == 1 && "Invalid number of operands!");
882     Inst.addOperand(MCOperand::createReg(getFGRH32Reg()));
883   }
884 
885   void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const {
886     assert(N == 1 && "Invalid number of operands!");
887     Inst.addOperand(MCOperand::createReg(getFCCReg()));
888   }
889 
890   void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const {
891     assert(N == 1 && "Invalid number of operands!");
892     Inst.addOperand(MCOperand::createReg(getMSA128Reg()));
893   }
894 
895   void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const {
896     assert(N == 1 && "Invalid number of operands!");
897     Inst.addOperand(MCOperand::createReg(getMSACtrlReg()));
898   }
899 
900   void addCOP0AsmRegOperands(MCInst &Inst, unsigned N) const {
901     assert(N == 1 && "Invalid number of operands!");
902     Inst.addOperand(MCOperand::createReg(getCOP0Reg()));
903   }
904 
905   void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const {
906     assert(N == 1 && "Invalid number of operands!");
907     Inst.addOperand(MCOperand::createReg(getCOP2Reg()));
908   }
909 
910   void addCOP3AsmRegOperands(MCInst &Inst, unsigned N) const {
911     assert(N == 1 && "Invalid number of operands!");
912     Inst.addOperand(MCOperand::createReg(getCOP3Reg()));
913   }
914 
915   void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
916     assert(N == 1 && "Invalid number of operands!");
917     Inst.addOperand(MCOperand::createReg(getACC64DSPReg()));
918   }
919 
920   void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
921     assert(N == 1 && "Invalid number of operands!");
922     Inst.addOperand(MCOperand::createReg(getHI32DSPReg()));
923   }
924 
925   void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const {
926     assert(N == 1 && "Invalid number of operands!");
927     Inst.addOperand(MCOperand::createReg(getLO32DSPReg()));
928   }
929 
930   void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const {
931     assert(N == 1 && "Invalid number of operands!");
932     Inst.addOperand(MCOperand::createReg(getCCRReg()));
933   }
934 
935   void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const {
936     assert(N == 1 && "Invalid number of operands!");
937     Inst.addOperand(MCOperand::createReg(getHWRegsReg()));
938   }
939 
940   template <unsigned Bits, int Offset = 0, int AdjustOffset = 0>
941   void addConstantUImmOperands(MCInst &Inst, unsigned N) const {
942     assert(N == 1 && "Invalid number of operands!");
943     uint64_t Imm = getConstantImm() - Offset;
944     Imm &= (1 << Bits) - 1;
945     Imm += Offset;
946     Imm += AdjustOffset;
947     Inst.addOperand(MCOperand::createImm(Imm));
948   }
949 
950   template <unsigned Bits>
951   void addSImmOperands(MCInst &Inst, unsigned N) const {
952     if (isImm() && !isConstantImm()) {
953       addExpr(Inst, getImm());
954       return;
955     }
956     addConstantSImmOperands<Bits, 0, 0>(Inst, N);
957   }
958 
959   template <unsigned Bits>
960   void addUImmOperands(MCInst &Inst, unsigned N) const {
961     if (isImm() && !isConstantImm()) {
962       addExpr(Inst, getImm());
963       return;
964     }
965     addConstantUImmOperands<Bits, 0, 0>(Inst, N);
966   }
967 
968   template <unsigned Bits, int Offset = 0, int AdjustOffset = 0>
969   void addConstantSImmOperands(MCInst &Inst, unsigned N) const {
970     assert(N == 1 && "Invalid number of operands!");
971     int64_t Imm = getConstantImm() - Offset;
972     Imm = SignExtend64<Bits>(Imm);
973     Imm += Offset;
974     Imm += AdjustOffset;
975     Inst.addOperand(MCOperand::createImm(Imm));
976   }
977 
978   void addImmOperands(MCInst &Inst, unsigned N) const {
979     assert(N == 1 && "Invalid number of operands!");
980     const MCExpr *Expr = getImm();
981     addExpr(Inst, Expr);
982   }
983 
984   void addMemOperands(MCInst &Inst, unsigned N) const {
985     assert(N == 2 && "Invalid number of operands!");
986 
987     Inst.addOperand(MCOperand::createReg(AsmParser.getABI().ArePtrs64bit()
988                                              ? getMemBase()->getGPR64Reg()
989                                              : getMemBase()->getGPR32Reg()));
990 
991     const MCExpr *Expr = getMemOff();
992     addExpr(Inst, Expr);
993   }
994 
995   void addMicroMipsMemOperands(MCInst &Inst, unsigned N) const {
996     assert(N == 2 && "Invalid number of operands!");
997 
998     Inst.addOperand(MCOperand::createReg(getMemBase()->getGPRMM16Reg()));
999 
1000     const MCExpr *Expr = getMemOff();
1001     addExpr(Inst, Expr);
1002   }
1003 
1004   void addRegListOperands(MCInst &Inst, unsigned N) const {
1005     assert(N == 1 && "Invalid number of operands!");
1006 
1007     for (auto RegNo : getRegList())
1008       Inst.addOperand(MCOperand::createReg(RegNo));
1009   }
1010 
1011   void addRegPairOperands(MCInst &Inst, unsigned N) const {
1012     assert(N == 2 && "Invalid number of operands!");
1013     unsigned RegNo = getRegPair();
1014     Inst.addOperand(MCOperand::createReg(RegNo++));
1015     Inst.addOperand(MCOperand::createReg(RegNo));
1016   }
1017 
1018   void addMovePRegPairOperands(MCInst &Inst, unsigned N) const {
1019     assert(N == 2 && "Invalid number of operands!");
1020     for (auto RegNo : getRegList())
1021       Inst.addOperand(MCOperand::createReg(RegNo));
1022   }
1023 
1024   bool isReg() const override {
1025     // As a special case until we sort out the definition of div/divu, pretend
1026     // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
1027     if (isGPRAsmReg() && RegIdx.Index == 0)
1028       return true;
1029 
1030     return Kind == k_PhysRegister;
1031   }
1032   bool isRegIdx() const { return Kind == k_RegisterIndex; }
1033   bool isImm() const override { return Kind == k_Immediate; }
1034   bool isConstantImm() const {
1035     return isImm() && isa<MCConstantExpr>(getImm());
1036   }
1037   bool isConstantImmz() const {
1038     return isConstantImm() && getConstantImm() == 0;
1039   }
1040   template <unsigned Bits, int Offset = 0> bool isConstantUImm() const {
1041     return isConstantImm() && isUInt<Bits>(getConstantImm() - Offset);
1042   }
1043   template <unsigned Bits> bool isSImm() const {
1044     return isConstantImm() ? isInt<Bits>(getConstantImm()) : isImm();
1045   }
1046   template <unsigned Bits> bool isUImm() const {
1047     return isConstantImm() ? isUInt<Bits>(getConstantImm()) : isImm();
1048   }
1049   template <unsigned Bits> bool isAnyImm() const {
1050     return isConstantImm() ? (isInt<Bits>(getConstantImm()) ||
1051                               isUInt<Bits>(getConstantImm()))
1052                            : isImm();
1053   }
1054   template <unsigned Bits, int Offset = 0> bool isConstantSImm() const {
1055     return isConstantImm() && isInt<Bits>(getConstantImm() - Offset);
1056   }
1057   template <unsigned Bottom, unsigned Top> bool isConstantUImmRange() const {
1058     return isConstantImm() && getConstantImm() >= Bottom &&
1059            getConstantImm() <= Top;
1060   }
1061   bool isToken() const override {
1062     // Note: It's not possible to pretend that other operand kinds are tokens.
1063     // The matcher emitter checks tokens first.
1064     return Kind == k_Token;
1065   }
1066   bool isMem() const override { return Kind == k_Memory; }
1067   bool isConstantMemOff() const {
1068     return isMem() && isa<MCConstantExpr>(getMemOff());
1069   }
1070   template <unsigned Bits, unsigned ShiftAmount = 0>
1071   bool isMemWithSimmOffset() const {
1072     return isMem() && isConstantMemOff() &&
1073            isShiftedInt<Bits, ShiftAmount>(getConstantMemOff()) &&
1074            getMemBase()->isGPRAsmReg();
1075   }
1076   template <unsigned Bits> bool isMemWithSimmOffsetGPR() const {
1077     return isMem() && isConstantMemOff() && isInt<Bits>(getConstantMemOff()) &&
1078            getMemBase()->isGPRAsmReg();
1079   }
1080   bool isMemWithGRPMM16Base() const {
1081     return isMem() && getMemBase()->isMM16AsmReg();
1082   }
1083   template <unsigned Bits> bool isMemWithUimmOffsetSP() const {
1084     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
1085       && getMemBase()->isRegIdx() && (getMemBase()->getGPR32Reg() == Mips::SP);
1086   }
1087   template <unsigned Bits> bool isMemWithUimmWordAlignedOffsetSP() const {
1088     return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff())
1089       && (getConstantMemOff() % 4 == 0) && getMemBase()->isRegIdx()
1090       && (getMemBase()->getGPR32Reg() == Mips::SP);
1091   }
1092   template <unsigned Bits, unsigned ShiftLeftAmount>
1093   bool isScaledUImm() const {
1094     return isConstantImm() &&
1095            isShiftedUInt<Bits, ShiftLeftAmount>(getConstantImm());
1096   }
1097   template <unsigned Bits, unsigned ShiftLeftAmount>
1098   bool isScaledSImm() const {
1099     return isConstantImm() &&
1100            isShiftedInt<Bits, ShiftLeftAmount>(getConstantImm());
1101   }
1102   bool isRegList16() const {
1103     if (!isRegList())
1104       return false;
1105 
1106     int Size = RegList.List->size();
1107     if (Size < 2 || Size > 5)
1108       return false;
1109 
1110     unsigned R0 = RegList.List->front();
1111     unsigned R1 = RegList.List->back();
1112     if (!((R0 == Mips::S0 && R1 == Mips::RA) ||
1113           (R0 == Mips::S0_64 && R1 == Mips::RA_64)))
1114       return false;
1115 
1116     int PrevReg = *RegList.List->begin();
1117     for (int i = 1; i < Size - 1; i++) {
1118       int Reg = (*(RegList.List))[i];
1119       if ( Reg != PrevReg + 1)
1120         return false;
1121       PrevReg = Reg;
1122     }
1123 
1124     return true;
1125   }
1126   bool isInvNum() const { return Kind == k_Immediate; }
1127   bool isLSAImm() const {
1128     if (!isConstantImm())
1129       return false;
1130     int64_t Val = getConstantImm();
1131     return 1 <= Val && Val <= 4;
1132   }
1133   bool isRegList() const { return Kind == k_RegList; }
1134   bool isMovePRegPair() const {
1135     if (Kind != k_RegList || RegList.List->size() != 2)
1136       return false;
1137 
1138     unsigned R0 = RegList.List->front();
1139     unsigned R1 = RegList.List->back();
1140 
1141     if ((R0 == Mips::A1 && R1 == Mips::A2) ||
1142         (R0 == Mips::A1 && R1 == Mips::A3) ||
1143         (R0 == Mips::A2 && R1 == Mips::A3) ||
1144         (R0 == Mips::A0 && R1 == Mips::S5) ||
1145         (R0 == Mips::A0 && R1 == Mips::S6) ||
1146         (R0 == Mips::A0 && R1 == Mips::A1) ||
1147         (R0 == Mips::A0 && R1 == Mips::A2) ||
1148         (R0 == Mips::A0 && R1 == Mips::A3))
1149       return true;
1150 
1151     return false;
1152   }
1153 
1154   StringRef getToken() const {
1155     assert(Kind == k_Token && "Invalid access!");
1156     return StringRef(Tok.Data, Tok.Length);
1157   }
1158   bool isRegPair() const { return Kind == k_RegPair; }
1159 
1160   unsigned getReg() const override {
1161     // As a special case until we sort out the definition of div/divu, pretend
1162     // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly.
1163     if (Kind == k_RegisterIndex && RegIdx.Index == 0 &&
1164         RegIdx.Kind & RegKind_GPR)
1165       return getGPR32Reg(); // FIXME: GPR64 too
1166 
1167     assert(Kind == k_PhysRegister && "Invalid access!");
1168     return PhysReg.Num;
1169   }
1170 
1171   const MCExpr *getImm() const {
1172     assert((Kind == k_Immediate) && "Invalid access!");
1173     return Imm.Val;
1174   }
1175 
1176   int64_t getConstantImm() const {
1177     const MCExpr *Val = getImm();
1178     return static_cast<const MCConstantExpr *>(Val)->getValue();
1179   }
1180 
1181   MipsOperand *getMemBase() const {
1182     assert((Kind == k_Memory) && "Invalid access!");
1183     return Mem.Base;
1184   }
1185 
1186   const MCExpr *getMemOff() const {
1187     assert((Kind == k_Memory) && "Invalid access!");
1188     return Mem.Off;
1189   }
1190 
1191   int64_t getConstantMemOff() const {
1192     return static_cast<const MCConstantExpr *>(getMemOff())->getValue();
1193   }
1194 
1195   const SmallVectorImpl<unsigned> &getRegList() const {
1196     assert((Kind == k_RegList) && "Invalid access!");
1197     return *(RegList.List);
1198   }
1199 
1200   unsigned getRegPair() const {
1201     assert((Kind == k_RegPair) && "Invalid access!");
1202     return RegIdx.Index;
1203   }
1204 
1205   static std::unique_ptr<MipsOperand> CreateToken(StringRef Str, SMLoc S,
1206                                                   MipsAsmParser &Parser) {
1207     auto Op = make_unique<MipsOperand>(k_Token, Parser);
1208     Op->Tok.Data = Str.data();
1209     Op->Tok.Length = Str.size();
1210     Op->StartLoc = S;
1211     Op->EndLoc = S;
1212     return Op;
1213   }
1214 
1215   /// Create a numeric register (e.g. $1). The exact register remains
1216   /// unresolved until an instruction successfully matches
1217   static std::unique_ptr<MipsOperand>
1218   createNumericReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
1219                    SMLoc E, MipsAsmParser &Parser) {
1220     DEBUG(dbgs() << "createNumericReg(" << Index << ", ...)\n");
1221     return CreateReg(Index, RegKind_Numeric, RegInfo, S, E, Parser);
1222   }
1223 
1224   /// Create a register that is definitely a GPR.
1225   /// This is typically only used for named registers such as $gp.
1226   static std::unique_ptr<MipsOperand>
1227   createGPRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
1228                MipsAsmParser &Parser) {
1229     return CreateReg(Index, RegKind_GPR, RegInfo, S, E, Parser);
1230   }
1231 
1232   /// Create a register that is definitely a FGR.
1233   /// This is typically only used for named registers such as $f0.
1234   static std::unique_ptr<MipsOperand>
1235   createFGRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
1236                MipsAsmParser &Parser) {
1237     return CreateReg(Index, RegKind_FGR, RegInfo, S, E, Parser);
1238   }
1239 
1240   /// Create a register that is definitely a HWReg.
1241   /// This is typically only used for named registers such as $hwr_cpunum.
1242   static std::unique_ptr<MipsOperand>
1243   createHWRegsReg(unsigned Index, const MCRegisterInfo *RegInfo,
1244                   SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1245     return CreateReg(Index, RegKind_HWRegs, RegInfo, S, E, Parser);
1246   }
1247 
1248   /// Create a register that is definitely an FCC.
1249   /// This is typically only used for named registers such as $fcc0.
1250   static std::unique_ptr<MipsOperand>
1251   createFCCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
1252                MipsAsmParser &Parser) {
1253     return CreateReg(Index, RegKind_FCC, RegInfo, S, E, Parser);
1254   }
1255 
1256   /// Create a register that is definitely an ACC.
1257   /// This is typically only used for named registers such as $ac0.
1258   static std::unique_ptr<MipsOperand>
1259   createACCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E,
1260                MipsAsmParser &Parser) {
1261     return CreateReg(Index, RegKind_ACC, RegInfo, S, E, Parser);
1262   }
1263 
1264   /// Create a register that is definitely an MSA128.
1265   /// This is typically only used for named registers such as $w0.
1266   static std::unique_ptr<MipsOperand>
1267   createMSA128Reg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
1268                   SMLoc E, MipsAsmParser &Parser) {
1269     return CreateReg(Index, RegKind_MSA128, RegInfo, S, E, Parser);
1270   }
1271 
1272   /// Create a register that is definitely an MSACtrl.
1273   /// This is typically only used for named registers such as $msaaccess.
1274   static std::unique_ptr<MipsOperand>
1275   createMSACtrlReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S,
1276                    SMLoc E, MipsAsmParser &Parser) {
1277     return CreateReg(Index, RegKind_MSACtrl, RegInfo, S, E, Parser);
1278   }
1279 
1280   static std::unique_ptr<MipsOperand>
1281   CreateImm(const MCExpr *Val, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1282     auto Op = make_unique<MipsOperand>(k_Immediate, Parser);
1283     Op->Imm.Val = Val;
1284     Op->StartLoc = S;
1285     Op->EndLoc = E;
1286     return Op;
1287   }
1288 
1289   static std::unique_ptr<MipsOperand>
1290   CreateMem(std::unique_ptr<MipsOperand> Base, const MCExpr *Off, SMLoc S,
1291             SMLoc E, MipsAsmParser &Parser) {
1292     auto Op = make_unique<MipsOperand>(k_Memory, Parser);
1293     Op->Mem.Base = Base.release();
1294     Op->Mem.Off = Off;
1295     Op->StartLoc = S;
1296     Op->EndLoc = E;
1297     return Op;
1298   }
1299 
1300   static std::unique_ptr<MipsOperand>
1301   CreateRegList(SmallVectorImpl<unsigned> &Regs, SMLoc StartLoc, SMLoc EndLoc,
1302                 MipsAsmParser &Parser) {
1303     assert (Regs.size() > 0 && "Empty list not allowed");
1304 
1305     auto Op = make_unique<MipsOperand>(k_RegList, Parser);
1306     Op->RegList.List = new SmallVector<unsigned, 10>(Regs.begin(), Regs.end());
1307     Op->StartLoc = StartLoc;
1308     Op->EndLoc = EndLoc;
1309     return Op;
1310   }
1311 
1312   static std::unique_ptr<MipsOperand>
1313   CreateRegPair(unsigned RegNo, SMLoc S, SMLoc E, MipsAsmParser &Parser) {
1314     auto Op = make_unique<MipsOperand>(k_RegPair, Parser);
1315     Op->RegIdx.Index = RegNo;
1316     Op->StartLoc = S;
1317     Op->EndLoc = E;
1318     return Op;
1319   }
1320 
1321   bool isGPRAsmReg() const {
1322     return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31;
1323   }
1324   bool isMM16AsmReg() const {
1325     if (!(isRegIdx() && RegIdx.Kind))
1326       return false;
1327     return ((RegIdx.Index >= 2 && RegIdx.Index <= 7)
1328             || RegIdx.Index == 16 || RegIdx.Index == 17);
1329   }
1330   bool isMM16AsmRegZero() const {
1331     if (!(isRegIdx() && RegIdx.Kind))
1332       return false;
1333     return (RegIdx.Index == 0 ||
1334             (RegIdx.Index >= 2 && RegIdx.Index <= 7) ||
1335             RegIdx.Index == 17);
1336   }
1337   bool isMM16AsmRegMoveP() const {
1338     if (!(isRegIdx() && RegIdx.Kind))
1339       return false;
1340     return (RegIdx.Index == 0 || (RegIdx.Index >= 2 && RegIdx.Index <= 3) ||
1341       (RegIdx.Index >= 16 && RegIdx.Index <= 20));
1342   }
1343   bool isFGRAsmReg() const {
1344     // AFGR64 is $0-$15 but we handle this in getAFGR64()
1345     return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31;
1346   }
1347   bool isHWRegsAsmReg() const {
1348     return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31;
1349   }
1350   bool isCCRAsmReg() const {
1351     return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31;
1352   }
1353   bool isFCCAsmReg() const {
1354     if (!(isRegIdx() && RegIdx.Kind & RegKind_FCC))
1355       return false;
1356     if (!AsmParser.hasEightFccRegisters())
1357       return RegIdx.Index == 0;
1358     return RegIdx.Index <= 7;
1359   }
1360   bool isACCAsmReg() const {
1361     return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3;
1362   }
1363   bool isCOP0AsmReg() const {
1364     return isRegIdx() && RegIdx.Kind & RegKind_COP0 && RegIdx.Index <= 31;
1365   }
1366   bool isCOP2AsmReg() const {
1367     return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31;
1368   }
1369   bool isCOP3AsmReg() const {
1370     return isRegIdx() && RegIdx.Kind & RegKind_COP3 && RegIdx.Index <= 31;
1371   }
1372   bool isMSA128AsmReg() const {
1373     return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31;
1374   }
1375   bool isMSACtrlAsmReg() const {
1376     return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7;
1377   }
1378 
1379   /// getStartLoc - Get the location of the first token of this operand.
1380   SMLoc getStartLoc() const override { return StartLoc; }
1381   /// getEndLoc - Get the location of the last token of this operand.
1382   SMLoc getEndLoc() const override { return EndLoc; }
1383 
1384   virtual ~MipsOperand() {
1385     switch (Kind) {
1386     case k_Immediate:
1387       break;
1388     case k_Memory:
1389       delete Mem.Base;
1390       break;
1391     case k_RegList:
1392       delete RegList.List;
1393     case k_PhysRegister:
1394     case k_RegisterIndex:
1395     case k_Token:
1396     case k_RegPair:
1397       break;
1398     }
1399   }
1400 
1401   void print(raw_ostream &OS) const override {
1402     switch (Kind) {
1403     case k_Immediate:
1404       OS << "Imm<";
1405       OS << *Imm.Val;
1406       OS << ">";
1407       break;
1408     case k_Memory:
1409       OS << "Mem<";
1410       Mem.Base->print(OS);
1411       OS << ", ";
1412       OS << *Mem.Off;
1413       OS << ">";
1414       break;
1415     case k_PhysRegister:
1416       OS << "PhysReg<" << PhysReg.Num << ">";
1417       break;
1418     case k_RegisterIndex:
1419       OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ">";
1420       break;
1421     case k_Token:
1422       OS << Tok.Data;
1423       break;
1424     case k_RegList:
1425       OS << "RegList< ";
1426       for (auto Reg : (*RegList.List))
1427         OS << Reg << " ";
1428       OS <<  ">";
1429       break;
1430     case k_RegPair:
1431       OS << "RegPair<" << RegIdx.Index << "," << RegIdx.Index + 1 << ">";
1432       break;
1433     }
1434   }
1435 }; // class MipsOperand
1436 } // namespace
1437 
1438 namespace llvm {
1439 extern const MCInstrDesc MipsInsts[];
1440 }
1441 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
1442   return MipsInsts[Opcode];
1443 }
1444 
1445 static bool hasShortDelaySlot(unsigned Opcode) {
1446   switch (Opcode) {
1447     case Mips::JALS_MM:
1448     case Mips::JALRS_MM:
1449     case Mips::JALRS16_MM:
1450     case Mips::BGEZALS_MM:
1451     case Mips::BLTZALS_MM:
1452       return true;
1453     default:
1454       return false;
1455   }
1456 }
1457 
1458 static const MCSymbol *getSingleMCSymbol(const MCExpr *Expr) {
1459   if (const MCSymbolRefExpr *SRExpr = dyn_cast<MCSymbolRefExpr>(Expr)) {
1460     return &SRExpr->getSymbol();
1461   }
1462 
1463   if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr)) {
1464     const MCSymbol *LHSSym = getSingleMCSymbol(BExpr->getLHS());
1465     const MCSymbol *RHSSym = getSingleMCSymbol(BExpr->getRHS());
1466 
1467     if (LHSSym)
1468       return LHSSym;
1469 
1470     if (RHSSym)
1471       return RHSSym;
1472 
1473     return nullptr;
1474   }
1475 
1476   if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr))
1477     return getSingleMCSymbol(UExpr->getSubExpr());
1478 
1479   return nullptr;
1480 }
1481 
1482 static unsigned countMCSymbolRefExpr(const MCExpr *Expr) {
1483   if (isa<MCSymbolRefExpr>(Expr))
1484     return 1;
1485 
1486   if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr))
1487     return countMCSymbolRefExpr(BExpr->getLHS()) +
1488            countMCSymbolRefExpr(BExpr->getRHS());
1489 
1490   if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr))
1491     return countMCSymbolRefExpr(UExpr->getSubExpr());
1492 
1493   return 0;
1494 }
1495 
1496 namespace {
1497 void emitRX(unsigned Opcode, unsigned Reg0, MCOperand Op1, SMLoc IDLoc,
1498             SmallVectorImpl<MCInst> &Instructions) {
1499   MCInst tmpInst;
1500   tmpInst.setOpcode(Opcode);
1501   tmpInst.addOperand(MCOperand::createReg(Reg0));
1502   tmpInst.addOperand(Op1);
1503   tmpInst.setLoc(IDLoc);
1504   Instructions.push_back(tmpInst);
1505 }
1506 
1507 void emitRI(unsigned Opcode, unsigned Reg0, int32_t Imm, SMLoc IDLoc,
1508             SmallVectorImpl<MCInst> &Instructions) {
1509   emitRX(Opcode, Reg0, MCOperand::createImm(Imm), IDLoc, Instructions);
1510 }
1511 
1512 void emitRR(unsigned Opcode, unsigned Reg0, unsigned Reg1, SMLoc IDLoc,
1513             SmallVectorImpl<MCInst> &Instructions) {
1514   emitRX(Opcode, Reg0, MCOperand::createReg(Reg1), IDLoc, Instructions);
1515 }
1516 
1517 void emitII(unsigned Opcode, int16_t Imm1, int16_t Imm2, SMLoc IDLoc,
1518             SmallVectorImpl<MCInst> &Instructions) {
1519   MCInst tmpInst;
1520   tmpInst.setOpcode(Opcode);
1521   tmpInst.addOperand(MCOperand::createImm(Imm1));
1522   tmpInst.addOperand(MCOperand::createImm(Imm2));
1523   tmpInst.setLoc(IDLoc);
1524   Instructions.push_back(tmpInst);
1525 }
1526 
1527 void emitR(unsigned Opcode, unsigned Reg0, SMLoc IDLoc,
1528            SmallVectorImpl<MCInst> &Instructions) {
1529   MCInst tmpInst;
1530   tmpInst.setOpcode(Opcode);
1531   tmpInst.addOperand(MCOperand::createReg(Reg0));
1532   tmpInst.setLoc(IDLoc);
1533   Instructions.push_back(tmpInst);
1534 }
1535 
1536 void emitRRX(unsigned Opcode, unsigned Reg0, unsigned Reg1, MCOperand Op2,
1537              SMLoc IDLoc, SmallVectorImpl<MCInst> &Instructions) {
1538   MCInst tmpInst;
1539   tmpInst.setOpcode(Opcode);
1540   tmpInst.addOperand(MCOperand::createReg(Reg0));
1541   tmpInst.addOperand(MCOperand::createReg(Reg1));
1542   tmpInst.addOperand(Op2);
1543   tmpInst.setLoc(IDLoc);
1544   Instructions.push_back(tmpInst);
1545 }
1546 
1547 void emitRRR(unsigned Opcode, unsigned Reg0, unsigned Reg1, unsigned Reg2,
1548              SMLoc IDLoc, SmallVectorImpl<MCInst> &Instructions) {
1549   emitRRX(Opcode, Reg0, Reg1, MCOperand::createReg(Reg2), IDLoc,
1550           Instructions);
1551 }
1552 
1553 void emitRRI(unsigned Opcode, unsigned Reg0, unsigned Reg1, int16_t Imm,
1554              SMLoc IDLoc, SmallVectorImpl<MCInst> &Instructions) {
1555   emitRRX(Opcode, Reg0, Reg1, MCOperand::createImm(Imm), IDLoc,
1556           Instructions);
1557 }
1558 
1559 void emitAppropriateDSLL(unsigned DstReg, unsigned SrcReg, int16_t ShiftAmount,
1560                          SMLoc IDLoc, SmallVectorImpl<MCInst> &Instructions) {
1561   if (ShiftAmount >= 32) {
1562     emitRRI(Mips::DSLL32, DstReg, SrcReg, ShiftAmount - 32, IDLoc,
1563             Instructions);
1564     return;
1565   }
1566 
1567   emitRRI(Mips::DSLL, DstReg, SrcReg, ShiftAmount, IDLoc, Instructions);
1568 }
1569 } // end anonymous namespace.
1570 
1571 bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
1572                                        SmallVectorImpl<MCInst> &Instructions) {
1573   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
1574   bool ExpandedJalSym = false;
1575 
1576   Inst.setLoc(IDLoc);
1577 
1578   if (MCID.isBranch() || MCID.isCall()) {
1579     const unsigned Opcode = Inst.getOpcode();
1580     MCOperand Offset;
1581 
1582     switch (Opcode) {
1583     default:
1584       break;
1585     case Mips::BBIT0:
1586     case Mips::BBIT032:
1587     case Mips::BBIT1:
1588     case Mips::BBIT132:
1589       assert(hasCnMips() && "instruction only valid for octeon cpus");
1590       // Fall through
1591 
1592     case Mips::BEQ:
1593     case Mips::BNE:
1594     case Mips::BEQ_MM:
1595     case Mips::BNE_MM:
1596       assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1597       Offset = Inst.getOperand(2);
1598       if (!Offset.isImm())
1599         break; // We'll deal with this situation later on when applying fixups.
1600       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1601         return Error(IDLoc, "branch target out of range");
1602       if (OffsetToAlignment(Offset.getImm(),
1603                             1LL << (inMicroMipsMode() ? 1 : 2)))
1604         return Error(IDLoc, "branch to misaligned address");
1605       break;
1606     case Mips::BGEZ:
1607     case Mips::BGTZ:
1608     case Mips::BLEZ:
1609     case Mips::BLTZ:
1610     case Mips::BGEZAL:
1611     case Mips::BLTZAL:
1612     case Mips::BC1F:
1613     case Mips::BC1T:
1614     case Mips::BGEZ_MM:
1615     case Mips::BGTZ_MM:
1616     case Mips::BLEZ_MM:
1617     case Mips::BLTZ_MM:
1618     case Mips::BGEZAL_MM:
1619     case Mips::BLTZAL_MM:
1620     case Mips::BC1F_MM:
1621     case Mips::BC1T_MM:
1622       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1623       Offset = Inst.getOperand(1);
1624       if (!Offset.isImm())
1625         break; // We'll deal with this situation later on when applying fixups.
1626       if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm()))
1627         return Error(IDLoc, "branch target out of range");
1628       if (OffsetToAlignment(Offset.getImm(),
1629                             1LL << (inMicroMipsMode() ? 1 : 2)))
1630         return Error(IDLoc, "branch to misaligned address");
1631       break;
1632     case Mips::BEQZ16_MM:
1633     case Mips::BEQZC16_MMR6:
1634     case Mips::BNEZ16_MM:
1635     case Mips::BNEZC16_MMR6:
1636       assert(MCID.getNumOperands() == 2 && "unexpected number of operands");
1637       Offset = Inst.getOperand(1);
1638       if (!Offset.isImm())
1639         break; // We'll deal with this situation later on when applying fixups.
1640       if (!isInt<8>(Offset.getImm()))
1641         return Error(IDLoc, "branch target out of range");
1642       if (OffsetToAlignment(Offset.getImm(), 2LL))
1643         return Error(IDLoc, "branch to misaligned address");
1644       break;
1645     }
1646   }
1647 
1648   // SSNOP is deprecated on MIPS32r6/MIPS64r6
1649   // We still accept it but it is a normal nop.
1650   if (hasMips32r6() && Inst.getOpcode() == Mips::SSNOP) {
1651     std::string ISA = hasMips64r6() ? "MIPS64r6" : "MIPS32r6";
1652     Warning(IDLoc, "ssnop is deprecated for " + ISA + " and is equivalent to a "
1653                                                       "nop instruction");
1654   }
1655 
1656   if (hasCnMips()) {
1657     const unsigned Opcode = Inst.getOpcode();
1658     MCOperand Opnd;
1659     int Imm;
1660 
1661     switch (Opcode) {
1662       default:
1663         break;
1664 
1665       case Mips::BBIT0:
1666       case Mips::BBIT032:
1667       case Mips::BBIT1:
1668       case Mips::BBIT132:
1669         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1670         // The offset is handled above
1671         Opnd = Inst.getOperand(1);
1672         if (!Opnd.isImm())
1673           return Error(IDLoc, "expected immediate operand kind");
1674         Imm = Opnd.getImm();
1675         if (Imm < 0 || Imm > (Opcode == Mips::BBIT0 ||
1676                               Opcode == Mips::BBIT1 ? 63 : 31))
1677           return Error(IDLoc, "immediate operand value out of range");
1678         if (Imm > 31) {
1679           Inst.setOpcode(Opcode == Mips::BBIT0 ? Mips::BBIT032
1680                                                : Mips::BBIT132);
1681           Inst.getOperand(1).setImm(Imm - 32);
1682         }
1683         break;
1684 
1685       case Mips::SEQi:
1686       case Mips::SNEi:
1687         assert(MCID.getNumOperands() == 3 && "unexpected number of operands");
1688         Opnd = Inst.getOperand(2);
1689         if (!Opnd.isImm())
1690           return Error(IDLoc, "expected immediate operand kind");
1691         Imm = Opnd.getImm();
1692         if (!isInt<10>(Imm))
1693           return Error(IDLoc, "immediate operand value out of range");
1694         break;
1695     }
1696   }
1697 
1698   // This expansion is not in a function called by tryExpandInstruction()
1699   // because the pseudo-instruction doesn't have a distinct opcode.
1700   if ((Inst.getOpcode() == Mips::JAL || Inst.getOpcode() == Mips::JAL_MM) &&
1701       inPicMode()) {
1702     warnIfNoMacro(IDLoc);
1703 
1704     const MCExpr *JalExpr = Inst.getOperand(0).getExpr();
1705 
1706     // We can do this expansion if there's only 1 symbol in the argument
1707     // expression.
1708     if (countMCSymbolRefExpr(JalExpr) > 1)
1709       return Error(IDLoc, "jal doesn't support multiple symbols in PIC mode");
1710 
1711     // FIXME: This is checking the expression can be handled by the later stages
1712     //        of the assembler. We ought to leave it to those later stages but
1713     //        we can't do that until we stop evaluateRelocExpr() rewriting the
1714     //        expressions into non-equivalent forms.
1715     const MCSymbol *JalSym = getSingleMCSymbol(JalExpr);
1716 
1717     // FIXME: Add support for label+offset operands (currently causes an error).
1718     // FIXME: Add support for forward-declared local symbols.
1719     // FIXME: Add expansion for when the LargeGOT option is enabled.
1720     if (JalSym->isInSection() || JalSym->isTemporary()) {
1721       if (isABI_O32()) {
1722         // If it's a local symbol and the O32 ABI is being used, we expand to:
1723         //  lw $25, 0($gp)
1724         //    R_(MICRO)MIPS_GOT16  label
1725         //  addiu $25, $25, 0
1726         //    R_(MICRO)MIPS_LO16   label
1727         //  jalr  $25
1728         const MCExpr *Got16RelocExpr = evaluateRelocExpr(JalExpr, "got");
1729         const MCExpr *Lo16RelocExpr = evaluateRelocExpr(JalExpr, "lo");
1730 
1731         emitRRX(Mips::LW, Mips::T9, Mips::GP,
1732                 MCOperand::createExpr(Got16RelocExpr), IDLoc, Instructions);
1733         emitRRX(Mips::ADDiu, Mips::T9, Mips::T9,
1734                 MCOperand::createExpr(Lo16RelocExpr), IDLoc, Instructions);
1735       } else if (isABI_N32() || isABI_N64()) {
1736         // If it's a local symbol and the N32/N64 ABIs are being used,
1737         // we expand to:
1738         //  lw/ld $25, 0($gp)
1739         //    R_(MICRO)MIPS_GOT_DISP  label
1740         //  jalr  $25
1741         const MCExpr *GotDispRelocExpr = evaluateRelocExpr(JalExpr, "got_disp");
1742 
1743         emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9, Mips::GP,
1744                 MCOperand::createExpr(GotDispRelocExpr), IDLoc, Instructions);
1745       }
1746     } else {
1747       // If it's an external/weak symbol, we expand to:
1748       //  lw/ld    $25, 0($gp)
1749       //    R_(MICRO)MIPS_CALL16  label
1750       //  jalr  $25
1751       const MCExpr *Call16RelocExpr = evaluateRelocExpr(JalExpr, "call16");
1752 
1753       emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9, Mips::GP,
1754               MCOperand::createExpr(Call16RelocExpr), IDLoc, Instructions);
1755     }
1756 
1757     MCInst JalrInst;
1758     if (IsCpRestoreSet && inMicroMipsMode())
1759       JalrInst.setOpcode(Mips::JALRS_MM);
1760     else
1761       JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR);
1762     JalrInst.addOperand(MCOperand::createReg(Mips::RA));
1763     JalrInst.addOperand(MCOperand::createReg(Mips::T9));
1764 
1765     // FIXME: Add an R_(MICRO)MIPS_JALR relocation after the JALR.
1766     // This relocation is supposed to be an optimization hint for the linker
1767     // and is not necessary for correctness.
1768 
1769     Inst = JalrInst;
1770     ExpandedJalSym = true;
1771   }
1772 
1773   if (MCID.mayLoad() || MCID.mayStore()) {
1774     // Check the offset of memory operand, if it is a symbol
1775     // reference or immediate we may have to expand instructions.
1776     for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
1777       const MCOperandInfo &OpInfo = MCID.OpInfo[i];
1778       if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
1779           (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
1780         MCOperand &Op = Inst.getOperand(i);
1781         if (Op.isImm()) {
1782           int MemOffset = Op.getImm();
1783           if (MemOffset < -32768 || MemOffset > 32767) {
1784             // Offset can't exceed 16bit value.
1785             expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), true);
1786             return false;
1787           }
1788         } else if (Op.isExpr()) {
1789           const MCExpr *Expr = Op.getExpr();
1790           if (Expr->getKind() == MCExpr::SymbolRef) {
1791             const MCSymbolRefExpr *SR =
1792                 static_cast<const MCSymbolRefExpr *>(Expr);
1793             if (SR->getKind() == MCSymbolRefExpr::VK_None) {
1794               // Expand symbol.
1795               expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
1796               return false;
1797             }
1798           } else if (!isEvaluated(Expr)) {
1799             expandMemInst(Inst, IDLoc, Instructions, MCID.mayLoad(), false);
1800             return false;
1801           }
1802         }
1803       }
1804     } // for
1805   }   // if load/store
1806 
1807   if (inMicroMipsMode()) {
1808     if (MCID.mayLoad()) {
1809       // Try to create 16-bit GP relative load instruction.
1810       for (unsigned i = 0; i < MCID.getNumOperands(); i++) {
1811         const MCOperandInfo &OpInfo = MCID.OpInfo[i];
1812         if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) ||
1813             (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) {
1814           MCOperand &Op = Inst.getOperand(i);
1815           if (Op.isImm()) {
1816             int MemOffset = Op.getImm();
1817             MCOperand &DstReg = Inst.getOperand(0);
1818             MCOperand &BaseReg = Inst.getOperand(1);
1819             if (isInt<9>(MemOffset) && (MemOffset % 4 == 0) &&
1820                 getContext().getRegisterInfo()->getRegClass(
1821                   Mips::GPRMM16RegClassID).contains(DstReg.getReg()) &&
1822                 (BaseReg.getReg() == Mips::GP ||
1823                 BaseReg.getReg() == Mips::GP_64)) {
1824 
1825               emitRRI(Mips::LWGP_MM, DstReg.getReg(), Mips::GP, MemOffset,
1826                       IDLoc, Instructions);
1827               return false;
1828             }
1829           }
1830         }
1831       } // for
1832     }   // if load
1833 
1834     // TODO: Handle this with the AsmOperandClass.PredicateMethod.
1835 
1836     MCOperand Opnd;
1837     int Imm;
1838 
1839     switch (Inst.getOpcode()) {
1840       default:
1841         break;
1842       case Mips::ADDIUSP_MM:
1843         Opnd = Inst.getOperand(0);
1844         if (!Opnd.isImm())
1845           return Error(IDLoc, "expected immediate operand kind");
1846         Imm = Opnd.getImm();
1847         if (Imm < -1032 || Imm > 1028 || (Imm < 8 && Imm > -12) ||
1848             Imm % 4 != 0)
1849           return Error(IDLoc, "immediate operand value out of range");
1850         break;
1851       case Mips::SLL16_MM:
1852       case Mips::SRL16_MM:
1853         Opnd = Inst.getOperand(2);
1854         if (!Opnd.isImm())
1855           return Error(IDLoc, "expected immediate operand kind");
1856         Imm = Opnd.getImm();
1857         if (Imm < 1 || Imm > 8)
1858           return Error(IDLoc, "immediate operand value out of range");
1859         break;
1860       case Mips::LI16_MM:
1861         Opnd = Inst.getOperand(1);
1862         if (!Opnd.isImm())
1863           return Error(IDLoc, "expected immediate operand kind");
1864         Imm = Opnd.getImm();
1865         if (Imm < -1 || Imm > 126)
1866           return Error(IDLoc, "immediate operand value out of range");
1867         break;
1868       case Mips::ADDIUR2_MM:
1869         Opnd = Inst.getOperand(2);
1870         if (!Opnd.isImm())
1871           return Error(IDLoc, "expected immediate operand kind");
1872         Imm = Opnd.getImm();
1873         if (!(Imm == 1 || Imm == -1 ||
1874               ((Imm % 4 == 0) && Imm < 28 && Imm > 0)))
1875           return Error(IDLoc, "immediate operand value out of range");
1876         break;
1877       case Mips::ANDI16_MM:
1878         Opnd = Inst.getOperand(2);
1879         if (!Opnd.isImm())
1880           return Error(IDLoc, "expected immediate operand kind");
1881         Imm = Opnd.getImm();
1882         if (!(Imm == 128 || (Imm >= 1 && Imm <= 4) || Imm == 7 || Imm == 8 ||
1883               Imm == 15 || Imm == 16 || Imm == 31 || Imm == 32 || Imm == 63 ||
1884               Imm == 64 || Imm == 255 || Imm == 32768 || Imm == 65535))
1885           return Error(IDLoc, "immediate operand value out of range");
1886         break;
1887       case Mips::LBU16_MM:
1888         Opnd = Inst.getOperand(2);
1889         if (!Opnd.isImm())
1890           return Error(IDLoc, "expected immediate operand kind");
1891         Imm = Opnd.getImm();
1892         if (Imm < -1 || Imm > 14)
1893           return Error(IDLoc, "immediate operand value out of range");
1894         break;
1895       case Mips::SB16_MM:
1896       case Mips::SB16_MMR6:
1897         Opnd = Inst.getOperand(2);
1898         if (!Opnd.isImm())
1899           return Error(IDLoc, "expected immediate operand kind");
1900         Imm = Opnd.getImm();
1901         if (Imm < 0 || Imm > 15)
1902           return Error(IDLoc, "immediate operand value out of range");
1903         break;
1904       case Mips::LHU16_MM:
1905       case Mips::SH16_MM:
1906       case Mips::SH16_MMR6:
1907         Opnd = Inst.getOperand(2);
1908         if (!Opnd.isImm())
1909           return Error(IDLoc, "expected immediate operand kind");
1910         Imm = Opnd.getImm();
1911         if (Imm < 0 || Imm > 30 || (Imm % 2 != 0))
1912           return Error(IDLoc, "immediate operand value out of range");
1913         break;
1914       case Mips::LW16_MM:
1915       case Mips::SW16_MM:
1916       case Mips::SW16_MMR6:
1917         Opnd = Inst.getOperand(2);
1918         if (!Opnd.isImm())
1919           return Error(IDLoc, "expected immediate operand kind");
1920         Imm = Opnd.getImm();
1921         if (Imm < 0 || Imm > 60 || (Imm % 4 != 0))
1922           return Error(IDLoc, "immediate operand value out of range");
1923         break;
1924       case Mips::ADDIUPC_MM:
1925         MCOperand Opnd = Inst.getOperand(1);
1926         if (!Opnd.isImm())
1927           return Error(IDLoc, "expected immediate operand kind");
1928         int Imm = Opnd.getImm();
1929         if ((Imm % 4 != 0) || !isInt<25>(Imm))
1930           return Error(IDLoc, "immediate operand value out of range");
1931         break;
1932     }
1933   }
1934 
1935   MacroExpanderResultTy ExpandResult =
1936       tryExpandInstruction(Inst, IDLoc, Instructions);
1937   switch (ExpandResult) {
1938   case MER_NotAMacro:
1939     Instructions.push_back(Inst);
1940     break;
1941   case MER_Success:
1942     break;
1943   case MER_Fail:
1944     return true;
1945   }
1946 
1947   // If this instruction has a delay slot and .set reorder is active,
1948   // emit a NOP after it.
1949   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder())
1950     createNop(hasShortDelaySlot(Inst.getOpcode()), IDLoc, Instructions);
1951 
1952   if ((Inst.getOpcode() == Mips::JalOneReg ||
1953        Inst.getOpcode() == Mips::JalTwoReg || ExpandedJalSym) &&
1954       isPicAndNotNxxAbi()) {
1955     if (IsCpRestoreSet) {
1956       // We need a NOP between the JALR and the LW:
1957       // If .set reorder has been used, we've already emitted a NOP.
1958       // If .set noreorder has been used, we need to emit a NOP at this point.
1959       if (!AssemblerOptions.back()->isReorder())
1960         createNop(hasShortDelaySlot(Inst.getOpcode()), IDLoc, Instructions);
1961 
1962       // Load the $gp from the stack.
1963       SmallVector<MCInst, 3> LoadInsts;
1964       createCpRestoreMemOp(true /*IsLoad*/, CpRestoreOffset /*StackOffset*/,
1965                            IDLoc, LoadInsts);
1966 
1967       for (const MCInst &Inst : LoadInsts)
1968         Instructions.push_back(Inst);
1969 
1970     } else
1971       Warning(IDLoc, "no .cprestore used in PIC mode");
1972   }
1973 
1974   return false;
1975 }
1976 
1977 MipsAsmParser::MacroExpanderResultTy
1978 MipsAsmParser::tryExpandInstruction(MCInst &Inst, SMLoc IDLoc,
1979                                     SmallVectorImpl<MCInst> &Instructions) {
1980   switch (Inst.getOpcode()) {
1981   default:
1982     return MER_NotAMacro;
1983   case Mips::LoadImm32:
1984     return expandLoadImm(Inst, true, IDLoc, Instructions) ? MER_Fail
1985                                                           : MER_Success;
1986   case Mips::LoadImm64:
1987     return expandLoadImm(Inst, false, IDLoc, Instructions) ? MER_Fail
1988                                                            : MER_Success;
1989   case Mips::LoadAddrImm32:
1990   case Mips::LoadAddrImm64:
1991     assert(Inst.getOperand(0).isReg() && "expected register operand kind");
1992     assert((Inst.getOperand(1).isImm() || Inst.getOperand(1).isExpr()) &&
1993            "expected immediate operand kind");
1994 
1995     return expandLoadAddress(Inst.getOperand(0).getReg(), Mips::NoRegister,
1996                              Inst.getOperand(1),
1997                              Inst.getOpcode() == Mips::LoadAddrImm32, IDLoc,
1998                              Instructions)
1999                ? MER_Fail
2000                : MER_Success;
2001   case Mips::LoadAddrReg32:
2002   case Mips::LoadAddrReg64:
2003     assert(Inst.getOperand(0).isReg() && "expected register operand kind");
2004     assert(Inst.getOperand(1).isReg() && "expected register operand kind");
2005     assert((Inst.getOperand(2).isImm() || Inst.getOperand(2).isExpr()) &&
2006            "expected immediate operand kind");
2007 
2008     return expandLoadAddress(Inst.getOperand(0).getReg(),
2009                              Inst.getOperand(1).getReg(), Inst.getOperand(2),
2010                              Inst.getOpcode() == Mips::LoadAddrReg32, IDLoc,
2011                              Instructions)
2012                ? MER_Fail
2013                : MER_Success;
2014   case Mips::B_MM_Pseudo:
2015   case Mips::B_MMR6_Pseudo:
2016     return expandUncondBranchMMPseudo(Inst, IDLoc, Instructions) ? MER_Fail
2017                                                                  : MER_Success;
2018   case Mips::SWM_MM:
2019   case Mips::LWM_MM:
2020     return expandLoadStoreMultiple(Inst, IDLoc, Instructions) ? MER_Fail
2021                                                               : MER_Success;
2022   case Mips::JalOneReg:
2023   case Mips::JalTwoReg:
2024     return expandJalWithRegs(Inst, IDLoc, Instructions) ? MER_Fail
2025                                                         : MER_Success;
2026   case Mips::BneImm:
2027   case Mips::BeqImm:
2028     return expandBranchImm(Inst, IDLoc, Instructions) ? MER_Fail : MER_Success;
2029   case Mips::BLT:
2030   case Mips::BLE:
2031   case Mips::BGE:
2032   case Mips::BGT:
2033   case Mips::BLTU:
2034   case Mips::BLEU:
2035   case Mips::BGEU:
2036   case Mips::BGTU:
2037   case Mips::BLTL:
2038   case Mips::BLEL:
2039   case Mips::BGEL:
2040   case Mips::BGTL:
2041   case Mips::BLTUL:
2042   case Mips::BLEUL:
2043   case Mips::BGEUL:
2044   case Mips::BGTUL:
2045   case Mips::BLTImmMacro:
2046   case Mips::BLEImmMacro:
2047   case Mips::BGEImmMacro:
2048   case Mips::BGTImmMacro:
2049   case Mips::BLTUImmMacro:
2050   case Mips::BLEUImmMacro:
2051   case Mips::BGEUImmMacro:
2052   case Mips::BGTUImmMacro:
2053   case Mips::BLTLImmMacro:
2054   case Mips::BLELImmMacro:
2055   case Mips::BGELImmMacro:
2056   case Mips::BGTLImmMacro:
2057   case Mips::BLTULImmMacro:
2058   case Mips::BLEULImmMacro:
2059   case Mips::BGEULImmMacro:
2060   case Mips::BGTULImmMacro:
2061     return expandCondBranches(Inst, IDLoc, Instructions) ? MER_Fail
2062                                                          : MER_Success;
2063   case Mips::SDivMacro:
2064     return expandDiv(Inst, IDLoc, Instructions, false, true) ? MER_Fail
2065                                                              : MER_Success;
2066   case Mips::DSDivMacro:
2067     return expandDiv(Inst, IDLoc, Instructions, true, true) ? MER_Fail
2068                                                             : MER_Success;
2069   case Mips::UDivMacro:
2070     return expandDiv(Inst, IDLoc, Instructions, false, false) ? MER_Fail
2071                                                               : MER_Success;
2072   case Mips::DUDivMacro:
2073     return expandDiv(Inst, IDLoc, Instructions, true, false) ? MER_Fail
2074                                                              : MER_Success;
2075   case Mips::PseudoTRUNC_W_S:
2076     return expandTrunc(Inst, false, false, IDLoc, Instructions) ? MER_Fail
2077                                                                 : MER_Success;
2078   case Mips::PseudoTRUNC_W_D32:
2079     return expandTrunc(Inst, true, false, IDLoc, Instructions) ? MER_Fail
2080                                                                : MER_Success;
2081   case Mips::PseudoTRUNC_W_D:
2082     return expandTrunc(Inst, true, true, IDLoc, Instructions) ? MER_Fail
2083                                                               : MER_Success;
2084   case Mips::Ulh:
2085     return expandUlh(Inst, true, IDLoc, Instructions) ? MER_Fail : MER_Success;
2086   case Mips::Ulhu:
2087     return expandUlh(Inst, false, IDLoc, Instructions) ? MER_Fail : MER_Success;
2088   case Mips::Ulw:
2089     return expandUlw(Inst, IDLoc, Instructions) ? MER_Fail : MER_Success;
2090   case Mips::NORImm:
2091     return expandAliasImmediate(Inst, IDLoc, Instructions) ? MER_Fail
2092                                                            : MER_Success;
2093   case Mips::ADDi:
2094   case Mips::ADDiu:
2095   case Mips::SLTi:
2096   case Mips::SLTiu:
2097     if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() &&
2098         Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) {
2099       int64_t ImmValue = Inst.getOperand(2).getImm();
2100       if (isInt<16>(ImmValue))
2101         return MER_NotAMacro;
2102       return expandAliasImmediate(Inst, IDLoc, Instructions) ? MER_Fail
2103                                                              : MER_Success;
2104     }
2105     return MER_NotAMacro;
2106   case Mips::ANDi:
2107   case Mips::ORi:
2108   case Mips::XORi:
2109     if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() &&
2110         Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) {
2111       int64_t ImmValue = Inst.getOperand(2).getImm();
2112       if (isUInt<16>(ImmValue))
2113         return MER_NotAMacro;
2114       return expandAliasImmediate(Inst, IDLoc, Instructions) ? MER_Fail
2115                                                              : MER_Success;
2116     }
2117     return MER_NotAMacro;
2118   case Mips::ROL:
2119   case Mips::ROR:
2120     return expandRotation(Inst, IDLoc, Instructions) ? MER_Fail
2121                                                      : MER_Success;
2122   case Mips::ROLImm:
2123   case Mips::RORImm:
2124     return expandRotationImm(Inst, IDLoc, Instructions) ? MER_Fail
2125                                                         : MER_Success;
2126   case Mips::DROL:
2127   case Mips::DROR:
2128     return expandDRotation(Inst, IDLoc, Instructions) ? MER_Fail
2129                                                       : MER_Success;
2130   case Mips::DROLImm:
2131   case Mips::DRORImm:
2132     return expandDRotationImm(Inst, IDLoc, Instructions) ? MER_Fail
2133                                                          : MER_Success;
2134   case Mips::ABSMacro:
2135     return expandAbs(Inst, IDLoc, Instructions) ? MER_Fail
2136                                                 : MER_Success;
2137   }
2138 }
2139 
2140 bool MipsAsmParser::expandJalWithRegs(MCInst &Inst, SMLoc IDLoc,
2141                                       SmallVectorImpl<MCInst> &Instructions) {
2142   // Create a JALR instruction which is going to replace the pseudo-JAL.
2143   MCInst JalrInst;
2144   JalrInst.setLoc(IDLoc);
2145   const MCOperand FirstRegOp = Inst.getOperand(0);
2146   const unsigned Opcode = Inst.getOpcode();
2147 
2148   if (Opcode == Mips::JalOneReg) {
2149     // jal $rs => jalr $rs
2150     if (IsCpRestoreSet && inMicroMipsMode()) {
2151       JalrInst.setOpcode(Mips::JALRS16_MM);
2152       JalrInst.addOperand(FirstRegOp);
2153     } else if (inMicroMipsMode()) {
2154       JalrInst.setOpcode(hasMips32r6() ? Mips::JALRC16_MMR6 : Mips::JALR16_MM);
2155       JalrInst.addOperand(FirstRegOp);
2156     } else {
2157       JalrInst.setOpcode(Mips::JALR);
2158       JalrInst.addOperand(MCOperand::createReg(Mips::RA));
2159       JalrInst.addOperand(FirstRegOp);
2160     }
2161   } else if (Opcode == Mips::JalTwoReg) {
2162     // jal $rd, $rs => jalr $rd, $rs
2163     if (IsCpRestoreSet && inMicroMipsMode())
2164       JalrInst.setOpcode(Mips::JALRS_MM);
2165     else
2166       JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR);
2167     JalrInst.addOperand(FirstRegOp);
2168     const MCOperand SecondRegOp = Inst.getOperand(1);
2169     JalrInst.addOperand(SecondRegOp);
2170   }
2171   Instructions.push_back(JalrInst);
2172 
2173   // If .set reorder is active and branch instruction has a delay slot,
2174   // emit a NOP after it.
2175   const MCInstrDesc &MCID = getInstDesc(JalrInst.getOpcode());
2176   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder()) {
2177     createNop(hasShortDelaySlot(JalrInst.getOpcode()), IDLoc, Instructions);
2178   }
2179 
2180   return false;
2181 }
2182 
2183 /// Can the value be represented by a unsigned N-bit value and a shift left?
2184 template <unsigned N> static bool isShiftedUIntAtAnyPosition(uint64_t x) {
2185   unsigned BitNum = findFirstSet(x);
2186 
2187   return (x == x >> BitNum << BitNum) && isUInt<N>(x >> BitNum);
2188 }
2189 
2190 /// Load (or add) an immediate into a register.
2191 ///
2192 /// @param ImmValue     The immediate to load.
2193 /// @param DstReg       The register that will hold the immediate.
2194 /// @param SrcReg       A register to add to the immediate or Mips::NoRegister
2195 ///                     for a simple initialization.
2196 /// @param Is32BitImm   Is ImmValue 32-bit or 64-bit?
2197 /// @param IsAddress    True if the immediate represents an address. False if it
2198 ///                     is an integer.
2199 /// @param IDLoc        Location of the immediate in the source file.
2200 /// @param Instructions The instructions emitted by this expansion.
2201 bool MipsAsmParser::loadImmediate(int64_t ImmValue, unsigned DstReg,
2202                                   unsigned SrcReg, bool Is32BitImm,
2203                                   bool IsAddress, SMLoc IDLoc,
2204                                   SmallVectorImpl<MCInst> &Instructions) {
2205   if (!Is32BitImm && !isGP64bit()) {
2206     Error(IDLoc, "instruction requires a 64-bit architecture");
2207     return true;
2208   }
2209 
2210   if (Is32BitImm) {
2211     if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) {
2212       // Sign extend up to 64-bit so that the predicates match the hardware
2213       // behaviour. In particular, isInt<16>(0xffff8000) and similar should be
2214       // true.
2215       ImmValue = SignExtend64<32>(ImmValue);
2216     } else {
2217       Error(IDLoc, "instruction requires a 32-bit immediate");
2218       return true;
2219     }
2220   }
2221 
2222   unsigned ZeroReg = IsAddress ? ABI.GetNullPtr() : ABI.GetZeroReg();
2223   unsigned AdduOp = !Is32BitImm ? Mips::DADDu : Mips::ADDu;
2224 
2225   bool UseSrcReg = false;
2226   if (SrcReg != Mips::NoRegister)
2227     UseSrcReg = true;
2228 
2229   unsigned TmpReg = DstReg;
2230   if (UseSrcReg &&
2231       getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) {
2232     // At this point we need AT to perform the expansions and we exit if it is
2233     // not available.
2234     unsigned ATReg = getATReg(IDLoc);
2235     if (!ATReg)
2236       return true;
2237     TmpReg = ATReg;
2238   }
2239 
2240   if (isInt<16>(ImmValue)) {
2241     if (!UseSrcReg)
2242       SrcReg = ZeroReg;
2243 
2244     // This doesn't quite follow the usual ABI expectations for N32 but matches
2245     // traditional assembler behaviour. N32 would normally use addiu for both
2246     // integers and addresses.
2247     if (IsAddress && !Is32BitImm) {
2248       emitRRI(Mips::DADDiu, DstReg, SrcReg, ImmValue, IDLoc, Instructions);
2249       return false;
2250     }
2251 
2252     emitRRI(Mips::ADDiu, DstReg, SrcReg, ImmValue, IDLoc, Instructions);
2253     return false;
2254   }
2255 
2256   if (isUInt<16>(ImmValue)) {
2257     unsigned TmpReg = DstReg;
2258     if (SrcReg == DstReg) {
2259       TmpReg = getATReg(IDLoc);
2260       if (!TmpReg)
2261         return true;
2262     }
2263 
2264     emitRRI(Mips::ORi, TmpReg, ZeroReg, ImmValue, IDLoc, Instructions);
2265     if (UseSrcReg)
2266       emitRRR(ABI.GetPtrAdduOp(), DstReg, TmpReg, SrcReg, IDLoc, Instructions);
2267     return false;
2268   }
2269 
2270   if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) {
2271     warnIfNoMacro(IDLoc);
2272 
2273     uint16_t Bits31To16 = (ImmValue >> 16) & 0xffff;
2274     uint16_t Bits15To0 = ImmValue & 0xffff;
2275 
2276     if (!Is32BitImm && !isInt<32>(ImmValue)) {
2277       // Traditional behaviour seems to special case this particular value. It's
2278       // not clear why other masks are handled differently.
2279       if (ImmValue == 0xffffffff) {
2280         emitRI(Mips::LUi, TmpReg, 0xffff, IDLoc, Instructions);
2281         emitRRI(Mips::DSRL32, TmpReg, TmpReg, 0, IDLoc, Instructions);
2282         if (UseSrcReg)
2283           emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, Instructions);
2284         return false;
2285       }
2286 
2287       // Expand to an ORi instead of a LUi to avoid sign-extending into the
2288       // upper 32 bits.
2289       emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits31To16, IDLoc, Instructions);
2290       emitRRI(Mips::DSLL, TmpReg, TmpReg, 16, IDLoc, Instructions);
2291       if (Bits15To0)
2292         emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, Instructions);
2293       if (UseSrcReg)
2294         emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, Instructions);
2295       return false;
2296     }
2297 
2298     emitRI(Mips::LUi, TmpReg, Bits31To16, IDLoc, Instructions);
2299     if (Bits15To0)
2300       emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, Instructions);
2301     if (UseSrcReg)
2302       emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, Instructions);
2303     return false;
2304   }
2305 
2306   if (isShiftedUIntAtAnyPosition<16>(ImmValue)) {
2307     if (Is32BitImm) {
2308       Error(IDLoc, "instruction requires a 32-bit immediate");
2309       return true;
2310     }
2311 
2312     // Traditionally, these immediates are shifted as little as possible and as
2313     // such we align the most significant bit to bit 15 of our temporary.
2314     unsigned FirstSet = findFirstSet((uint64_t)ImmValue);
2315     unsigned LastSet = findLastSet((uint64_t)ImmValue);
2316     unsigned ShiftAmount = FirstSet - (15 - (LastSet - FirstSet));
2317     uint16_t Bits = (ImmValue >> ShiftAmount) & 0xffff;
2318     emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits, IDLoc, Instructions);
2319     emitRRI(Mips::DSLL, TmpReg, TmpReg, ShiftAmount, IDLoc, Instructions);
2320 
2321     if (UseSrcReg)
2322       emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, Instructions);
2323 
2324     return false;
2325   }
2326 
2327   warnIfNoMacro(IDLoc);
2328 
2329   // The remaining case is packed with a sequence of dsll and ori with zeros
2330   // being omitted and any neighbouring dsll's being coalesced.
2331   // The highest 32-bit's are equivalent to a 32-bit immediate load.
2332 
2333   // Load bits 32-63 of ImmValue into bits 0-31 of the temporary register.
2334   if (loadImmediate(ImmValue >> 32, TmpReg, Mips::NoRegister, true, false,
2335                     IDLoc, Instructions))
2336     return false;
2337 
2338   // Shift and accumulate into the register. If a 16-bit chunk is zero, then
2339   // skip it and defer the shift to the next chunk.
2340   unsigned ShiftCarriedForwards = 16;
2341   for (int BitNum = 16; BitNum >= 0; BitNum -= 16) {
2342     uint16_t ImmChunk = (ImmValue >> BitNum) & 0xffff;
2343 
2344     if (ImmChunk != 0) {
2345       emitAppropriateDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc,
2346                           Instructions);
2347       emitRRI(Mips::ORi, TmpReg, TmpReg, ImmChunk, IDLoc, Instructions);
2348       ShiftCarriedForwards = 0;
2349     }
2350 
2351     ShiftCarriedForwards += 16;
2352   }
2353   ShiftCarriedForwards -= 16;
2354 
2355   // Finish any remaining shifts left by trailing zeros.
2356   if (ShiftCarriedForwards)
2357     emitAppropriateDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc,
2358                         Instructions);
2359 
2360   if (UseSrcReg)
2361     emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, Instructions);
2362 
2363   return false;
2364 }
2365 
2366 bool MipsAsmParser::expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc,
2367                                   SmallVectorImpl<MCInst> &Instructions) {
2368   const MCOperand &ImmOp = Inst.getOperand(1);
2369   assert(ImmOp.isImm() && "expected immediate operand kind");
2370   const MCOperand &DstRegOp = Inst.getOperand(0);
2371   assert(DstRegOp.isReg() && "expected register operand kind");
2372 
2373   if (loadImmediate(ImmOp.getImm(), DstRegOp.getReg(), Mips::NoRegister,
2374                     Is32BitImm, false, IDLoc, Instructions))
2375     return true;
2376 
2377   return false;
2378 }
2379 
2380 bool MipsAsmParser::expandLoadAddress(unsigned DstReg, unsigned BaseReg,
2381                                       const MCOperand &Offset,
2382                                       bool Is32BitAddress, SMLoc IDLoc,
2383                                       SmallVectorImpl<MCInst> &Instructions) {
2384   // la can't produce a usable address when addresses are 64-bit.
2385   if (Is32BitAddress && ABI.ArePtrs64bit()) {
2386     // FIXME: Demote this to a warning and continue as if we had 'dla' instead.
2387     //        We currently can't do this because we depend on the equality
2388     //        operator and N64 can end up with a GPR32/GPR64 mismatch.
2389     Error(IDLoc, "la used to load 64-bit address");
2390     // Continue as if we had 'dla' instead.
2391     Is32BitAddress = false;
2392   }
2393 
2394   // dla requires 64-bit addresses.
2395   if (!Is32BitAddress && !hasMips3()) {
2396     Error(IDLoc, "instruction requires a 64-bit architecture");
2397     return true;
2398   }
2399 
2400   if (!Offset.isImm())
2401     return loadAndAddSymbolAddress(Offset.getExpr(), DstReg, BaseReg,
2402                                    Is32BitAddress, IDLoc, Instructions);
2403 
2404   if (!ABI.ArePtrs64bit()) {
2405     // Continue as if we had 'la' whether we had 'la' or 'dla'.
2406     Is32BitAddress = true;
2407   }
2408 
2409   return loadImmediate(Offset.getImm(), DstReg, BaseReg, Is32BitAddress, true,
2410                        IDLoc, Instructions);
2411 }
2412 
2413 bool MipsAsmParser::loadAndAddSymbolAddress(
2414     const MCExpr *SymExpr, unsigned DstReg, unsigned SrcReg, bool Is32BitSym,
2415     SMLoc IDLoc, SmallVectorImpl<MCInst> &Instructions) {
2416   warnIfNoMacro(IDLoc);
2417 
2418   const MCExpr *Symbol = cast<MCExpr>(SymExpr);
2419   const MipsMCExpr *HiExpr = MipsMCExpr::create(
2420       MCSymbolRefExpr::VK_Mips_ABS_HI, Symbol, getContext());
2421   const MipsMCExpr *LoExpr = MipsMCExpr::create(
2422       MCSymbolRefExpr::VK_Mips_ABS_LO, Symbol, getContext());
2423 
2424   bool UseSrcReg = SrcReg != Mips::NoRegister;
2425 
2426   // This is the 64-bit symbol address expansion.
2427   if (ABI.ArePtrs64bit() && isGP64bit()) {
2428     // We always need AT for the 64-bit expansion.
2429     // If it is not available we exit.
2430     unsigned ATReg = getATReg(IDLoc);
2431     if (!ATReg)
2432       return true;
2433 
2434     const MipsMCExpr *HighestExpr = MipsMCExpr::create(
2435         MCSymbolRefExpr::VK_Mips_HIGHEST, Symbol, getContext());
2436     const MipsMCExpr *HigherExpr = MipsMCExpr::create(
2437         MCSymbolRefExpr::VK_Mips_HIGHER, Symbol, getContext());
2438 
2439     if (UseSrcReg &&
2440         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg,
2441                                                                SrcReg)) {
2442       // If $rs is the same as $rd:
2443       // (d)la $rd, sym($rd) => lui    $at, %highest(sym)
2444       //                        daddiu $at, $at, %higher(sym)
2445       //                        dsll   $at, $at, 16
2446       //                        daddiu $at, $at, %hi(sym)
2447       //                        dsll   $at, $at, 16
2448       //                        daddiu $at, $at, %lo(sym)
2449       //                        daddu  $rd, $at, $rd
2450       emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HighestExpr), IDLoc,
2451              Instructions);
2452       emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(HigherExpr),
2453               IDLoc, Instructions);
2454       emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, Instructions);
2455       emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(HiExpr), IDLoc,
2456               Instructions);
2457       emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, Instructions);
2458       emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr), IDLoc,
2459               Instructions);
2460       emitRRR(Mips::DADDu, DstReg, ATReg, SrcReg, IDLoc, Instructions);
2461 
2462       return false;
2463     }
2464 
2465     // Otherwise, if the $rs is different from $rd or if $rs isn't specified:
2466     // (d)la $rd, sym/sym($rs) => lui    $rd, %highest(sym)
2467     //                            lui    $at, %hi(sym)
2468     //                            daddiu $rd, $rd, %higher(sym)
2469     //                            daddiu $at, $at, %lo(sym)
2470     //                            dsll32 $rd, $rd, 0
2471     //                            daddu  $rd, $rd, $at
2472     //                            (daddu  $rd, $rd, $rs)
2473     emitRX(Mips::LUi, DstReg, MCOperand::createExpr(HighestExpr), IDLoc,
2474            Instructions);
2475     emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HiExpr), IDLoc,
2476            Instructions);
2477     emitRRX(Mips::DADDiu, DstReg, DstReg, MCOperand::createExpr(HigherExpr),
2478             IDLoc, Instructions);
2479     emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr), IDLoc,
2480             Instructions);
2481     emitRRI(Mips::DSLL32, DstReg, DstReg, 0, IDLoc, Instructions);
2482     emitRRR(Mips::DADDu, DstReg, DstReg, ATReg, IDLoc, Instructions);
2483     if (UseSrcReg)
2484       emitRRR(Mips::DADDu, DstReg, DstReg, SrcReg, IDLoc, Instructions);
2485 
2486     return false;
2487   }
2488 
2489   // And now, the 32-bit symbol address expansion:
2490   // If $rs is the same as $rd:
2491   // (d)la $rd, sym($rd)     => lui   $at, %hi(sym)
2492   //                            ori   $at, $at, %lo(sym)
2493   //                            addu  $rd, $at, $rd
2494   // Otherwise, if the $rs is different from $rd or if $rs isn't specified:
2495   // (d)la $rd, sym/sym($rs) => lui   $rd, %hi(sym)
2496   //                            ori   $rd, $rd, %lo(sym)
2497   //                            (addu $rd, $rd, $rs)
2498   unsigned TmpReg = DstReg;
2499   if (UseSrcReg &&
2500       getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) {
2501     // If $rs is the same as $rd, we need to use AT.
2502     // If it is not available we exit.
2503     unsigned ATReg = getATReg(IDLoc);
2504     if (!ATReg)
2505       return true;
2506     TmpReg = ATReg;
2507   }
2508 
2509   emitRX(Mips::LUi, TmpReg, MCOperand::createExpr(HiExpr), IDLoc, Instructions);
2510   emitRRX(Mips::ADDiu, TmpReg, TmpReg, MCOperand::createExpr(LoExpr), IDLoc,
2511           Instructions);
2512 
2513   if (UseSrcReg)
2514     emitRRR(Mips::ADDu, DstReg, TmpReg, SrcReg, IDLoc, Instructions);
2515   else
2516     assert(
2517         getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, TmpReg));
2518 
2519   return false;
2520 }
2521 
2522 bool MipsAsmParser::expandUncondBranchMMPseudo(
2523     MCInst &Inst, SMLoc IDLoc, SmallVectorImpl<MCInst> &Instructions) {
2524   assert(getInstDesc(Inst.getOpcode()).getNumOperands() == 1 &&
2525          "unexpected number of operands");
2526 
2527   MCOperand Offset = Inst.getOperand(0);
2528   if (Offset.isExpr()) {
2529     Inst.clear();
2530     Inst.setOpcode(Mips::BEQ_MM);
2531     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2532     Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2533     Inst.addOperand(MCOperand::createExpr(Offset.getExpr()));
2534   } else {
2535     assert(Offset.isImm() && "expected immediate operand kind");
2536     if (isInt<11>(Offset.getImm())) {
2537       // If offset fits into 11 bits then this instruction becomes microMIPS
2538       // 16-bit unconditional branch instruction.
2539       if (inMicroMipsMode())
2540         Inst.setOpcode(hasMips32r6() ? Mips::BC16_MMR6 : Mips::B16_MM);
2541     } else {
2542       if (!isInt<17>(Offset.getImm()))
2543         Error(IDLoc, "branch target out of range");
2544       if (OffsetToAlignment(Offset.getImm(), 1LL << 1))
2545         Error(IDLoc, "branch to misaligned address");
2546       Inst.clear();
2547       Inst.setOpcode(Mips::BEQ_MM);
2548       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2549       Inst.addOperand(MCOperand::createReg(Mips::ZERO));
2550       Inst.addOperand(MCOperand::createImm(Offset.getImm()));
2551     }
2552   }
2553   Instructions.push_back(Inst);
2554 
2555   // If .set reorder is active and branch instruction has a delay slot,
2556   // emit a NOP after it.
2557   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
2558   if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder())
2559     createNop(true, IDLoc, Instructions);
2560 
2561   return false;
2562 }
2563 
2564 bool MipsAsmParser::expandBranchImm(MCInst &Inst, SMLoc IDLoc,
2565                                     SmallVectorImpl<MCInst> &Instructions) {
2566   const MCOperand &DstRegOp = Inst.getOperand(0);
2567   assert(DstRegOp.isReg() && "expected register operand kind");
2568 
2569   const MCOperand &ImmOp = Inst.getOperand(1);
2570   assert(ImmOp.isImm() && "expected immediate operand kind");
2571 
2572   const MCOperand &MemOffsetOp = Inst.getOperand(2);
2573   assert((MemOffsetOp.isImm() || MemOffsetOp.isExpr()) &&
2574          "expected immediate or expression operand");
2575 
2576   unsigned OpCode = 0;
2577   switch(Inst.getOpcode()) {
2578     case Mips::BneImm:
2579       OpCode = Mips::BNE;
2580       break;
2581     case Mips::BeqImm:
2582       OpCode = Mips::BEQ;
2583       break;
2584     default:
2585       llvm_unreachable("Unknown immediate branch pseudo-instruction.");
2586       break;
2587   }
2588 
2589   int64_t ImmValue = ImmOp.getImm();
2590   if (ImmValue == 0)
2591     emitRRX(OpCode, DstRegOp.getReg(), Mips::ZERO, MemOffsetOp, IDLoc,
2592             Instructions);
2593   else {
2594     warnIfNoMacro(IDLoc);
2595 
2596     unsigned ATReg = getATReg(IDLoc);
2597     if (!ATReg)
2598       return true;
2599 
2600     if (loadImmediate(ImmValue, ATReg, Mips::NoRegister, !isGP64bit(), true,
2601                       IDLoc, Instructions))
2602       return true;
2603 
2604     emitRRX(OpCode, DstRegOp.getReg(), ATReg, MemOffsetOp, IDLoc, Instructions);
2605   }
2606   return false;
2607 }
2608 
2609 void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc,
2610                                   SmallVectorImpl<MCInst> &Instructions,
2611                                   bool isLoad, bool isImmOpnd) {
2612   MCOperand HiOperand, LoOperand;
2613   unsigned TmpRegNum;
2614   // 1st operand is either the source or destination register.
2615   assert(Inst.getOperand(0).isReg() && "expected register operand kind");
2616   unsigned RegOpNum = Inst.getOperand(0).getReg();
2617   // 2nd operand is the base register.
2618   assert(Inst.getOperand(1).isReg() && "expected register operand kind");
2619   unsigned BaseRegNum = Inst.getOperand(1).getReg();
2620   // 3rd operand is either an immediate or expression.
2621   if (isImmOpnd) {
2622     assert(Inst.getOperand(2).isImm() && "expected immediate operand kind");
2623     unsigned ImmOffset = Inst.getOperand(2).getImm();
2624     unsigned LoOffset = ImmOffset & 0x0000ffff;
2625     unsigned HiOffset = (ImmOffset & 0xffff0000) >> 16;
2626     // If msb of LoOffset is 1(negative number) we must increment HiOffset.
2627     if (LoOffset & 0x8000)
2628       HiOffset++;
2629     LoOperand = MCOperand::createImm(LoOffset);
2630     HiOperand = MCOperand::createImm(HiOffset);
2631   } else {
2632     const MCExpr *ExprOffset = Inst.getOperand(2).getExpr();
2633     LoOperand = MCOperand::createExpr(evaluateRelocExpr(ExprOffset, "lo"));
2634     HiOperand = MCOperand::createExpr(evaluateRelocExpr(ExprOffset, "hi"));
2635   }
2636   // These are some of the types of expansions we perform here:
2637   // 1) lw $8, sym        => lui $8, %hi(sym)
2638   //                         lw $8, %lo(sym)($8)
2639   // 2) lw $8, offset($9) => lui $8, %hi(offset)
2640   //                         add $8, $8, $9
2641   //                         lw $8, %lo(offset)($9)
2642   // 3) lw $8, offset($8) => lui $at, %hi(offset)
2643   //                         add $at, $at, $8
2644   //                         lw $8, %lo(offset)($at)
2645   // 4) sw $8, sym        => lui $at, %hi(sym)
2646   //                         sw $8, %lo(sym)($at)
2647   // 5) sw $8, offset($8) => lui $at, %hi(offset)
2648   //                         add $at, $at, $8
2649   //                         sw $8, %lo(offset)($at)
2650   // 6) ldc1 $f0, sym     => lui $at, %hi(sym)
2651   //                         ldc1 $f0, %lo(sym)($at)
2652   //
2653   // For load instructions we can use the destination register as a temporary
2654   // if base and dst are different (examples 1 and 2) and if the base register
2655   // is general purpose otherwise we must use $at (example 6) and error if it's
2656   // not available. For stores we must use $at (examples 4 and 5) because we
2657   // must not clobber the source register setting up the offset.
2658   const MCInstrDesc &Desc = getInstDesc(Inst.getOpcode());
2659   int16_t RegClassOp0 = Desc.OpInfo[0].RegClass;
2660   unsigned RegClassIDOp0 =
2661       getContext().getRegisterInfo()->getRegClass(RegClassOp0).getID();
2662   bool IsGPR = (RegClassIDOp0 == Mips::GPR32RegClassID) ||
2663                (RegClassIDOp0 == Mips::GPR64RegClassID);
2664   if (isLoad && IsGPR && (BaseRegNum != RegOpNum))
2665     TmpRegNum = RegOpNum;
2666   else {
2667     // At this point we need AT to perform the expansions and we exit if it is
2668     // not available.
2669     TmpRegNum = getATReg(IDLoc);
2670     if (!TmpRegNum)
2671       return;
2672   }
2673 
2674   emitRX(Mips::LUi, TmpRegNum, HiOperand, IDLoc, Instructions);
2675   // Add temp register to base.
2676   if (BaseRegNum != Mips::ZERO)
2677     emitRRR(Mips::ADDu, TmpRegNum, TmpRegNum, BaseRegNum, IDLoc, Instructions);
2678   // And finally, create original instruction with low part
2679   // of offset and new base.
2680   emitRRX(Inst.getOpcode(), RegOpNum, TmpRegNum, LoOperand, IDLoc, Instructions);
2681 }
2682 
2683 bool
2684 MipsAsmParser::expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc,
2685                                        SmallVectorImpl<MCInst> &Instructions) {
2686   unsigned OpNum = Inst.getNumOperands();
2687   unsigned Opcode = Inst.getOpcode();
2688   unsigned NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM32_MM : Mips::LWM32_MM;
2689 
2690   assert (Inst.getOperand(OpNum - 1).isImm() &&
2691           Inst.getOperand(OpNum - 2).isReg() &&
2692           Inst.getOperand(OpNum - 3).isReg() && "Invalid instruction operand.");
2693 
2694   if (OpNum < 8 && Inst.getOperand(OpNum - 1).getImm() <= 60 &&
2695       Inst.getOperand(OpNum - 1).getImm() >= 0 &&
2696       (Inst.getOperand(OpNum - 2).getReg() == Mips::SP ||
2697        Inst.getOperand(OpNum - 2).getReg() == Mips::SP_64) &&
2698       (Inst.getOperand(OpNum - 3).getReg() == Mips::RA ||
2699        Inst.getOperand(OpNum - 3).getReg() == Mips::RA_64)) {
2700     // It can be implemented as SWM16 or LWM16 instruction.
2701     if (inMicroMipsMode() && hasMips32r6())
2702       NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MMR6 : Mips::LWM16_MMR6;
2703     else
2704       NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MM : Mips::LWM16_MM;
2705   }
2706 
2707   Inst.setOpcode(NewOpcode);
2708   Instructions.push_back(Inst);
2709   return false;
2710 }
2711 
2712 bool MipsAsmParser::expandCondBranches(MCInst &Inst, SMLoc IDLoc,
2713                                        SmallVectorImpl<MCInst> &Instructions) {
2714   bool EmittedNoMacroWarning = false;
2715   unsigned PseudoOpcode = Inst.getOpcode();
2716   unsigned SrcReg = Inst.getOperand(0).getReg();
2717   const MCOperand &TrgOp = Inst.getOperand(1);
2718   const MCExpr *OffsetExpr = Inst.getOperand(2).getExpr();
2719 
2720   unsigned ZeroSrcOpcode, ZeroTrgOpcode;
2721   bool ReverseOrderSLT, IsUnsigned, IsLikely, AcceptsEquality;
2722 
2723   unsigned TrgReg;
2724   if (TrgOp.isReg())
2725     TrgReg = TrgOp.getReg();
2726   else if (TrgOp.isImm()) {
2727     warnIfNoMacro(IDLoc);
2728     EmittedNoMacroWarning = true;
2729 
2730     TrgReg = getATReg(IDLoc);
2731     if (!TrgReg)
2732       return true;
2733 
2734     switch(PseudoOpcode) {
2735     default:
2736       llvm_unreachable("unknown opcode for branch pseudo-instruction");
2737     case Mips::BLTImmMacro:
2738       PseudoOpcode = Mips::BLT;
2739       break;
2740     case Mips::BLEImmMacro:
2741       PseudoOpcode = Mips::BLE;
2742       break;
2743     case Mips::BGEImmMacro:
2744       PseudoOpcode = Mips::BGE;
2745       break;
2746     case Mips::BGTImmMacro:
2747       PseudoOpcode = Mips::BGT;
2748       break;
2749     case Mips::BLTUImmMacro:
2750       PseudoOpcode = Mips::BLTU;
2751       break;
2752     case Mips::BLEUImmMacro:
2753       PseudoOpcode = Mips::BLEU;
2754       break;
2755     case Mips::BGEUImmMacro:
2756       PseudoOpcode = Mips::BGEU;
2757       break;
2758     case Mips::BGTUImmMacro:
2759       PseudoOpcode = Mips::BGTU;
2760       break;
2761     case Mips::BLTLImmMacro:
2762       PseudoOpcode = Mips::BLTL;
2763       break;
2764     case Mips::BLELImmMacro:
2765       PseudoOpcode = Mips::BLEL;
2766       break;
2767     case Mips::BGELImmMacro:
2768       PseudoOpcode = Mips::BGEL;
2769       break;
2770     case Mips::BGTLImmMacro:
2771       PseudoOpcode = Mips::BGTL;
2772       break;
2773     case Mips::BLTULImmMacro:
2774       PseudoOpcode = Mips::BLTUL;
2775       break;
2776     case Mips::BLEULImmMacro:
2777       PseudoOpcode = Mips::BLEUL;
2778       break;
2779     case Mips::BGEULImmMacro:
2780       PseudoOpcode = Mips::BGEUL;
2781       break;
2782     case Mips::BGTULImmMacro:
2783       PseudoOpcode = Mips::BGTUL;
2784       break;
2785     }
2786 
2787     if (loadImmediate(TrgOp.getImm(), TrgReg, Mips::NoRegister, !isGP64bit(),
2788                       false, IDLoc, Instructions))
2789       return true;
2790   }
2791 
2792   switch (PseudoOpcode) {
2793   case Mips::BLT:
2794   case Mips::BLTU:
2795   case Mips::BLTL:
2796   case Mips::BLTUL:
2797     AcceptsEquality = false;
2798     ReverseOrderSLT = false;
2799     IsUnsigned = ((PseudoOpcode == Mips::BLTU) || (PseudoOpcode == Mips::BLTUL));
2800     IsLikely = ((PseudoOpcode == Mips::BLTL) || (PseudoOpcode == Mips::BLTUL));
2801     ZeroSrcOpcode = Mips::BGTZ;
2802     ZeroTrgOpcode = Mips::BLTZ;
2803     break;
2804   case Mips::BLE:
2805   case Mips::BLEU:
2806   case Mips::BLEL:
2807   case Mips::BLEUL:
2808     AcceptsEquality = true;
2809     ReverseOrderSLT = true;
2810     IsUnsigned = ((PseudoOpcode == Mips::BLEU) || (PseudoOpcode == Mips::BLEUL));
2811     IsLikely = ((PseudoOpcode == Mips::BLEL) || (PseudoOpcode == Mips::BLEUL));
2812     ZeroSrcOpcode = Mips::BGEZ;
2813     ZeroTrgOpcode = Mips::BLEZ;
2814     break;
2815   case Mips::BGE:
2816   case Mips::BGEU:
2817   case Mips::BGEL:
2818   case Mips::BGEUL:
2819     AcceptsEquality = true;
2820     ReverseOrderSLT = false;
2821     IsUnsigned = ((PseudoOpcode == Mips::BGEU) || (PseudoOpcode == Mips::BGEUL));
2822     IsLikely = ((PseudoOpcode == Mips::BGEL) || (PseudoOpcode == Mips::BGEUL));
2823     ZeroSrcOpcode = Mips::BLEZ;
2824     ZeroTrgOpcode = Mips::BGEZ;
2825     break;
2826   case Mips::BGT:
2827   case Mips::BGTU:
2828   case Mips::BGTL:
2829   case Mips::BGTUL:
2830     AcceptsEquality = false;
2831     ReverseOrderSLT = true;
2832     IsUnsigned = ((PseudoOpcode == Mips::BGTU) || (PseudoOpcode == Mips::BGTUL));
2833     IsLikely = ((PseudoOpcode == Mips::BGTL) || (PseudoOpcode == Mips::BGTUL));
2834     ZeroSrcOpcode = Mips::BLTZ;
2835     ZeroTrgOpcode = Mips::BGTZ;
2836     break;
2837   default:
2838     llvm_unreachable("unknown opcode for branch pseudo-instruction");
2839   }
2840 
2841   bool IsTrgRegZero = (TrgReg == Mips::ZERO);
2842   bool IsSrcRegZero = (SrcReg == Mips::ZERO);
2843   if (IsSrcRegZero && IsTrgRegZero) {
2844     // FIXME: All of these Opcode-specific if's are needed for compatibility
2845     // with GAS' behaviour. However, they may not generate the most efficient
2846     // code in some circumstances.
2847     if (PseudoOpcode == Mips::BLT) {
2848       emitRX(Mips::BLTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
2849              Instructions);
2850       return false;
2851     }
2852     if (PseudoOpcode == Mips::BLE) {
2853       emitRX(Mips::BLEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
2854              Instructions);
2855       Warning(IDLoc, "branch is always taken");
2856       return false;
2857     }
2858     if (PseudoOpcode == Mips::BGE) {
2859       emitRX(Mips::BGEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
2860              Instructions);
2861       Warning(IDLoc, "branch is always taken");
2862       return false;
2863     }
2864     if (PseudoOpcode == Mips::BGT) {
2865       emitRX(Mips::BGTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
2866              Instructions);
2867       return false;
2868     }
2869     if (PseudoOpcode == Mips::BGTU) {
2870       emitRRX(Mips::BNE, Mips::ZERO, Mips::ZERO,
2871               MCOperand::createExpr(OffsetExpr), IDLoc, Instructions);
2872       return false;
2873     }
2874     if (AcceptsEquality) {
2875       // If both registers are $0 and the pseudo-branch accepts equality, it
2876       // will always be taken, so we emit an unconditional branch.
2877       emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO,
2878               MCOperand::createExpr(OffsetExpr), IDLoc, Instructions);
2879       Warning(IDLoc, "branch is always taken");
2880       return false;
2881     }
2882     // If both registers are $0 and the pseudo-branch does not accept
2883     // equality, it will never be taken, so we don't have to emit anything.
2884     return false;
2885   }
2886   if (IsSrcRegZero || IsTrgRegZero) {
2887     if ((IsSrcRegZero && PseudoOpcode == Mips::BGTU) ||
2888         (IsTrgRegZero && PseudoOpcode == Mips::BLTU)) {
2889       // If the $rs is $0 and the pseudo-branch is BGTU (0 > x) or
2890       // if the $rt is $0 and the pseudo-branch is BLTU (x < 0),
2891       // the pseudo-branch will never be taken, so we don't emit anything.
2892       // This only applies to unsigned pseudo-branches.
2893       return false;
2894     }
2895     if ((IsSrcRegZero && PseudoOpcode == Mips::BLEU) ||
2896         (IsTrgRegZero && PseudoOpcode == Mips::BGEU)) {
2897       // If the $rs is $0 and the pseudo-branch is BLEU (0 <= x) or
2898       // if the $rt is $0 and the pseudo-branch is BGEU (x >= 0),
2899       // the pseudo-branch will always be taken, so we emit an unconditional
2900       // branch.
2901       // This only applies to unsigned pseudo-branches.
2902       emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO,
2903               MCOperand::createExpr(OffsetExpr), IDLoc, Instructions);
2904       Warning(IDLoc, "branch is always taken");
2905       return false;
2906     }
2907     if (IsUnsigned) {
2908       // If the $rs is $0 and the pseudo-branch is BLTU (0 < x) or
2909       // if the $rt is $0 and the pseudo-branch is BGTU (x > 0),
2910       // the pseudo-branch will be taken only when the non-zero register is
2911       // different from 0, so we emit a BNEZ.
2912       //
2913       // If the $rs is $0 and the pseudo-branch is BGEU (0 >= x) or
2914       // if the $rt is $0 and the pseudo-branch is BLEU (x <= 0),
2915       // the pseudo-branch will be taken only when the non-zero register is
2916       // equal to 0, so we emit a BEQZ.
2917       //
2918       // Because only BLEU and BGEU branch on equality, we can use the
2919       // AcceptsEquality variable to decide when to emit the BEQZ.
2920       emitRRX(AcceptsEquality ? Mips::BEQ : Mips::BNE,
2921               IsSrcRegZero ? TrgReg : SrcReg, Mips::ZERO,
2922               MCOperand::createExpr(OffsetExpr), IDLoc, Instructions);
2923       return false;
2924     }
2925     // If we have a signed pseudo-branch and one of the registers is $0,
2926     // we can use an appropriate compare-to-zero branch. We select which one
2927     // to use in the switch statement above.
2928     emitRX(IsSrcRegZero ? ZeroSrcOpcode : ZeroTrgOpcode,
2929            IsSrcRegZero ? TrgReg : SrcReg, MCOperand::createExpr(OffsetExpr),
2930            IDLoc, Instructions);
2931     return false;
2932   }
2933 
2934   // If neither the SrcReg nor the TrgReg are $0, we need AT to perform the
2935   // expansions. If it is not available, we return.
2936   unsigned ATRegNum = getATReg(IDLoc);
2937   if (!ATRegNum)
2938     return true;
2939 
2940   if (!EmittedNoMacroWarning)
2941     warnIfNoMacro(IDLoc);
2942 
2943   // SLT fits well with 2 of our 4 pseudo-branches:
2944   //   BLT, where $rs < $rt, translates into "slt $at, $rs, $rt" and
2945   //   BGT, where $rs > $rt, translates into "slt $at, $rt, $rs".
2946   // If the result of the SLT is 1, we branch, and if it's 0, we don't.
2947   // This is accomplished by using a BNEZ with the result of the SLT.
2948   //
2949   // The other 2 pseudo-branches are opposites of the above 2 (BGE with BLT
2950   // and BLE with BGT), so we change the BNEZ into a a BEQZ.
2951   // Because only BGE and BLE branch on equality, we can use the
2952   // AcceptsEquality variable to decide when to emit the BEQZ.
2953   // Note that the order of the SLT arguments doesn't change between
2954   // opposites.
2955   //
2956   // The same applies to the unsigned variants, except that SLTu is used
2957   // instead of SLT.
2958   emitRRR(IsUnsigned ? Mips::SLTu : Mips::SLT, ATRegNum,
2959           ReverseOrderSLT ? TrgReg : SrcReg, ReverseOrderSLT ? SrcReg : TrgReg,
2960           IDLoc, Instructions);
2961 
2962   emitRRX(IsLikely ? (AcceptsEquality ? Mips::BEQL : Mips::BNEL)
2963                    : (AcceptsEquality ? Mips::BEQ : Mips::BNE),
2964           ATRegNum, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc,
2965           Instructions);
2966   return false;
2967 }
2968 
2969 bool MipsAsmParser::expandDiv(MCInst &Inst, SMLoc IDLoc,
2970                               SmallVectorImpl<MCInst> &Instructions,
2971                               const bool IsMips64, const bool Signed) {
2972   if (hasMips32r6()) {
2973     Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
2974     return false;
2975   }
2976 
2977   warnIfNoMacro(IDLoc);
2978 
2979   const MCOperand &RsRegOp = Inst.getOperand(0);
2980   assert(RsRegOp.isReg() && "expected register operand kind");
2981   unsigned RsReg = RsRegOp.getReg();
2982 
2983   const MCOperand &RtRegOp = Inst.getOperand(1);
2984   assert(RtRegOp.isReg() && "expected register operand kind");
2985   unsigned RtReg = RtRegOp.getReg();
2986   unsigned DivOp;
2987   unsigned ZeroReg;
2988 
2989   if (IsMips64) {
2990     DivOp = Signed ? Mips::DSDIV : Mips::DUDIV;
2991     ZeroReg = Mips::ZERO_64;
2992   } else {
2993     DivOp = Signed ? Mips::SDIV : Mips::UDIV;
2994     ZeroReg = Mips::ZERO;
2995   }
2996 
2997   bool UseTraps = useTraps();
2998 
2999   if (RsReg == Mips::ZERO || RsReg == Mips::ZERO_64) {
3000     if (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64)
3001       Warning(IDLoc, "dividing zero by zero");
3002     if (IsMips64) {
3003       if (Signed && (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64)) {
3004         if (UseTraps) {
3005           emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, Instructions);
3006           return false;
3007         }
3008 
3009         emitII(Mips::BREAK, 0x7, 0, IDLoc, Instructions);
3010         return false;
3011       }
3012     } else {
3013       emitRR(DivOp, RsReg, RtReg, IDLoc, Instructions);
3014       return false;
3015     }
3016   }
3017 
3018   if (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64) {
3019     Warning(IDLoc, "division by zero");
3020     if (Signed) {
3021       if (UseTraps) {
3022         emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, Instructions);
3023         return false;
3024       }
3025 
3026       emitII(Mips::BREAK, 0x7, 0, IDLoc, Instructions);
3027       return false;
3028     }
3029   }
3030 
3031   // FIXME: The values for these two BranchTarget variables may be different in
3032   // micromips. These magic numbers need to be removed.
3033   unsigned BranchTargetNoTraps;
3034   unsigned BranchTarget;
3035 
3036   if (UseTraps) {
3037     BranchTarget = IsMips64 ? 12 : 8;
3038     emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, Instructions);
3039   } else {
3040     BranchTarget = IsMips64 ? 20 : 16;
3041     BranchTargetNoTraps = 8;
3042     // Branch to the li instruction.
3043     emitRRI(Mips::BNE, RtReg, ZeroReg, BranchTargetNoTraps, IDLoc,
3044             Instructions);
3045   }
3046 
3047   emitRR(DivOp, RsReg, RtReg, IDLoc, Instructions);
3048 
3049   if (!UseTraps)
3050     emitII(Mips::BREAK, 0x7, 0, IDLoc, Instructions);
3051 
3052   if (!Signed) {
3053     emitR(Mips::MFLO, RsReg, IDLoc, Instructions);
3054     return false;
3055   }
3056 
3057   unsigned ATReg = getATReg(IDLoc);
3058   if (!ATReg)
3059     return true;
3060 
3061   emitRRI(Mips::ADDiu, ATReg, ZeroReg, -1, IDLoc, Instructions);
3062   if (IsMips64) {
3063     // Branch to the mflo instruction.
3064     emitRRI(Mips::BNE, RtReg, ATReg, BranchTarget, IDLoc, Instructions);
3065     emitRRI(Mips::ADDiu, ATReg, ZeroReg, 1, IDLoc, Instructions);
3066     emitRRI(Mips::DSLL32, ATReg, ATReg, 0x1f, IDLoc, Instructions);
3067   } else {
3068     // Branch to the mflo instruction.
3069     emitRRI(Mips::BNE, RtReg, ATReg, BranchTarget, IDLoc, Instructions);
3070     emitRI(Mips::LUi, ATReg, (uint16_t)0x8000, IDLoc, Instructions);
3071   }
3072 
3073   if (UseTraps)
3074     emitRRI(Mips::TEQ, RsReg, ATReg, 0x6, IDLoc, Instructions);
3075   else {
3076     // Branch to the mflo instruction.
3077     emitRRI(Mips::BNE, RsReg, ATReg, BranchTargetNoTraps, IDLoc, Instructions);
3078     emitRRI(Mips::SLL, ZeroReg, ZeroReg, 0, IDLoc, Instructions);
3079     emitII(Mips::BREAK, 0x6, 0, IDLoc, Instructions);
3080   }
3081   emitR(Mips::MFLO, RsReg, IDLoc, Instructions);
3082   return false;
3083 }
3084 
3085 bool MipsAsmParser::expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU,
3086                                 SMLoc IDLoc,
3087                                 SmallVectorImpl<MCInst> &Instructions) {
3088 
3089   assert(Inst.getNumOperands() == 3 && "Invalid operand count");
3090   assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg() &&
3091          Inst.getOperand(2).isReg() && "Invalid instruction operand.");
3092 
3093   unsigned FirstReg = Inst.getOperand(0).getReg();
3094   unsigned SecondReg = Inst.getOperand(1).getReg();
3095   unsigned ThirdReg = Inst.getOperand(2).getReg();
3096 
3097   if (hasMips1() && !hasMips2()) {
3098     unsigned ATReg = getATReg(IDLoc);
3099     if (!ATReg)
3100       return true;
3101     emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, Instructions);
3102     emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, Instructions);
3103     createNop(false, IDLoc, Instructions);
3104     emitRRI(Mips::ORi, ATReg, ThirdReg, 0x3, IDLoc, Instructions);
3105     emitRRI(Mips::XORi, ATReg, ATReg, 0x2, IDLoc, Instructions);
3106     emitRR(Mips::CTC1, Mips::RA, ATReg, IDLoc, Instructions);
3107     createNop(false, IDLoc, Instructions);
3108     emitRR(IsDouble ? (Is64FPU ? Mips::CVT_W_D64 : Mips::CVT_W_D32)
3109                     : Mips::CVT_W_S,
3110            FirstReg, SecondReg, IDLoc, Instructions);
3111     emitRR(Mips::CTC1, Mips::RA, ThirdReg, IDLoc, Instructions);
3112     createNop(false, IDLoc, Instructions);
3113     return false;
3114   }
3115 
3116   emitRR(IsDouble ? (Is64FPU ? Mips::TRUNC_W_D64 : Mips::TRUNC_W_D32)
3117                   : Mips::TRUNC_W_S,
3118          FirstReg, SecondReg, IDLoc, Instructions);
3119 
3120   return false;
3121 }
3122 
3123 bool MipsAsmParser::expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc,
3124                               SmallVectorImpl<MCInst> &Instructions) {
3125   if (hasMips32r6() || hasMips64r6()) {
3126     Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
3127     return false;
3128   }
3129 
3130   warnIfNoMacro(IDLoc);
3131 
3132   const MCOperand &DstRegOp = Inst.getOperand(0);
3133   assert(DstRegOp.isReg() && "expected register operand kind");
3134 
3135   const MCOperand &SrcRegOp = Inst.getOperand(1);
3136   assert(SrcRegOp.isReg() && "expected register operand kind");
3137 
3138   const MCOperand &OffsetImmOp = Inst.getOperand(2);
3139   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
3140 
3141   unsigned DstReg = DstRegOp.getReg();
3142   unsigned SrcReg = SrcRegOp.getReg();
3143   int64_t OffsetValue = OffsetImmOp.getImm();
3144 
3145   // NOTE: We always need AT for ULHU, as it is always used as the source
3146   // register for one of the LBu's.
3147   unsigned ATReg = getATReg(IDLoc);
3148   if (!ATReg)
3149     return true;
3150 
3151   // When the value of offset+1 does not fit in 16 bits, we have to load the
3152   // offset in AT, (D)ADDu the original source register (if there was one), and
3153   // then use AT as the source register for the 2 generated LBu's.
3154   bool LoadedOffsetInAT = false;
3155   if (!isInt<16>(OffsetValue + 1) || !isInt<16>(OffsetValue)) {
3156     LoadedOffsetInAT = true;
3157 
3158     if (loadImmediate(OffsetValue, ATReg, Mips::NoRegister, !ABI.ArePtrs64bit(),
3159                       true, IDLoc, Instructions))
3160       return true;
3161 
3162     // NOTE: We do this (D)ADDu here instead of doing it in loadImmediate()
3163     // because it will make our output more similar to GAS'. For example,
3164     // generating an "ori $1, $zero, 32768" followed by an "addu $1, $1, $9",
3165     // instead of just an "ori $1, $9, 32768".
3166     // NOTE: If there is no source register specified in the ULHU, the parser
3167     // will interpret it as $0.
3168     if (SrcReg != Mips::ZERO && SrcReg != Mips::ZERO_64)
3169       createAddu(ATReg, ATReg, SrcReg, ABI.ArePtrs64bit(), Instructions);
3170   }
3171 
3172   unsigned FirstLbuDstReg = LoadedOffsetInAT ? DstReg : ATReg;
3173   unsigned SecondLbuDstReg = LoadedOffsetInAT ? ATReg : DstReg;
3174   unsigned LbuSrcReg = LoadedOffsetInAT ? ATReg : SrcReg;
3175 
3176   int64_t FirstLbuOffset = 0, SecondLbuOffset = 0;
3177   if (isLittle()) {
3178     FirstLbuOffset = LoadedOffsetInAT ? 1 : (OffsetValue + 1);
3179     SecondLbuOffset = LoadedOffsetInAT ? 0 : OffsetValue;
3180   } else {
3181     FirstLbuOffset = LoadedOffsetInAT ? 0 : OffsetValue;
3182     SecondLbuOffset = LoadedOffsetInAT ? 1 : (OffsetValue + 1);
3183   }
3184 
3185   unsigned SllReg = LoadedOffsetInAT ? DstReg : ATReg;
3186 
3187   emitRRI(Signed ? Mips::LB : Mips::LBu, FirstLbuDstReg, LbuSrcReg,
3188           FirstLbuOffset, IDLoc, Instructions);
3189 
3190   emitRRI(Mips::LBu, SecondLbuDstReg, LbuSrcReg, SecondLbuOffset, IDLoc,
3191           Instructions);
3192 
3193   emitRRI(Mips::SLL, SllReg, SllReg, 8, IDLoc, Instructions);
3194 
3195   emitRRR(Mips::OR, DstReg, DstReg, ATReg, IDLoc, Instructions);
3196 
3197   return false;
3198 }
3199 
3200 bool MipsAsmParser::expandUlw(MCInst &Inst, SMLoc IDLoc,
3201                               SmallVectorImpl<MCInst> &Instructions) {
3202   if (hasMips32r6() || hasMips64r6()) {
3203     Error(IDLoc, "instruction not supported on mips32r6 or mips64r6");
3204     return false;
3205   }
3206 
3207   const MCOperand &DstRegOp = Inst.getOperand(0);
3208   assert(DstRegOp.isReg() && "expected register operand kind");
3209 
3210   const MCOperand &SrcRegOp = Inst.getOperand(1);
3211   assert(SrcRegOp.isReg() && "expected register operand kind");
3212 
3213   const MCOperand &OffsetImmOp = Inst.getOperand(2);
3214   assert(OffsetImmOp.isImm() && "expected immediate operand kind");
3215 
3216   unsigned SrcReg = SrcRegOp.getReg();
3217   int64_t OffsetValue = OffsetImmOp.getImm();
3218   unsigned ATReg = 0;
3219 
3220   // When the value of offset+3 does not fit in 16 bits, we have to load the
3221   // offset in AT, (D)ADDu the original source register (if there was one), and
3222   // then use AT as the source register for the generated LWL and LWR.
3223   bool LoadedOffsetInAT = false;
3224   if (!isInt<16>(OffsetValue + 3) || !isInt<16>(OffsetValue)) {
3225     ATReg = getATReg(IDLoc);
3226     if (!ATReg)
3227       return true;
3228     LoadedOffsetInAT = true;
3229 
3230     warnIfNoMacro(IDLoc);
3231 
3232     if (loadImmediate(OffsetValue, ATReg, Mips::NoRegister, !ABI.ArePtrs64bit(),
3233                       true, IDLoc, Instructions))
3234       return true;
3235 
3236     // NOTE: We do this (D)ADDu here instead of doing it in loadImmediate()
3237     // because it will make our output more similar to GAS'. For example,
3238     // generating an "ori $1, $zero, 32768" followed by an "addu $1, $1, $9",
3239     // instead of just an "ori $1, $9, 32768".
3240     // NOTE: If there is no source register specified in the ULW, the parser
3241     // will interpret it as $0.
3242     if (SrcReg != Mips::ZERO && SrcReg != Mips::ZERO_64)
3243       createAddu(ATReg, ATReg, SrcReg, ABI.ArePtrs64bit(), Instructions);
3244   }
3245 
3246   unsigned FinalSrcReg = LoadedOffsetInAT ? ATReg : SrcReg;
3247   int64_t LeftLoadOffset = 0, RightLoadOffset  = 0;
3248   if (isLittle()) {
3249     LeftLoadOffset = LoadedOffsetInAT ? 3 : (OffsetValue + 3);
3250     RightLoadOffset  = LoadedOffsetInAT ? 0 : OffsetValue;
3251   } else {
3252     LeftLoadOffset = LoadedOffsetInAT ? 0 : OffsetValue;
3253     RightLoadOffset  = LoadedOffsetInAT ? 3 : (OffsetValue + 3);
3254   }
3255 
3256   emitRRI(Mips::LWL, DstRegOp.getReg(), FinalSrcReg, LeftLoadOffset, IDLoc,
3257           Instructions);
3258 
3259   emitRRI(Mips::LWR, DstRegOp.getReg(), FinalSrcReg, RightLoadOffset, IDLoc,
3260           Instructions);
3261 
3262   return false;
3263 }
3264 
3265 bool MipsAsmParser::expandAliasImmediate(MCInst &Inst, SMLoc IDLoc,
3266                                          SmallVectorImpl<MCInst> &Instructions) {
3267 
3268   assert (Inst.getNumOperands() == 3 && "Invalid operand count");
3269   assert (Inst.getOperand(0).isReg() &&
3270           Inst.getOperand(1).isReg() &&
3271           Inst.getOperand(2).isImm() && "Invalid instruction operand.");
3272 
3273   unsigned ATReg = Mips::NoRegister;
3274   unsigned FinalDstReg = Mips::NoRegister;
3275   unsigned DstReg = Inst.getOperand(0).getReg();
3276   unsigned SrcReg = Inst.getOperand(1).getReg();
3277   int64_t ImmValue = Inst.getOperand(2).getImm();
3278 
3279   bool Is32Bit = isInt<32>(ImmValue) || isUInt<32>(ImmValue);
3280 
3281   unsigned FinalOpcode = Inst.getOpcode();
3282 
3283   if (DstReg == SrcReg) {
3284     ATReg = getATReg(Inst.getLoc());
3285     if (!ATReg)
3286       return true;
3287     FinalDstReg = DstReg;
3288     DstReg = ATReg;
3289   }
3290 
3291   if (!loadImmediate(ImmValue, DstReg, Mips::NoRegister, Is32Bit, false, Inst.getLoc(), Instructions)) {
3292     switch (FinalOpcode) {
3293     default:
3294       llvm_unreachable("unimplemented expansion");
3295     case (Mips::ADDi):
3296       FinalOpcode = Mips::ADD;
3297       break;
3298     case (Mips::ADDiu):
3299       FinalOpcode = Mips::ADDu;
3300       break;
3301     case (Mips::ANDi):
3302       FinalOpcode = Mips::AND;
3303       break;
3304     case (Mips::NORImm):
3305       FinalOpcode = Mips::NOR;
3306       break;
3307     case (Mips::ORi):
3308       FinalOpcode = Mips::OR;
3309       break;
3310     case (Mips::SLTi):
3311       FinalOpcode = Mips::SLT;
3312       break;
3313     case (Mips::SLTiu):
3314       FinalOpcode = Mips::SLTu;
3315       break;
3316     case (Mips::XORi):
3317       FinalOpcode = Mips::XOR;
3318       break;
3319     }
3320 
3321     if (FinalDstReg == Mips::NoRegister)
3322       emitRRR(FinalOpcode, DstReg, DstReg, SrcReg, IDLoc, Instructions);
3323     else
3324       emitRRR(FinalOpcode, FinalDstReg, FinalDstReg, DstReg, IDLoc,
3325               Instructions);
3326     return false;
3327   }
3328   return true;
3329 }
3330 
3331 bool MipsAsmParser::expandRotation(MCInst &Inst, SMLoc IDLoc,
3332                                    SmallVectorImpl<MCInst> &Instructions) {
3333   unsigned ATReg = Mips::NoRegister;
3334   unsigned DReg = Inst.getOperand(0).getReg();
3335   unsigned SReg = Inst.getOperand(1).getReg();
3336   unsigned TReg = Inst.getOperand(2).getReg();
3337   unsigned TmpReg = DReg;
3338 
3339   unsigned FirstShift = Mips::NOP;
3340   unsigned SecondShift = Mips::NOP;
3341 
3342   if (hasMips32r2()) {
3343 
3344     if (DReg == SReg) {
3345       TmpReg = getATReg(Inst.getLoc());
3346       if (!TmpReg)
3347         return true;
3348     }
3349 
3350     if (Inst.getOpcode() == Mips::ROL) {
3351       emitRRR(Mips::SUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), Instructions);
3352       emitRRR(Mips::ROTRV, DReg, SReg, TmpReg, Inst.getLoc(), Instructions);
3353       return false;
3354     }
3355 
3356     if (Inst.getOpcode() == Mips::ROR) {
3357       emitRRR(Mips::ROTRV, DReg, SReg, TReg, Inst.getLoc(), Instructions);
3358       return false;
3359     }
3360 
3361     return true;
3362   }
3363 
3364   if (hasMips32()) {
3365 
3366     switch (Inst.getOpcode()) {
3367     default:
3368       llvm_unreachable("unexpected instruction opcode");
3369     case Mips::ROL:
3370       FirstShift = Mips::SRLV;
3371       SecondShift = Mips::SLLV;
3372       break;
3373     case Mips::ROR:
3374       FirstShift = Mips::SLLV;
3375       SecondShift = Mips::SRLV;
3376       break;
3377     }
3378 
3379     ATReg = getATReg(Inst.getLoc());
3380     if (!ATReg)
3381       return true;
3382 
3383     emitRRR(Mips::SUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), Instructions);
3384     emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), Instructions);
3385     emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), Instructions);
3386     emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), Instructions);
3387 
3388     return false;
3389   }
3390 
3391   return true;
3392 }
3393 
3394 bool MipsAsmParser::expandRotationImm(MCInst &Inst, SMLoc IDLoc,
3395                                       SmallVectorImpl<MCInst> &Instructions) {
3396 
3397   unsigned ATReg = Mips::NoRegister;
3398   unsigned DReg = Inst.getOperand(0).getReg();
3399   unsigned SReg = Inst.getOperand(1).getReg();
3400   int64_t ImmValue = Inst.getOperand(2).getImm();
3401 
3402   unsigned FirstShift = Mips::NOP;
3403   unsigned SecondShift = Mips::NOP;
3404 
3405   if (hasMips32r2()) {
3406 
3407     if (Inst.getOpcode() == Mips::ROLImm) {
3408       uint64_t MaxShift = 32;
3409       uint64_t ShiftValue = ImmValue;
3410       if (ImmValue != 0)
3411         ShiftValue = MaxShift - ImmValue;
3412       emitRRI(Mips::ROTR, DReg, SReg, ShiftValue, Inst.getLoc(), Instructions);
3413       return false;
3414     }
3415 
3416     if (Inst.getOpcode() == Mips::RORImm) {
3417       emitRRI(Mips::ROTR, DReg, SReg, ImmValue, Inst.getLoc(), Instructions);
3418       return false;
3419     }
3420 
3421     return true;
3422   }
3423 
3424   if (hasMips32()) {
3425 
3426     if (ImmValue == 0) {
3427       emitRRI(Mips::SRL, DReg, SReg, 0, Inst.getLoc(), Instructions);
3428       return false;
3429     }
3430 
3431     switch (Inst.getOpcode()) {
3432     default:
3433       llvm_unreachable("unexpected instruction opcode");
3434     case Mips::ROLImm:
3435       FirstShift = Mips::SLL;
3436       SecondShift = Mips::SRL;
3437       break;
3438     case Mips::RORImm:
3439       FirstShift = Mips::SRL;
3440       SecondShift = Mips::SLL;
3441       break;
3442     }
3443 
3444     ATReg = getATReg(Inst.getLoc());
3445     if (!ATReg)
3446       return true;
3447 
3448     emitRRI(FirstShift, ATReg, SReg, ImmValue, Inst.getLoc(), Instructions);
3449     emitRRI(SecondShift, DReg, SReg, 32 - ImmValue, Inst.getLoc(), Instructions);
3450     emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), Instructions);
3451 
3452     return false;
3453   }
3454 
3455   return true;
3456 }
3457 
3458 bool MipsAsmParser::expandDRotation(MCInst &Inst, SMLoc IDLoc,
3459                                     SmallVectorImpl<MCInst> &Instructions) {
3460 
3461   unsigned ATReg = Mips::NoRegister;
3462   unsigned DReg = Inst.getOperand(0).getReg();
3463   unsigned SReg = Inst.getOperand(1).getReg();
3464   unsigned TReg = Inst.getOperand(2).getReg();
3465   unsigned TmpReg = DReg;
3466 
3467   unsigned FirstShift = Mips::NOP;
3468   unsigned SecondShift = Mips::NOP;
3469 
3470   if (hasMips64r2()) {
3471 
3472     if (TmpReg == SReg) {
3473       TmpReg = getATReg(Inst.getLoc());
3474       if (!TmpReg)
3475         return true;
3476     }
3477 
3478     if (Inst.getOpcode() == Mips::DROL) {
3479       emitRRR(Mips::DSUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), Instructions);
3480       emitRRR(Mips::DROTRV, DReg, SReg, TmpReg, Inst.getLoc(), Instructions);
3481       return false;
3482     }
3483 
3484     if (Inst.getOpcode() == Mips::DROR) {
3485       emitRRR(Mips::DROTRV, DReg, SReg, TReg, Inst.getLoc(), Instructions);
3486       return false;
3487     }
3488 
3489     return true;
3490   }
3491 
3492   if (hasMips64()) {
3493 
3494     switch (Inst.getOpcode()) {
3495     default:
3496       llvm_unreachable("unexpected instruction opcode");
3497     case Mips::DROL:
3498       FirstShift = Mips::DSRLV;
3499       SecondShift = Mips::DSLLV;
3500       break;
3501     case Mips::DROR:
3502       FirstShift = Mips::DSLLV;
3503       SecondShift = Mips::DSRLV;
3504       break;
3505     }
3506 
3507     ATReg = getATReg(Inst.getLoc());
3508     if (!ATReg)
3509       return true;
3510 
3511     emitRRR(Mips::DSUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), Instructions);
3512     emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), Instructions);
3513     emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), Instructions);
3514     emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), Instructions);
3515 
3516     return false;
3517   }
3518 
3519   return true;
3520 }
3521 
3522 bool MipsAsmParser::expandDRotationImm(MCInst &Inst, SMLoc IDLoc,
3523                                        SmallVectorImpl<MCInst> &Instructions) {
3524 
3525   unsigned ATReg = Mips::NoRegister;
3526   unsigned DReg = Inst.getOperand(0).getReg();
3527   unsigned SReg = Inst.getOperand(1).getReg();
3528   int64_t ImmValue = Inst.getOperand(2).getImm() % 64;
3529 
3530   unsigned FirstShift = Mips::NOP;
3531   unsigned SecondShift = Mips::NOP;
3532 
3533   MCInst TmpInst;
3534 
3535   if (hasMips64r2()) {
3536 
3537     unsigned FinalOpcode = Mips::NOP;
3538     if (ImmValue == 0)
3539       FinalOpcode = Mips::DROTR;
3540     else if (ImmValue % 32 == 0)
3541       FinalOpcode = Mips::DROTR32;
3542     else if ((ImmValue >= 1) && (ImmValue <= 32)) {
3543       if (Inst.getOpcode() == Mips::DROLImm)
3544         FinalOpcode = Mips::DROTR32;
3545       else
3546         FinalOpcode = Mips::DROTR;
3547     } else if (ImmValue >= 33) {
3548       if (Inst.getOpcode() == Mips::DROLImm)
3549         FinalOpcode = Mips::DROTR;
3550       else
3551         FinalOpcode = Mips::DROTR32;
3552     }
3553 
3554     uint64_t ShiftValue = ImmValue % 32;
3555     if (Inst.getOpcode() == Mips::DROLImm)
3556       ShiftValue = (32 - ImmValue % 32) % 32;
3557 
3558     emitRRI(FinalOpcode, DReg, SReg, ShiftValue, Inst.getLoc(), Instructions);
3559 
3560     return false;
3561   }
3562 
3563   if (hasMips64()) {
3564 
3565     if (ImmValue == 0) {
3566       emitRRI(Mips::DSRL, DReg, SReg, 0, Inst.getLoc(), Instructions);
3567       return false;
3568     }
3569 
3570     switch (Inst.getOpcode()) {
3571     default:
3572       llvm_unreachable("unexpected instruction opcode");
3573     case Mips::DROLImm:
3574       if ((ImmValue >= 1) && (ImmValue <= 31)) {
3575         FirstShift = Mips::DSLL;
3576         SecondShift = Mips::DSRL32;
3577       }
3578       if (ImmValue == 32) {
3579         FirstShift = Mips::DSLL32;
3580         SecondShift = Mips::DSRL32;
3581       }
3582       if ((ImmValue >= 33) && (ImmValue <= 63)) {
3583         FirstShift = Mips::DSLL32;
3584         SecondShift = Mips::DSRL;
3585       }
3586       break;
3587     case Mips::DRORImm:
3588       if ((ImmValue >= 1) && (ImmValue <= 31)) {
3589         FirstShift = Mips::DSRL;
3590         SecondShift = Mips::DSLL32;
3591       }
3592       if (ImmValue == 32) {
3593         FirstShift = Mips::DSRL32;
3594         SecondShift = Mips::DSLL32;
3595       }
3596       if ((ImmValue >= 33) && (ImmValue <= 63)) {
3597         FirstShift = Mips::DSRL32;
3598         SecondShift = Mips::DSLL;
3599       }
3600       break;
3601     }
3602 
3603     ATReg = getATReg(Inst.getLoc());
3604     if (!ATReg)
3605       return true;
3606 
3607     emitRRI(FirstShift, ATReg, SReg, ImmValue % 32, Inst.getLoc(), Instructions);
3608     emitRRI(SecondShift, DReg, SReg, (32 - ImmValue % 32) % 32, Inst.getLoc(), Instructions);
3609     emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), Instructions);
3610 
3611     return false;
3612   }
3613 
3614   return true;
3615 }
3616 
3617 bool MipsAsmParser::expandAbs(MCInst &Inst, SMLoc IDLoc,
3618                               SmallVectorImpl<MCInst> &Instructions) {
3619 
3620   unsigned FirstRegOp = Inst.getOperand(0).getReg();
3621   unsigned SecondRegOp = Inst.getOperand(1).getReg();
3622 
3623   emitRI(Mips::BGEZ, SecondRegOp, 8, IDLoc, Instructions);
3624   if (FirstRegOp != SecondRegOp)
3625     emitRRR(Mips::ADDu, FirstRegOp, SecondRegOp, Mips::ZERO, IDLoc, Instructions);
3626   else
3627     createNop(false, IDLoc, Instructions);
3628   emitRRR(Mips::SUB, FirstRegOp, Mips::ZERO, SecondRegOp, IDLoc, Instructions);
3629 
3630   return false;
3631 }
3632 
3633 void MipsAsmParser::createNop(bool hasShortDelaySlot, SMLoc IDLoc,
3634                               SmallVectorImpl<MCInst> &Instructions) {
3635   if (hasShortDelaySlot)
3636     emitRR(Mips::MOVE16_MM, Mips::ZERO, Mips::ZERO, IDLoc, Instructions);
3637   else
3638     emitRRI(Mips::SLL, Mips::ZERO, Mips::ZERO, 0, IDLoc, Instructions);
3639 }
3640 
3641 void MipsAsmParser::createAddu(unsigned DstReg, unsigned SrcReg,
3642                                unsigned TrgReg, bool Is64Bit,
3643                                SmallVectorImpl<MCInst> &Instructions) {
3644   emitRRR(Is64Bit ? Mips::DADDu : Mips::ADDu, DstReg, SrcReg, TrgReg, SMLoc(),
3645           Instructions);
3646 }
3647 
3648 void MipsAsmParser::createCpRestoreMemOp(
3649     bool IsLoad, int StackOffset, SMLoc IDLoc,
3650     SmallVectorImpl<MCInst> &Instructions) {
3651   // If the offset can not fit into 16 bits, we need to expand.
3652   if (!isInt<16>(StackOffset)) {
3653     MCInst MemInst;
3654     MemInst.setOpcode(IsLoad ? Mips::LW : Mips::SW);
3655     MemInst.addOperand(MCOperand::createReg(Mips::GP));
3656     MemInst.addOperand(MCOperand::createReg(Mips::SP));
3657     MemInst.addOperand(MCOperand::createImm(StackOffset));
3658     expandMemInst(MemInst, IDLoc, Instructions, IsLoad, true /*HasImmOpnd*/);
3659     return;
3660   }
3661 
3662   emitRRI(IsLoad ? Mips::LW : Mips::SW, Mips::GP, Mips::SP, StackOffset, IDLoc,
3663           Instructions);
3664 }
3665 
3666 unsigned MipsAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
3667   // As described by the Mips32r2 spec, the registers Rd and Rs for
3668   // jalr.hb must be different.
3669   unsigned Opcode = Inst.getOpcode();
3670 
3671   if (Opcode == Mips::JALR_HB &&
3672       (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()))
3673     return Match_RequiresDifferentSrcAndDst;
3674 
3675   return Match_Success;
3676 }
3677 
3678 static SMLoc RefineErrorLoc(const SMLoc Loc, const OperandVector &Operands,
3679                             uint64_t ErrorInfo) {
3680   if (ErrorInfo != ~0ULL && ErrorInfo < Operands.size()) {
3681     SMLoc ErrorLoc = Operands[ErrorInfo]->getStartLoc();
3682     if (ErrorLoc == SMLoc())
3683       return Loc;
3684     return ErrorLoc;
3685   }
3686   return Loc;
3687 }
3688 
3689 bool MipsAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
3690                                             OperandVector &Operands,
3691                                             MCStreamer &Out,
3692                                             uint64_t &ErrorInfo,
3693                                             bool MatchingInlineAsm) {
3694 
3695   MCInst Inst;
3696   SmallVector<MCInst, 8> Instructions;
3697   unsigned MatchResult =
3698       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
3699 
3700   switch (MatchResult) {
3701   case Match_Success: {
3702     if (processInstruction(Inst, IDLoc, Instructions))
3703       return true;
3704     for (unsigned i = 0; i < Instructions.size(); i++)
3705       Out.EmitInstruction(Instructions[i], getSTI());
3706     return false;
3707   }
3708   case Match_MissingFeature:
3709     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
3710     return true;
3711   case Match_InvalidOperand: {
3712     SMLoc ErrorLoc = IDLoc;
3713     if (ErrorInfo != ~0ULL) {
3714       if (ErrorInfo >= Operands.size())
3715         return Error(IDLoc, "too few operands for instruction");
3716 
3717       ErrorLoc = Operands[ErrorInfo]->getStartLoc();
3718       if (ErrorLoc == SMLoc())
3719         ErrorLoc = IDLoc;
3720     }
3721 
3722     return Error(ErrorLoc, "invalid operand for instruction");
3723   }
3724   case Match_MnemonicFail:
3725     return Error(IDLoc, "invalid instruction");
3726   case Match_RequiresDifferentSrcAndDst:
3727     return Error(IDLoc, "source and destination must be different");
3728   case Match_Immz:
3729     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected '0'");
3730   case Match_UImm1_0:
3731     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3732                  "expected 1-bit unsigned immediate");
3733   case Match_UImm2_0:
3734     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3735                  "expected 2-bit unsigned immediate");
3736   case Match_UImm2_1:
3737     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3738                  "expected immediate in range 1 .. 4");
3739   case Match_UImm3_0:
3740     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3741                  "expected 3-bit unsigned immediate");
3742   case Match_UImm4_0:
3743     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3744                  "expected 4-bit unsigned immediate");
3745   case Match_SImm4_0:
3746     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3747                  "expected 4-bit signed immediate");
3748   case Match_UImm5_0:
3749     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3750                  "expected 5-bit unsigned immediate");
3751   case Match_SImm5_0:
3752     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3753                  "expected 5-bit signed immediate");
3754   case Match_UImm5_1:
3755     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3756                  "expected immediate in range 1 .. 32");
3757   case Match_UImm5_32:
3758     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3759                  "expected immediate in range 32 .. 63");
3760   case Match_UImm5_33:
3761     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3762                  "expected immediate in range 33 .. 64");
3763   case Match_UImm5_0_Report_UImm6:
3764     // This is used on UImm5 operands that have a corresponding UImm5_32
3765     // operand to avoid confusing the user.
3766     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3767                  "expected 6-bit unsigned immediate");
3768   case Match_UImm5_Lsl2:
3769     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3770                  "expected both 7-bit unsigned immediate and multiple of 4");
3771   case Match_UImmRange2_64:
3772     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3773                  "expected immediate in range 2 .. 64");
3774   case Match_UImm6_0:
3775     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3776                  "expected 6-bit unsigned immediate");
3777   case Match_UImm6_Lsl2:
3778     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3779                  "expected both 8-bit unsigned immediate and multiple of 4");
3780   case Match_SImm6_0:
3781     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3782                  "expected 6-bit signed immediate");
3783   case Match_UImm7_0:
3784     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3785                  "expected 7-bit unsigned immediate");
3786   case Match_UImm7_N1:
3787     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3788                  "expected immediate in range -1 .. 126");
3789   case Match_SImm7_Lsl2:
3790     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3791                  "expected both 9-bit signed immediate and multiple of 4");
3792   case Match_UImm8_0:
3793     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3794                  "expected 8-bit unsigned immediate");
3795   case Match_UImm10_0:
3796     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3797                  "expected 10-bit unsigned immediate");
3798   case Match_SImm10_0:
3799     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3800                  "expected 10-bit signed immediate");
3801   case Match_SImm11_0:
3802     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3803                  "expected 11-bit signed immediate");
3804   case Match_UImm16:
3805   case Match_UImm16_Relaxed:
3806     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3807                  "expected 16-bit unsigned immediate");
3808   case Match_SImm16:
3809   case Match_SImm16_Relaxed:
3810     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3811                  "expected 16-bit signed immediate");
3812   case Match_UImm20_0:
3813     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3814                  "expected 20-bit unsigned immediate");
3815   case Match_UImm26_0:
3816     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3817                  "expected 26-bit unsigned immediate");
3818   case Match_SImm32:
3819   case Match_SImm32_Relaxed:
3820     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3821                  "expected 32-bit signed immediate");
3822   case Match_MemSImm9:
3823     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3824                  "expected memory with 9-bit signed offset");
3825   case Match_MemGPSImm9:
3826     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3827                  "expected memory with $gp and 9-bit signed offset");
3828   case Match_MemSImm10:
3829     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3830                  "expected memory with 10-bit signed offset");
3831   case Match_MemSImm10Lsl1:
3832     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3833                  "expected memory with 11-bit signed offset and multiple of 2");
3834   case Match_MemSImm10Lsl2:
3835     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3836                  "expected memory with 12-bit signed offset and multiple of 4");
3837   case Match_MemSImm10Lsl3:
3838     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3839                  "expected memory with 13-bit signed offset and multiple of 8");
3840   case Match_MemSImm11:
3841     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3842                  "expected memory with 11-bit signed offset");
3843   case Match_MemSImm16:
3844     return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo),
3845                  "expected memory with 16-bit signed offset");
3846   }
3847 
3848   llvm_unreachable("Implement any new match types added!");
3849 }
3850 
3851 void MipsAsmParser::warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc) {
3852   if (RegIndex != 0 && AssemblerOptions.back()->getATRegIndex() == RegIndex)
3853     Warning(Loc, "used $at (currently $" + Twine(RegIndex) +
3854                      ") without \".set noat\"");
3855 }
3856 
3857 void MipsAsmParser::warnIfNoMacro(SMLoc Loc) {
3858   if (!AssemblerOptions.back()->isMacro())
3859     Warning(Loc, "macro instruction expanded into multiple instructions");
3860 }
3861 
3862 void
3863 MipsAsmParser::printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg,
3864                                      SMRange Range, bool ShowColors) {
3865   getSourceManager().PrintMessage(Range.Start, SourceMgr::DK_Warning, Msg,
3866                                   Range, SMFixIt(Range, FixMsg),
3867                                   ShowColors);
3868 }
3869 
3870 int MipsAsmParser::matchCPURegisterName(StringRef Name) {
3871   int CC;
3872 
3873   CC = StringSwitch<unsigned>(Name)
3874            .Case("zero", 0)
3875            .Case("at", 1)
3876            .Case("a0", 4)
3877            .Case("a1", 5)
3878            .Case("a2", 6)
3879            .Case("a3", 7)
3880            .Case("v0", 2)
3881            .Case("v1", 3)
3882            .Case("s0", 16)
3883            .Case("s1", 17)
3884            .Case("s2", 18)
3885            .Case("s3", 19)
3886            .Case("s4", 20)
3887            .Case("s5", 21)
3888            .Case("s6", 22)
3889            .Case("s7", 23)
3890            .Case("k0", 26)
3891            .Case("k1", 27)
3892            .Case("gp", 28)
3893            .Case("sp", 29)
3894            .Case("fp", 30)
3895            .Case("s8", 30)
3896            .Case("ra", 31)
3897            .Case("t0", 8)
3898            .Case("t1", 9)
3899            .Case("t2", 10)
3900            .Case("t3", 11)
3901            .Case("t4", 12)
3902            .Case("t5", 13)
3903            .Case("t6", 14)
3904            .Case("t7", 15)
3905            .Case("t8", 24)
3906            .Case("t9", 25)
3907            .Default(-1);
3908 
3909   if (!(isABI_N32() || isABI_N64()))
3910     return CC;
3911 
3912   if (12 <= CC && CC <= 15) {
3913     // Name is one of t4-t7
3914     AsmToken RegTok = getLexer().peekTok();
3915     SMRange RegRange = RegTok.getLocRange();
3916 
3917     StringRef FixedName = StringSwitch<StringRef>(Name)
3918                               .Case("t4", "t0")
3919                               .Case("t5", "t1")
3920                               .Case("t6", "t2")
3921                               .Case("t7", "t3")
3922                               .Default("");
3923     assert(FixedName != "" &&  "Register name is not one of t4-t7.");
3924 
3925     printWarningWithFixIt("register names $t4-$t7 are only available in O32.",
3926                           "Did you mean $" + FixedName + "?", RegRange);
3927   }
3928 
3929   // Although SGI documentation just cuts out t0-t3 for n32/n64,
3930   // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7
3931   // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7.
3932   if (8 <= CC && CC <= 11)
3933     CC += 4;
3934 
3935   if (CC == -1)
3936     CC = StringSwitch<unsigned>(Name)
3937              .Case("a4", 8)
3938              .Case("a5", 9)
3939              .Case("a6", 10)
3940              .Case("a7", 11)
3941              .Case("kt0", 26)
3942              .Case("kt1", 27)
3943              .Default(-1);
3944 
3945   return CC;
3946 }
3947 
3948 int MipsAsmParser::matchHWRegsRegisterName(StringRef Name) {
3949   int CC;
3950 
3951   CC = StringSwitch<unsigned>(Name)
3952             .Case("hwr_cpunum", 0)
3953             .Case("hwr_synci_step", 1)
3954             .Case("hwr_cc", 2)
3955             .Case("hwr_ccres", 3)
3956             .Case("hwr_ulr", 29)
3957             .Default(-1);
3958 
3959   return CC;
3960 }
3961 
3962 int MipsAsmParser::matchFPURegisterName(StringRef Name) {
3963 
3964   if (Name[0] == 'f') {
3965     StringRef NumString = Name.substr(1);
3966     unsigned IntVal;
3967     if (NumString.getAsInteger(10, IntVal))
3968       return -1;     // This is not an integer.
3969     if (IntVal > 31) // Maximum index for fpu register.
3970       return -1;
3971     return IntVal;
3972   }
3973   return -1;
3974 }
3975 
3976 int MipsAsmParser::matchFCCRegisterName(StringRef Name) {
3977 
3978   if (Name.startswith("fcc")) {
3979     StringRef NumString = Name.substr(3);
3980     unsigned IntVal;
3981     if (NumString.getAsInteger(10, IntVal))
3982       return -1;    // This is not an integer.
3983     if (IntVal > 7) // There are only 8 fcc registers.
3984       return -1;
3985     return IntVal;
3986   }
3987   return -1;
3988 }
3989 
3990 int MipsAsmParser::matchACRegisterName(StringRef Name) {
3991 
3992   if (Name.startswith("ac")) {
3993     StringRef NumString = Name.substr(2);
3994     unsigned IntVal;
3995     if (NumString.getAsInteger(10, IntVal))
3996       return -1;    // This is not an integer.
3997     if (IntVal > 3) // There are only 3 acc registers.
3998       return -1;
3999     return IntVal;
4000   }
4001   return -1;
4002 }
4003 
4004 int MipsAsmParser::matchMSA128RegisterName(StringRef Name) {
4005   unsigned IntVal;
4006 
4007   if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal))
4008     return -1;
4009 
4010   if (IntVal > 31)
4011     return -1;
4012 
4013   return IntVal;
4014 }
4015 
4016 int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) {
4017   int CC;
4018 
4019   CC = StringSwitch<unsigned>(Name)
4020            .Case("msair", 0)
4021            .Case("msacsr", 1)
4022            .Case("msaaccess", 2)
4023            .Case("msasave", 3)
4024            .Case("msamodify", 4)
4025            .Case("msarequest", 5)
4026            .Case("msamap", 6)
4027            .Case("msaunmap", 7)
4028            .Default(-1);
4029 
4030   return CC;
4031 }
4032 
4033 unsigned MipsAsmParser::getATReg(SMLoc Loc) {
4034   unsigned ATIndex = AssemblerOptions.back()->getATRegIndex();
4035   if (ATIndex == 0) {
4036     reportParseError(Loc,
4037                      "pseudo-instruction requires $at, which is not available");
4038     return 0;
4039   }
4040   unsigned AT = getReg(
4041       (isGP64bit()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, ATIndex);
4042   return AT;
4043 }
4044 
4045 unsigned MipsAsmParser::getReg(int RC, int RegNo) {
4046   return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo);
4047 }
4048 
4049 unsigned MipsAsmParser::getGPR(int RegNo) {
4050   return getReg(isGP64bit() ? Mips::GPR64RegClassID : Mips::GPR32RegClassID,
4051                 RegNo);
4052 }
4053 
4054 int MipsAsmParser::matchRegisterByNumber(unsigned RegNum, unsigned RegClass) {
4055   if (RegNum >
4056       getContext().getRegisterInfo()->getRegClass(RegClass).getNumRegs() - 1)
4057     return -1;
4058 
4059   return getReg(RegClass, RegNum);
4060 }
4061 
4062 bool MipsAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
4063   MCAsmParser &Parser = getParser();
4064   DEBUG(dbgs() << "parseOperand\n");
4065 
4066   // Check if the current operand has a custom associated parser, if so, try to
4067   // custom parse the operand, or fallback to the general approach.
4068   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
4069   if (ResTy == MatchOperand_Success)
4070     return false;
4071   // If there wasn't a custom match, try the generic matcher below. Otherwise,
4072   // there was a match, but an error occurred, in which case, just return that
4073   // the operand parsing failed.
4074   if (ResTy == MatchOperand_ParseFail)
4075     return true;
4076 
4077   DEBUG(dbgs() << ".. Generic Parser\n");
4078 
4079   switch (getLexer().getKind()) {
4080   default:
4081     Error(Parser.getTok().getLoc(), "unexpected token in operand");
4082     return true;
4083   case AsmToken::Dollar: {
4084     // Parse the register.
4085     SMLoc S = Parser.getTok().getLoc();
4086 
4087     // Almost all registers have been parsed by custom parsers. There is only
4088     // one exception to this. $zero (and it's alias $0) will reach this point
4089     // for div, divu, and similar instructions because it is not an operand
4090     // to the instruction definition but an explicit register. Special case
4091     // this situation for now.
4092     if (parseAnyRegister(Operands) != MatchOperand_NoMatch)
4093       return false;
4094 
4095     // Maybe it is a symbol reference.
4096     StringRef Identifier;
4097     if (Parser.parseIdentifier(Identifier))
4098       return true;
4099 
4100     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4101     MCSymbol *Sym = getContext().getOrCreateSymbol("$" + Identifier);
4102     // Otherwise create a symbol reference.
4103     const MCExpr *Res =
4104         MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
4105 
4106     Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this));
4107     return false;
4108   }
4109   // Else drop to expression parsing.
4110   case AsmToken::LParen:
4111   case AsmToken::Minus:
4112   case AsmToken::Plus:
4113   case AsmToken::Integer:
4114   case AsmToken::Tilde:
4115   case AsmToken::String: {
4116     DEBUG(dbgs() << ".. generic integer\n");
4117     OperandMatchResultTy ResTy = parseImm(Operands);
4118     return ResTy != MatchOperand_Success;
4119   }
4120   case AsmToken::Percent: {
4121     // It is a symbol reference or constant expression.
4122     const MCExpr *IdVal;
4123     SMLoc S = Parser.getTok().getLoc(); // Start location of the operand.
4124     if (parseRelocOperand(IdVal))
4125       return true;
4126 
4127     SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4128 
4129     Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
4130     return false;
4131   } // case AsmToken::Percent
4132   } // switch(getLexer().getKind())
4133   return true;
4134 }
4135 
4136 const MCExpr *MipsAsmParser::evaluateRelocExpr(const MCExpr *Expr,
4137                                                StringRef RelocStr) {
4138   const MCExpr *Res;
4139   // Check the type of the expression.
4140   if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Expr)) {
4141     // It's a constant, evaluate reloc value.
4142     int16_t Val;
4143     switch (getVariantKind(RelocStr)) {
4144     case MCSymbolRefExpr::VK_Mips_ABS_LO:
4145       // Get the 1st 16-bits.
4146       Val = MCE->getValue() & 0xffff;
4147       break;
4148     case MCSymbolRefExpr::VK_Mips_ABS_HI:
4149     case MCSymbolRefExpr::VK_Mips_GOT:
4150       // Get the 2nd 16-bits. Also add 1 if bit 15 is 1, to compensate for low
4151       // 16 bits being negative.
4152       Val = ((MCE->getValue() + 0x8000) >> 16) & 0xffff;
4153       break;
4154     case MCSymbolRefExpr::VK_Mips_HIGHER:
4155       // Get the 3rd 16-bits.
4156       Val = ((MCE->getValue() + 0x80008000LL) >> 32) & 0xffff;
4157       break;
4158     case MCSymbolRefExpr::VK_Mips_HIGHEST:
4159       // Get the 4th 16-bits.
4160       Val = ((MCE->getValue() + 0x800080008000LL) >> 48) & 0xffff;
4161       break;
4162     default:
4163       report_fatal_error("unsupported reloc value");
4164     }
4165     return MCConstantExpr::create(Val, getContext());
4166   }
4167 
4168   if (const MCSymbolRefExpr *MSRE = dyn_cast<MCSymbolRefExpr>(Expr)) {
4169     // It's a symbol, create a symbolic expression from the symbol.
4170     const MCSymbol *Symbol = &MSRE->getSymbol();
4171     MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
4172     Res = MCSymbolRefExpr::create(Symbol, VK, getContext());
4173     return Res;
4174   }
4175 
4176   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
4177     MCSymbolRefExpr::VariantKind VK = getVariantKind(RelocStr);
4178 
4179     // Try to create target expression.
4180     if (MipsMCExpr::isSupportedBinaryExpr(VK, BE))
4181       return MipsMCExpr::create(VK, Expr, getContext());
4182 
4183     const MCExpr *LExp = evaluateRelocExpr(BE->getLHS(), RelocStr);
4184     const MCExpr *RExp = evaluateRelocExpr(BE->getRHS(), RelocStr);
4185     Res = MCBinaryExpr::create(BE->getOpcode(), LExp, RExp, getContext());
4186     return Res;
4187   }
4188 
4189   if (const MCUnaryExpr *UN = dyn_cast<MCUnaryExpr>(Expr)) {
4190     const MCExpr *UnExp = evaluateRelocExpr(UN->getSubExpr(), RelocStr);
4191     Res = MCUnaryExpr::create(UN->getOpcode(), UnExp, getContext());
4192     return Res;
4193   }
4194   // Just return the original expression.
4195   return Expr;
4196 }
4197 
4198 bool MipsAsmParser::isEvaluated(const MCExpr *Expr) {
4199 
4200   switch (Expr->getKind()) {
4201   case MCExpr::Constant:
4202     return true;
4203   case MCExpr::SymbolRef:
4204     return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None);
4205   case MCExpr::Binary:
4206     if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
4207       if (!isEvaluated(BE->getLHS()))
4208         return false;
4209       return isEvaluated(BE->getRHS());
4210     }
4211   case MCExpr::Unary:
4212     return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr());
4213   case MCExpr::Target:
4214     return true;
4215   }
4216   return false;
4217 }
4218 
4219 bool MipsAsmParser::parseRelocOperand(const MCExpr *&Res) {
4220   MCAsmParser &Parser = getParser();
4221   Parser.Lex();                          // Eat the % token.
4222   const AsmToken &Tok = Parser.getTok(); // Get next token, operation.
4223   if (Tok.isNot(AsmToken::Identifier))
4224     return true;
4225 
4226   std::string Str = Tok.getIdentifier();
4227 
4228   Parser.Lex(); // Eat the identifier.
4229   // Now make an expression from the rest of the operand.
4230   const MCExpr *IdVal;
4231   SMLoc EndLoc;
4232 
4233   if (getLexer().getKind() == AsmToken::LParen) {
4234     while (1) {
4235       Parser.Lex(); // Eat the '(' token.
4236       if (getLexer().getKind() == AsmToken::Percent) {
4237         Parser.Lex(); // Eat the % token.
4238         const AsmToken &nextTok = Parser.getTok();
4239         if (nextTok.isNot(AsmToken::Identifier))
4240           return true;
4241         Str += "(%";
4242         Str += nextTok.getIdentifier();
4243         Parser.Lex(); // Eat the identifier.
4244         if (getLexer().getKind() != AsmToken::LParen)
4245           return true;
4246       } else
4247         break;
4248     }
4249     if (getParser().parseParenExpression(IdVal, EndLoc))
4250       return true;
4251 
4252     while (getLexer().getKind() == AsmToken::RParen)
4253       Parser.Lex(); // Eat the ')' token.
4254 
4255   } else
4256     return true; // Parenthesis must follow the relocation operand.
4257 
4258   Res = evaluateRelocExpr(IdVal, Str);
4259   return false;
4260 }
4261 
4262 bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
4263                                   SMLoc &EndLoc) {
4264   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
4265   OperandMatchResultTy ResTy = parseAnyRegister(Operands);
4266   if (ResTy == MatchOperand_Success) {
4267     assert(Operands.size() == 1);
4268     MipsOperand &Operand = static_cast<MipsOperand &>(*Operands.front());
4269     StartLoc = Operand.getStartLoc();
4270     EndLoc = Operand.getEndLoc();
4271 
4272     // AFAIK, we only support numeric registers and named GPR's in CFI
4273     // directives.
4274     // Don't worry about eating tokens before failing. Using an unrecognised
4275     // register is a parse error.
4276     if (Operand.isGPRAsmReg()) {
4277       // Resolve to GPR32 or GPR64 appropriately.
4278       RegNo = isGP64bit() ? Operand.getGPR64Reg() : Operand.getGPR32Reg();
4279     }
4280 
4281     return (RegNo == (unsigned)-1);
4282   }
4283 
4284   assert(Operands.size() == 0);
4285   return (RegNo == (unsigned)-1);
4286 }
4287 
4288 bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) {
4289   MCAsmParser &Parser = getParser();
4290   SMLoc S;
4291   bool Result = true;
4292   unsigned NumOfLParen = 0;
4293 
4294   while (getLexer().getKind() == AsmToken::LParen) {
4295     Parser.Lex();
4296     ++NumOfLParen;
4297   }
4298 
4299   switch (getLexer().getKind()) {
4300   default:
4301     return true;
4302   case AsmToken::Identifier:
4303   case AsmToken::LParen:
4304   case AsmToken::Integer:
4305   case AsmToken::Minus:
4306   case AsmToken::Plus:
4307     if (isParenExpr)
4308       Result = getParser().parseParenExprOfDepth(NumOfLParen, Res, S);
4309     else
4310       Result = (getParser().parseExpression(Res));
4311     while (getLexer().getKind() == AsmToken::RParen)
4312       Parser.Lex();
4313     break;
4314   case AsmToken::Percent:
4315     Result = parseRelocOperand(Res);
4316   }
4317   return Result;
4318 }
4319 
4320 MipsAsmParser::OperandMatchResultTy
4321 MipsAsmParser::parseMemOperand(OperandVector &Operands) {
4322   MCAsmParser &Parser = getParser();
4323   DEBUG(dbgs() << "parseMemOperand\n");
4324   const MCExpr *IdVal = nullptr;
4325   SMLoc S;
4326   bool isParenExpr = false;
4327   MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch;
4328   // First operand is the offset.
4329   S = Parser.getTok().getLoc();
4330 
4331   if (getLexer().getKind() == AsmToken::LParen) {
4332     Parser.Lex();
4333     isParenExpr = true;
4334   }
4335 
4336   if (getLexer().getKind() != AsmToken::Dollar) {
4337     if (parseMemOffset(IdVal, isParenExpr))
4338       return MatchOperand_ParseFail;
4339 
4340     const AsmToken &Tok = Parser.getTok(); // Get the next token.
4341     if (Tok.isNot(AsmToken::LParen)) {
4342       MipsOperand &Mnemonic = static_cast<MipsOperand &>(*Operands[0]);
4343       if (Mnemonic.getToken() == "la" || Mnemonic.getToken() == "dla") {
4344         SMLoc E =
4345             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4346         Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
4347         return MatchOperand_Success;
4348       }
4349       if (Tok.is(AsmToken::EndOfStatement)) {
4350         SMLoc E =
4351             SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4352 
4353         // Zero register assumed, add a memory operand with ZERO as its base.
4354         // "Base" will be managed by k_Memory.
4355         auto Base = MipsOperand::createGPRReg(0, getContext().getRegisterInfo(),
4356                                               S, E, *this);
4357         Operands.push_back(
4358             MipsOperand::CreateMem(std::move(Base), IdVal, S, E, *this));
4359         return MatchOperand_Success;
4360       }
4361       Error(Parser.getTok().getLoc(), "'(' expected");
4362       return MatchOperand_ParseFail;
4363     }
4364 
4365     Parser.Lex(); // Eat the '(' token.
4366   }
4367 
4368   Res = parseAnyRegister(Operands);
4369   if (Res != MatchOperand_Success)
4370     return Res;
4371 
4372   if (Parser.getTok().isNot(AsmToken::RParen)) {
4373     Error(Parser.getTok().getLoc(), "')' expected");
4374     return MatchOperand_ParseFail;
4375   }
4376 
4377   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4378 
4379   Parser.Lex(); // Eat the ')' token.
4380 
4381   if (!IdVal)
4382     IdVal = MCConstantExpr::create(0, getContext());
4383 
4384   // Replace the register operand with the memory operand.
4385   std::unique_ptr<MipsOperand> op(
4386       static_cast<MipsOperand *>(Operands.back().release()));
4387   // Remove the register from the operands.
4388   // "op" will be managed by k_Memory.
4389   Operands.pop_back();
4390   // Add the memory operand.
4391   if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) {
4392     int64_t Imm;
4393     if (IdVal->evaluateAsAbsolute(Imm))
4394       IdVal = MCConstantExpr::create(Imm, getContext());
4395     else if (BE->getLHS()->getKind() != MCExpr::SymbolRef)
4396       IdVal = MCBinaryExpr::create(BE->getOpcode(), BE->getRHS(), BE->getLHS(),
4397                                    getContext());
4398   }
4399 
4400   Operands.push_back(MipsOperand::CreateMem(std::move(op), IdVal, S, E, *this));
4401   return MatchOperand_Success;
4402 }
4403 
4404 bool MipsAsmParser::searchSymbolAlias(OperandVector &Operands) {
4405   MCAsmParser &Parser = getParser();
4406   MCSymbol *Sym = getContext().lookupSymbol(Parser.getTok().getIdentifier());
4407   if (Sym) {
4408     SMLoc S = Parser.getTok().getLoc();
4409     const MCExpr *Expr;
4410     if (Sym->isVariable())
4411       Expr = Sym->getVariableValue();
4412     else
4413       return false;
4414     if (Expr->getKind() == MCExpr::SymbolRef) {
4415       const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
4416       StringRef DefSymbol = Ref->getSymbol().getName();
4417       if (DefSymbol.startswith("$")) {
4418         OperandMatchResultTy ResTy =
4419             matchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S);
4420         if (ResTy == MatchOperand_Success) {
4421           Parser.Lex();
4422           return true;
4423         } else if (ResTy == MatchOperand_ParseFail)
4424           llvm_unreachable("Should never ParseFail");
4425         return false;
4426       }
4427     } else if (Expr->getKind() == MCExpr::Constant) {
4428       Parser.Lex();
4429       const MCConstantExpr *Const = static_cast<const MCConstantExpr *>(Expr);
4430       Operands.push_back(
4431           MipsOperand::CreateImm(Const, S, Parser.getTok().getLoc(), *this));
4432       return true;
4433     }
4434   }
4435   return false;
4436 }
4437 
4438 MipsAsmParser::OperandMatchResultTy
4439 MipsAsmParser::matchAnyRegisterNameWithoutDollar(OperandVector &Operands,
4440                                                  StringRef Identifier,
4441                                                  SMLoc S) {
4442   int Index = matchCPURegisterName(Identifier);
4443   if (Index != -1) {
4444     Operands.push_back(MipsOperand::createGPRReg(
4445         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4446     return MatchOperand_Success;
4447   }
4448 
4449   Index = matchHWRegsRegisterName(Identifier);
4450   if (Index != -1) {
4451     Operands.push_back(MipsOperand::createHWRegsReg(
4452         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4453     return MatchOperand_Success;
4454   }
4455 
4456   Index = matchFPURegisterName(Identifier);
4457   if (Index != -1) {
4458     Operands.push_back(MipsOperand::createFGRReg(
4459         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4460     return MatchOperand_Success;
4461   }
4462 
4463   Index = matchFCCRegisterName(Identifier);
4464   if (Index != -1) {
4465     Operands.push_back(MipsOperand::createFCCReg(
4466         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4467     return MatchOperand_Success;
4468   }
4469 
4470   Index = matchACRegisterName(Identifier);
4471   if (Index != -1) {
4472     Operands.push_back(MipsOperand::createACCReg(
4473         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4474     return MatchOperand_Success;
4475   }
4476 
4477   Index = matchMSA128RegisterName(Identifier);
4478   if (Index != -1) {
4479     Operands.push_back(MipsOperand::createMSA128Reg(
4480         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4481     return MatchOperand_Success;
4482   }
4483 
4484   Index = matchMSA128CtrlRegisterName(Identifier);
4485   if (Index != -1) {
4486     Operands.push_back(MipsOperand::createMSACtrlReg(
4487         Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this));
4488     return MatchOperand_Success;
4489   }
4490 
4491   return MatchOperand_NoMatch;
4492 }
4493 
4494 MipsAsmParser::OperandMatchResultTy
4495 MipsAsmParser::matchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S) {
4496   MCAsmParser &Parser = getParser();
4497   auto Token = Parser.getLexer().peekTok(false);
4498 
4499   if (Token.is(AsmToken::Identifier)) {
4500     DEBUG(dbgs() << ".. identifier\n");
4501     StringRef Identifier = Token.getIdentifier();
4502     OperandMatchResultTy ResTy =
4503         matchAnyRegisterNameWithoutDollar(Operands, Identifier, S);
4504     return ResTy;
4505   } else if (Token.is(AsmToken::Integer)) {
4506     DEBUG(dbgs() << ".. integer\n");
4507     Operands.push_back(MipsOperand::createNumericReg(
4508         Token.getIntVal(), getContext().getRegisterInfo(), S, Token.getLoc(),
4509         *this));
4510     return MatchOperand_Success;
4511   }
4512 
4513   DEBUG(dbgs() << Parser.getTok().getKind() << "\n");
4514 
4515   return MatchOperand_NoMatch;
4516 }
4517 
4518 MipsAsmParser::OperandMatchResultTy
4519 MipsAsmParser::parseAnyRegister(OperandVector &Operands) {
4520   MCAsmParser &Parser = getParser();
4521   DEBUG(dbgs() << "parseAnyRegister\n");
4522 
4523   auto Token = Parser.getTok();
4524 
4525   SMLoc S = Token.getLoc();
4526 
4527   if (Token.isNot(AsmToken::Dollar)) {
4528     DEBUG(dbgs() << ".. !$ -> try sym aliasing\n");
4529     if (Token.is(AsmToken::Identifier)) {
4530       if (searchSymbolAlias(Operands))
4531         return MatchOperand_Success;
4532     }
4533     DEBUG(dbgs() << ".. !symalias -> NoMatch\n");
4534     return MatchOperand_NoMatch;
4535   }
4536   DEBUG(dbgs() << ".. $\n");
4537 
4538   OperandMatchResultTy ResTy = matchAnyRegisterWithoutDollar(Operands, S);
4539   if (ResTy == MatchOperand_Success) {
4540     Parser.Lex(); // $
4541     Parser.Lex(); // identifier
4542   }
4543   return ResTy;
4544 }
4545 
4546 MipsAsmParser::OperandMatchResultTy
4547 MipsAsmParser::parseImm(OperandVector &Operands) {
4548   MCAsmParser &Parser = getParser();
4549   switch (getLexer().getKind()) {
4550   default:
4551     return MatchOperand_NoMatch;
4552   case AsmToken::LParen:
4553   case AsmToken::Minus:
4554   case AsmToken::Plus:
4555   case AsmToken::Integer:
4556   case AsmToken::Tilde:
4557   case AsmToken::String:
4558     break;
4559   }
4560 
4561   const MCExpr *IdVal;
4562   SMLoc S = Parser.getTok().getLoc();
4563   if (getParser().parseExpression(IdVal))
4564     return MatchOperand_ParseFail;
4565 
4566   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4567   Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this));
4568   return MatchOperand_Success;
4569 }
4570 
4571 MipsAsmParser::OperandMatchResultTy
4572 MipsAsmParser::parseJumpTarget(OperandVector &Operands) {
4573   MCAsmParser &Parser = getParser();
4574   DEBUG(dbgs() << "parseJumpTarget\n");
4575 
4576   SMLoc S = getLexer().getLoc();
4577 
4578   // Integers and expressions are acceptable
4579   OperandMatchResultTy ResTy = parseImm(Operands);
4580   if (ResTy != MatchOperand_NoMatch)
4581     return ResTy;
4582 
4583   // Registers are a valid target and have priority over symbols.
4584   ResTy = parseAnyRegister(Operands);
4585   if (ResTy != MatchOperand_NoMatch)
4586     return ResTy;
4587 
4588   const MCExpr *Expr = nullptr;
4589   if (Parser.parseExpression(Expr)) {
4590     // We have no way of knowing if a symbol was consumed so we must ParseFail
4591     return MatchOperand_ParseFail;
4592   }
4593   Operands.push_back(
4594       MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this));
4595   return MatchOperand_Success;
4596 }
4597 
4598 MipsAsmParser::OperandMatchResultTy
4599 MipsAsmParser::parseInvNum(OperandVector &Operands) {
4600   MCAsmParser &Parser = getParser();
4601   const MCExpr *IdVal;
4602   // If the first token is '$' we may have register operand.
4603   if (Parser.getTok().is(AsmToken::Dollar))
4604     return MatchOperand_NoMatch;
4605   SMLoc S = Parser.getTok().getLoc();
4606   if (getParser().parseExpression(IdVal))
4607     return MatchOperand_ParseFail;
4608   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal);
4609   assert(MCE && "Unexpected MCExpr type.");
4610   int64_t Val = MCE->getValue();
4611   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4612   Operands.push_back(MipsOperand::CreateImm(
4613       MCConstantExpr::create(0 - Val, getContext()), S, E, *this));
4614   return MatchOperand_Success;
4615 }
4616 
4617 MipsAsmParser::OperandMatchResultTy
4618 MipsAsmParser::parseLSAImm(OperandVector &Operands) {
4619   MCAsmParser &Parser = getParser();
4620   switch (getLexer().getKind()) {
4621   default:
4622     return MatchOperand_NoMatch;
4623   case AsmToken::LParen:
4624   case AsmToken::Plus:
4625   case AsmToken::Minus:
4626   case AsmToken::Integer:
4627     break;
4628   }
4629 
4630   const MCExpr *Expr;
4631   SMLoc S = Parser.getTok().getLoc();
4632 
4633   if (getParser().parseExpression(Expr))
4634     return MatchOperand_ParseFail;
4635 
4636   int64_t Val;
4637   if (!Expr->evaluateAsAbsolute(Val)) {
4638     Error(S, "expected immediate value");
4639     return MatchOperand_ParseFail;
4640   }
4641 
4642   // The LSA instruction allows a 2-bit unsigned immediate. For this reason
4643   // and because the CPU always adds one to the immediate field, the allowed
4644   // range becomes 1..4. We'll only check the range here and will deal
4645   // with the addition/subtraction when actually decoding/encoding
4646   // the instruction.
4647   if (Val < 1 || Val > 4) {
4648     Error(S, "immediate not in range (1..4)");
4649     return MatchOperand_ParseFail;
4650   }
4651 
4652   Operands.push_back(
4653       MipsOperand::CreateImm(Expr, S, Parser.getTok().getLoc(), *this));
4654   return MatchOperand_Success;
4655 }
4656 
4657 MipsAsmParser::OperandMatchResultTy
4658 MipsAsmParser::parseRegisterList(OperandVector &Operands) {
4659   MCAsmParser &Parser = getParser();
4660   SmallVector<unsigned, 10> Regs;
4661   unsigned RegNo;
4662   unsigned PrevReg = Mips::NoRegister;
4663   bool RegRange = false;
4664   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands;
4665 
4666   if (Parser.getTok().isNot(AsmToken::Dollar))
4667     return MatchOperand_ParseFail;
4668 
4669   SMLoc S = Parser.getTok().getLoc();
4670   while (parseAnyRegister(TmpOperands) == MatchOperand_Success) {
4671     SMLoc E = getLexer().getLoc();
4672     MipsOperand &Reg = static_cast<MipsOperand &>(*TmpOperands.back());
4673     RegNo = isGP64bit() ? Reg.getGPR64Reg() : Reg.getGPR32Reg();
4674     if (RegRange) {
4675       // Remove last register operand because registers from register range
4676       // should be inserted first.
4677       if ((isGP64bit() && RegNo == Mips::RA_64) ||
4678           (!isGP64bit() && RegNo == Mips::RA)) {
4679         Regs.push_back(RegNo);
4680       } else {
4681         unsigned TmpReg = PrevReg + 1;
4682         while (TmpReg <= RegNo) {
4683           if ((((TmpReg < Mips::S0) || (TmpReg > Mips::S7)) && !isGP64bit()) ||
4684               (((TmpReg < Mips::S0_64) || (TmpReg > Mips::S7_64)) &&
4685                isGP64bit())) {
4686             Error(E, "invalid register operand");
4687             return MatchOperand_ParseFail;
4688           }
4689 
4690           PrevReg = TmpReg;
4691           Regs.push_back(TmpReg++);
4692         }
4693       }
4694 
4695       RegRange = false;
4696     } else {
4697       if ((PrevReg == Mips::NoRegister) &&
4698           ((isGP64bit() && (RegNo != Mips::S0_64) && (RegNo != Mips::RA_64)) ||
4699           (!isGP64bit() && (RegNo != Mips::S0) && (RegNo != Mips::RA)))) {
4700         Error(E, "$16 or $31 expected");
4701         return MatchOperand_ParseFail;
4702       } else if (!(((RegNo == Mips::FP || RegNo == Mips::RA ||
4703                     (RegNo >= Mips::S0 && RegNo <= Mips::S7)) &&
4704                     !isGP64bit()) ||
4705                    ((RegNo == Mips::FP_64 || RegNo == Mips::RA_64 ||
4706                     (RegNo >= Mips::S0_64 && RegNo <= Mips::S7_64)) &&
4707                     isGP64bit()))) {
4708         Error(E, "invalid register operand");
4709         return MatchOperand_ParseFail;
4710       } else if ((PrevReg != Mips::NoRegister) && (RegNo != PrevReg + 1) &&
4711                  ((RegNo != Mips::FP && RegNo != Mips::RA && !isGP64bit()) ||
4712                   (RegNo != Mips::FP_64 && RegNo != Mips::RA_64 &&
4713                    isGP64bit()))) {
4714         Error(E, "consecutive register numbers expected");
4715         return MatchOperand_ParseFail;
4716       }
4717 
4718       Regs.push_back(RegNo);
4719     }
4720 
4721     if (Parser.getTok().is(AsmToken::Minus))
4722       RegRange = true;
4723 
4724     if (!Parser.getTok().isNot(AsmToken::Minus) &&
4725         !Parser.getTok().isNot(AsmToken::Comma)) {
4726       Error(E, "',' or '-' expected");
4727       return MatchOperand_ParseFail;
4728     }
4729 
4730     Lex(); // Consume comma or minus
4731     if (Parser.getTok().isNot(AsmToken::Dollar))
4732       break;
4733 
4734     PrevReg = RegNo;
4735   }
4736 
4737   SMLoc E = Parser.getTok().getLoc();
4738   Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this));
4739   parseMemOperand(Operands);
4740   return MatchOperand_Success;
4741 }
4742 
4743 MipsAsmParser::OperandMatchResultTy
4744 MipsAsmParser::parseRegisterPair(OperandVector &Operands) {
4745   MCAsmParser &Parser = getParser();
4746 
4747   SMLoc S = Parser.getTok().getLoc();
4748   if (parseAnyRegister(Operands) != MatchOperand_Success)
4749     return MatchOperand_ParseFail;
4750 
4751   SMLoc E = Parser.getTok().getLoc();
4752   MipsOperand &Op = static_cast<MipsOperand &>(*Operands.back());
4753   unsigned Reg = Op.getGPR32Reg();
4754   Operands.pop_back();
4755   Operands.push_back(MipsOperand::CreateRegPair(Reg, S, E, *this));
4756   return MatchOperand_Success;
4757 }
4758 
4759 MipsAsmParser::OperandMatchResultTy
4760 MipsAsmParser::parseMovePRegPair(OperandVector &Operands) {
4761   MCAsmParser &Parser = getParser();
4762   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands;
4763   SmallVector<unsigned, 10> Regs;
4764 
4765   if (Parser.getTok().isNot(AsmToken::Dollar))
4766     return MatchOperand_ParseFail;
4767 
4768   SMLoc S = Parser.getTok().getLoc();
4769 
4770   if (parseAnyRegister(TmpOperands) != MatchOperand_Success)
4771     return MatchOperand_ParseFail;
4772 
4773   MipsOperand *Reg = &static_cast<MipsOperand &>(*TmpOperands.back());
4774   unsigned RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg();
4775   Regs.push_back(RegNo);
4776 
4777   SMLoc E = Parser.getTok().getLoc();
4778   if (Parser.getTok().isNot(AsmToken::Comma)) {
4779     Error(E, "',' expected");
4780     return MatchOperand_ParseFail;
4781   }
4782 
4783   // Remove comma.
4784   Parser.Lex();
4785 
4786   if (parseAnyRegister(TmpOperands) != MatchOperand_Success)
4787     return MatchOperand_ParseFail;
4788 
4789   Reg = &static_cast<MipsOperand &>(*TmpOperands.back());
4790   RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg();
4791   Regs.push_back(RegNo);
4792 
4793   Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this));
4794 
4795   return MatchOperand_Success;
4796 }
4797 
4798 MCSymbolRefExpr::VariantKind MipsAsmParser::getVariantKind(StringRef Symbol) {
4799 
4800   MCSymbolRefExpr::VariantKind VK =
4801       StringSwitch<MCSymbolRefExpr::VariantKind>(Symbol)
4802           .Case("hi", MCSymbolRefExpr::VK_Mips_ABS_HI)
4803           .Case("lo", MCSymbolRefExpr::VK_Mips_ABS_LO)
4804           .Case("gp_rel", MCSymbolRefExpr::VK_Mips_GPREL)
4805           .Case("call16", MCSymbolRefExpr::VK_Mips_GOT_CALL)
4806           .Case("got", MCSymbolRefExpr::VK_Mips_GOT)
4807           .Case("tlsgd", MCSymbolRefExpr::VK_Mips_TLSGD)
4808           .Case("tlsldm", MCSymbolRefExpr::VK_Mips_TLSLDM)
4809           .Case("dtprel_hi", MCSymbolRefExpr::VK_Mips_DTPREL_HI)
4810           .Case("dtprel_lo", MCSymbolRefExpr::VK_Mips_DTPREL_LO)
4811           .Case("gottprel", MCSymbolRefExpr::VK_Mips_GOTTPREL)
4812           .Case("tprel_hi", MCSymbolRefExpr::VK_Mips_TPREL_HI)
4813           .Case("tprel_lo", MCSymbolRefExpr::VK_Mips_TPREL_LO)
4814           .Case("got_disp", MCSymbolRefExpr::VK_Mips_GOT_DISP)
4815           .Case("got_page", MCSymbolRefExpr::VK_Mips_GOT_PAGE)
4816           .Case("got_ofst", MCSymbolRefExpr::VK_Mips_GOT_OFST)
4817           .Case("hi(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_HI)
4818           .Case("lo(%neg(%gp_rel", MCSymbolRefExpr::VK_Mips_GPOFF_LO)
4819           .Case("got_hi", MCSymbolRefExpr::VK_Mips_GOT_HI16)
4820           .Case("got_lo", MCSymbolRefExpr::VK_Mips_GOT_LO16)
4821           .Case("call_hi", MCSymbolRefExpr::VK_Mips_CALL_HI16)
4822           .Case("call_lo", MCSymbolRefExpr::VK_Mips_CALL_LO16)
4823           .Case("higher", MCSymbolRefExpr::VK_Mips_HIGHER)
4824           .Case("highest", MCSymbolRefExpr::VK_Mips_HIGHEST)
4825           .Case("pcrel_hi", MCSymbolRefExpr::VK_Mips_PCREL_HI16)
4826           .Case("pcrel_lo", MCSymbolRefExpr::VK_Mips_PCREL_LO16)
4827           .Default(MCSymbolRefExpr::VK_None);
4828 
4829   assert(VK != MCSymbolRefExpr::VK_None);
4830 
4831   return VK;
4832 }
4833 
4834 /// Sometimes (i.e. load/stores) the operand may be followed immediately by
4835 /// either this.
4836 /// ::= '(', register, ')'
4837 /// handle it before we iterate so we don't get tripped up by the lack of
4838 /// a comma.
4839 bool MipsAsmParser::parseParenSuffix(StringRef Name, OperandVector &Operands) {
4840   MCAsmParser &Parser = getParser();
4841   if (getLexer().is(AsmToken::LParen)) {
4842     Operands.push_back(
4843         MipsOperand::CreateToken("(", getLexer().getLoc(), *this));
4844     Parser.Lex();
4845     if (parseOperand(Operands, Name)) {
4846       SMLoc Loc = getLexer().getLoc();
4847       Parser.eatToEndOfStatement();
4848       return Error(Loc, "unexpected token in argument list");
4849     }
4850     if (Parser.getTok().isNot(AsmToken::RParen)) {
4851       SMLoc Loc = getLexer().getLoc();
4852       Parser.eatToEndOfStatement();
4853       return Error(Loc, "unexpected token, expected ')'");
4854     }
4855     Operands.push_back(
4856         MipsOperand::CreateToken(")", getLexer().getLoc(), *this));
4857     Parser.Lex();
4858   }
4859   return false;
4860 }
4861 
4862 /// Sometimes (i.e. in MSA) the operand may be followed immediately by
4863 /// either one of these.
4864 /// ::= '[', register, ']'
4865 /// ::= '[', integer, ']'
4866 /// handle it before we iterate so we don't get tripped up by the lack of
4867 /// a comma.
4868 bool MipsAsmParser::parseBracketSuffix(StringRef Name,
4869                                        OperandVector &Operands) {
4870   MCAsmParser &Parser = getParser();
4871   if (getLexer().is(AsmToken::LBrac)) {
4872     Operands.push_back(
4873         MipsOperand::CreateToken("[", getLexer().getLoc(), *this));
4874     Parser.Lex();
4875     if (parseOperand(Operands, Name)) {
4876       SMLoc Loc = getLexer().getLoc();
4877       Parser.eatToEndOfStatement();
4878       return Error(Loc, "unexpected token in argument list");
4879     }
4880     if (Parser.getTok().isNot(AsmToken::RBrac)) {
4881       SMLoc Loc = getLexer().getLoc();
4882       Parser.eatToEndOfStatement();
4883       return Error(Loc, "unexpected token, expected ']'");
4884     }
4885     Operands.push_back(
4886         MipsOperand::CreateToken("]", getLexer().getLoc(), *this));
4887     Parser.Lex();
4888   }
4889   return false;
4890 }
4891 
4892 bool MipsAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
4893                                      SMLoc NameLoc, OperandVector &Operands) {
4894   MCAsmParser &Parser = getParser();
4895   DEBUG(dbgs() << "ParseInstruction\n");
4896 
4897   // We have reached first instruction, module directive are now forbidden.
4898   getTargetStreamer().forbidModuleDirective();
4899 
4900   // Check if we have valid mnemonic
4901   if (!mnemonicIsValid(Name, 0)) {
4902     Parser.eatToEndOfStatement();
4903     return Error(NameLoc, "unknown instruction");
4904   }
4905   // First operand in MCInst is instruction mnemonic.
4906   Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this));
4907 
4908   // Read the remaining operands.
4909   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4910     // Read the first operand.
4911     if (parseOperand(Operands, Name)) {
4912       SMLoc Loc = getLexer().getLoc();
4913       Parser.eatToEndOfStatement();
4914       return Error(Loc, "unexpected token in argument list");
4915     }
4916     if (getLexer().is(AsmToken::LBrac) && parseBracketSuffix(Name, Operands))
4917       return true;
4918     // AFAIK, parenthesis suffixes are never on the first operand
4919 
4920     while (getLexer().is(AsmToken::Comma)) {
4921       Parser.Lex(); // Eat the comma.
4922       // Parse and remember the operand.
4923       if (parseOperand(Operands, Name)) {
4924         SMLoc Loc = getLexer().getLoc();
4925         Parser.eatToEndOfStatement();
4926         return Error(Loc, "unexpected token in argument list");
4927       }
4928       // Parse bracket and parenthesis suffixes before we iterate
4929       if (getLexer().is(AsmToken::LBrac)) {
4930         if (parseBracketSuffix(Name, Operands))
4931           return true;
4932       } else if (getLexer().is(AsmToken::LParen) &&
4933                  parseParenSuffix(Name, Operands))
4934         return true;
4935     }
4936   }
4937   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4938     SMLoc Loc = getLexer().getLoc();
4939     Parser.eatToEndOfStatement();
4940     return Error(Loc, "unexpected token in argument list");
4941   }
4942   Parser.Lex(); // Consume the EndOfStatement.
4943   return false;
4944 }
4945 
4946 bool MipsAsmParser::reportParseError(Twine ErrorMsg) {
4947   MCAsmParser &Parser = getParser();
4948   SMLoc Loc = getLexer().getLoc();
4949   Parser.eatToEndOfStatement();
4950   return Error(Loc, ErrorMsg);
4951 }
4952 
4953 bool MipsAsmParser::reportParseError(SMLoc Loc, Twine ErrorMsg) {
4954   return Error(Loc, ErrorMsg);
4955 }
4956 
4957 bool MipsAsmParser::parseSetNoAtDirective() {
4958   MCAsmParser &Parser = getParser();
4959   // Line should look like: ".set noat".
4960 
4961   // Set the $at register to $0.
4962   AssemblerOptions.back()->setATRegIndex(0);
4963 
4964   Parser.Lex(); // Eat "noat".
4965 
4966   // If this is not the end of the statement, report an error.
4967   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4968     reportParseError("unexpected token, expected end of statement");
4969     return false;
4970   }
4971 
4972   getTargetStreamer().emitDirectiveSetNoAt();
4973   Parser.Lex(); // Consume the EndOfStatement.
4974   return false;
4975 }
4976 
4977 bool MipsAsmParser::parseSetAtDirective() {
4978   // Line can be: ".set at", which sets $at to $1
4979   //          or  ".set at=$reg", which sets $at to $reg.
4980   MCAsmParser &Parser = getParser();
4981   Parser.Lex(); // Eat "at".
4982 
4983   if (getLexer().is(AsmToken::EndOfStatement)) {
4984     // No register was specified, so we set $at to $1.
4985     AssemblerOptions.back()->setATRegIndex(1);
4986 
4987     getTargetStreamer().emitDirectiveSetAt();
4988     Parser.Lex(); // Consume the EndOfStatement.
4989     return false;
4990   }
4991 
4992   if (getLexer().isNot(AsmToken::Equal)) {
4993     reportParseError("unexpected token, expected equals sign");
4994     return false;
4995   }
4996   Parser.Lex(); // Eat "=".
4997 
4998   if (getLexer().isNot(AsmToken::Dollar)) {
4999     if (getLexer().is(AsmToken::EndOfStatement)) {
5000       reportParseError("no register specified");
5001       return false;
5002     } else {
5003       reportParseError("unexpected token, expected dollar sign '$'");
5004       return false;
5005     }
5006   }
5007   Parser.Lex(); // Eat "$".
5008 
5009   // Find out what "reg" is.
5010   unsigned AtRegNo;
5011   const AsmToken &Reg = Parser.getTok();
5012   if (Reg.is(AsmToken::Identifier)) {
5013     AtRegNo = matchCPURegisterName(Reg.getIdentifier());
5014   } else if (Reg.is(AsmToken::Integer)) {
5015     AtRegNo = Reg.getIntVal();
5016   } else {
5017     reportParseError("unexpected token, expected identifier or integer");
5018     return false;
5019   }
5020 
5021   // Check if $reg is a valid register. If it is, set $at to $reg.
5022   if (!AssemblerOptions.back()->setATRegIndex(AtRegNo)) {
5023     reportParseError("invalid register");
5024     return false;
5025   }
5026   Parser.Lex(); // Eat "reg".
5027 
5028   // If this is not the end of the statement, report an error.
5029   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5030     reportParseError("unexpected token, expected end of statement");
5031     return false;
5032   }
5033 
5034   getTargetStreamer().emitDirectiveSetAtWithArg(AtRegNo);
5035 
5036   Parser.Lex(); // Consume the EndOfStatement.
5037   return false;
5038 }
5039 
5040 bool MipsAsmParser::parseSetReorderDirective() {
5041   MCAsmParser &Parser = getParser();
5042   Parser.Lex();
5043   // If this is not the end of the statement, report an error.
5044   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5045     reportParseError("unexpected token, expected end of statement");
5046     return false;
5047   }
5048   AssemblerOptions.back()->setReorder();
5049   getTargetStreamer().emitDirectiveSetReorder();
5050   Parser.Lex(); // Consume the EndOfStatement.
5051   return false;
5052 }
5053 
5054 bool MipsAsmParser::parseSetNoReorderDirective() {
5055   MCAsmParser &Parser = getParser();
5056   Parser.Lex();
5057   // If this is not the end of the statement, report an error.
5058   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5059     reportParseError("unexpected token, expected end of statement");
5060     return false;
5061   }
5062   AssemblerOptions.back()->setNoReorder();
5063   getTargetStreamer().emitDirectiveSetNoReorder();
5064   Parser.Lex(); // Consume the EndOfStatement.
5065   return false;
5066 }
5067 
5068 bool MipsAsmParser::parseSetMacroDirective() {
5069   MCAsmParser &Parser = getParser();
5070   Parser.Lex();
5071   // If this is not the end of the statement, report an error.
5072   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5073     reportParseError("unexpected token, expected end of statement");
5074     return false;
5075   }
5076   AssemblerOptions.back()->setMacro();
5077   getTargetStreamer().emitDirectiveSetMacro();
5078   Parser.Lex(); // Consume the EndOfStatement.
5079   return false;
5080 }
5081 
5082 bool MipsAsmParser::parseSetNoMacroDirective() {
5083   MCAsmParser &Parser = getParser();
5084   Parser.Lex();
5085   // If this is not the end of the statement, report an error.
5086   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5087     reportParseError("unexpected token, expected end of statement");
5088     return false;
5089   }
5090   if (AssemblerOptions.back()->isReorder()) {
5091     reportParseError("`noreorder' must be set before `nomacro'");
5092     return false;
5093   }
5094   AssemblerOptions.back()->setNoMacro();
5095   getTargetStreamer().emitDirectiveSetNoMacro();
5096   Parser.Lex(); // Consume the EndOfStatement.
5097   return false;
5098 }
5099 
5100 bool MipsAsmParser::parseSetMsaDirective() {
5101   MCAsmParser &Parser = getParser();
5102   Parser.Lex();
5103 
5104   // If this is not the end of the statement, report an error.
5105   if (getLexer().isNot(AsmToken::EndOfStatement))
5106     return reportParseError("unexpected token, expected end of statement");
5107 
5108   setFeatureBits(Mips::FeatureMSA, "msa");
5109   getTargetStreamer().emitDirectiveSetMsa();
5110   return false;
5111 }
5112 
5113 bool MipsAsmParser::parseSetNoMsaDirective() {
5114   MCAsmParser &Parser = getParser();
5115   Parser.Lex();
5116 
5117   // If this is not the end of the statement, report an error.
5118   if (getLexer().isNot(AsmToken::EndOfStatement))
5119     return reportParseError("unexpected token, expected end of statement");
5120 
5121   clearFeatureBits(Mips::FeatureMSA, "msa");
5122   getTargetStreamer().emitDirectiveSetNoMsa();
5123   return false;
5124 }
5125 
5126 bool MipsAsmParser::parseSetNoDspDirective() {
5127   MCAsmParser &Parser = getParser();
5128   Parser.Lex(); // Eat "nodsp".
5129 
5130   // If this is not the end of the statement, report an error.
5131   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5132     reportParseError("unexpected token, expected end of statement");
5133     return false;
5134   }
5135 
5136   clearFeatureBits(Mips::FeatureDSP, "dsp");
5137   getTargetStreamer().emitDirectiveSetNoDsp();
5138   return false;
5139 }
5140 
5141 bool MipsAsmParser::parseSetMips16Directive() {
5142   MCAsmParser &Parser = getParser();
5143   Parser.Lex(); // Eat "mips16".
5144 
5145   // If this is not the end of the statement, report an error.
5146   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5147     reportParseError("unexpected token, expected end of statement");
5148     return false;
5149   }
5150 
5151   setFeatureBits(Mips::FeatureMips16, "mips16");
5152   getTargetStreamer().emitDirectiveSetMips16();
5153   Parser.Lex(); // Consume the EndOfStatement.
5154   return false;
5155 }
5156 
5157 bool MipsAsmParser::parseSetNoMips16Directive() {
5158   MCAsmParser &Parser = getParser();
5159   Parser.Lex(); // Eat "nomips16".
5160 
5161   // If this is not the end of the statement, report an error.
5162   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5163     reportParseError("unexpected token, expected end of statement");
5164     return false;
5165   }
5166 
5167   clearFeatureBits(Mips::FeatureMips16, "mips16");
5168   getTargetStreamer().emitDirectiveSetNoMips16();
5169   Parser.Lex(); // Consume the EndOfStatement.
5170   return false;
5171 }
5172 
5173 bool MipsAsmParser::parseSetFpDirective() {
5174   MCAsmParser &Parser = getParser();
5175   MipsABIFlagsSection::FpABIKind FpAbiVal;
5176   // Line can be: .set fp=32
5177   //              .set fp=xx
5178   //              .set fp=64
5179   Parser.Lex(); // Eat fp token
5180   AsmToken Tok = Parser.getTok();
5181   if (Tok.isNot(AsmToken::Equal)) {
5182     reportParseError("unexpected token, expected equals sign '='");
5183     return false;
5184   }
5185   Parser.Lex(); // Eat '=' token.
5186   Tok = Parser.getTok();
5187 
5188   if (!parseFpABIValue(FpAbiVal, ".set"))
5189     return false;
5190 
5191   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5192     reportParseError("unexpected token, expected end of statement");
5193     return false;
5194   }
5195   getTargetStreamer().emitDirectiveSetFp(FpAbiVal);
5196   Parser.Lex(); // Consume the EndOfStatement.
5197   return false;
5198 }
5199 
5200 bool MipsAsmParser::parseSetOddSPRegDirective() {
5201   MCAsmParser &Parser = getParser();
5202 
5203   Parser.Lex(); // Eat "oddspreg".
5204   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5205     reportParseError("unexpected token, expected end of statement");
5206     return false;
5207   }
5208 
5209   clearFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5210   getTargetStreamer().emitDirectiveSetOddSPReg();
5211   return false;
5212 }
5213 
5214 bool MipsAsmParser::parseSetNoOddSPRegDirective() {
5215   MCAsmParser &Parser = getParser();
5216 
5217   Parser.Lex(); // Eat "nooddspreg".
5218   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5219     reportParseError("unexpected token, expected end of statement");
5220     return false;
5221   }
5222 
5223   setFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5224   getTargetStreamer().emitDirectiveSetNoOddSPReg();
5225   return false;
5226 }
5227 
5228 bool MipsAsmParser::parseSetPopDirective() {
5229   MCAsmParser &Parser = getParser();
5230   SMLoc Loc = getLexer().getLoc();
5231 
5232   Parser.Lex();
5233   if (getLexer().isNot(AsmToken::EndOfStatement))
5234     return reportParseError("unexpected token, expected end of statement");
5235 
5236   // Always keep an element on the options "stack" to prevent the user
5237   // from changing the initial options. This is how we remember them.
5238   if (AssemblerOptions.size() == 2)
5239     return reportParseError(Loc, ".set pop with no .set push");
5240 
5241   MCSubtargetInfo &STI = copySTI();
5242   AssemblerOptions.pop_back();
5243   setAvailableFeatures(
5244       ComputeAvailableFeatures(AssemblerOptions.back()->getFeatures()));
5245   STI.setFeatureBits(AssemblerOptions.back()->getFeatures());
5246 
5247   getTargetStreamer().emitDirectiveSetPop();
5248   return false;
5249 }
5250 
5251 bool MipsAsmParser::parseSetPushDirective() {
5252   MCAsmParser &Parser = getParser();
5253   Parser.Lex();
5254   if (getLexer().isNot(AsmToken::EndOfStatement))
5255     return reportParseError("unexpected token, expected end of statement");
5256 
5257   // Create a copy of the current assembler options environment and push it.
5258   AssemblerOptions.push_back(
5259               make_unique<MipsAssemblerOptions>(AssemblerOptions.back().get()));
5260 
5261   getTargetStreamer().emitDirectiveSetPush();
5262   return false;
5263 }
5264 
5265 bool MipsAsmParser::parseSetSoftFloatDirective() {
5266   MCAsmParser &Parser = getParser();
5267   Parser.Lex();
5268   if (getLexer().isNot(AsmToken::EndOfStatement))
5269     return reportParseError("unexpected token, expected end of statement");
5270 
5271   setFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5272   getTargetStreamer().emitDirectiveSetSoftFloat();
5273   return false;
5274 }
5275 
5276 bool MipsAsmParser::parseSetHardFloatDirective() {
5277   MCAsmParser &Parser = getParser();
5278   Parser.Lex();
5279   if (getLexer().isNot(AsmToken::EndOfStatement))
5280     return reportParseError("unexpected token, expected end of statement");
5281 
5282   clearFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5283   getTargetStreamer().emitDirectiveSetHardFloat();
5284   return false;
5285 }
5286 
5287 bool MipsAsmParser::parseSetAssignment() {
5288   StringRef Name;
5289   const MCExpr *Value;
5290   MCAsmParser &Parser = getParser();
5291 
5292   if (Parser.parseIdentifier(Name))
5293     reportParseError("expected identifier after .set");
5294 
5295   if (getLexer().isNot(AsmToken::Comma))
5296     return reportParseError("unexpected token, expected comma");
5297   Lex(); // Eat comma
5298 
5299   if (Parser.parseExpression(Value))
5300     return reportParseError("expected valid expression after comma");
5301 
5302   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5303   Sym->setVariableValue(Value);
5304 
5305   return false;
5306 }
5307 
5308 bool MipsAsmParser::parseSetMips0Directive() {
5309   MCAsmParser &Parser = getParser();
5310   Parser.Lex();
5311   if (getLexer().isNot(AsmToken::EndOfStatement))
5312     return reportParseError("unexpected token, expected end of statement");
5313 
5314   // Reset assembler options to their initial values.
5315   MCSubtargetInfo &STI = copySTI();
5316   setAvailableFeatures(
5317       ComputeAvailableFeatures(AssemblerOptions.front()->getFeatures()));
5318   STI.setFeatureBits(AssemblerOptions.front()->getFeatures());
5319   AssemblerOptions.back()->setFeatures(AssemblerOptions.front()->getFeatures());
5320 
5321   getTargetStreamer().emitDirectiveSetMips0();
5322   return false;
5323 }
5324 
5325 bool MipsAsmParser::parseSetArchDirective() {
5326   MCAsmParser &Parser = getParser();
5327   Parser.Lex();
5328   if (getLexer().isNot(AsmToken::Equal))
5329     return reportParseError("unexpected token, expected equals sign");
5330 
5331   Parser.Lex();
5332   StringRef Arch;
5333   if (Parser.parseIdentifier(Arch))
5334     return reportParseError("expected arch identifier");
5335 
5336   StringRef ArchFeatureName =
5337       StringSwitch<StringRef>(Arch)
5338           .Case("mips1", "mips1")
5339           .Case("mips2", "mips2")
5340           .Case("mips3", "mips3")
5341           .Case("mips4", "mips4")
5342           .Case("mips5", "mips5")
5343           .Case("mips32", "mips32")
5344           .Case("mips32r2", "mips32r2")
5345           .Case("mips32r3", "mips32r3")
5346           .Case("mips32r5", "mips32r5")
5347           .Case("mips32r6", "mips32r6")
5348           .Case("mips64", "mips64")
5349           .Case("mips64r2", "mips64r2")
5350           .Case("mips64r3", "mips64r3")
5351           .Case("mips64r5", "mips64r5")
5352           .Case("mips64r6", "mips64r6")
5353           .Case("octeon", "cnmips")
5354           .Case("r4000", "mips3") // This is an implementation of Mips3.
5355           .Default("");
5356 
5357   if (ArchFeatureName.empty())
5358     return reportParseError("unsupported architecture");
5359 
5360   selectArch(ArchFeatureName);
5361   getTargetStreamer().emitDirectiveSetArch(Arch);
5362   return false;
5363 }
5364 
5365 bool MipsAsmParser::parseSetFeature(uint64_t Feature) {
5366   MCAsmParser &Parser = getParser();
5367   Parser.Lex();
5368   if (getLexer().isNot(AsmToken::EndOfStatement))
5369     return reportParseError("unexpected token, expected end of statement");
5370 
5371   switch (Feature) {
5372   default:
5373     llvm_unreachable("Unimplemented feature");
5374   case Mips::FeatureDSP:
5375     setFeatureBits(Mips::FeatureDSP, "dsp");
5376     getTargetStreamer().emitDirectiveSetDsp();
5377     break;
5378   case Mips::FeatureMicroMips:
5379     getTargetStreamer().emitDirectiveSetMicroMips();
5380     break;
5381   case Mips::FeatureMips1:
5382     selectArch("mips1");
5383     getTargetStreamer().emitDirectiveSetMips1();
5384     break;
5385   case Mips::FeatureMips2:
5386     selectArch("mips2");
5387     getTargetStreamer().emitDirectiveSetMips2();
5388     break;
5389   case Mips::FeatureMips3:
5390     selectArch("mips3");
5391     getTargetStreamer().emitDirectiveSetMips3();
5392     break;
5393   case Mips::FeatureMips4:
5394     selectArch("mips4");
5395     getTargetStreamer().emitDirectiveSetMips4();
5396     break;
5397   case Mips::FeatureMips5:
5398     selectArch("mips5");
5399     getTargetStreamer().emitDirectiveSetMips5();
5400     break;
5401   case Mips::FeatureMips32:
5402     selectArch("mips32");
5403     getTargetStreamer().emitDirectiveSetMips32();
5404     break;
5405   case Mips::FeatureMips32r2:
5406     selectArch("mips32r2");
5407     getTargetStreamer().emitDirectiveSetMips32R2();
5408     break;
5409   case Mips::FeatureMips32r3:
5410     selectArch("mips32r3");
5411     getTargetStreamer().emitDirectiveSetMips32R3();
5412     break;
5413   case Mips::FeatureMips32r5:
5414     selectArch("mips32r5");
5415     getTargetStreamer().emitDirectiveSetMips32R5();
5416     break;
5417   case Mips::FeatureMips32r6:
5418     selectArch("mips32r6");
5419     getTargetStreamer().emitDirectiveSetMips32R6();
5420     break;
5421   case Mips::FeatureMips64:
5422     selectArch("mips64");
5423     getTargetStreamer().emitDirectiveSetMips64();
5424     break;
5425   case Mips::FeatureMips64r2:
5426     selectArch("mips64r2");
5427     getTargetStreamer().emitDirectiveSetMips64R2();
5428     break;
5429   case Mips::FeatureMips64r3:
5430     selectArch("mips64r3");
5431     getTargetStreamer().emitDirectiveSetMips64R3();
5432     break;
5433   case Mips::FeatureMips64r5:
5434     selectArch("mips64r5");
5435     getTargetStreamer().emitDirectiveSetMips64R5();
5436     break;
5437   case Mips::FeatureMips64r6:
5438     selectArch("mips64r6");
5439     getTargetStreamer().emitDirectiveSetMips64R6();
5440     break;
5441   }
5442   return false;
5443 }
5444 
5445 bool MipsAsmParser::eatComma(StringRef ErrorStr) {
5446   MCAsmParser &Parser = getParser();
5447   if (getLexer().isNot(AsmToken::Comma)) {
5448     SMLoc Loc = getLexer().getLoc();
5449     Parser.eatToEndOfStatement();
5450     return Error(Loc, ErrorStr);
5451   }
5452 
5453   Parser.Lex(); // Eat the comma.
5454   return true;
5455 }
5456 
5457 // Used to determine if .cpload, .cprestore, and .cpsetup have any effect.
5458 // In this class, it is only used for .cprestore.
5459 // FIXME: Only keep track of IsPicEnabled in one place, instead of in both
5460 // MipsTargetELFStreamer and MipsAsmParser.
5461 bool MipsAsmParser::isPicAndNotNxxAbi() {
5462   return inPicMode() && !(isABI_N32() || isABI_N64());
5463 }
5464 
5465 bool MipsAsmParser::parseDirectiveCpLoad(SMLoc Loc) {
5466   if (AssemblerOptions.back()->isReorder())
5467     Warning(Loc, ".cpload should be inside a noreorder section");
5468 
5469   if (inMips16Mode()) {
5470     reportParseError(".cpload is not supported in Mips16 mode");
5471     return false;
5472   }
5473 
5474   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Reg;
5475   OperandMatchResultTy ResTy = parseAnyRegister(Reg);
5476   if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
5477     reportParseError("expected register containing function address");
5478     return false;
5479   }
5480 
5481   MipsOperand &RegOpnd = static_cast<MipsOperand &>(*Reg[0]);
5482   if (!RegOpnd.isGPRAsmReg()) {
5483     reportParseError(RegOpnd.getStartLoc(), "invalid register");
5484     return false;
5485   }
5486 
5487   // If this is not the end of the statement, report an error.
5488   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5489     reportParseError("unexpected token, expected end of statement");
5490     return false;
5491   }
5492 
5493   getTargetStreamer().emitDirectiveCpLoad(RegOpnd.getGPR32Reg());
5494   return false;
5495 }
5496 
5497 bool MipsAsmParser::parseDirectiveCpRestore(SMLoc Loc) {
5498   MCAsmParser &Parser = getParser();
5499 
5500   // Note that .cprestore is ignored if used with the N32 and N64 ABIs or if it
5501   // is used in non-PIC mode.
5502 
5503   if (inMips16Mode()) {
5504     reportParseError(".cprestore is not supported in Mips16 mode");
5505     return false;
5506   }
5507 
5508   // Get the stack offset value.
5509   const MCExpr *StackOffset;
5510   int64_t StackOffsetVal;
5511   if (Parser.parseExpression(StackOffset)) {
5512     reportParseError("expected stack offset value");
5513     return false;
5514   }
5515 
5516   if (!StackOffset->evaluateAsAbsolute(StackOffsetVal)) {
5517     reportParseError("stack offset is not an absolute expression");
5518     return false;
5519   }
5520 
5521   if (StackOffsetVal < 0) {
5522     Warning(Loc, ".cprestore with negative stack offset has no effect");
5523     IsCpRestoreSet = false;
5524   } else {
5525     IsCpRestoreSet = true;
5526     CpRestoreOffset = StackOffsetVal;
5527   }
5528 
5529   // If this is not the end of the statement, report an error.
5530   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5531     reportParseError("unexpected token, expected end of statement");
5532     return false;
5533   }
5534 
5535   // Store the $gp on the stack.
5536   SmallVector<MCInst, 3> StoreInsts;
5537   createCpRestoreMemOp(false /*IsLoad*/, CpRestoreOffset /*StackOffset*/, Loc,
5538                        StoreInsts);
5539 
5540   getTargetStreamer().emitDirectiveCpRestore(StoreInsts, CpRestoreOffset);
5541   Parser.Lex(); // Consume the EndOfStatement.
5542   return false;
5543 }
5544 
5545 bool MipsAsmParser::parseDirectiveCPSetup() {
5546   MCAsmParser &Parser = getParser();
5547   unsigned FuncReg;
5548   unsigned Save;
5549   bool SaveIsReg = true;
5550 
5551   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
5552   OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
5553   if (ResTy == MatchOperand_NoMatch) {
5554     reportParseError("expected register containing function address");
5555     Parser.eatToEndOfStatement();
5556     return false;
5557   }
5558 
5559   MipsOperand &FuncRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
5560   if (!FuncRegOpnd.isGPRAsmReg()) {
5561     reportParseError(FuncRegOpnd.getStartLoc(), "invalid register");
5562     Parser.eatToEndOfStatement();
5563     return false;
5564   }
5565 
5566   FuncReg = FuncRegOpnd.getGPR32Reg();
5567   TmpReg.clear();
5568 
5569   if (!eatComma("unexpected token, expected comma"))
5570     return true;
5571 
5572   ResTy = parseAnyRegister(TmpReg);
5573   if (ResTy == MatchOperand_NoMatch) {
5574     const MCExpr *OffsetExpr;
5575     int64_t OffsetVal;
5576     SMLoc ExprLoc = getLexer().getLoc();
5577 
5578     if (Parser.parseExpression(OffsetExpr) ||
5579         !OffsetExpr->evaluateAsAbsolute(OffsetVal)) {
5580       reportParseError(ExprLoc, "expected save register or stack offset");
5581       Parser.eatToEndOfStatement();
5582       return false;
5583     }
5584 
5585     Save = OffsetVal;
5586     SaveIsReg = false;
5587   } else {
5588     MipsOperand &SaveOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
5589     if (!SaveOpnd.isGPRAsmReg()) {
5590       reportParseError(SaveOpnd.getStartLoc(), "invalid register");
5591       Parser.eatToEndOfStatement();
5592       return false;
5593     }
5594     Save = SaveOpnd.getGPR32Reg();
5595   }
5596 
5597   if (!eatComma("unexpected token, expected comma"))
5598     return true;
5599 
5600   const MCExpr *Expr;
5601   if (Parser.parseExpression(Expr)) {
5602     reportParseError("expected expression");
5603     return false;
5604   }
5605 
5606   if (Expr->getKind() != MCExpr::SymbolRef) {
5607     reportParseError("expected symbol");
5608     return false;
5609   }
5610   const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
5611 
5612   CpSaveLocation = Save;
5613   CpSaveLocationIsRegister = SaveIsReg;
5614 
5615   getTargetStreamer().emitDirectiveCpsetup(FuncReg, Save, Ref->getSymbol(),
5616                                            SaveIsReg);
5617   return false;
5618 }
5619 
5620 bool MipsAsmParser::parseDirectiveCPReturn() {
5621   getTargetStreamer().emitDirectiveCpreturn(CpSaveLocation,
5622                                             CpSaveLocationIsRegister);
5623   return false;
5624 }
5625 
5626 bool MipsAsmParser::parseDirectiveNaN() {
5627   MCAsmParser &Parser = getParser();
5628   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5629     const AsmToken &Tok = Parser.getTok();
5630 
5631     if (Tok.getString() == "2008") {
5632       Parser.Lex();
5633       getTargetStreamer().emitDirectiveNaN2008();
5634       return false;
5635     } else if (Tok.getString() == "legacy") {
5636       Parser.Lex();
5637       getTargetStreamer().emitDirectiveNaNLegacy();
5638       return false;
5639     }
5640   }
5641   // If we don't recognize the option passed to the .nan
5642   // directive (e.g. no option or unknown option), emit an error.
5643   reportParseError("invalid option in .nan directive");
5644   return false;
5645 }
5646 
5647 bool MipsAsmParser::parseDirectiveSet() {
5648   MCAsmParser &Parser = getParser();
5649   // Get the next token.
5650   const AsmToken &Tok = Parser.getTok();
5651 
5652   if (Tok.getString() == "noat") {
5653     return parseSetNoAtDirective();
5654   } else if (Tok.getString() == "at") {
5655     return parseSetAtDirective();
5656   } else if (Tok.getString() == "arch") {
5657     return parseSetArchDirective();
5658   } else if (Tok.getString() == "fp") {
5659     return parseSetFpDirective();
5660   } else if (Tok.getString() == "oddspreg") {
5661     return parseSetOddSPRegDirective();
5662   } else if (Tok.getString() == "nooddspreg") {
5663     return parseSetNoOddSPRegDirective();
5664   } else if (Tok.getString() == "pop") {
5665     return parseSetPopDirective();
5666   } else if (Tok.getString() == "push") {
5667     return parseSetPushDirective();
5668   } else if (Tok.getString() == "reorder") {
5669     return parseSetReorderDirective();
5670   } else if (Tok.getString() == "noreorder") {
5671     return parseSetNoReorderDirective();
5672   } else if (Tok.getString() == "macro") {
5673     return parseSetMacroDirective();
5674   } else if (Tok.getString() == "nomacro") {
5675     return parseSetNoMacroDirective();
5676   } else if (Tok.getString() == "mips16") {
5677     return parseSetMips16Directive();
5678   } else if (Tok.getString() == "nomips16") {
5679     return parseSetNoMips16Directive();
5680   } else if (Tok.getString() == "nomicromips") {
5681     getTargetStreamer().emitDirectiveSetNoMicroMips();
5682     Parser.eatToEndOfStatement();
5683     return false;
5684   } else if (Tok.getString() == "micromips") {
5685     return parseSetFeature(Mips::FeatureMicroMips);
5686   } else if (Tok.getString() == "mips0") {
5687     return parseSetMips0Directive();
5688   } else if (Tok.getString() == "mips1") {
5689     return parseSetFeature(Mips::FeatureMips1);
5690   } else if (Tok.getString() == "mips2") {
5691     return parseSetFeature(Mips::FeatureMips2);
5692   } else if (Tok.getString() == "mips3") {
5693     return parseSetFeature(Mips::FeatureMips3);
5694   } else if (Tok.getString() == "mips4") {
5695     return parseSetFeature(Mips::FeatureMips4);
5696   } else if (Tok.getString() == "mips5") {
5697     return parseSetFeature(Mips::FeatureMips5);
5698   } else if (Tok.getString() == "mips32") {
5699     return parseSetFeature(Mips::FeatureMips32);
5700   } else if (Tok.getString() == "mips32r2") {
5701     return parseSetFeature(Mips::FeatureMips32r2);
5702   } else if (Tok.getString() == "mips32r3") {
5703     return parseSetFeature(Mips::FeatureMips32r3);
5704   } else if (Tok.getString() == "mips32r5") {
5705     return parseSetFeature(Mips::FeatureMips32r5);
5706   } else if (Tok.getString() == "mips32r6") {
5707     return parseSetFeature(Mips::FeatureMips32r6);
5708   } else if (Tok.getString() == "mips64") {
5709     return parseSetFeature(Mips::FeatureMips64);
5710   } else if (Tok.getString() == "mips64r2") {
5711     return parseSetFeature(Mips::FeatureMips64r2);
5712   } else if (Tok.getString() == "mips64r3") {
5713     return parseSetFeature(Mips::FeatureMips64r3);
5714   } else if (Tok.getString() == "mips64r5") {
5715     return parseSetFeature(Mips::FeatureMips64r5);
5716   } else if (Tok.getString() == "mips64r6") {
5717     return parseSetFeature(Mips::FeatureMips64r6);
5718   } else if (Tok.getString() == "dsp") {
5719     return parseSetFeature(Mips::FeatureDSP);
5720   } else if (Tok.getString() == "nodsp") {
5721     return parseSetNoDspDirective();
5722   } else if (Tok.getString() == "msa") {
5723     return parseSetMsaDirective();
5724   } else if (Tok.getString() == "nomsa") {
5725     return parseSetNoMsaDirective();
5726   } else if (Tok.getString() == "softfloat") {
5727     return parseSetSoftFloatDirective();
5728   } else if (Tok.getString() == "hardfloat") {
5729     return parseSetHardFloatDirective();
5730   } else {
5731     // It is just an identifier, look for an assignment.
5732     parseSetAssignment();
5733     return false;
5734   }
5735 
5736   return true;
5737 }
5738 
5739 /// parseDataDirective
5740 ///  ::= .word [ expression (, expression)* ]
5741 bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) {
5742   MCAsmParser &Parser = getParser();
5743   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5744     for (;;) {
5745       const MCExpr *Value;
5746       if (getParser().parseExpression(Value))
5747         return true;
5748 
5749       getParser().getStreamer().EmitValue(Value, Size);
5750 
5751       if (getLexer().is(AsmToken::EndOfStatement))
5752         break;
5753 
5754       if (getLexer().isNot(AsmToken::Comma))
5755         return Error(L, "unexpected token, expected comma");
5756       Parser.Lex();
5757     }
5758   }
5759 
5760   Parser.Lex();
5761   return false;
5762 }
5763 
5764 /// parseDirectiveGpWord
5765 ///  ::= .gpword local_sym
5766 bool MipsAsmParser::parseDirectiveGpWord() {
5767   MCAsmParser &Parser = getParser();
5768   const MCExpr *Value;
5769   // EmitGPRel32Value requires an expression, so we are using base class
5770   // method to evaluate the expression.
5771   if (getParser().parseExpression(Value))
5772     return true;
5773   getParser().getStreamer().EmitGPRel32Value(Value);
5774 
5775   if (getLexer().isNot(AsmToken::EndOfStatement))
5776     return Error(getLexer().getLoc(),
5777                 "unexpected token, expected end of statement");
5778   Parser.Lex(); // Eat EndOfStatement token.
5779   return false;
5780 }
5781 
5782 /// parseDirectiveGpDWord
5783 ///  ::= .gpdword local_sym
5784 bool MipsAsmParser::parseDirectiveGpDWord() {
5785   MCAsmParser &Parser = getParser();
5786   const MCExpr *Value;
5787   // EmitGPRel64Value requires an expression, so we are using base class
5788   // method to evaluate the expression.
5789   if (getParser().parseExpression(Value))
5790     return true;
5791   getParser().getStreamer().EmitGPRel64Value(Value);
5792 
5793   if (getLexer().isNot(AsmToken::EndOfStatement))
5794     return Error(getLexer().getLoc(),
5795                 "unexpected token, expected end of statement");
5796   Parser.Lex(); // Eat EndOfStatement token.
5797   return false;
5798 }
5799 
5800 bool MipsAsmParser::parseDirectiveOption() {
5801   MCAsmParser &Parser = getParser();
5802   // Get the option token.
5803   AsmToken Tok = Parser.getTok();
5804   // At the moment only identifiers are supported.
5805   if (Tok.isNot(AsmToken::Identifier)) {
5806     Error(Parser.getTok().getLoc(), "unexpected token, expected identifier");
5807     Parser.eatToEndOfStatement();
5808     return false;
5809   }
5810 
5811   StringRef Option = Tok.getIdentifier();
5812 
5813   if (Option == "pic0") {
5814     // MipsAsmParser needs to know if the current PIC mode changes.
5815     IsPicEnabled = false;
5816 
5817     getTargetStreamer().emitDirectiveOptionPic0();
5818     Parser.Lex();
5819     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
5820       Error(Parser.getTok().getLoc(),
5821             "unexpected token, expected end of statement");
5822       Parser.eatToEndOfStatement();
5823     }
5824     return false;
5825   }
5826 
5827   if (Option == "pic2") {
5828     // MipsAsmParser needs to know if the current PIC mode changes.
5829     IsPicEnabled = true;
5830 
5831     getTargetStreamer().emitDirectiveOptionPic2();
5832     Parser.Lex();
5833     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
5834       Error(Parser.getTok().getLoc(),
5835             "unexpected token, expected end of statement");
5836       Parser.eatToEndOfStatement();
5837     }
5838     return false;
5839   }
5840 
5841   // Unknown option.
5842   Warning(Parser.getTok().getLoc(),
5843           "unknown option, expected 'pic0' or 'pic2'");
5844   Parser.eatToEndOfStatement();
5845   return false;
5846 }
5847 
5848 /// parseInsnDirective
5849 ///  ::= .insn
5850 bool MipsAsmParser::parseInsnDirective() {
5851   // If this is not the end of the statement, report an error.
5852   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5853     reportParseError("unexpected token, expected end of statement");
5854     return false;
5855   }
5856 
5857   // The actual label marking happens in
5858   // MipsELFStreamer::createPendingLabelRelocs().
5859   getTargetStreamer().emitDirectiveInsn();
5860 
5861   getParser().Lex(); // Eat EndOfStatement token.
5862   return false;
5863 }
5864 
5865 /// parseSSectionDirective
5866 ///  ::= .sbss
5867 ///  ::= .sdata
5868 bool MipsAsmParser::parseSSectionDirective(StringRef Section, unsigned Type) {
5869   // If this is not the end of the statement, report an error.
5870   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5871     reportParseError("unexpected token, expected end of statement");
5872     return false;
5873   }
5874 
5875   MCSection *ELFSection = getContext().getELFSection(
5876       Section, Type, ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_MIPS_GPREL);
5877   getParser().getStreamer().SwitchSection(ELFSection);
5878 
5879   getParser().Lex(); // Eat EndOfStatement token.
5880   return false;
5881 }
5882 
5883 /// parseDirectiveModule
5884 ///  ::= .module oddspreg
5885 ///  ::= .module nooddspreg
5886 ///  ::= .module fp=value
5887 ///  ::= .module softfloat
5888 ///  ::= .module hardfloat
5889 bool MipsAsmParser::parseDirectiveModule() {
5890   MCAsmParser &Parser = getParser();
5891   MCAsmLexer &Lexer = getLexer();
5892   SMLoc L = Lexer.getLoc();
5893 
5894   if (!getTargetStreamer().isModuleDirectiveAllowed()) {
5895     // TODO : get a better message.
5896     reportParseError(".module directive must appear before any code");
5897     return false;
5898   }
5899 
5900   StringRef Option;
5901   if (Parser.parseIdentifier(Option)) {
5902     reportParseError("expected .module option identifier");
5903     return false;
5904   }
5905 
5906   if (Option == "oddspreg") {
5907     clearModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5908 
5909     // Synchronize the abiflags information with the FeatureBits information we
5910     // changed above.
5911     getTargetStreamer().updateABIInfo(*this);
5912 
5913     // If printing assembly, use the recently updated abiflags information.
5914     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5915     // emitted at the end).
5916     getTargetStreamer().emitDirectiveModuleOddSPReg();
5917 
5918     // If this is not the end of the statement, report an error.
5919     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5920       reportParseError("unexpected token, expected end of statement");
5921       return false;
5922     }
5923 
5924     return false; // parseDirectiveModule has finished successfully.
5925   } else if (Option == "nooddspreg") {
5926     if (!isABI_O32()) {
5927       Error(L, "'.module nooddspreg' requires the O32 ABI");
5928       return false;
5929     }
5930 
5931     setModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg");
5932 
5933     // Synchronize the abiflags information with the FeatureBits information we
5934     // changed above.
5935     getTargetStreamer().updateABIInfo(*this);
5936 
5937     // If printing assembly, use the recently updated abiflags information.
5938     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5939     // emitted at the end).
5940     getTargetStreamer().emitDirectiveModuleOddSPReg();
5941 
5942     // If this is not the end of the statement, report an error.
5943     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5944       reportParseError("unexpected token, expected end of statement");
5945       return false;
5946     }
5947 
5948     return false; // parseDirectiveModule has finished successfully.
5949   } else if (Option == "fp") {
5950     return parseDirectiveModuleFP();
5951   } else if (Option == "softfloat") {
5952     setModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5953 
5954     // Synchronize the ABI Flags information with the FeatureBits information we
5955     // updated above.
5956     getTargetStreamer().updateABIInfo(*this);
5957 
5958     // If printing assembly, use the recently updated ABI Flags information.
5959     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5960     // emitted later).
5961     getTargetStreamer().emitDirectiveModuleSoftFloat();
5962 
5963     // If this is not the end of the statement, report an error.
5964     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5965       reportParseError("unexpected token, expected end of statement");
5966       return false;
5967     }
5968 
5969     return false; // parseDirectiveModule has finished successfully.
5970   } else if (Option == "hardfloat") {
5971     clearModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float");
5972 
5973     // Synchronize the ABI Flags information with the FeatureBits information we
5974     // updated above.
5975     getTargetStreamer().updateABIInfo(*this);
5976 
5977     // If printing assembly, use the recently updated ABI Flags information.
5978     // If generating ELF, don't do anything (the .MIPS.abiflags section gets
5979     // emitted later).
5980     getTargetStreamer().emitDirectiveModuleHardFloat();
5981 
5982     // If this is not the end of the statement, report an error.
5983     if (getLexer().isNot(AsmToken::EndOfStatement)) {
5984       reportParseError("unexpected token, expected end of statement");
5985       return false;
5986     }
5987 
5988     return false; // parseDirectiveModule has finished successfully.
5989   } else {
5990     return Error(L, "'" + Twine(Option) + "' is not a valid .module option.");
5991   }
5992 }
5993 
5994 /// parseDirectiveModuleFP
5995 ///  ::= =32
5996 ///  ::= =xx
5997 ///  ::= =64
5998 bool MipsAsmParser::parseDirectiveModuleFP() {
5999   MCAsmParser &Parser = getParser();
6000   MCAsmLexer &Lexer = getLexer();
6001 
6002   if (Lexer.isNot(AsmToken::Equal)) {
6003     reportParseError("unexpected token, expected equals sign '='");
6004     return false;
6005   }
6006   Parser.Lex(); // Eat '=' token.
6007 
6008   MipsABIFlagsSection::FpABIKind FpABI;
6009   if (!parseFpABIValue(FpABI, ".module"))
6010     return false;
6011 
6012   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6013     reportParseError("unexpected token, expected end of statement");
6014     return false;
6015   }
6016 
6017   // Synchronize the abiflags information with the FeatureBits information we
6018   // changed above.
6019   getTargetStreamer().updateABIInfo(*this);
6020 
6021   // If printing assembly, use the recently updated abiflags information.
6022   // If generating ELF, don't do anything (the .MIPS.abiflags section gets
6023   // emitted at the end).
6024   getTargetStreamer().emitDirectiveModuleFP();
6025 
6026   Parser.Lex(); // Consume the EndOfStatement.
6027   return false;
6028 }
6029 
6030 bool MipsAsmParser::parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI,
6031                                     StringRef Directive) {
6032   MCAsmParser &Parser = getParser();
6033   MCAsmLexer &Lexer = getLexer();
6034   bool ModuleLevelOptions = Directive == ".module";
6035 
6036   if (Lexer.is(AsmToken::Identifier)) {
6037     StringRef Value = Parser.getTok().getString();
6038     Parser.Lex();
6039 
6040     if (Value != "xx") {
6041       reportParseError("unsupported value, expected 'xx', '32' or '64'");
6042       return false;
6043     }
6044 
6045     if (!isABI_O32()) {
6046       reportParseError("'" + Directive + " fp=xx' requires the O32 ABI");
6047       return false;
6048     }
6049 
6050     FpABI = MipsABIFlagsSection::FpABIKind::XX;
6051     if (ModuleLevelOptions) {
6052       setModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
6053       clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
6054     } else {
6055       setFeatureBits(Mips::FeatureFPXX, "fpxx");
6056       clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
6057     }
6058     return true;
6059   }
6060 
6061   if (Lexer.is(AsmToken::Integer)) {
6062     unsigned Value = Parser.getTok().getIntVal();
6063     Parser.Lex();
6064 
6065     if (Value != 32 && Value != 64) {
6066       reportParseError("unsupported value, expected 'xx', '32' or '64'");
6067       return false;
6068     }
6069 
6070     if (Value == 32) {
6071       if (!isABI_O32()) {
6072         reportParseError("'" + Directive + " fp=32' requires the O32 ABI");
6073         return false;
6074       }
6075 
6076       FpABI = MipsABIFlagsSection::FpABIKind::S32;
6077       if (ModuleLevelOptions) {
6078         clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
6079         clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
6080       } else {
6081         clearFeatureBits(Mips::FeatureFPXX, "fpxx");
6082         clearFeatureBits(Mips::FeatureFP64Bit, "fp64");
6083       }
6084     } else {
6085       FpABI = MipsABIFlagsSection::FpABIKind::S64;
6086       if (ModuleLevelOptions) {
6087         clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx");
6088         setModuleFeatureBits(Mips::FeatureFP64Bit, "fp64");
6089       } else {
6090         clearFeatureBits(Mips::FeatureFPXX, "fpxx");
6091         setFeatureBits(Mips::FeatureFP64Bit, "fp64");
6092       }
6093     }
6094 
6095     return true;
6096   }
6097 
6098   return false;
6099 }
6100 
6101 bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) {
6102   MCAsmParser &Parser = getParser();
6103   StringRef IDVal = DirectiveID.getString();
6104 
6105   if (IDVal == ".cpload")
6106     return parseDirectiveCpLoad(DirectiveID.getLoc());
6107   if (IDVal == ".cprestore")
6108     return parseDirectiveCpRestore(DirectiveID.getLoc());
6109   if (IDVal == ".dword") {
6110     parseDataDirective(8, DirectiveID.getLoc());
6111     return false;
6112   }
6113   if (IDVal == ".ent") {
6114     StringRef SymbolName;
6115 
6116     if (Parser.parseIdentifier(SymbolName)) {
6117       reportParseError("expected identifier after .ent");
6118       return false;
6119     }
6120 
6121     // There's an undocumented extension that allows an integer to
6122     // follow the name of the procedure which AFAICS is ignored by GAS.
6123     // Example: .ent foo,2
6124     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6125       if (getLexer().isNot(AsmToken::Comma)) {
6126         // Even though we accept this undocumented extension for compatibility
6127         // reasons, the additional integer argument does not actually change
6128         // the behaviour of the '.ent' directive, so we would like to discourage
6129         // its use. We do this by not referring to the extended version in
6130         // error messages which are not directly related to its use.
6131         reportParseError("unexpected token, expected end of statement");
6132         return false;
6133       }
6134       Parser.Lex(); // Eat the comma.
6135       const MCExpr *DummyNumber;
6136       int64_t DummyNumberVal;
6137       // If the user was explicitly trying to use the extended version,
6138       // we still give helpful extension-related error messages.
6139       if (Parser.parseExpression(DummyNumber)) {
6140         reportParseError("expected number after comma");
6141         return false;
6142       }
6143       if (!DummyNumber->evaluateAsAbsolute(DummyNumberVal)) {
6144         reportParseError("expected an absolute expression after comma");
6145         return false;
6146       }
6147     }
6148 
6149     // If this is not the end of the statement, report an error.
6150     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6151       reportParseError("unexpected token, expected end of statement");
6152       return false;
6153     }
6154 
6155     MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
6156 
6157     getTargetStreamer().emitDirectiveEnt(*Sym);
6158     CurrentFn = Sym;
6159     IsCpRestoreSet = false;
6160     return false;
6161   }
6162 
6163   if (IDVal == ".end") {
6164     StringRef SymbolName;
6165 
6166     if (Parser.parseIdentifier(SymbolName)) {
6167       reportParseError("expected identifier after .end");
6168       return false;
6169     }
6170 
6171     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6172       reportParseError("unexpected token, expected end of statement");
6173       return false;
6174     }
6175 
6176     if (CurrentFn == nullptr) {
6177       reportParseError(".end used without .ent");
6178       return false;
6179     }
6180 
6181     if ((SymbolName != CurrentFn->getName())) {
6182       reportParseError(".end symbol does not match .ent symbol");
6183       return false;
6184     }
6185 
6186     getTargetStreamer().emitDirectiveEnd(SymbolName);
6187     CurrentFn = nullptr;
6188     IsCpRestoreSet = false;
6189     return false;
6190   }
6191 
6192   if (IDVal == ".frame") {
6193     // .frame $stack_reg, frame_size_in_bytes, $return_reg
6194     SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg;
6195     OperandMatchResultTy ResTy = parseAnyRegister(TmpReg);
6196     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
6197       reportParseError("expected stack register");
6198       return false;
6199     }
6200 
6201     MipsOperand &StackRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
6202     if (!StackRegOpnd.isGPRAsmReg()) {
6203       reportParseError(StackRegOpnd.getStartLoc(),
6204                        "expected general purpose register");
6205       return false;
6206     }
6207     unsigned StackReg = StackRegOpnd.getGPR32Reg();
6208 
6209     if (Parser.getTok().is(AsmToken::Comma))
6210       Parser.Lex();
6211     else {
6212       reportParseError("unexpected token, expected comma");
6213       return false;
6214     }
6215 
6216     // Parse the frame size.
6217     const MCExpr *FrameSize;
6218     int64_t FrameSizeVal;
6219 
6220     if (Parser.parseExpression(FrameSize)) {
6221       reportParseError("expected frame size value");
6222       return false;
6223     }
6224 
6225     if (!FrameSize->evaluateAsAbsolute(FrameSizeVal)) {
6226       reportParseError("frame size not an absolute expression");
6227       return false;
6228     }
6229 
6230     if (Parser.getTok().is(AsmToken::Comma))
6231       Parser.Lex();
6232     else {
6233       reportParseError("unexpected token, expected comma");
6234       return false;
6235     }
6236 
6237     // Parse the return register.
6238     TmpReg.clear();
6239     ResTy = parseAnyRegister(TmpReg);
6240     if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) {
6241       reportParseError("expected return register");
6242       return false;
6243     }
6244 
6245     MipsOperand &ReturnRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]);
6246     if (!ReturnRegOpnd.isGPRAsmReg()) {
6247       reportParseError(ReturnRegOpnd.getStartLoc(),
6248                        "expected general purpose register");
6249       return false;
6250     }
6251 
6252     // If this is not the end of the statement, report an error.
6253     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6254       reportParseError("unexpected token, expected end of statement");
6255       return false;
6256     }
6257 
6258     getTargetStreamer().emitFrame(StackReg, FrameSizeVal,
6259                                   ReturnRegOpnd.getGPR32Reg());
6260     IsCpRestoreSet = false;
6261     return false;
6262   }
6263 
6264   if (IDVal == ".set") {
6265     return parseDirectiveSet();
6266   }
6267 
6268   if (IDVal == ".mask" || IDVal == ".fmask") {
6269     // .mask bitmask, frame_offset
6270     // bitmask: One bit for each register used.
6271     // frame_offset: Offset from Canonical Frame Address ($sp on entry) where
6272     //               first register is expected to be saved.
6273     // Examples:
6274     //   .mask 0x80000000, -4
6275     //   .fmask 0x80000000, -4
6276     //
6277 
6278     // Parse the bitmask
6279     const MCExpr *BitMask;
6280     int64_t BitMaskVal;
6281 
6282     if (Parser.parseExpression(BitMask)) {
6283       reportParseError("expected bitmask value");
6284       return false;
6285     }
6286 
6287     if (!BitMask->evaluateAsAbsolute(BitMaskVal)) {
6288       reportParseError("bitmask not an absolute expression");
6289       return false;
6290     }
6291 
6292     if (Parser.getTok().is(AsmToken::Comma))
6293       Parser.Lex();
6294     else {
6295       reportParseError("unexpected token, expected comma");
6296       return false;
6297     }
6298 
6299     // Parse the frame_offset
6300     const MCExpr *FrameOffset;
6301     int64_t FrameOffsetVal;
6302 
6303     if (Parser.parseExpression(FrameOffset)) {
6304       reportParseError("expected frame offset value");
6305       return false;
6306     }
6307 
6308     if (!FrameOffset->evaluateAsAbsolute(FrameOffsetVal)) {
6309       reportParseError("frame offset not an absolute expression");
6310       return false;
6311     }
6312 
6313     // If this is not the end of the statement, report an error.
6314     if (getLexer().isNot(AsmToken::EndOfStatement)) {
6315       reportParseError("unexpected token, expected end of statement");
6316       return false;
6317     }
6318 
6319     if (IDVal == ".mask")
6320       getTargetStreamer().emitMask(BitMaskVal, FrameOffsetVal);
6321     else
6322       getTargetStreamer().emitFMask(BitMaskVal, FrameOffsetVal);
6323     return false;
6324   }
6325 
6326   if (IDVal == ".nan")
6327     return parseDirectiveNaN();
6328 
6329   if (IDVal == ".gpword") {
6330     parseDirectiveGpWord();
6331     return false;
6332   }
6333 
6334   if (IDVal == ".gpdword") {
6335     parseDirectiveGpDWord();
6336     return false;
6337   }
6338 
6339   if (IDVal == ".word") {
6340     parseDataDirective(4, DirectiveID.getLoc());
6341     return false;
6342   }
6343 
6344   if (IDVal == ".hword") {
6345     parseDataDirective(2, DirectiveID.getLoc());
6346     return false;
6347   }
6348 
6349   if (IDVal == ".option")
6350     return parseDirectiveOption();
6351 
6352   if (IDVal == ".abicalls") {
6353     getTargetStreamer().emitDirectiveAbiCalls();
6354     if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
6355       Error(Parser.getTok().getLoc(),
6356             "unexpected token, expected end of statement");
6357       // Clear line
6358       Parser.eatToEndOfStatement();
6359     }
6360     return false;
6361   }
6362 
6363   if (IDVal == ".cpsetup")
6364     return parseDirectiveCPSetup();
6365 
6366   if (IDVal == ".cpreturn")
6367     return parseDirectiveCPReturn();
6368 
6369   if (IDVal == ".module")
6370     return parseDirectiveModule();
6371 
6372   if (IDVal == ".llvm_internal_mips_reallow_module_directive")
6373     return parseInternalDirectiveReallowModule();
6374 
6375   if (IDVal == ".insn")
6376     return parseInsnDirective();
6377 
6378   if (IDVal == ".sbss")
6379     return parseSSectionDirective(IDVal, ELF::SHT_NOBITS);
6380   if (IDVal == ".sdata")
6381     return parseSSectionDirective(IDVal, ELF::SHT_PROGBITS);
6382 
6383   return true;
6384 }
6385 
6386 bool MipsAsmParser::parseInternalDirectiveReallowModule() {
6387   // If this is not the end of the statement, report an error.
6388   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6389     reportParseError("unexpected token, expected end of statement");
6390     return false;
6391   }
6392 
6393   getTargetStreamer().reallowModuleDirective();
6394 
6395   getParser().Lex(); // Eat EndOfStatement token.
6396   return false;
6397 }
6398 
6399 extern "C" void LLVMInitializeMipsAsmParser() {
6400   RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget);
6401   RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget);
6402   RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target);
6403   RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget);
6404 }
6405 
6406 #define GET_REGISTER_MATCHER
6407 #define GET_MATCHER_IMPLEMENTATION
6408 #include "MipsGenAsmMatcher.inc"
6409