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