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