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