1 //===- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ARMFeatures.h"
10 #include "ARMBaseInstrInfo.h"
11 #include "Utils/ARMBaseInfo.h"
12 #include "MCTargetDesc/ARMAddressingModes.h"
13 #include "MCTargetDesc/ARMBaseInfo.h"
14 #include "MCTargetDesc/ARMInstPrinter.h"
15 #include "MCTargetDesc/ARMMCExpr.h"
16 #include "MCTargetDesc/ARMMCTargetDesc.h"
17 #include "TargetInfo/ARMTargetInfo.h"
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/StringSet.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCInst.h"
33 #include "llvm/MC/MCInstrDesc.h"
34 #include "llvm/MC/MCInstrInfo.h"
35 #include "llvm/MC/MCObjectFileInfo.h"
36 #include "llvm/MC/MCParser/MCAsmLexer.h"
37 #include "llvm/MC/MCParser/MCAsmParser.h"
38 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
39 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
40 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
41 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
42 #include "llvm/MC/MCRegisterInfo.h"
43 #include "llvm/MC/MCSection.h"
44 #include "llvm/MC/MCStreamer.h"
45 #include "llvm/MC/MCSubtargetInfo.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/MC/SubtargetFeature.h"
48 #include "llvm/Support/ARMBuildAttributes.h"
49 #include "llvm/Support/ARMEHABI.h"
50 #include "llvm/Support/Casting.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/SMLoc.h"
56 #include "llvm/Support/TargetParser.h"
57 #include "llvm/Support/TargetRegistry.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include <algorithm>
60 #include <cassert>
61 #include <cstddef>
62 #include <cstdint>
63 #include <iterator>
64 #include <limits>
65 #include <memory>
66 #include <string>
67 #include <utility>
68 #include <vector>
69 
70 #define DEBUG_TYPE "asm-parser"
71 
72 using namespace llvm;
73 
74 namespace llvm {
75 extern const MCInstrDesc ARMInsts[];
76 } // end namespace llvm
77 
78 namespace {
79 
80 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
81 
82 static cl::opt<ImplicitItModeTy> ImplicitItMode(
83     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
84     cl::desc("Allow conditional instructions outdside of an IT block"),
85     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
86                           "Accept in both ISAs, emit implicit ITs in Thumb"),
87                clEnumValN(ImplicitItModeTy::Never, "never",
88                           "Warn in ARM, reject in Thumb"),
89                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
90                           "Accept in ARM, reject in Thumb"),
91                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
92                           "Warn in ARM, emit implicit ITs in Thumb")));
93 
94 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
95                                         cl::init(false));
96 
97 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
98 
99 static inline unsigned extractITMaskBit(unsigned Mask, unsigned Position) {
100   // Position==0 means we're not in an IT block at all. Position==1
101   // means we want the first state bit, which is always 0 (Then).
102   // Position==2 means we want the second state bit, stored at bit 3
103   // of Mask, and so on downwards. So (5 - Position) will shift the
104   // right bit down to bit 0, including the always-0 bit at bit 4 for
105   // the mandatory initial Then.
106   return (Mask >> (5 - Position) & 1);
107 }
108 
109 class UnwindContext {
110   using Locs = SmallVector<SMLoc, 4>;
111 
112   MCAsmParser &Parser;
113   Locs FnStartLocs;
114   Locs CantUnwindLocs;
115   Locs PersonalityLocs;
116   Locs PersonalityIndexLocs;
117   Locs HandlerDataLocs;
118   int FPReg;
119 
120 public:
121   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
122 
123   bool hasFnStart() const { return !FnStartLocs.empty(); }
124   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
125   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
126 
127   bool hasPersonality() const {
128     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
129   }
130 
131   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
132   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
133   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
134   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
135   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
136 
137   void saveFPReg(int Reg) { FPReg = Reg; }
138   int getFPReg() const { return FPReg; }
139 
140   void emitFnStartLocNotes() const {
141     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
142          FI != FE; ++FI)
143       Parser.Note(*FI, ".fnstart was specified here");
144   }
145 
146   void emitCantUnwindLocNotes() const {
147     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
148                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
149       Parser.Note(*UI, ".cantunwind was specified here");
150   }
151 
152   void emitHandlerDataLocNotes() const {
153     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
154                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
155       Parser.Note(*HI, ".handlerdata was specified here");
156   }
157 
158   void emitPersonalityLocNotes() const {
159     for (Locs::const_iterator PI = PersonalityLocs.begin(),
160                               PE = PersonalityLocs.end(),
161                               PII = PersonalityIndexLocs.begin(),
162                               PIE = PersonalityIndexLocs.end();
163          PI != PE || PII != PIE;) {
164       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
165         Parser.Note(*PI++, ".personality was specified here");
166       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
167         Parser.Note(*PII++, ".personalityindex was specified here");
168       else
169         llvm_unreachable(".personality and .personalityindex cannot be "
170                          "at the same location");
171     }
172   }
173 
174   void reset() {
175     FnStartLocs = Locs();
176     CantUnwindLocs = Locs();
177     PersonalityLocs = Locs();
178     HandlerDataLocs = Locs();
179     PersonalityIndexLocs = Locs();
180     FPReg = ARM::SP;
181   }
182 };
183 
184 // Various sets of ARM instruction mnemonics which are used by the asm parser
185 class ARMMnemonicSets {
186   StringSet<> CDE;
187   StringSet<> CDEWithVPTSuffix;
188 public:
189   ARMMnemonicSets(const MCSubtargetInfo &STI);
190 
191   /// Returns true iff a given mnemonic is a CDE instruction
192   bool isCDEInstr(StringRef Mnemonic) {
193     // Quick check before searching the set
194     if (!Mnemonic.startswith("cx") && !Mnemonic.startswith("vcx"))
195       return false;
196     return CDE.count(Mnemonic);
197   }
198 
199   /// Returns true iff a given mnemonic is a VPT-predicable CDE instruction
200   /// (possibly with a predication suffix "e" or "t")
201   bool isVPTPredicableCDEInstr(StringRef Mnemonic) {
202     if (!Mnemonic.startswith("vcx"))
203       return false;
204     return CDEWithVPTSuffix.count(Mnemonic);
205   }
206 
207   /// Returns true iff a given mnemonic is an IT-predicable CDE instruction
208   /// (possibly with a condition suffix)
209   bool isITPredicableCDEInstr(StringRef Mnemonic) {
210     if (!Mnemonic.startswith("cx"))
211       return false;
212     return Mnemonic.startswith("cx1a") || Mnemonic.startswith("cx1da") ||
213            Mnemonic.startswith("cx2a") || Mnemonic.startswith("cx2da") ||
214            Mnemonic.startswith("cx3a") || Mnemonic.startswith("cx3da");
215   }
216 
217   /// Return true iff a given mnemonic is an integer CDE instruction with
218   /// dual-register destination
219   bool isCDEDualRegInstr(StringRef Mnemonic) {
220     if (!Mnemonic.startswith("cx"))
221       return false;
222     return Mnemonic == "cx1d" || Mnemonic == "cx1da" ||
223            Mnemonic == "cx2d" || Mnemonic == "cx2da" ||
224            Mnemonic == "cx3d" || Mnemonic == "cx3da";
225   }
226 };
227 
228 ARMMnemonicSets::ARMMnemonicSets(const MCSubtargetInfo &STI) {
229   for (StringRef Mnemonic: { "cx1", "cx1a", "cx1d", "cx1da",
230                              "cx2", "cx2a", "cx2d", "cx2da",
231                              "cx3", "cx3a", "cx3d", "cx3da", })
232     CDE.insert(Mnemonic);
233   for (StringRef Mnemonic :
234        {"vcx1", "vcx1a", "vcx2", "vcx2a", "vcx3", "vcx3a"}) {
235     CDE.insert(Mnemonic);
236     CDEWithVPTSuffix.insert(Mnemonic);
237     CDEWithVPTSuffix.insert(std::string(Mnemonic) + "t");
238     CDEWithVPTSuffix.insert(std::string(Mnemonic) + "e");
239   }
240 }
241 
242 class ARMAsmParser : public MCTargetAsmParser {
243   const MCRegisterInfo *MRI;
244   UnwindContext UC;
245   ARMMnemonicSets MS;
246 
247   ARMTargetStreamer &getTargetStreamer() {
248     assert(getParser().getStreamer().getTargetStreamer() &&
249            "do not have a target streamer");
250     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
251     return static_cast<ARMTargetStreamer &>(TS);
252   }
253 
254   // Map of register aliases registers via the .req directive.
255   StringMap<unsigned> RegisterReqs;
256 
257   bool NextSymbolIsThumb;
258 
259   bool useImplicitITThumb() const {
260     return ImplicitItMode == ImplicitItModeTy::Always ||
261            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
262   }
263 
264   bool useImplicitITARM() const {
265     return ImplicitItMode == ImplicitItModeTy::Always ||
266            ImplicitItMode == ImplicitItModeTy::ARMOnly;
267   }
268 
269   struct {
270     ARMCC::CondCodes Cond;    // Condition for IT block.
271     unsigned Mask:4;          // Condition mask for instructions.
272                               // Starting at first 1 (from lsb).
273                               //   '1'  condition as indicated in IT.
274                               //   '0'  inverse of condition (else).
275                               // Count of instructions in IT block is
276                               // 4 - trailingzeroes(mask)
277                               // Note that this does not have the same encoding
278                               // as in the IT instruction, which also depends
279                               // on the low bit of the condition code.
280 
281     unsigned CurPosition;     // Current position in parsing of IT
282                               // block. In range [0,4], with 0 being the IT
283                               // instruction itself. Initialized according to
284                               // count of instructions in block.  ~0U if no
285                               // active IT block.
286 
287     bool IsExplicit;          // true  - The IT instruction was present in the
288                               //         input, we should not modify it.
289                               // false - The IT instruction was added
290                               //         implicitly, we can extend it if that
291                               //         would be legal.
292   } ITState;
293 
294   SmallVector<MCInst, 4> PendingConditionalInsts;
295 
296   void flushPendingInstructions(MCStreamer &Out) override {
297     if (!inImplicitITBlock()) {
298       assert(PendingConditionalInsts.size() == 0);
299       return;
300     }
301 
302     // Emit the IT instruction
303     MCInst ITInst;
304     ITInst.setOpcode(ARM::t2IT);
305     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
306     ITInst.addOperand(MCOperand::createImm(ITState.Mask));
307     Out.emitInstruction(ITInst, getSTI());
308 
309     // Emit the conditonal instructions
310     assert(PendingConditionalInsts.size() <= 4);
311     for (const MCInst &Inst : PendingConditionalInsts) {
312       Out.emitInstruction(Inst, getSTI());
313     }
314     PendingConditionalInsts.clear();
315 
316     // Clear the IT state
317     ITState.Mask = 0;
318     ITState.CurPosition = ~0U;
319   }
320 
321   bool inITBlock() { return ITState.CurPosition != ~0U; }
322   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
323   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
324 
325   bool lastInITBlock() {
326     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
327   }
328 
329   void forwardITPosition() {
330     if (!inITBlock()) return;
331     // Move to the next instruction in the IT block, if there is one. If not,
332     // mark the block as done, except for implicit IT blocks, which we leave
333     // open until we find an instruction that can't be added to it.
334     unsigned TZ = countTrailingZeros(ITState.Mask);
335     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
336       ITState.CurPosition = ~0U; // Done with the IT block after this.
337   }
338 
339   // Rewind the state of the current IT block, removing the last slot from it.
340   void rewindImplicitITPosition() {
341     assert(inImplicitITBlock());
342     assert(ITState.CurPosition > 1);
343     ITState.CurPosition--;
344     unsigned TZ = countTrailingZeros(ITState.Mask);
345     unsigned NewMask = 0;
346     NewMask |= ITState.Mask & (0xC << TZ);
347     NewMask |= 0x2 << TZ;
348     ITState.Mask = NewMask;
349   }
350 
351   // Rewind the state of the current IT block, removing the last slot from it.
352   // If we were at the first slot, this closes the IT block.
353   void discardImplicitITBlock() {
354     assert(inImplicitITBlock());
355     assert(ITState.CurPosition == 1);
356     ITState.CurPosition = ~0U;
357   }
358 
359   // Return the low-subreg of a given Q register.
360   unsigned getDRegFromQReg(unsigned QReg) const {
361     return MRI->getSubReg(QReg, ARM::dsub_0);
362   }
363 
364   // Get the condition code corresponding to the current IT block slot.
365   ARMCC::CondCodes currentITCond() {
366     unsigned MaskBit = extractITMaskBit(ITState.Mask, ITState.CurPosition);
367     return MaskBit ? ARMCC::getOppositeCondition(ITState.Cond) : ITState.Cond;
368   }
369 
370   // Invert the condition of the current IT block slot without changing any
371   // other slots in the same block.
372   void invertCurrentITCondition() {
373     if (ITState.CurPosition == 1) {
374       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
375     } else {
376       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
377     }
378   }
379 
380   // Returns true if the current IT block is full (all 4 slots used).
381   bool isITBlockFull() {
382     return inITBlock() && (ITState.Mask & 1);
383   }
384 
385   // Extend the current implicit IT block to have one more slot with the given
386   // condition code.
387   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
388     assert(inImplicitITBlock());
389     assert(!isITBlockFull());
390     assert(Cond == ITState.Cond ||
391            Cond == ARMCC::getOppositeCondition(ITState.Cond));
392     unsigned TZ = countTrailingZeros(ITState.Mask);
393     unsigned NewMask = 0;
394     // Keep any existing condition bits.
395     NewMask |= ITState.Mask & (0xE << TZ);
396     // Insert the new condition bit.
397     NewMask |= (Cond != ITState.Cond) << TZ;
398     // Move the trailing 1 down one bit.
399     NewMask |= 1 << (TZ - 1);
400     ITState.Mask = NewMask;
401   }
402 
403   // Create a new implicit IT block with a dummy condition code.
404   void startImplicitITBlock() {
405     assert(!inITBlock());
406     ITState.Cond = ARMCC::AL;
407     ITState.Mask = 8;
408     ITState.CurPosition = 1;
409     ITState.IsExplicit = false;
410   }
411 
412   // Create a new explicit IT block with the given condition and mask.
413   // The mask should be in the format used in ARMOperand and
414   // MCOperand, with a 1 implying 'e', regardless of the low bit of
415   // the condition.
416   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
417     assert(!inITBlock());
418     ITState.Cond = Cond;
419     ITState.Mask = Mask;
420     ITState.CurPosition = 0;
421     ITState.IsExplicit = true;
422   }
423 
424   struct {
425     unsigned Mask : 4;
426     unsigned CurPosition;
427   } VPTState;
428   bool inVPTBlock() { return VPTState.CurPosition != ~0U; }
429   void forwardVPTPosition() {
430     if (!inVPTBlock()) return;
431     unsigned TZ = countTrailingZeros(VPTState.Mask);
432     if (++VPTState.CurPosition == 5 - TZ)
433       VPTState.CurPosition = ~0U;
434   }
435 
436   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
437     return getParser().Note(L, Msg, Range);
438   }
439 
440   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
441     return getParser().Warning(L, Msg, Range);
442   }
443 
444   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
445     return getParser().Error(L, Msg, Range);
446   }
447 
448   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
449                            unsigned ListNo, bool IsARPop = false);
450   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
451                            unsigned ListNo);
452 
453   int tryParseRegister();
454   bool tryParseRegisterWithWriteBack(OperandVector &);
455   int tryParseShiftRegister(OperandVector &);
456   bool parseRegisterList(OperandVector &, bool EnforceOrder = true);
457   bool parseMemory(OperandVector &);
458   bool parseOperand(OperandVector &, StringRef Mnemonic);
459   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
460   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
461                               unsigned &ShiftAmount);
462   bool parseLiteralValues(unsigned Size, SMLoc L);
463   bool parseDirectiveThumb(SMLoc L);
464   bool parseDirectiveARM(SMLoc L);
465   bool parseDirectiveThumbFunc(SMLoc L);
466   bool parseDirectiveCode(SMLoc L);
467   bool parseDirectiveSyntax(SMLoc L);
468   bool parseDirectiveReq(StringRef Name, SMLoc L);
469   bool parseDirectiveUnreq(SMLoc L);
470   bool parseDirectiveArch(SMLoc L);
471   bool parseDirectiveEabiAttr(SMLoc L);
472   bool parseDirectiveCPU(SMLoc L);
473   bool parseDirectiveFPU(SMLoc L);
474   bool parseDirectiveFnStart(SMLoc L);
475   bool parseDirectiveFnEnd(SMLoc L);
476   bool parseDirectiveCantUnwind(SMLoc L);
477   bool parseDirectivePersonality(SMLoc L);
478   bool parseDirectiveHandlerData(SMLoc L);
479   bool parseDirectiveSetFP(SMLoc L);
480   bool parseDirectivePad(SMLoc L);
481   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
482   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
483   bool parseDirectiveLtorg(SMLoc L);
484   bool parseDirectiveEven(SMLoc L);
485   bool parseDirectivePersonalityIndex(SMLoc L);
486   bool parseDirectiveUnwindRaw(SMLoc L);
487   bool parseDirectiveTLSDescSeq(SMLoc L);
488   bool parseDirectiveMovSP(SMLoc L);
489   bool parseDirectiveObjectArch(SMLoc L);
490   bool parseDirectiveArchExtension(SMLoc L);
491   bool parseDirectiveAlign(SMLoc L);
492   bool parseDirectiveThumbSet(SMLoc L);
493 
494   bool isMnemonicVPTPredicable(StringRef Mnemonic, StringRef ExtraToken);
495   StringRef splitMnemonic(StringRef Mnemonic, StringRef ExtraToken,
496                           unsigned &PredicationCode,
497                           unsigned &VPTPredicationCode, bool &CarrySetting,
498                           unsigned &ProcessorIMod, StringRef &ITMask);
499   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef ExtraToken,
500                              StringRef FullInst, bool &CanAcceptCarrySet,
501                              bool &CanAcceptPredicationCode,
502                              bool &CanAcceptVPTPredicationCode);
503 
504   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
505                                      OperandVector &Operands);
506   bool CDEConvertDualRegOperand(StringRef Mnemonic, OperandVector &Operands);
507 
508   bool isThumb() const {
509     // FIXME: Can tablegen auto-generate this?
510     return getSTI().getFeatureBits()[ARM::ModeThumb];
511   }
512 
513   bool isThumbOne() const {
514     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
515   }
516 
517   bool isThumbTwo() const {
518     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
519   }
520 
521   bool hasThumb() const {
522     return getSTI().getFeatureBits()[ARM::HasV4TOps];
523   }
524 
525   bool hasThumb2() const {
526     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
527   }
528 
529   bool hasV6Ops() const {
530     return getSTI().getFeatureBits()[ARM::HasV6Ops];
531   }
532 
533   bool hasV6T2Ops() const {
534     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
535   }
536 
537   bool hasV6MOps() const {
538     return getSTI().getFeatureBits()[ARM::HasV6MOps];
539   }
540 
541   bool hasV7Ops() const {
542     return getSTI().getFeatureBits()[ARM::HasV7Ops];
543   }
544 
545   bool hasV8Ops() const {
546     return getSTI().getFeatureBits()[ARM::HasV8Ops];
547   }
548 
549   bool hasV8MBaseline() const {
550     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
551   }
552 
553   bool hasV8MMainline() const {
554     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
555   }
556   bool hasV8_1MMainline() const {
557     return getSTI().getFeatureBits()[ARM::HasV8_1MMainlineOps];
558   }
559   bool hasMVE() const {
560     return getSTI().getFeatureBits()[ARM::HasMVEIntegerOps];
561   }
562   bool hasMVEFloat() const {
563     return getSTI().getFeatureBits()[ARM::HasMVEFloatOps];
564   }
565   bool hasCDE() const {
566     return getSTI().getFeatureBits()[ARM::HasCDEOps];
567   }
568   bool has8MSecExt() const {
569     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
570   }
571 
572   bool hasARM() const {
573     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
574   }
575 
576   bool hasDSP() const {
577     return getSTI().getFeatureBits()[ARM::FeatureDSP];
578   }
579 
580   bool hasD32() const {
581     return getSTI().getFeatureBits()[ARM::FeatureD32];
582   }
583 
584   bool hasV8_1aOps() const {
585     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
586   }
587 
588   bool hasRAS() const {
589     return getSTI().getFeatureBits()[ARM::FeatureRAS];
590   }
591 
592   void SwitchMode() {
593     MCSubtargetInfo &STI = copySTI();
594     auto FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
595     setAvailableFeatures(FB);
596   }
597 
598   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
599 
600   bool isMClass() const {
601     return getSTI().getFeatureBits()[ARM::FeatureMClass];
602   }
603 
604   /// @name Auto-generated Match Functions
605   /// {
606 
607 #define GET_ASSEMBLER_HEADER
608 #include "ARMGenAsmMatcher.inc"
609 
610   /// }
611 
612   OperandMatchResultTy parseITCondCode(OperandVector &);
613   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
614   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
615   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
616   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
617   OperandMatchResultTy parseTraceSyncBarrierOptOperand(OperandVector &);
618   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
619   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
620   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
621   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
622   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
623                                    int High);
624   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
625     return parsePKHImm(O, "lsl", 0, 31);
626   }
627   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
628     return parsePKHImm(O, "asr", 1, 32);
629   }
630   OperandMatchResultTy parseSetEndImm(OperandVector &);
631   OperandMatchResultTy parseShifterImm(OperandVector &);
632   OperandMatchResultTy parseRotImm(OperandVector &);
633   OperandMatchResultTy parseModImm(OperandVector &);
634   OperandMatchResultTy parseBitfield(OperandVector &);
635   OperandMatchResultTy parsePostIdxReg(OperandVector &);
636   OperandMatchResultTy parseAM3Offset(OperandVector &);
637   OperandMatchResultTy parseFPImm(OperandVector &);
638   OperandMatchResultTy parseVectorList(OperandVector &);
639   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
640                                        SMLoc &EndLoc);
641 
642   // Asm Match Converter Methods
643   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
644   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
645   void cvtMVEVMOVQtoDReg(MCInst &Inst, const OperandVector &);
646 
647   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
648   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
649   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
650   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
651   bool shouldOmitVectorPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
652   bool isITBlockTerminator(MCInst &Inst) const;
653   void fixupGNULDRDAlias(StringRef Mnemonic, OperandVector &Operands);
654   bool validateLDRDSTRD(MCInst &Inst, const OperandVector &Operands,
655                         bool Load, bool ARMMode, bool Writeback);
656 
657 public:
658   enum ARMMatchResultTy {
659     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
660     Match_RequiresNotITBlock,
661     Match_RequiresV6,
662     Match_RequiresThumb2,
663     Match_RequiresV8,
664     Match_RequiresFlagSetting,
665 #define GET_OPERAND_DIAGNOSTIC_TYPES
666 #include "ARMGenAsmMatcher.inc"
667 
668   };
669 
670   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
671                const MCInstrInfo &MII, const MCTargetOptions &Options)
672     : MCTargetAsmParser(Options, STI, MII), UC(Parser), MS(STI) {
673     MCAsmParserExtension::Initialize(Parser);
674 
675     // Cache the MCRegisterInfo.
676     MRI = getContext().getRegisterInfo();
677 
678     // Initialize the set of available features.
679     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
680 
681     // Add build attributes based on the selected target.
682     if (AddBuildAttributes)
683       getTargetStreamer().emitTargetAttributes(STI);
684 
685     // Not in an ITBlock to start with.
686     ITState.CurPosition = ~0U;
687 
688     VPTState.CurPosition = ~0U;
689 
690     NextSymbolIsThumb = false;
691   }
692 
693   // Implementation of the MCTargetAsmParser interface:
694   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
695   OperandMatchResultTy tryParseRegister(unsigned &RegNo, SMLoc &StartLoc,
696                                         SMLoc &EndLoc) override;
697   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
698                         SMLoc NameLoc, OperandVector &Operands) override;
699   bool ParseDirective(AsmToken DirectiveID) override;
700 
701   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
702                                       unsigned Kind) override;
703   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
704 
705   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
706                                OperandVector &Operands, MCStreamer &Out,
707                                uint64_t &ErrorInfo,
708                                bool MatchingInlineAsm) override;
709   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
710                             SmallVectorImpl<NearMissInfo> &NearMisses,
711                             bool MatchingInlineAsm, bool &EmitInITBlock,
712                             MCStreamer &Out);
713 
714   struct NearMissMessage {
715     SMLoc Loc;
716     SmallString<128> Message;
717   };
718 
719   const char *getCustomOperandDiag(ARMMatchResultTy MatchError);
720 
721   void FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
722                         SmallVectorImpl<NearMissMessage> &NearMissesOut,
723                         SMLoc IDLoc, OperandVector &Operands);
724   void ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses, SMLoc IDLoc,
725                         OperandVector &Operands);
726 
727   void doBeforeLabelEmit(MCSymbol *Symbol) override;
728 
729   void onLabelParsed(MCSymbol *Symbol) override;
730 };
731 
732 /// ARMOperand - Instances of this class represent a parsed ARM machine
733 /// operand.
734 class ARMOperand : public MCParsedAsmOperand {
735   enum KindTy {
736     k_CondCode,
737     k_VPTPred,
738     k_CCOut,
739     k_ITCondMask,
740     k_CoprocNum,
741     k_CoprocReg,
742     k_CoprocOption,
743     k_Immediate,
744     k_MemBarrierOpt,
745     k_InstSyncBarrierOpt,
746     k_TraceSyncBarrierOpt,
747     k_Memory,
748     k_PostIndexRegister,
749     k_MSRMask,
750     k_BankedReg,
751     k_ProcIFlags,
752     k_VectorIndex,
753     k_Register,
754     k_RegisterList,
755     k_RegisterListWithAPSR,
756     k_DPRRegisterList,
757     k_SPRRegisterList,
758     k_FPSRegisterListWithVPR,
759     k_FPDRegisterListWithVPR,
760     k_VectorList,
761     k_VectorListAllLanes,
762     k_VectorListIndexed,
763     k_ShiftedRegister,
764     k_ShiftedImmediate,
765     k_ShifterImmediate,
766     k_RotateImmediate,
767     k_ModifiedImmediate,
768     k_ConstantPoolImmediate,
769     k_BitfieldDescriptor,
770     k_Token,
771   } Kind;
772 
773   SMLoc StartLoc, EndLoc, AlignmentLoc;
774   SmallVector<unsigned, 8> Registers;
775 
776   struct CCOp {
777     ARMCC::CondCodes Val;
778   };
779 
780   struct VCCOp {
781     ARMVCC::VPTCodes Val;
782   };
783 
784   struct CopOp {
785     unsigned Val;
786   };
787 
788   struct CoprocOptionOp {
789     unsigned Val;
790   };
791 
792   struct ITMaskOp {
793     unsigned Mask:4;
794   };
795 
796   struct MBOptOp {
797     ARM_MB::MemBOpt Val;
798   };
799 
800   struct ISBOptOp {
801     ARM_ISB::InstSyncBOpt Val;
802   };
803 
804   struct TSBOptOp {
805     ARM_TSB::TraceSyncBOpt Val;
806   };
807 
808   struct IFlagsOp {
809     ARM_PROC::IFlags Val;
810   };
811 
812   struct MMaskOp {
813     unsigned Val;
814   };
815 
816   struct BankedRegOp {
817     unsigned Val;
818   };
819 
820   struct TokOp {
821     const char *Data;
822     unsigned Length;
823   };
824 
825   struct RegOp {
826     unsigned RegNum;
827   };
828 
829   // A vector register list is a sequential list of 1 to 4 registers.
830   struct VectorListOp {
831     unsigned RegNum;
832     unsigned Count;
833     unsigned LaneIndex;
834     bool isDoubleSpaced;
835   };
836 
837   struct VectorIndexOp {
838     unsigned Val;
839   };
840 
841   struct ImmOp {
842     const MCExpr *Val;
843   };
844 
845   /// Combined record for all forms of ARM address expressions.
846   struct MemoryOp {
847     unsigned BaseRegNum;
848     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
849     // was specified.
850     const MCConstantExpr *OffsetImm;  // Offset immediate value
851     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
852     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
853     unsigned ShiftImm;        // shift for OffsetReg.
854     unsigned Alignment;       // 0 = no alignment specified
855     // n = alignment in bytes (2, 4, 8, 16, or 32)
856     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
857   };
858 
859   struct PostIdxRegOp {
860     unsigned RegNum;
861     bool isAdd;
862     ARM_AM::ShiftOpc ShiftTy;
863     unsigned ShiftImm;
864   };
865 
866   struct ShifterImmOp {
867     bool isASR;
868     unsigned Imm;
869   };
870 
871   struct RegShiftedRegOp {
872     ARM_AM::ShiftOpc ShiftTy;
873     unsigned SrcReg;
874     unsigned ShiftReg;
875     unsigned ShiftImm;
876   };
877 
878   struct RegShiftedImmOp {
879     ARM_AM::ShiftOpc ShiftTy;
880     unsigned SrcReg;
881     unsigned ShiftImm;
882   };
883 
884   struct RotImmOp {
885     unsigned Imm;
886   };
887 
888   struct ModImmOp {
889     unsigned Bits;
890     unsigned Rot;
891   };
892 
893   struct BitfieldOp {
894     unsigned LSB;
895     unsigned Width;
896   };
897 
898   union {
899     struct CCOp CC;
900     struct VCCOp VCC;
901     struct CopOp Cop;
902     struct CoprocOptionOp CoprocOption;
903     struct MBOptOp MBOpt;
904     struct ISBOptOp ISBOpt;
905     struct TSBOptOp TSBOpt;
906     struct ITMaskOp ITMask;
907     struct IFlagsOp IFlags;
908     struct MMaskOp MMask;
909     struct BankedRegOp BankedReg;
910     struct TokOp Tok;
911     struct RegOp Reg;
912     struct VectorListOp VectorList;
913     struct VectorIndexOp VectorIndex;
914     struct ImmOp Imm;
915     struct MemoryOp Memory;
916     struct PostIdxRegOp PostIdxReg;
917     struct ShifterImmOp ShifterImm;
918     struct RegShiftedRegOp RegShiftedReg;
919     struct RegShiftedImmOp RegShiftedImm;
920     struct RotImmOp RotImm;
921     struct ModImmOp ModImm;
922     struct BitfieldOp Bitfield;
923   };
924 
925 public:
926   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
927 
928   /// getStartLoc - Get the location of the first token of this operand.
929   SMLoc getStartLoc() const override { return StartLoc; }
930 
931   /// getEndLoc - Get the location of the last token of this operand.
932   SMLoc getEndLoc() const override { return EndLoc; }
933 
934   /// getLocRange - Get the range between the first and last token of this
935   /// operand.
936   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
937 
938   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
939   SMLoc getAlignmentLoc() const {
940     assert(Kind == k_Memory && "Invalid access!");
941     return AlignmentLoc;
942   }
943 
944   ARMCC::CondCodes getCondCode() const {
945     assert(Kind == k_CondCode && "Invalid access!");
946     return CC.Val;
947   }
948 
949   ARMVCC::VPTCodes getVPTPred() const {
950     assert(isVPTPred() && "Invalid access!");
951     return VCC.Val;
952   }
953 
954   unsigned getCoproc() const {
955     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
956     return Cop.Val;
957   }
958 
959   StringRef getToken() const {
960     assert(Kind == k_Token && "Invalid access!");
961     return StringRef(Tok.Data, Tok.Length);
962   }
963 
964   unsigned getReg() const override {
965     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
966     return Reg.RegNum;
967   }
968 
969   const SmallVectorImpl<unsigned> &getRegList() const {
970     assert((Kind == k_RegisterList || Kind == k_RegisterListWithAPSR ||
971             Kind == k_DPRRegisterList || Kind == k_SPRRegisterList ||
972             Kind == k_FPSRegisterListWithVPR ||
973             Kind == k_FPDRegisterListWithVPR) &&
974            "Invalid access!");
975     return Registers;
976   }
977 
978   const MCExpr *getImm() const {
979     assert(isImm() && "Invalid access!");
980     return Imm.Val;
981   }
982 
983   const MCExpr *getConstantPoolImm() const {
984     assert(isConstantPoolImm() && "Invalid access!");
985     return Imm.Val;
986   }
987 
988   unsigned getVectorIndex() const {
989     assert(Kind == k_VectorIndex && "Invalid access!");
990     return VectorIndex.Val;
991   }
992 
993   ARM_MB::MemBOpt getMemBarrierOpt() const {
994     assert(Kind == k_MemBarrierOpt && "Invalid access!");
995     return MBOpt.Val;
996   }
997 
998   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
999     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
1000     return ISBOpt.Val;
1001   }
1002 
1003   ARM_TSB::TraceSyncBOpt getTraceSyncBarrierOpt() const {
1004     assert(Kind == k_TraceSyncBarrierOpt && "Invalid access!");
1005     return TSBOpt.Val;
1006   }
1007 
1008   ARM_PROC::IFlags getProcIFlags() const {
1009     assert(Kind == k_ProcIFlags && "Invalid access!");
1010     return IFlags.Val;
1011   }
1012 
1013   unsigned getMSRMask() const {
1014     assert(Kind == k_MSRMask && "Invalid access!");
1015     return MMask.Val;
1016   }
1017 
1018   unsigned getBankedReg() const {
1019     assert(Kind == k_BankedReg && "Invalid access!");
1020     return BankedReg.Val;
1021   }
1022 
1023   bool isCoprocNum() const { return Kind == k_CoprocNum; }
1024   bool isCoprocReg() const { return Kind == k_CoprocReg; }
1025   bool isCoprocOption() const { return Kind == k_CoprocOption; }
1026   bool isCondCode() const { return Kind == k_CondCode; }
1027   bool isVPTPred() const { return Kind == k_VPTPred; }
1028   bool isCCOut() const { return Kind == k_CCOut; }
1029   bool isITMask() const { return Kind == k_ITCondMask; }
1030   bool isITCondCode() const { return Kind == k_CondCode; }
1031   bool isImm() const override {
1032     return Kind == k_Immediate;
1033   }
1034 
1035   bool isARMBranchTarget() const {
1036     if (!isImm()) return false;
1037 
1038     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
1039       return CE->getValue() % 4 == 0;
1040     return true;
1041   }
1042 
1043 
1044   bool isThumbBranchTarget() const {
1045     if (!isImm()) return false;
1046 
1047     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
1048       return CE->getValue() % 2 == 0;
1049     return true;
1050   }
1051 
1052   // checks whether this operand is an unsigned offset which fits is a field
1053   // of specified width and scaled by a specific number of bits
1054   template<unsigned width, unsigned scale>
1055   bool isUnsignedOffset() const {
1056     if (!isImm()) return false;
1057     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1058     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1059       int64_t Val = CE->getValue();
1060       int64_t Align = 1LL << scale;
1061       int64_t Max = Align * ((1LL << width) - 1);
1062       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
1063     }
1064     return false;
1065   }
1066 
1067   // checks whether this operand is an signed offset which fits is a field
1068   // of specified width and scaled by a specific number of bits
1069   template<unsigned width, unsigned scale>
1070   bool isSignedOffset() const {
1071     if (!isImm()) return false;
1072     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1073     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1074       int64_t Val = CE->getValue();
1075       int64_t Align = 1LL << scale;
1076       int64_t Max = Align * ((1LL << (width-1)) - 1);
1077       int64_t Min = -Align * (1LL << (width-1));
1078       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
1079     }
1080     return false;
1081   }
1082 
1083   // checks whether this operand is an offset suitable for the LE /
1084   // LETP instructions in Arm v8.1M
1085   bool isLEOffset() const {
1086     if (!isImm()) return false;
1087     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1088     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1089       int64_t Val = CE->getValue();
1090       return Val < 0 && Val >= -4094 && (Val & 1) == 0;
1091     }
1092     return false;
1093   }
1094 
1095   // checks whether this operand is a memory operand computed as an offset
1096   // applied to PC. the offset may have 8 bits of magnitude and is represented
1097   // with two bits of shift. textually it may be either [pc, #imm], #imm or
1098   // relocable expression...
1099   bool isThumbMemPC() const {
1100     int64_t Val = 0;
1101     if (isImm()) {
1102       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1103       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
1104       if (!CE) return false;
1105       Val = CE->getValue();
1106     }
1107     else if (isGPRMem()) {
1108       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
1109       if(Memory.BaseRegNum != ARM::PC) return false;
1110       Val = Memory.OffsetImm->getValue();
1111     }
1112     else return false;
1113     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
1114   }
1115 
1116   bool isFPImm() const {
1117     if (!isImm()) return false;
1118     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1119     if (!CE) return false;
1120     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1121     return Val != -1;
1122   }
1123 
1124   template<int64_t N, int64_t M>
1125   bool isImmediate() const {
1126     if (!isImm()) return false;
1127     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1128     if (!CE) return false;
1129     int64_t Value = CE->getValue();
1130     return Value >= N && Value <= M;
1131   }
1132 
1133   template<int64_t N, int64_t M>
1134   bool isImmediateS4() const {
1135     if (!isImm()) return false;
1136     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1137     if (!CE) return false;
1138     int64_t Value = CE->getValue();
1139     return ((Value & 3) == 0) && Value >= N && Value <= M;
1140   }
1141   template<int64_t N, int64_t M>
1142   bool isImmediateS2() const {
1143     if (!isImm()) return false;
1144     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1145     if (!CE) return false;
1146     int64_t Value = CE->getValue();
1147     return ((Value & 1) == 0) && Value >= N && Value <= M;
1148   }
1149   bool isFBits16() const {
1150     return isImmediate<0, 17>();
1151   }
1152   bool isFBits32() const {
1153     return isImmediate<1, 33>();
1154   }
1155   bool isImm8s4() const {
1156     return isImmediateS4<-1020, 1020>();
1157   }
1158   bool isImm7s4() const {
1159     return isImmediateS4<-508, 508>();
1160   }
1161   bool isImm7Shift0() const {
1162     return isImmediate<-127, 127>();
1163   }
1164   bool isImm7Shift1() const {
1165     return isImmediateS2<-255, 255>();
1166   }
1167   bool isImm7Shift2() const {
1168     return isImmediateS4<-511, 511>();
1169   }
1170   bool isImm7() const {
1171     return isImmediate<-127, 127>();
1172   }
1173   bool isImm0_1020s4() const {
1174     return isImmediateS4<0, 1020>();
1175   }
1176   bool isImm0_508s4() const {
1177     return isImmediateS4<0, 508>();
1178   }
1179   bool isImm0_508s4Neg() const {
1180     if (!isImm()) return false;
1181     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1182     if (!CE) return false;
1183     int64_t Value = -CE->getValue();
1184     // explicitly exclude zero. we want that to use the normal 0_508 version.
1185     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1186   }
1187 
1188   bool isImm0_4095Neg() const {
1189     if (!isImm()) return false;
1190     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1191     if (!CE) return false;
1192     // isImm0_4095Neg is used with 32-bit immediates only.
1193     // 32-bit immediates are zero extended to 64-bit when parsed,
1194     // thus simple -CE->getValue() results in a big negative number,
1195     // not a small positive number as intended
1196     if ((CE->getValue() >> 32) > 0) return false;
1197     uint32_t Value = -static_cast<uint32_t>(CE->getValue());
1198     return Value > 0 && Value < 4096;
1199   }
1200 
1201   bool isImm0_7() const {
1202     return isImmediate<0, 7>();
1203   }
1204 
1205   bool isImm1_16() const {
1206     return isImmediate<1, 16>();
1207   }
1208 
1209   bool isImm1_32() const {
1210     return isImmediate<1, 32>();
1211   }
1212 
1213   bool isImm8_255() const {
1214     return isImmediate<8, 255>();
1215   }
1216 
1217   bool isImm256_65535Expr() const {
1218     if (!isImm()) return false;
1219     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1220     // If it's not a constant expression, it'll generate a fixup and be
1221     // handled later.
1222     if (!CE) return true;
1223     int64_t Value = CE->getValue();
1224     return Value >= 256 && Value < 65536;
1225   }
1226 
1227   bool isImm0_65535Expr() const {
1228     if (!isImm()) return false;
1229     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1230     // If it's not a constant expression, it'll generate a fixup and be
1231     // handled later.
1232     if (!CE) return true;
1233     int64_t Value = CE->getValue();
1234     return Value >= 0 && Value < 65536;
1235   }
1236 
1237   bool isImm24bit() const {
1238     return isImmediate<0, 0xffffff + 1>();
1239   }
1240 
1241   bool isImmThumbSR() const {
1242     return isImmediate<1, 33>();
1243   }
1244 
1245   template<int shift>
1246   bool isExpImmValue(uint64_t Value) const {
1247     uint64_t mask = (1 << shift) - 1;
1248     if ((Value & mask) != 0 || (Value >> shift) > 0xff)
1249       return false;
1250     return true;
1251   }
1252 
1253   template<int shift>
1254   bool isExpImm() const {
1255     if (!isImm()) return false;
1256     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1257     if (!CE) return false;
1258 
1259     return isExpImmValue<shift>(CE->getValue());
1260   }
1261 
1262   template<int shift, int size>
1263   bool isInvertedExpImm() const {
1264     if (!isImm()) return false;
1265     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1266     if (!CE) return false;
1267 
1268     uint64_t OriginalValue = CE->getValue();
1269     uint64_t InvertedValue = OriginalValue ^ (((uint64_t)1 << size) - 1);
1270     return isExpImmValue<shift>(InvertedValue);
1271   }
1272 
1273   bool isPKHLSLImm() const {
1274     return isImmediate<0, 32>();
1275   }
1276 
1277   bool isPKHASRImm() const {
1278     return isImmediate<0, 33>();
1279   }
1280 
1281   bool isAdrLabel() const {
1282     // If we have an immediate that's not a constant, treat it as a label
1283     // reference needing a fixup.
1284     if (isImm() && !isa<MCConstantExpr>(getImm()))
1285       return true;
1286 
1287     // If it is a constant, it must fit into a modified immediate encoding.
1288     if (!isImm()) return false;
1289     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1290     if (!CE) return false;
1291     int64_t Value = CE->getValue();
1292     return (ARM_AM::getSOImmVal(Value) != -1 ||
1293             ARM_AM::getSOImmVal(-Value) != -1);
1294   }
1295 
1296   bool isT2SOImm() const {
1297     // If we have an immediate that's not a constant, treat it as an expression
1298     // needing a fixup.
1299     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1300       // We want to avoid matching :upper16: and :lower16: as we want these
1301       // expressions to match in isImm0_65535Expr()
1302       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1303       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1304                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1305     }
1306     if (!isImm()) return false;
1307     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1308     if (!CE) return false;
1309     int64_t Value = CE->getValue();
1310     return ARM_AM::getT2SOImmVal(Value) != -1;
1311   }
1312 
1313   bool isT2SOImmNot() const {
1314     if (!isImm()) return false;
1315     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1316     if (!CE) return false;
1317     int64_t Value = CE->getValue();
1318     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1319       ARM_AM::getT2SOImmVal(~Value) != -1;
1320   }
1321 
1322   bool isT2SOImmNeg() const {
1323     if (!isImm()) return false;
1324     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1325     if (!CE) return false;
1326     int64_t Value = CE->getValue();
1327     // Only use this when not representable as a plain so_imm.
1328     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1329       ARM_AM::getT2SOImmVal(-Value) != -1;
1330   }
1331 
1332   bool isSetEndImm() const {
1333     if (!isImm()) return false;
1334     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1335     if (!CE) return false;
1336     int64_t Value = CE->getValue();
1337     return Value == 1 || Value == 0;
1338   }
1339 
1340   bool isReg() const override { return Kind == k_Register; }
1341   bool isRegList() const { return Kind == k_RegisterList; }
1342   bool isRegListWithAPSR() const {
1343     return Kind == k_RegisterListWithAPSR || Kind == k_RegisterList;
1344   }
1345   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1346   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1347   bool isFPSRegListWithVPR() const { return Kind == k_FPSRegisterListWithVPR; }
1348   bool isFPDRegListWithVPR() const { return Kind == k_FPDRegisterListWithVPR; }
1349   bool isToken() const override { return Kind == k_Token; }
1350   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1351   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1352   bool isTraceSyncBarrierOpt() const { return Kind == k_TraceSyncBarrierOpt; }
1353   bool isMem() const override {
1354       return isGPRMem() || isMVEMem();
1355   }
1356   bool isMVEMem() const {
1357     if (Kind != k_Memory)
1358       return false;
1359     if (Memory.BaseRegNum &&
1360         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum) &&
1361         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Memory.BaseRegNum))
1362       return false;
1363     if (Memory.OffsetRegNum &&
1364         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1365             Memory.OffsetRegNum))
1366       return false;
1367     return true;
1368   }
1369   bool isGPRMem() const {
1370     if (Kind != k_Memory)
1371       return false;
1372     if (Memory.BaseRegNum &&
1373         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum))
1374       return false;
1375     if (Memory.OffsetRegNum &&
1376         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.OffsetRegNum))
1377       return false;
1378     return true;
1379   }
1380   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1381   bool isRegShiftedReg() const {
1382     return Kind == k_ShiftedRegister &&
1383            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1384                RegShiftedReg.SrcReg) &&
1385            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1386                RegShiftedReg.ShiftReg);
1387   }
1388   bool isRegShiftedImm() const {
1389     return Kind == k_ShiftedImmediate &&
1390            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1391                RegShiftedImm.SrcReg);
1392   }
1393   bool isRotImm() const { return Kind == k_RotateImmediate; }
1394 
1395   template<unsigned Min, unsigned Max>
1396   bool isPowerTwoInRange() const {
1397     if (!isImm()) return false;
1398     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1399     if (!CE) return false;
1400     int64_t Value = CE->getValue();
1401     return Value > 0 && countPopulation((uint64_t)Value) == 1 &&
1402            Value >= Min && Value <= Max;
1403   }
1404   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1405 
1406   bool isModImmNot() const {
1407     if (!isImm()) return false;
1408     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1409     if (!CE) return false;
1410     int64_t Value = CE->getValue();
1411     return ARM_AM::getSOImmVal(~Value) != -1;
1412   }
1413 
1414   bool isModImmNeg() const {
1415     if (!isImm()) return false;
1416     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1417     if (!CE) return false;
1418     int64_t Value = CE->getValue();
1419     return ARM_AM::getSOImmVal(Value) == -1 &&
1420       ARM_AM::getSOImmVal(-Value) != -1;
1421   }
1422 
1423   bool isThumbModImmNeg1_7() const {
1424     if (!isImm()) return false;
1425     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1426     if (!CE) return false;
1427     int32_t Value = -(int32_t)CE->getValue();
1428     return 0 < Value && Value < 8;
1429   }
1430 
1431   bool isThumbModImmNeg8_255() const {
1432     if (!isImm()) return false;
1433     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1434     if (!CE) return false;
1435     int32_t Value = -(int32_t)CE->getValue();
1436     return 7 < Value && Value < 256;
1437   }
1438 
1439   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1440   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1441   bool isPostIdxRegShifted() const {
1442     return Kind == k_PostIndexRegister &&
1443            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(PostIdxReg.RegNum);
1444   }
1445   bool isPostIdxReg() const {
1446     return isPostIdxRegShifted() && PostIdxReg.ShiftTy == ARM_AM::no_shift;
1447   }
1448   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1449     if (!isGPRMem())
1450       return false;
1451     // No offset of any kind.
1452     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1453      (alignOK || Memory.Alignment == Alignment);
1454   }
1455   bool isMemNoOffsetT2(bool alignOK = false, unsigned Alignment = 0) const {
1456     if (!isGPRMem())
1457       return false;
1458 
1459     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1460             Memory.BaseRegNum))
1461       return false;
1462 
1463     // No offset of any kind.
1464     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1465      (alignOK || Memory.Alignment == Alignment);
1466   }
1467   bool isMemNoOffsetT2NoSp(bool alignOK = false, unsigned Alignment = 0) const {
1468     if (!isGPRMem())
1469       return false;
1470 
1471     if (!ARMMCRegisterClasses[ARM::rGPRRegClassID].contains(
1472             Memory.BaseRegNum))
1473       return false;
1474 
1475     // No offset of any kind.
1476     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1477      (alignOK || Memory.Alignment == Alignment);
1478   }
1479   bool isMemNoOffsetT(bool alignOK = false, unsigned Alignment = 0) const {
1480     if (!isGPRMem())
1481       return false;
1482 
1483     if (!ARMMCRegisterClasses[ARM::tGPRRegClassID].contains(
1484             Memory.BaseRegNum))
1485       return false;
1486 
1487     // No offset of any kind.
1488     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1489      (alignOK || Memory.Alignment == Alignment);
1490   }
1491   bool isMemPCRelImm12() const {
1492     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1493       return false;
1494     // Base register must be PC.
1495     if (Memory.BaseRegNum != ARM::PC)
1496       return false;
1497     // Immediate offset in range [-4095, 4095].
1498     if (!Memory.OffsetImm) return true;
1499     int64_t Val = Memory.OffsetImm->getValue();
1500     return (Val > -4096 && Val < 4096) ||
1501            (Val == std::numeric_limits<int32_t>::min());
1502   }
1503 
1504   bool isAlignedMemory() const {
1505     return isMemNoOffset(true);
1506   }
1507 
1508   bool isAlignedMemoryNone() const {
1509     return isMemNoOffset(false, 0);
1510   }
1511 
1512   bool isDupAlignedMemoryNone() const {
1513     return isMemNoOffset(false, 0);
1514   }
1515 
1516   bool isAlignedMemory16() const {
1517     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1518       return true;
1519     return isMemNoOffset(false, 0);
1520   }
1521 
1522   bool isDupAlignedMemory16() const {
1523     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1524       return true;
1525     return isMemNoOffset(false, 0);
1526   }
1527 
1528   bool isAlignedMemory32() const {
1529     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1530       return true;
1531     return isMemNoOffset(false, 0);
1532   }
1533 
1534   bool isDupAlignedMemory32() const {
1535     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1536       return true;
1537     return isMemNoOffset(false, 0);
1538   }
1539 
1540   bool isAlignedMemory64() const {
1541     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1542       return true;
1543     return isMemNoOffset(false, 0);
1544   }
1545 
1546   bool isDupAlignedMemory64() const {
1547     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1548       return true;
1549     return isMemNoOffset(false, 0);
1550   }
1551 
1552   bool isAlignedMemory64or128() const {
1553     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1554       return true;
1555     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1556       return true;
1557     return isMemNoOffset(false, 0);
1558   }
1559 
1560   bool isDupAlignedMemory64or128() const {
1561     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1562       return true;
1563     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1564       return true;
1565     return isMemNoOffset(false, 0);
1566   }
1567 
1568   bool isAlignedMemory64or128or256() const {
1569     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1570       return true;
1571     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1572       return true;
1573     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1574       return true;
1575     return isMemNoOffset(false, 0);
1576   }
1577 
1578   bool isAddrMode2() const {
1579     if (!isGPRMem() || Memory.Alignment != 0) return false;
1580     // Check for register offset.
1581     if (Memory.OffsetRegNum) return true;
1582     // Immediate offset in range [-4095, 4095].
1583     if (!Memory.OffsetImm) return true;
1584     int64_t Val = Memory.OffsetImm->getValue();
1585     return Val > -4096 && Val < 4096;
1586   }
1587 
1588   bool isAM2OffsetImm() const {
1589     if (!isImm()) return false;
1590     // Immediate offset in range [-4095, 4095].
1591     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1592     if (!CE) return false;
1593     int64_t Val = CE->getValue();
1594     return (Val == std::numeric_limits<int32_t>::min()) ||
1595            (Val > -4096 && Val < 4096);
1596   }
1597 
1598   bool isAddrMode3() const {
1599     // If we have an immediate that's not a constant, treat it as a label
1600     // reference needing a fixup. If it is a constant, it's something else
1601     // and we reject it.
1602     if (isImm() && !isa<MCConstantExpr>(getImm()))
1603       return true;
1604     if (!isGPRMem() || Memory.Alignment != 0) return false;
1605     // No shifts are legal for AM3.
1606     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1607     // Check for register offset.
1608     if (Memory.OffsetRegNum) return true;
1609     // Immediate offset in range [-255, 255].
1610     if (!Memory.OffsetImm) return true;
1611     int64_t Val = Memory.OffsetImm->getValue();
1612     // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and we
1613     // have to check for this too.
1614     return (Val > -256 && Val < 256) ||
1615            Val == std::numeric_limits<int32_t>::min();
1616   }
1617 
1618   bool isAM3Offset() const {
1619     if (isPostIdxReg())
1620       return true;
1621     if (!isImm())
1622       return false;
1623     // Immediate offset in range [-255, 255].
1624     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1625     if (!CE) return false;
1626     int64_t Val = CE->getValue();
1627     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1628     return (Val > -256 && Val < 256) ||
1629            Val == std::numeric_limits<int32_t>::min();
1630   }
1631 
1632   bool isAddrMode5() const {
1633     // If we have an immediate that's not a constant, treat it as a label
1634     // reference needing a fixup. If it is a constant, it's something else
1635     // and we reject it.
1636     if (isImm() && !isa<MCConstantExpr>(getImm()))
1637       return true;
1638     if (!isGPRMem() || Memory.Alignment != 0) return false;
1639     // Check for register offset.
1640     if (Memory.OffsetRegNum) return false;
1641     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1642     if (!Memory.OffsetImm) return true;
1643     int64_t Val = Memory.OffsetImm->getValue();
1644     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1645       Val == std::numeric_limits<int32_t>::min();
1646   }
1647 
1648   bool isAddrMode5FP16() const {
1649     // If we have an immediate that's not a constant, treat it as a label
1650     // reference needing a fixup. If it is a constant, it's something else
1651     // and we reject it.
1652     if (isImm() && !isa<MCConstantExpr>(getImm()))
1653       return true;
1654     if (!isGPRMem() || Memory.Alignment != 0) return false;
1655     // Check for register offset.
1656     if (Memory.OffsetRegNum) return false;
1657     // Immediate offset in range [-510, 510] and a multiple of 2.
1658     if (!Memory.OffsetImm) return true;
1659     int64_t Val = Memory.OffsetImm->getValue();
1660     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1661            Val == std::numeric_limits<int32_t>::min();
1662   }
1663 
1664   bool isMemTBB() const {
1665     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1666         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1667       return false;
1668     return true;
1669   }
1670 
1671   bool isMemTBH() const {
1672     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1673         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1674         Memory.Alignment != 0 )
1675       return false;
1676     return true;
1677   }
1678 
1679   bool isMemRegOffset() const {
1680     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1681       return false;
1682     return true;
1683   }
1684 
1685   bool isT2MemRegOffset() const {
1686     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1687         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1688       return false;
1689     // Only lsl #{0, 1, 2, 3} allowed.
1690     if (Memory.ShiftType == ARM_AM::no_shift)
1691       return true;
1692     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1693       return false;
1694     return true;
1695   }
1696 
1697   bool isMemThumbRR() const {
1698     // Thumb reg+reg addressing is simple. Just two registers, a base and
1699     // an offset. No shifts, negations or any other complicating factors.
1700     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1701         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1702       return false;
1703     return isARMLowRegister(Memory.BaseRegNum) &&
1704       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1705   }
1706 
1707   bool isMemThumbRIs4() const {
1708     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1709         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1710       return false;
1711     // Immediate offset, multiple of 4 in range [0, 124].
1712     if (!Memory.OffsetImm) return true;
1713     int64_t Val = Memory.OffsetImm->getValue();
1714     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1715   }
1716 
1717   bool isMemThumbRIs2() const {
1718     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1719         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1720       return false;
1721     // Immediate offset, multiple of 4 in range [0, 62].
1722     if (!Memory.OffsetImm) return true;
1723     int64_t Val = Memory.OffsetImm->getValue();
1724     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1725   }
1726 
1727   bool isMemThumbRIs1() const {
1728     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1729         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1730       return false;
1731     // Immediate offset in range [0, 31].
1732     if (!Memory.OffsetImm) return true;
1733     int64_t Val = Memory.OffsetImm->getValue();
1734     return Val >= 0 && Val <= 31;
1735   }
1736 
1737   bool isMemThumbSPI() const {
1738     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1739         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1740       return false;
1741     // Immediate offset, multiple of 4 in range [0, 1020].
1742     if (!Memory.OffsetImm) return true;
1743     int64_t Val = Memory.OffsetImm->getValue();
1744     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1745   }
1746 
1747   bool isMemImm8s4Offset() const {
1748     // If we have an immediate that's not a constant, treat it as a label
1749     // reference needing a fixup. If it is a constant, it's something else
1750     // and we reject it.
1751     if (isImm() && !isa<MCConstantExpr>(getImm()))
1752       return true;
1753     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1754       return false;
1755     // Immediate offset a multiple of 4 in range [-1020, 1020].
1756     if (!Memory.OffsetImm) return true;
1757     int64_t Val = Memory.OffsetImm->getValue();
1758     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1759     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1760            Val == std::numeric_limits<int32_t>::min();
1761   }
1762   bool isMemImm7s4Offset() const {
1763     // If we have an immediate that's not a constant, treat it as a label
1764     // reference needing a fixup. If it is a constant, it's something else
1765     // and we reject it.
1766     if (isImm() && !isa<MCConstantExpr>(getImm()))
1767       return true;
1768     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1769         !ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1770             Memory.BaseRegNum))
1771       return false;
1772     // Immediate offset a multiple of 4 in range [-508, 508].
1773     if (!Memory.OffsetImm) return true;
1774     int64_t Val = Memory.OffsetImm->getValue();
1775     // Special case, #-0 is INT32_MIN.
1776     return (Val >= -508 && Val <= 508 && (Val & 3) == 0) || Val == INT32_MIN;
1777   }
1778   bool isMemImm0_1020s4Offset() const {
1779     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1780       return false;
1781     // Immediate offset a multiple of 4 in range [0, 1020].
1782     if (!Memory.OffsetImm) return true;
1783     int64_t Val = Memory.OffsetImm->getValue();
1784     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1785   }
1786 
1787   bool isMemImm8Offset() const {
1788     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1789       return false;
1790     // Base reg of PC isn't allowed for these encodings.
1791     if (Memory.BaseRegNum == ARM::PC) return false;
1792     // Immediate offset in range [-255, 255].
1793     if (!Memory.OffsetImm) return true;
1794     int64_t Val = Memory.OffsetImm->getValue();
1795     return (Val == std::numeric_limits<int32_t>::min()) ||
1796            (Val > -256 && Val < 256);
1797   }
1798 
1799   template<unsigned Bits, unsigned RegClassID>
1800   bool isMemImm7ShiftedOffset() const {
1801     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1802         !ARMMCRegisterClasses[RegClassID].contains(Memory.BaseRegNum))
1803       return false;
1804 
1805     // Expect an immediate offset equal to an element of the range
1806     // [-127, 127], shifted left by Bits.
1807 
1808     if (!Memory.OffsetImm) return true;
1809     int64_t Val = Memory.OffsetImm->getValue();
1810 
1811     // INT32_MIN is a special-case value (indicating the encoding with
1812     // zero offset and the subtract bit set)
1813     if (Val == INT32_MIN)
1814       return true;
1815 
1816     unsigned Divisor = 1U << Bits;
1817 
1818     // Check that the low bits are zero
1819     if (Val % Divisor != 0)
1820       return false;
1821 
1822     // Check that the remaining offset is within range.
1823     Val /= Divisor;
1824     return (Val >= -127 && Val <= 127);
1825   }
1826 
1827   template <int shift> bool isMemRegRQOffset() const {
1828     if (!isMVEMem() || Memory.OffsetImm != 0 || Memory.Alignment != 0)
1829       return false;
1830 
1831     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1832             Memory.BaseRegNum))
1833       return false;
1834     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1835             Memory.OffsetRegNum))
1836       return false;
1837 
1838     if (shift == 0 && Memory.ShiftType != ARM_AM::no_shift)
1839       return false;
1840 
1841     if (shift > 0 &&
1842         (Memory.ShiftType != ARM_AM::uxtw || Memory.ShiftImm != shift))
1843       return false;
1844 
1845     return true;
1846   }
1847 
1848   template <int shift> bool isMemRegQOffset() const {
1849     if (!isMVEMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1850       return false;
1851 
1852     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1853             Memory.BaseRegNum))
1854       return false;
1855 
1856     if(!Memory.OffsetImm) return true;
1857     static_assert(shift < 56,
1858                   "Such that we dont shift by a value higher than 62");
1859     int64_t Val = Memory.OffsetImm->getValue();
1860 
1861     // The value must be a multiple of (1 << shift)
1862     if ((Val & ((1U << shift) - 1)) != 0)
1863       return false;
1864 
1865     // And be in the right range, depending on the amount that it is shifted
1866     // by.  Shift 0, is equal to 7 unsigned bits, the sign bit is set
1867     // separately.
1868     int64_t Range = (1U << (7+shift)) - 1;
1869     return (Val == INT32_MIN) || (Val > -Range && Val < Range);
1870   }
1871 
1872   bool isMemPosImm8Offset() const {
1873     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1874       return false;
1875     // Immediate offset in range [0, 255].
1876     if (!Memory.OffsetImm) return true;
1877     int64_t Val = Memory.OffsetImm->getValue();
1878     return Val >= 0 && Val < 256;
1879   }
1880 
1881   bool isMemNegImm8Offset() const {
1882     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1883       return false;
1884     // Base reg of PC isn't allowed for these encodings.
1885     if (Memory.BaseRegNum == ARM::PC) return false;
1886     // Immediate offset in range [-255, -1].
1887     if (!Memory.OffsetImm) return false;
1888     int64_t Val = Memory.OffsetImm->getValue();
1889     return (Val == std::numeric_limits<int32_t>::min()) ||
1890            (Val > -256 && Val < 0);
1891   }
1892 
1893   bool isMemUImm12Offset() const {
1894     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1895       return false;
1896     // Immediate offset in range [0, 4095].
1897     if (!Memory.OffsetImm) return true;
1898     int64_t Val = Memory.OffsetImm->getValue();
1899     return (Val >= 0 && Val < 4096);
1900   }
1901 
1902   bool isMemImm12Offset() const {
1903     // If we have an immediate that's not a constant, treat it as a label
1904     // reference needing a fixup. If it is a constant, it's something else
1905     // and we reject it.
1906 
1907     if (isImm() && !isa<MCConstantExpr>(getImm()))
1908       return true;
1909 
1910     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1911       return false;
1912     // Immediate offset in range [-4095, 4095].
1913     if (!Memory.OffsetImm) return true;
1914     int64_t Val = Memory.OffsetImm->getValue();
1915     return (Val > -4096 && Val < 4096) ||
1916            (Val == std::numeric_limits<int32_t>::min());
1917   }
1918 
1919   bool isConstPoolAsmImm() const {
1920     // Delay processing of Constant Pool Immediate, this will turn into
1921     // a constant. Match no other operand
1922     return (isConstantPoolImm());
1923   }
1924 
1925   bool isPostIdxImm8() const {
1926     if (!isImm()) return false;
1927     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1928     if (!CE) return false;
1929     int64_t Val = CE->getValue();
1930     return (Val > -256 && Val < 256) ||
1931            (Val == std::numeric_limits<int32_t>::min());
1932   }
1933 
1934   bool isPostIdxImm8s4() const {
1935     if (!isImm()) return false;
1936     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1937     if (!CE) return false;
1938     int64_t Val = CE->getValue();
1939     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1940            (Val == std::numeric_limits<int32_t>::min());
1941   }
1942 
1943   bool isMSRMask() const { return Kind == k_MSRMask; }
1944   bool isBankedReg() const { return Kind == k_BankedReg; }
1945   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1946 
1947   // NEON operands.
1948   bool isSingleSpacedVectorList() const {
1949     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1950   }
1951 
1952   bool isDoubleSpacedVectorList() const {
1953     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1954   }
1955 
1956   bool isVecListOneD() const {
1957     if (!isSingleSpacedVectorList()) return false;
1958     return VectorList.Count == 1;
1959   }
1960 
1961   bool isVecListTwoMQ() const {
1962     return isSingleSpacedVectorList() && VectorList.Count == 2 &&
1963            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1964                VectorList.RegNum);
1965   }
1966 
1967   bool isVecListDPair() const {
1968     if (!isSingleSpacedVectorList()) return false;
1969     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1970               .contains(VectorList.RegNum));
1971   }
1972 
1973   bool isVecListThreeD() const {
1974     if (!isSingleSpacedVectorList()) return false;
1975     return VectorList.Count == 3;
1976   }
1977 
1978   bool isVecListFourD() const {
1979     if (!isSingleSpacedVectorList()) return false;
1980     return VectorList.Count == 4;
1981   }
1982 
1983   bool isVecListDPairSpaced() const {
1984     if (Kind != k_VectorList) return false;
1985     if (isSingleSpacedVectorList()) return false;
1986     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1987               .contains(VectorList.RegNum));
1988   }
1989 
1990   bool isVecListThreeQ() const {
1991     if (!isDoubleSpacedVectorList()) return false;
1992     return VectorList.Count == 3;
1993   }
1994 
1995   bool isVecListFourQ() const {
1996     if (!isDoubleSpacedVectorList()) return false;
1997     return VectorList.Count == 4;
1998   }
1999 
2000   bool isVecListFourMQ() const {
2001     return isSingleSpacedVectorList() && VectorList.Count == 4 &&
2002            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
2003                VectorList.RegNum);
2004   }
2005 
2006   bool isSingleSpacedVectorAllLanes() const {
2007     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
2008   }
2009 
2010   bool isDoubleSpacedVectorAllLanes() const {
2011     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
2012   }
2013 
2014   bool isVecListOneDAllLanes() const {
2015     if (!isSingleSpacedVectorAllLanes()) return false;
2016     return VectorList.Count == 1;
2017   }
2018 
2019   bool isVecListDPairAllLanes() const {
2020     if (!isSingleSpacedVectorAllLanes()) return false;
2021     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
2022               .contains(VectorList.RegNum));
2023   }
2024 
2025   bool isVecListDPairSpacedAllLanes() const {
2026     if (!isDoubleSpacedVectorAllLanes()) return false;
2027     return VectorList.Count == 2;
2028   }
2029 
2030   bool isVecListThreeDAllLanes() const {
2031     if (!isSingleSpacedVectorAllLanes()) return false;
2032     return VectorList.Count == 3;
2033   }
2034 
2035   bool isVecListThreeQAllLanes() const {
2036     if (!isDoubleSpacedVectorAllLanes()) return false;
2037     return VectorList.Count == 3;
2038   }
2039 
2040   bool isVecListFourDAllLanes() const {
2041     if (!isSingleSpacedVectorAllLanes()) return false;
2042     return VectorList.Count == 4;
2043   }
2044 
2045   bool isVecListFourQAllLanes() const {
2046     if (!isDoubleSpacedVectorAllLanes()) return false;
2047     return VectorList.Count == 4;
2048   }
2049 
2050   bool isSingleSpacedVectorIndexed() const {
2051     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
2052   }
2053 
2054   bool isDoubleSpacedVectorIndexed() const {
2055     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
2056   }
2057 
2058   bool isVecListOneDByteIndexed() const {
2059     if (!isSingleSpacedVectorIndexed()) return false;
2060     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
2061   }
2062 
2063   bool isVecListOneDHWordIndexed() const {
2064     if (!isSingleSpacedVectorIndexed()) return false;
2065     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
2066   }
2067 
2068   bool isVecListOneDWordIndexed() const {
2069     if (!isSingleSpacedVectorIndexed()) return false;
2070     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
2071   }
2072 
2073   bool isVecListTwoDByteIndexed() const {
2074     if (!isSingleSpacedVectorIndexed()) return false;
2075     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
2076   }
2077 
2078   bool isVecListTwoDHWordIndexed() const {
2079     if (!isSingleSpacedVectorIndexed()) return false;
2080     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2081   }
2082 
2083   bool isVecListTwoQWordIndexed() const {
2084     if (!isDoubleSpacedVectorIndexed()) return false;
2085     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2086   }
2087 
2088   bool isVecListTwoQHWordIndexed() const {
2089     if (!isDoubleSpacedVectorIndexed()) return false;
2090     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2091   }
2092 
2093   bool isVecListTwoDWordIndexed() const {
2094     if (!isSingleSpacedVectorIndexed()) return false;
2095     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2096   }
2097 
2098   bool isVecListThreeDByteIndexed() const {
2099     if (!isSingleSpacedVectorIndexed()) return false;
2100     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
2101   }
2102 
2103   bool isVecListThreeDHWordIndexed() const {
2104     if (!isSingleSpacedVectorIndexed()) return false;
2105     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2106   }
2107 
2108   bool isVecListThreeQWordIndexed() const {
2109     if (!isDoubleSpacedVectorIndexed()) return false;
2110     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2111   }
2112 
2113   bool isVecListThreeQHWordIndexed() const {
2114     if (!isDoubleSpacedVectorIndexed()) return false;
2115     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2116   }
2117 
2118   bool isVecListThreeDWordIndexed() const {
2119     if (!isSingleSpacedVectorIndexed()) return false;
2120     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2121   }
2122 
2123   bool isVecListFourDByteIndexed() const {
2124     if (!isSingleSpacedVectorIndexed()) return false;
2125     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
2126   }
2127 
2128   bool isVecListFourDHWordIndexed() const {
2129     if (!isSingleSpacedVectorIndexed()) return false;
2130     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2131   }
2132 
2133   bool isVecListFourQWordIndexed() const {
2134     if (!isDoubleSpacedVectorIndexed()) return false;
2135     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2136   }
2137 
2138   bool isVecListFourQHWordIndexed() const {
2139     if (!isDoubleSpacedVectorIndexed()) return false;
2140     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2141   }
2142 
2143   bool isVecListFourDWordIndexed() const {
2144     if (!isSingleSpacedVectorIndexed()) return false;
2145     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2146   }
2147 
2148   bool isVectorIndex() const { return Kind == k_VectorIndex; }
2149 
2150   template <unsigned NumLanes>
2151   bool isVectorIndexInRange() const {
2152     if (Kind != k_VectorIndex) return false;
2153     return VectorIndex.Val < NumLanes;
2154   }
2155 
2156   bool isVectorIndex8()  const { return isVectorIndexInRange<8>(); }
2157   bool isVectorIndex16() const { return isVectorIndexInRange<4>(); }
2158   bool isVectorIndex32() const { return isVectorIndexInRange<2>(); }
2159   bool isVectorIndex64() const { return isVectorIndexInRange<1>(); }
2160 
2161   template<int PermittedValue, int OtherPermittedValue>
2162   bool isMVEPairVectorIndex() const {
2163     if (Kind != k_VectorIndex) return false;
2164     return VectorIndex.Val == PermittedValue ||
2165            VectorIndex.Val == OtherPermittedValue;
2166   }
2167 
2168   bool isNEONi8splat() const {
2169     if (!isImm()) return false;
2170     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2171     // Must be a constant.
2172     if (!CE) return false;
2173     int64_t Value = CE->getValue();
2174     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
2175     // value.
2176     return Value >= 0 && Value < 256;
2177   }
2178 
2179   bool isNEONi16splat() const {
2180     if (isNEONByteReplicate(2))
2181       return false; // Leave that for bytes replication and forbid by default.
2182     if (!isImm())
2183       return false;
2184     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2185     // Must be a constant.
2186     if (!CE) return false;
2187     unsigned Value = CE->getValue();
2188     return ARM_AM::isNEONi16splat(Value);
2189   }
2190 
2191   bool isNEONi16splatNot() const {
2192     if (!isImm())
2193       return false;
2194     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2195     // Must be a constant.
2196     if (!CE) return false;
2197     unsigned Value = CE->getValue();
2198     return ARM_AM::isNEONi16splat(~Value & 0xffff);
2199   }
2200 
2201   bool isNEONi32splat() const {
2202     if (isNEONByteReplicate(4))
2203       return false; // Leave that for bytes replication and forbid by default.
2204     if (!isImm())
2205       return false;
2206     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2207     // Must be a constant.
2208     if (!CE) return false;
2209     unsigned Value = CE->getValue();
2210     return ARM_AM::isNEONi32splat(Value);
2211   }
2212 
2213   bool isNEONi32splatNot() const {
2214     if (!isImm())
2215       return false;
2216     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2217     // Must be a constant.
2218     if (!CE) return false;
2219     unsigned Value = CE->getValue();
2220     return ARM_AM::isNEONi32splat(~Value);
2221   }
2222 
2223   static bool isValidNEONi32vmovImm(int64_t Value) {
2224     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
2225     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
2226     return ((Value & 0xffffffffffffff00) == 0) ||
2227            ((Value & 0xffffffffffff00ff) == 0) ||
2228            ((Value & 0xffffffffff00ffff) == 0) ||
2229            ((Value & 0xffffffff00ffffff) == 0) ||
2230            ((Value & 0xffffffffffff00ff) == 0xff) ||
2231            ((Value & 0xffffffffff00ffff) == 0xffff);
2232   }
2233 
2234   bool isNEONReplicate(unsigned Width, unsigned NumElems, bool Inv) const {
2235     assert((Width == 8 || Width == 16 || Width == 32) &&
2236            "Invalid element width");
2237     assert(NumElems * Width <= 64 && "Invalid result width");
2238 
2239     if (!isImm())
2240       return false;
2241     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2242     // Must be a constant.
2243     if (!CE)
2244       return false;
2245     int64_t Value = CE->getValue();
2246     if (!Value)
2247       return false; // Don't bother with zero.
2248     if (Inv)
2249       Value = ~Value;
2250 
2251     uint64_t Mask = (1ull << Width) - 1;
2252     uint64_t Elem = Value & Mask;
2253     if (Width == 16 && (Elem & 0x00ff) != 0 && (Elem & 0xff00) != 0)
2254       return false;
2255     if (Width == 32 && !isValidNEONi32vmovImm(Elem))
2256       return false;
2257 
2258     for (unsigned i = 1; i < NumElems; ++i) {
2259       Value >>= Width;
2260       if ((Value & Mask) != Elem)
2261         return false;
2262     }
2263     return true;
2264   }
2265 
2266   bool isNEONByteReplicate(unsigned NumBytes) const {
2267     return isNEONReplicate(8, NumBytes, false);
2268   }
2269 
2270   static void checkNeonReplicateArgs(unsigned FromW, unsigned ToW) {
2271     assert((FromW == 8 || FromW == 16 || FromW == 32) &&
2272            "Invalid source width");
2273     assert((ToW == 16 || ToW == 32 || ToW == 64) &&
2274            "Invalid destination width");
2275     assert(FromW < ToW && "ToW is not less than FromW");
2276   }
2277 
2278   template<unsigned FromW, unsigned ToW>
2279   bool isNEONmovReplicate() const {
2280     checkNeonReplicateArgs(FromW, ToW);
2281     if (ToW == 64 && isNEONi64splat())
2282       return false;
2283     return isNEONReplicate(FromW, ToW / FromW, false);
2284   }
2285 
2286   template<unsigned FromW, unsigned ToW>
2287   bool isNEONinvReplicate() const {
2288     checkNeonReplicateArgs(FromW, ToW);
2289     return isNEONReplicate(FromW, ToW / FromW, true);
2290   }
2291 
2292   bool isNEONi32vmov() const {
2293     if (isNEONByteReplicate(4))
2294       return false; // Let it to be classified as byte-replicate case.
2295     if (!isImm())
2296       return false;
2297     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2298     // Must be a constant.
2299     if (!CE)
2300       return false;
2301     return isValidNEONi32vmovImm(CE->getValue());
2302   }
2303 
2304   bool isNEONi32vmovNeg() const {
2305     if (!isImm()) return false;
2306     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2307     // Must be a constant.
2308     if (!CE) return false;
2309     return isValidNEONi32vmovImm(~CE->getValue());
2310   }
2311 
2312   bool isNEONi64splat() const {
2313     if (!isImm()) return false;
2314     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2315     // Must be a constant.
2316     if (!CE) return false;
2317     uint64_t Value = CE->getValue();
2318     // i64 value with each byte being either 0 or 0xff.
2319     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
2320       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
2321     return true;
2322   }
2323 
2324   template<int64_t Angle, int64_t Remainder>
2325   bool isComplexRotation() const {
2326     if (!isImm()) return false;
2327 
2328     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2329     if (!CE) return false;
2330     uint64_t Value = CE->getValue();
2331 
2332     return (Value % Angle == Remainder && Value <= 270);
2333   }
2334 
2335   bool isMVELongShift() const {
2336     if (!isImm()) return false;
2337     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2338     // Must be a constant.
2339     if (!CE) return false;
2340     uint64_t Value = CE->getValue();
2341     return Value >= 1 && Value <= 32;
2342   }
2343 
2344   bool isMveSaturateOp() const {
2345     if (!isImm()) return false;
2346     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2347     if (!CE) return false;
2348     uint64_t Value = CE->getValue();
2349     return Value == 48 || Value == 64;
2350   }
2351 
2352   bool isITCondCodeNoAL() const {
2353     if (!isITCondCode()) return false;
2354     ARMCC::CondCodes CC = getCondCode();
2355     return CC != ARMCC::AL;
2356   }
2357 
2358   bool isITCondCodeRestrictedI() const {
2359     if (!isITCondCode())
2360       return false;
2361     ARMCC::CondCodes CC = getCondCode();
2362     return CC == ARMCC::EQ || CC == ARMCC::NE;
2363   }
2364 
2365   bool isITCondCodeRestrictedS() const {
2366     if (!isITCondCode())
2367       return false;
2368     ARMCC::CondCodes CC = getCondCode();
2369     return CC == ARMCC::LT || CC == ARMCC::GT || CC == ARMCC::LE ||
2370            CC == ARMCC::GE;
2371   }
2372 
2373   bool isITCondCodeRestrictedU() const {
2374     if (!isITCondCode())
2375       return false;
2376     ARMCC::CondCodes CC = getCondCode();
2377     return CC == ARMCC::HS || CC == ARMCC::HI;
2378   }
2379 
2380   bool isITCondCodeRestrictedFP() const {
2381     if (!isITCondCode())
2382       return false;
2383     ARMCC::CondCodes CC = getCondCode();
2384     return CC == ARMCC::EQ || CC == ARMCC::NE || CC == ARMCC::LT ||
2385            CC == ARMCC::GT || CC == ARMCC::LE || CC == ARMCC::GE;
2386   }
2387 
2388   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
2389     // Add as immediates when possible.  Null MCExpr = 0.
2390     if (!Expr)
2391       Inst.addOperand(MCOperand::createImm(0));
2392     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
2393       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2394     else
2395       Inst.addOperand(MCOperand::createExpr(Expr));
2396   }
2397 
2398   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
2399     assert(N == 1 && "Invalid number of operands!");
2400     addExpr(Inst, getImm());
2401   }
2402 
2403   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
2404     assert(N == 1 && "Invalid number of operands!");
2405     addExpr(Inst, getImm());
2406   }
2407 
2408   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
2409     assert(N == 2 && "Invalid number of operands!");
2410     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2411     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
2412     Inst.addOperand(MCOperand::createReg(RegNum));
2413   }
2414 
2415   void addVPTPredNOperands(MCInst &Inst, unsigned N) const {
2416     assert(N == 2 && "Invalid number of operands!");
2417     Inst.addOperand(MCOperand::createImm(unsigned(getVPTPred())));
2418     unsigned RegNum = getVPTPred() == ARMVCC::None ? 0: ARM::P0;
2419     Inst.addOperand(MCOperand::createReg(RegNum));
2420   }
2421 
2422   void addVPTPredROperands(MCInst &Inst, unsigned N) const {
2423     assert(N == 3 && "Invalid number of operands!");
2424     addVPTPredNOperands(Inst, N-1);
2425     unsigned RegNum;
2426     if (getVPTPred() == ARMVCC::None) {
2427       RegNum = 0;
2428     } else {
2429       unsigned NextOpIndex = Inst.getNumOperands();
2430       const MCInstrDesc &MCID = ARMInsts[Inst.getOpcode()];
2431       int TiedOp = MCID.getOperandConstraint(NextOpIndex, MCOI::TIED_TO);
2432       assert(TiedOp >= 0 &&
2433              "Inactive register in vpred_r is not tied to an output!");
2434       RegNum = Inst.getOperand(TiedOp).getReg();
2435     }
2436     Inst.addOperand(MCOperand::createReg(RegNum));
2437   }
2438 
2439   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
2440     assert(N == 1 && "Invalid number of operands!");
2441     Inst.addOperand(MCOperand::createImm(getCoproc()));
2442   }
2443 
2444   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
2445     assert(N == 1 && "Invalid number of operands!");
2446     Inst.addOperand(MCOperand::createImm(getCoproc()));
2447   }
2448 
2449   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
2450     assert(N == 1 && "Invalid number of operands!");
2451     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
2452   }
2453 
2454   void addITMaskOperands(MCInst &Inst, unsigned N) const {
2455     assert(N == 1 && "Invalid number of operands!");
2456     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
2457   }
2458 
2459   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
2460     assert(N == 1 && "Invalid number of operands!");
2461     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2462   }
2463 
2464   void addITCondCodeInvOperands(MCInst &Inst, unsigned N) const {
2465     assert(N == 1 && "Invalid number of operands!");
2466     Inst.addOperand(MCOperand::createImm(unsigned(ARMCC::getOppositeCondition(getCondCode()))));
2467   }
2468 
2469   void addCCOutOperands(MCInst &Inst, unsigned N) const {
2470     assert(N == 1 && "Invalid number of operands!");
2471     Inst.addOperand(MCOperand::createReg(getReg()));
2472   }
2473 
2474   void addRegOperands(MCInst &Inst, unsigned N) const {
2475     assert(N == 1 && "Invalid number of operands!");
2476     Inst.addOperand(MCOperand::createReg(getReg()));
2477   }
2478 
2479   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
2480     assert(N == 3 && "Invalid number of operands!");
2481     assert(isRegShiftedReg() &&
2482            "addRegShiftedRegOperands() on non-RegShiftedReg!");
2483     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
2484     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
2485     Inst.addOperand(MCOperand::createImm(
2486       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
2487   }
2488 
2489   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
2490     assert(N == 2 && "Invalid number of operands!");
2491     assert(isRegShiftedImm() &&
2492            "addRegShiftedImmOperands() on non-RegShiftedImm!");
2493     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
2494     // Shift of #32 is encoded as 0 where permitted
2495     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2496     Inst.addOperand(MCOperand::createImm(
2497       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2498   }
2499 
2500   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2501     assert(N == 1 && "Invalid number of operands!");
2502     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2503                                          ShifterImm.Imm));
2504   }
2505 
2506   void addRegListOperands(MCInst &Inst, unsigned N) const {
2507     assert(N == 1 && "Invalid number of operands!");
2508     const SmallVectorImpl<unsigned> &RegList = getRegList();
2509     for (SmallVectorImpl<unsigned>::const_iterator
2510            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2511       Inst.addOperand(MCOperand::createReg(*I));
2512   }
2513 
2514   void addRegListWithAPSROperands(MCInst &Inst, unsigned N) const {
2515     assert(N == 1 && "Invalid number of operands!");
2516     const SmallVectorImpl<unsigned> &RegList = getRegList();
2517     for (SmallVectorImpl<unsigned>::const_iterator
2518            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2519       Inst.addOperand(MCOperand::createReg(*I));
2520   }
2521 
2522   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2523     addRegListOperands(Inst, N);
2524   }
2525 
2526   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2527     addRegListOperands(Inst, N);
2528   }
2529 
2530   void addFPSRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2531     addRegListOperands(Inst, N);
2532   }
2533 
2534   void addFPDRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2535     addRegListOperands(Inst, N);
2536   }
2537 
2538   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2539     assert(N == 1 && "Invalid number of operands!");
2540     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2541     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2542   }
2543 
2544   void addModImmOperands(MCInst &Inst, unsigned N) const {
2545     assert(N == 1 && "Invalid number of operands!");
2546 
2547     // Support for fixups (MCFixup)
2548     if (isImm())
2549       return addImmOperands(Inst, N);
2550 
2551     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2552   }
2553 
2554   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2555     assert(N == 1 && "Invalid number of operands!");
2556     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2557     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2558     Inst.addOperand(MCOperand::createImm(Enc));
2559   }
2560 
2561   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2562     assert(N == 1 && "Invalid number of operands!");
2563     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2564     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2565     Inst.addOperand(MCOperand::createImm(Enc));
2566   }
2567 
2568   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2569     assert(N == 1 && "Invalid number of operands!");
2570     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2571     uint32_t Val = -CE->getValue();
2572     Inst.addOperand(MCOperand::createImm(Val));
2573   }
2574 
2575   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2576     assert(N == 1 && "Invalid number of operands!");
2577     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2578     uint32_t Val = -CE->getValue();
2579     Inst.addOperand(MCOperand::createImm(Val));
2580   }
2581 
2582   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2583     assert(N == 1 && "Invalid number of operands!");
2584     // Munge the lsb/width into a bitfield mask.
2585     unsigned lsb = Bitfield.LSB;
2586     unsigned width = Bitfield.Width;
2587     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2588     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2589                       (32 - (lsb + width)));
2590     Inst.addOperand(MCOperand::createImm(Mask));
2591   }
2592 
2593   void addImmOperands(MCInst &Inst, unsigned N) const {
2594     assert(N == 1 && "Invalid number of operands!");
2595     addExpr(Inst, getImm());
2596   }
2597 
2598   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2599     assert(N == 1 && "Invalid number of operands!");
2600     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2601     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2602   }
2603 
2604   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2605     assert(N == 1 && "Invalid number of operands!");
2606     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2607     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2608   }
2609 
2610   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2611     assert(N == 1 && "Invalid number of operands!");
2612     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2613     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2614     Inst.addOperand(MCOperand::createImm(Val));
2615   }
2616 
2617   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2618     assert(N == 1 && "Invalid number of operands!");
2619     // FIXME: We really want to scale the value here, but the LDRD/STRD
2620     // instruction don't encode operands that way yet.
2621     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2622     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2623   }
2624 
2625   void addImm7s4Operands(MCInst &Inst, unsigned N) const {
2626     assert(N == 1 && "Invalid number of operands!");
2627     // FIXME: We really want to scale the value here, but the VSTR/VLDR_VSYSR
2628     // instruction don't encode operands that way yet.
2629     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2630     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2631   }
2632 
2633   void addImm7Shift0Operands(MCInst &Inst, unsigned N) const {
2634     assert(N == 1 && "Invalid number of operands!");
2635     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2636     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2637   }
2638 
2639   void addImm7Shift1Operands(MCInst &Inst, unsigned N) const {
2640     assert(N == 1 && "Invalid number of operands!");
2641     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2642     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2643   }
2644 
2645   void addImm7Shift2Operands(MCInst &Inst, unsigned N) const {
2646     assert(N == 1 && "Invalid number of operands!");
2647     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2648     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2649   }
2650 
2651   void addImm7Operands(MCInst &Inst, unsigned N) const {
2652     assert(N == 1 && "Invalid number of operands!");
2653     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2654     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2655   }
2656 
2657   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2658     assert(N == 1 && "Invalid number of operands!");
2659     // The immediate is scaled by four in the encoding and is stored
2660     // in the MCInst as such. Lop off the low two bits here.
2661     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2662     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2663   }
2664 
2665   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2666     assert(N == 1 && "Invalid number of operands!");
2667     // The immediate is scaled by four in the encoding and is stored
2668     // in the MCInst as such. Lop off the low two bits here.
2669     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2670     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2671   }
2672 
2673   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2674     assert(N == 1 && "Invalid number of operands!");
2675     // The immediate is scaled by four in the encoding and is stored
2676     // in the MCInst as such. Lop off the low two bits here.
2677     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2678     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2679   }
2680 
2681   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2682     assert(N == 1 && "Invalid number of operands!");
2683     // The constant encodes as the immediate-1, and we store in the instruction
2684     // the bits as encoded, so subtract off one here.
2685     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2686     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2687   }
2688 
2689   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2690     assert(N == 1 && "Invalid number of operands!");
2691     // The constant encodes as the immediate-1, and we store in the instruction
2692     // the bits as encoded, so subtract off one here.
2693     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2694     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2695   }
2696 
2697   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2698     assert(N == 1 && "Invalid number of operands!");
2699     // The constant encodes as the immediate, except for 32, which encodes as
2700     // zero.
2701     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2702     unsigned Imm = CE->getValue();
2703     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2704   }
2705 
2706   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2707     assert(N == 1 && "Invalid number of operands!");
2708     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2709     // the instruction as well.
2710     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2711     int Val = CE->getValue();
2712     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2713   }
2714 
2715   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2716     assert(N == 1 && "Invalid number of operands!");
2717     // The operand is actually a t2_so_imm, but we have its bitwise
2718     // negation in the assembly source, so twiddle it here.
2719     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2720     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2721   }
2722 
2723   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2724     assert(N == 1 && "Invalid number of operands!");
2725     // The operand is actually a t2_so_imm, but we have its
2726     // negation in the assembly source, so twiddle it here.
2727     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2728     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2729   }
2730 
2731   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2732     assert(N == 1 && "Invalid number of operands!");
2733     // The operand is actually an imm0_4095, but we have its
2734     // negation in the assembly source, so twiddle it here.
2735     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2736     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2737   }
2738 
2739   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2740     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2741       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2742       return;
2743     }
2744     const MCSymbolRefExpr *SR = cast<MCSymbolRefExpr>(Imm.Val);
2745     Inst.addOperand(MCOperand::createExpr(SR));
2746   }
2747 
2748   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2749     assert(N == 1 && "Invalid number of operands!");
2750     if (isImm()) {
2751       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2752       if (CE) {
2753         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2754         return;
2755       }
2756       const MCSymbolRefExpr *SR = cast<MCSymbolRefExpr>(Imm.Val);
2757       Inst.addOperand(MCOperand::createExpr(SR));
2758       return;
2759     }
2760 
2761     assert(isGPRMem()  && "Unknown value type!");
2762     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2763     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2764   }
2765 
2766   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2767     assert(N == 1 && "Invalid number of operands!");
2768     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2769   }
2770 
2771   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2772     assert(N == 1 && "Invalid number of operands!");
2773     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2774   }
2775 
2776   void addTraceSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2777     assert(N == 1 && "Invalid number of operands!");
2778     Inst.addOperand(MCOperand::createImm(unsigned(getTraceSyncBarrierOpt())));
2779   }
2780 
2781   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2782     assert(N == 1 && "Invalid number of operands!");
2783     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2784   }
2785 
2786   void addMemNoOffsetT2Operands(MCInst &Inst, unsigned N) const {
2787     assert(N == 1 && "Invalid number of operands!");
2788     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2789   }
2790 
2791   void addMemNoOffsetT2NoSpOperands(MCInst &Inst, unsigned N) const {
2792     assert(N == 1 && "Invalid number of operands!");
2793     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2794   }
2795 
2796   void addMemNoOffsetTOperands(MCInst &Inst, unsigned N) const {
2797     assert(N == 1 && "Invalid number of operands!");
2798     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2799   }
2800 
2801   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2802     assert(N == 1 && "Invalid number of operands!");
2803     int32_t Imm = Memory.OffsetImm->getValue();
2804     Inst.addOperand(MCOperand::createImm(Imm));
2805   }
2806 
2807   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2808     assert(N == 1 && "Invalid number of operands!");
2809     assert(isImm() && "Not an immediate!");
2810 
2811     // If we have an immediate that's not a constant, treat it as a label
2812     // reference needing a fixup.
2813     if (!isa<MCConstantExpr>(getImm())) {
2814       Inst.addOperand(MCOperand::createExpr(getImm()));
2815       return;
2816     }
2817 
2818     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2819     int Val = CE->getValue();
2820     Inst.addOperand(MCOperand::createImm(Val));
2821   }
2822 
2823   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2824     assert(N == 2 && "Invalid number of operands!");
2825     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2826     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2827   }
2828 
2829   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2830     addAlignedMemoryOperands(Inst, N);
2831   }
2832 
2833   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2834     addAlignedMemoryOperands(Inst, N);
2835   }
2836 
2837   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2838     addAlignedMemoryOperands(Inst, N);
2839   }
2840 
2841   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2842     addAlignedMemoryOperands(Inst, N);
2843   }
2844 
2845   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2846     addAlignedMemoryOperands(Inst, N);
2847   }
2848 
2849   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2850     addAlignedMemoryOperands(Inst, N);
2851   }
2852 
2853   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2854     addAlignedMemoryOperands(Inst, N);
2855   }
2856 
2857   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2858     addAlignedMemoryOperands(Inst, N);
2859   }
2860 
2861   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2862     addAlignedMemoryOperands(Inst, N);
2863   }
2864 
2865   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2866     addAlignedMemoryOperands(Inst, N);
2867   }
2868 
2869   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2870     addAlignedMemoryOperands(Inst, N);
2871   }
2872 
2873   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2874     assert(N == 3 && "Invalid number of operands!");
2875     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2876     if (!Memory.OffsetRegNum) {
2877       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2878       // Special case for #-0
2879       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2880       if (Val < 0) Val = -Val;
2881       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2882     } else {
2883       // For register offset, we encode the shift type and negation flag
2884       // here.
2885       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2886                               Memory.ShiftImm, Memory.ShiftType);
2887     }
2888     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2889     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2890     Inst.addOperand(MCOperand::createImm(Val));
2891   }
2892 
2893   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2894     assert(N == 2 && "Invalid number of operands!");
2895     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2896     assert(CE && "non-constant AM2OffsetImm operand!");
2897     int32_t Val = CE->getValue();
2898     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2899     // Special case for #-0
2900     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2901     if (Val < 0) Val = -Val;
2902     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2903     Inst.addOperand(MCOperand::createReg(0));
2904     Inst.addOperand(MCOperand::createImm(Val));
2905   }
2906 
2907   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2908     assert(N == 3 && "Invalid number of operands!");
2909     // If we have an immediate that's not a constant, treat it as a label
2910     // reference needing a fixup. If it is a constant, it's something else
2911     // and we reject it.
2912     if (isImm()) {
2913       Inst.addOperand(MCOperand::createExpr(getImm()));
2914       Inst.addOperand(MCOperand::createReg(0));
2915       Inst.addOperand(MCOperand::createImm(0));
2916       return;
2917     }
2918 
2919     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2920     if (!Memory.OffsetRegNum) {
2921       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2922       // Special case for #-0
2923       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2924       if (Val < 0) Val = -Val;
2925       Val = ARM_AM::getAM3Opc(AddSub, Val);
2926     } else {
2927       // For register offset, we encode the shift type and negation flag
2928       // here.
2929       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2930     }
2931     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2932     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2933     Inst.addOperand(MCOperand::createImm(Val));
2934   }
2935 
2936   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2937     assert(N == 2 && "Invalid number of operands!");
2938     if (Kind == k_PostIndexRegister) {
2939       int32_t Val =
2940         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2941       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2942       Inst.addOperand(MCOperand::createImm(Val));
2943       return;
2944     }
2945 
2946     // Constant offset.
2947     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2948     int32_t Val = CE->getValue();
2949     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2950     // Special case for #-0
2951     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2952     if (Val < 0) Val = -Val;
2953     Val = ARM_AM::getAM3Opc(AddSub, Val);
2954     Inst.addOperand(MCOperand::createReg(0));
2955     Inst.addOperand(MCOperand::createImm(Val));
2956   }
2957 
2958   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2959     assert(N == 2 && "Invalid number of operands!");
2960     // If we have an immediate that's not a constant, treat it as a label
2961     // reference needing a fixup. If it is a constant, it's something else
2962     // and we reject it.
2963     if (isImm()) {
2964       Inst.addOperand(MCOperand::createExpr(getImm()));
2965       Inst.addOperand(MCOperand::createImm(0));
2966       return;
2967     }
2968 
2969     // The lower two bits are always zero and as such are not encoded.
2970     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2971     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2972     // Special case for #-0
2973     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2974     if (Val < 0) Val = -Val;
2975     Val = ARM_AM::getAM5Opc(AddSub, Val);
2976     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2977     Inst.addOperand(MCOperand::createImm(Val));
2978   }
2979 
2980   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2981     assert(N == 2 && "Invalid number of operands!");
2982     // If we have an immediate that's not a constant, treat it as a label
2983     // reference needing a fixup. If it is a constant, it's something else
2984     // and we reject it.
2985     if (isImm()) {
2986       Inst.addOperand(MCOperand::createExpr(getImm()));
2987       Inst.addOperand(MCOperand::createImm(0));
2988       return;
2989     }
2990 
2991     // The lower bit is always zero and as such is not encoded.
2992     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2993     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2994     // Special case for #-0
2995     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2996     if (Val < 0) Val = -Val;
2997     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2998     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2999     Inst.addOperand(MCOperand::createImm(Val));
3000   }
3001 
3002   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
3003     assert(N == 2 && "Invalid number of operands!");
3004     // If we have an immediate that's not a constant, treat it as a label
3005     // reference needing a fixup. If it is a constant, it's something else
3006     // and we reject it.
3007     if (isImm()) {
3008       Inst.addOperand(MCOperand::createExpr(getImm()));
3009       Inst.addOperand(MCOperand::createImm(0));
3010       return;
3011     }
3012 
3013     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3014     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3015     Inst.addOperand(MCOperand::createImm(Val));
3016   }
3017 
3018   void addMemImm7s4OffsetOperands(MCInst &Inst, unsigned N) const {
3019     assert(N == 2 && "Invalid number of operands!");
3020     // If we have an immediate that's not a constant, treat it as a label
3021     // reference needing a fixup. If it is a constant, it's something else
3022     // and we reject it.
3023     if (isImm()) {
3024       Inst.addOperand(MCOperand::createExpr(getImm()));
3025       Inst.addOperand(MCOperand::createImm(0));
3026       return;
3027     }
3028 
3029     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3030     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3031     Inst.addOperand(MCOperand::createImm(Val));
3032   }
3033 
3034   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
3035     assert(N == 2 && "Invalid number of operands!");
3036     // The lower two bits are always zero and as such are not encoded.
3037     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
3038     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3039     Inst.addOperand(MCOperand::createImm(Val));
3040   }
3041 
3042   void addMemImmOffsetOperands(MCInst &Inst, unsigned N) const {
3043     assert(N == 2 && "Invalid number of operands!");
3044     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3045     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3046     Inst.addOperand(MCOperand::createImm(Val));
3047   }
3048 
3049   void addMemRegRQOffsetOperands(MCInst &Inst, unsigned N) const {
3050     assert(N == 2 && "Invalid number of operands!");
3051     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3052     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3053   }
3054 
3055   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
3056     assert(N == 2 && "Invalid number of operands!");
3057     // If this is an immediate, it's a label reference.
3058     if (isImm()) {
3059       addExpr(Inst, getImm());
3060       Inst.addOperand(MCOperand::createImm(0));
3061       return;
3062     }
3063 
3064     // Otherwise, it's a normal memory reg+offset.
3065     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3066     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3067     Inst.addOperand(MCOperand::createImm(Val));
3068   }
3069 
3070   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
3071     assert(N == 2 && "Invalid number of operands!");
3072     // If this is an immediate, it's a label reference.
3073     if (isImm()) {
3074       addExpr(Inst, getImm());
3075       Inst.addOperand(MCOperand::createImm(0));
3076       return;
3077     }
3078 
3079     // Otherwise, it's a normal memory reg+offset.
3080     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3081     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3082     Inst.addOperand(MCOperand::createImm(Val));
3083   }
3084 
3085   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
3086     assert(N == 1 && "Invalid number of operands!");
3087     // This is container for the immediate that we will create the constant
3088     // pool from
3089     addExpr(Inst, getConstantPoolImm());
3090     return;
3091   }
3092 
3093   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
3094     assert(N == 2 && "Invalid number of operands!");
3095     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3096     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3097   }
3098 
3099   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
3100     assert(N == 2 && "Invalid number of operands!");
3101     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3102     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3103   }
3104 
3105   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3106     assert(N == 3 && "Invalid number of operands!");
3107     unsigned Val =
3108       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
3109                         Memory.ShiftImm, Memory.ShiftType);
3110     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3111     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3112     Inst.addOperand(MCOperand::createImm(Val));
3113   }
3114 
3115   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3116     assert(N == 3 && "Invalid number of operands!");
3117     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3118     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3119     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
3120   }
3121 
3122   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
3123     assert(N == 2 && "Invalid number of operands!");
3124     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3125     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3126   }
3127 
3128   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
3129     assert(N == 2 && "Invalid number of operands!");
3130     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
3131     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3132     Inst.addOperand(MCOperand::createImm(Val));
3133   }
3134 
3135   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
3136     assert(N == 2 && "Invalid number of operands!");
3137     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
3138     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3139     Inst.addOperand(MCOperand::createImm(Val));
3140   }
3141 
3142   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
3143     assert(N == 2 && "Invalid number of operands!");
3144     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
3145     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3146     Inst.addOperand(MCOperand::createImm(Val));
3147   }
3148 
3149   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
3150     assert(N == 2 && "Invalid number of operands!");
3151     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
3152     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3153     Inst.addOperand(MCOperand::createImm(Val));
3154   }
3155 
3156   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
3157     assert(N == 1 && "Invalid number of operands!");
3158     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3159     assert(CE && "non-constant post-idx-imm8 operand!");
3160     int Imm = CE->getValue();
3161     bool isAdd = Imm >= 0;
3162     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3163     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
3164     Inst.addOperand(MCOperand::createImm(Imm));
3165   }
3166 
3167   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
3168     assert(N == 1 && "Invalid number of operands!");
3169     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3170     assert(CE && "non-constant post-idx-imm8s4 operand!");
3171     int Imm = CE->getValue();
3172     bool isAdd = Imm >= 0;
3173     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3174     // Immediate is scaled by 4.
3175     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
3176     Inst.addOperand(MCOperand::createImm(Imm));
3177   }
3178 
3179   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
3180     assert(N == 2 && "Invalid number of operands!");
3181     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3182     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
3183   }
3184 
3185   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
3186     assert(N == 2 && "Invalid number of operands!");
3187     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3188     // The sign, shift type, and shift amount are encoded in a single operand
3189     // using the AM2 encoding helpers.
3190     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
3191     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
3192                                      PostIdxReg.ShiftTy);
3193     Inst.addOperand(MCOperand::createImm(Imm));
3194   }
3195 
3196   void addPowerTwoOperands(MCInst &Inst, unsigned N) const {
3197     assert(N == 1 && "Invalid number of operands!");
3198     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3199     Inst.addOperand(MCOperand::createImm(CE->getValue()));
3200   }
3201 
3202   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
3203     assert(N == 1 && "Invalid number of operands!");
3204     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
3205   }
3206 
3207   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
3208     assert(N == 1 && "Invalid number of operands!");
3209     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
3210   }
3211 
3212   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
3213     assert(N == 1 && "Invalid number of operands!");
3214     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
3215   }
3216 
3217   void addVecListOperands(MCInst &Inst, unsigned N) const {
3218     assert(N == 1 && "Invalid number of operands!");
3219     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3220   }
3221 
3222   void addMVEVecListOperands(MCInst &Inst, unsigned N) const {
3223     assert(N == 1 && "Invalid number of operands!");
3224 
3225     // When we come here, the VectorList field will identify a range
3226     // of q-registers by its base register and length, and it will
3227     // have already been error-checked to be the expected length of
3228     // range and contain only q-regs in the range q0-q7. So we can
3229     // count on the base register being in the range q0-q6 (for 2
3230     // regs) or q0-q4 (for 4)
3231     //
3232     // The MVE instructions taking a register range of this kind will
3233     // need an operand in the QQPR or QQQQPR class, representing the
3234     // entire range as a unit. So we must translate into that class,
3235     // by finding the index of the base register in the MQPR reg
3236     // class, and returning the super-register at the corresponding
3237     // index in the target class.
3238 
3239     const MCRegisterClass *RC_in = &ARMMCRegisterClasses[ARM::MQPRRegClassID];
3240     const MCRegisterClass *RC_out = (VectorList.Count == 2) ?
3241       &ARMMCRegisterClasses[ARM::QQPRRegClassID] :
3242       &ARMMCRegisterClasses[ARM::QQQQPRRegClassID];
3243 
3244     unsigned I, E = RC_out->getNumRegs();
3245     for (I = 0; I < E; I++)
3246       if (RC_in->getRegister(I) == VectorList.RegNum)
3247         break;
3248     assert(I < E && "Invalid vector list start register!");
3249 
3250     Inst.addOperand(MCOperand::createReg(RC_out->getRegister(I)));
3251   }
3252 
3253   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
3254     assert(N == 2 && "Invalid number of operands!");
3255     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3256     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
3257   }
3258 
3259   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
3260     assert(N == 1 && "Invalid number of operands!");
3261     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3262   }
3263 
3264   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
3265     assert(N == 1 && "Invalid number of operands!");
3266     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3267   }
3268 
3269   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
3270     assert(N == 1 && "Invalid number of operands!");
3271     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3272   }
3273 
3274   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
3275     assert(N == 1 && "Invalid number of operands!");
3276     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3277   }
3278 
3279   void addMVEVectorIndexOperands(MCInst &Inst, unsigned N) const {
3280     assert(N == 1 && "Invalid number of operands!");
3281     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3282   }
3283 
3284   void addMVEPairVectorIndexOperands(MCInst &Inst, unsigned N) const {
3285     assert(N == 1 && "Invalid number of operands!");
3286     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3287   }
3288 
3289   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
3290     assert(N == 1 && "Invalid number of operands!");
3291     // The immediate encodes the type of constant as well as the value.
3292     // Mask in that this is an i8 splat.
3293     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3294     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
3295   }
3296 
3297   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
3298     assert(N == 1 && "Invalid number of operands!");
3299     // The immediate encodes the type of constant as well as the value.
3300     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3301     unsigned Value = CE->getValue();
3302     Value = ARM_AM::encodeNEONi16splat(Value);
3303     Inst.addOperand(MCOperand::createImm(Value));
3304   }
3305 
3306   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
3307     assert(N == 1 && "Invalid number of operands!");
3308     // The immediate encodes the type of constant as well as the value.
3309     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3310     unsigned Value = CE->getValue();
3311     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
3312     Inst.addOperand(MCOperand::createImm(Value));
3313   }
3314 
3315   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
3316     assert(N == 1 && "Invalid number of operands!");
3317     // The immediate encodes the type of constant as well as the value.
3318     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3319     unsigned Value = CE->getValue();
3320     Value = ARM_AM::encodeNEONi32splat(Value);
3321     Inst.addOperand(MCOperand::createImm(Value));
3322   }
3323 
3324   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
3325     assert(N == 1 && "Invalid number of operands!");
3326     // The immediate encodes the type of constant as well as the value.
3327     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3328     unsigned Value = CE->getValue();
3329     Value = ARM_AM::encodeNEONi32splat(~Value);
3330     Inst.addOperand(MCOperand::createImm(Value));
3331   }
3332 
3333   void addNEONi8ReplicateOperands(MCInst &Inst, bool Inv) const {
3334     // The immediate encodes the type of constant as well as the value.
3335     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3336     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
3337             Inst.getOpcode() == ARM::VMOVv16i8) &&
3338           "All instructions that wants to replicate non-zero byte "
3339           "always must be replaced with VMOVv8i8 or VMOVv16i8.");
3340     unsigned Value = CE->getValue();
3341     if (Inv)
3342       Value = ~Value;
3343     unsigned B = Value & 0xff;
3344     B |= 0xe00; // cmode = 0b1110
3345     Inst.addOperand(MCOperand::createImm(B));
3346   }
3347 
3348   void addNEONinvi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3349     assert(N == 1 && "Invalid number of operands!");
3350     addNEONi8ReplicateOperands(Inst, true);
3351   }
3352 
3353   static unsigned encodeNeonVMOVImmediate(unsigned Value) {
3354     if (Value >= 256 && Value <= 0xffff)
3355       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
3356     else if (Value > 0xffff && Value <= 0xffffff)
3357       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
3358     else if (Value > 0xffffff)
3359       Value = (Value >> 24) | 0x600;
3360     return Value;
3361   }
3362 
3363   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
3364     assert(N == 1 && "Invalid number of operands!");
3365     // The immediate encodes the type of constant as well as the value.
3366     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3367     unsigned Value = encodeNeonVMOVImmediate(CE->getValue());
3368     Inst.addOperand(MCOperand::createImm(Value));
3369   }
3370 
3371   void addNEONvmovi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3372     assert(N == 1 && "Invalid number of operands!");
3373     addNEONi8ReplicateOperands(Inst, false);
3374   }
3375 
3376   void addNEONvmovi16ReplicateOperands(MCInst &Inst, unsigned N) const {
3377     assert(N == 1 && "Invalid number of operands!");
3378     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3379     assert((Inst.getOpcode() == ARM::VMOVv4i16 ||
3380             Inst.getOpcode() == ARM::VMOVv8i16 ||
3381             Inst.getOpcode() == ARM::VMVNv4i16 ||
3382             Inst.getOpcode() == ARM::VMVNv8i16) &&
3383           "All instructions that want to replicate non-zero half-word "
3384           "always must be replaced with V{MOV,MVN}v{4,8}i16.");
3385     uint64_t Value = CE->getValue();
3386     unsigned Elem = Value & 0xffff;
3387     if (Elem >= 256)
3388       Elem = (Elem >> 8) | 0x200;
3389     Inst.addOperand(MCOperand::createImm(Elem));
3390   }
3391 
3392   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
3393     assert(N == 1 && "Invalid number of operands!");
3394     // The immediate encodes the type of constant as well as the value.
3395     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3396     unsigned Value = encodeNeonVMOVImmediate(~CE->getValue());
3397     Inst.addOperand(MCOperand::createImm(Value));
3398   }
3399 
3400   void addNEONvmovi32ReplicateOperands(MCInst &Inst, unsigned N) const {
3401     assert(N == 1 && "Invalid number of operands!");
3402     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3403     assert((Inst.getOpcode() == ARM::VMOVv2i32 ||
3404             Inst.getOpcode() == ARM::VMOVv4i32 ||
3405             Inst.getOpcode() == ARM::VMVNv2i32 ||
3406             Inst.getOpcode() == ARM::VMVNv4i32) &&
3407           "All instructions that want to replicate non-zero word "
3408           "always must be replaced with V{MOV,MVN}v{2,4}i32.");
3409     uint64_t Value = CE->getValue();
3410     unsigned Elem = encodeNeonVMOVImmediate(Value & 0xffffffff);
3411     Inst.addOperand(MCOperand::createImm(Elem));
3412   }
3413 
3414   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
3415     assert(N == 1 && "Invalid number of operands!");
3416     // The immediate encodes the type of constant as well as the value.
3417     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3418     uint64_t Value = CE->getValue();
3419     unsigned Imm = 0;
3420     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
3421       Imm |= (Value & 1) << i;
3422     }
3423     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
3424   }
3425 
3426   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
3427     assert(N == 1 && "Invalid number of operands!");
3428     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3429     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
3430   }
3431 
3432   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
3433     assert(N == 1 && "Invalid number of operands!");
3434     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3435     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
3436   }
3437 
3438   void addMveSaturateOperands(MCInst &Inst, unsigned N) const {
3439     assert(N == 1 && "Invalid number of operands!");
3440     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3441     unsigned Imm = CE->getValue();
3442     assert((Imm == 48 || Imm == 64) && "Invalid saturate operand");
3443     Inst.addOperand(MCOperand::createImm(Imm == 48 ? 1 : 0));
3444   }
3445 
3446   void print(raw_ostream &OS) const override;
3447 
3448   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
3449     auto Op = std::make_unique<ARMOperand>(k_ITCondMask);
3450     Op->ITMask.Mask = Mask;
3451     Op->StartLoc = S;
3452     Op->EndLoc = S;
3453     return Op;
3454   }
3455 
3456   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
3457                                                     SMLoc S) {
3458     auto Op = std::make_unique<ARMOperand>(k_CondCode);
3459     Op->CC.Val = CC;
3460     Op->StartLoc = S;
3461     Op->EndLoc = S;
3462     return Op;
3463   }
3464 
3465   static std::unique_ptr<ARMOperand> CreateVPTPred(ARMVCC::VPTCodes CC,
3466                                                    SMLoc S) {
3467     auto Op = std::make_unique<ARMOperand>(k_VPTPred);
3468     Op->VCC.Val = CC;
3469     Op->StartLoc = S;
3470     Op->EndLoc = S;
3471     return Op;
3472   }
3473 
3474   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
3475     auto Op = std::make_unique<ARMOperand>(k_CoprocNum);
3476     Op->Cop.Val = CopVal;
3477     Op->StartLoc = S;
3478     Op->EndLoc = S;
3479     return Op;
3480   }
3481 
3482   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
3483     auto Op = std::make_unique<ARMOperand>(k_CoprocReg);
3484     Op->Cop.Val = CopVal;
3485     Op->StartLoc = S;
3486     Op->EndLoc = S;
3487     return Op;
3488   }
3489 
3490   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
3491                                                         SMLoc E) {
3492     auto Op = std::make_unique<ARMOperand>(k_CoprocOption);
3493     Op->Cop.Val = Val;
3494     Op->StartLoc = S;
3495     Op->EndLoc = E;
3496     return Op;
3497   }
3498 
3499   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
3500     auto Op = std::make_unique<ARMOperand>(k_CCOut);
3501     Op->Reg.RegNum = RegNum;
3502     Op->StartLoc = S;
3503     Op->EndLoc = S;
3504     return Op;
3505   }
3506 
3507   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
3508     auto Op = std::make_unique<ARMOperand>(k_Token);
3509     Op->Tok.Data = Str.data();
3510     Op->Tok.Length = Str.size();
3511     Op->StartLoc = S;
3512     Op->EndLoc = S;
3513     return Op;
3514   }
3515 
3516   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
3517                                                SMLoc E) {
3518     auto Op = std::make_unique<ARMOperand>(k_Register);
3519     Op->Reg.RegNum = RegNum;
3520     Op->StartLoc = S;
3521     Op->EndLoc = E;
3522     return Op;
3523   }
3524 
3525   static std::unique_ptr<ARMOperand>
3526   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3527                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
3528                         SMLoc E) {
3529     auto Op = std::make_unique<ARMOperand>(k_ShiftedRegister);
3530     Op->RegShiftedReg.ShiftTy = ShTy;
3531     Op->RegShiftedReg.SrcReg = SrcReg;
3532     Op->RegShiftedReg.ShiftReg = ShiftReg;
3533     Op->RegShiftedReg.ShiftImm = ShiftImm;
3534     Op->StartLoc = S;
3535     Op->EndLoc = E;
3536     return Op;
3537   }
3538 
3539   static std::unique_ptr<ARMOperand>
3540   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3541                          unsigned ShiftImm, SMLoc S, SMLoc E) {
3542     auto Op = std::make_unique<ARMOperand>(k_ShiftedImmediate);
3543     Op->RegShiftedImm.ShiftTy = ShTy;
3544     Op->RegShiftedImm.SrcReg = SrcReg;
3545     Op->RegShiftedImm.ShiftImm = ShiftImm;
3546     Op->StartLoc = S;
3547     Op->EndLoc = E;
3548     return Op;
3549   }
3550 
3551   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
3552                                                       SMLoc S, SMLoc E) {
3553     auto Op = std::make_unique<ARMOperand>(k_ShifterImmediate);
3554     Op->ShifterImm.isASR = isASR;
3555     Op->ShifterImm.Imm = Imm;
3556     Op->StartLoc = S;
3557     Op->EndLoc = E;
3558     return Op;
3559   }
3560 
3561   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
3562                                                   SMLoc E) {
3563     auto Op = std::make_unique<ARMOperand>(k_RotateImmediate);
3564     Op->RotImm.Imm = Imm;
3565     Op->StartLoc = S;
3566     Op->EndLoc = E;
3567     return Op;
3568   }
3569 
3570   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
3571                                                   SMLoc S, SMLoc E) {
3572     auto Op = std::make_unique<ARMOperand>(k_ModifiedImmediate);
3573     Op->ModImm.Bits = Bits;
3574     Op->ModImm.Rot = Rot;
3575     Op->StartLoc = S;
3576     Op->EndLoc = E;
3577     return Op;
3578   }
3579 
3580   static std::unique_ptr<ARMOperand>
3581   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
3582     auto Op = std::make_unique<ARMOperand>(k_ConstantPoolImmediate);
3583     Op->Imm.Val = Val;
3584     Op->StartLoc = S;
3585     Op->EndLoc = E;
3586     return Op;
3587   }
3588 
3589   static std::unique_ptr<ARMOperand>
3590   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
3591     auto Op = std::make_unique<ARMOperand>(k_BitfieldDescriptor);
3592     Op->Bitfield.LSB = LSB;
3593     Op->Bitfield.Width = Width;
3594     Op->StartLoc = S;
3595     Op->EndLoc = E;
3596     return Op;
3597   }
3598 
3599   static std::unique_ptr<ARMOperand>
3600   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
3601                 SMLoc StartLoc, SMLoc EndLoc) {
3602     assert(Regs.size() > 0 && "RegList contains no registers?");
3603     KindTy Kind = k_RegisterList;
3604 
3605     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
3606             Regs.front().second)) {
3607       if (Regs.back().second == ARM::VPR)
3608         Kind = k_FPDRegisterListWithVPR;
3609       else
3610         Kind = k_DPRRegisterList;
3611     } else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
3612                    Regs.front().second)) {
3613       if (Regs.back().second == ARM::VPR)
3614         Kind = k_FPSRegisterListWithVPR;
3615       else
3616         Kind = k_SPRRegisterList;
3617     }
3618 
3619     if (Kind == k_RegisterList && Regs.back().second == ARM::APSR)
3620       Kind = k_RegisterListWithAPSR;
3621 
3622     assert(std::is_sorted(Regs.begin(), Regs.end()) &&
3623            "Register list must be sorted by encoding");
3624 
3625     auto Op = std::make_unique<ARMOperand>(Kind);
3626     for (const auto &P : Regs)
3627       Op->Registers.push_back(P.second);
3628 
3629     Op->StartLoc = StartLoc;
3630     Op->EndLoc = EndLoc;
3631     return Op;
3632   }
3633 
3634   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
3635                                                       unsigned Count,
3636                                                       bool isDoubleSpaced,
3637                                                       SMLoc S, SMLoc E) {
3638     auto Op = std::make_unique<ARMOperand>(k_VectorList);
3639     Op->VectorList.RegNum = RegNum;
3640     Op->VectorList.Count = Count;
3641     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3642     Op->StartLoc = S;
3643     Op->EndLoc = E;
3644     return Op;
3645   }
3646 
3647   static std::unique_ptr<ARMOperand>
3648   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
3649                            SMLoc S, SMLoc E) {
3650     auto Op = std::make_unique<ARMOperand>(k_VectorListAllLanes);
3651     Op->VectorList.RegNum = RegNum;
3652     Op->VectorList.Count = Count;
3653     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3654     Op->StartLoc = S;
3655     Op->EndLoc = E;
3656     return Op;
3657   }
3658 
3659   static std::unique_ptr<ARMOperand>
3660   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
3661                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
3662     auto Op = std::make_unique<ARMOperand>(k_VectorListIndexed);
3663     Op->VectorList.RegNum = RegNum;
3664     Op->VectorList.Count = Count;
3665     Op->VectorList.LaneIndex = Index;
3666     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3667     Op->StartLoc = S;
3668     Op->EndLoc = E;
3669     return Op;
3670   }
3671 
3672   static std::unique_ptr<ARMOperand>
3673   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3674     auto Op = std::make_unique<ARMOperand>(k_VectorIndex);
3675     Op->VectorIndex.Val = Idx;
3676     Op->StartLoc = S;
3677     Op->EndLoc = E;
3678     return Op;
3679   }
3680 
3681   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3682                                                SMLoc E) {
3683     auto Op = std::make_unique<ARMOperand>(k_Immediate);
3684     Op->Imm.Val = Val;
3685     Op->StartLoc = S;
3686     Op->EndLoc = E;
3687     return Op;
3688   }
3689 
3690   static std::unique_ptr<ARMOperand>
3691   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
3692             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
3693             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
3694             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3695     auto Op = std::make_unique<ARMOperand>(k_Memory);
3696     Op->Memory.BaseRegNum = BaseRegNum;
3697     Op->Memory.OffsetImm = OffsetImm;
3698     Op->Memory.OffsetRegNum = OffsetRegNum;
3699     Op->Memory.ShiftType = ShiftType;
3700     Op->Memory.ShiftImm = ShiftImm;
3701     Op->Memory.Alignment = Alignment;
3702     Op->Memory.isNegative = isNegative;
3703     Op->StartLoc = S;
3704     Op->EndLoc = E;
3705     Op->AlignmentLoc = AlignmentLoc;
3706     return Op;
3707   }
3708 
3709   static std::unique_ptr<ARMOperand>
3710   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3711                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3712     auto Op = std::make_unique<ARMOperand>(k_PostIndexRegister);
3713     Op->PostIdxReg.RegNum = RegNum;
3714     Op->PostIdxReg.isAdd = isAdd;
3715     Op->PostIdxReg.ShiftTy = ShiftTy;
3716     Op->PostIdxReg.ShiftImm = ShiftImm;
3717     Op->StartLoc = S;
3718     Op->EndLoc = E;
3719     return Op;
3720   }
3721 
3722   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3723                                                          SMLoc S) {
3724     auto Op = std::make_unique<ARMOperand>(k_MemBarrierOpt);
3725     Op->MBOpt.Val = Opt;
3726     Op->StartLoc = S;
3727     Op->EndLoc = S;
3728     return Op;
3729   }
3730 
3731   static std::unique_ptr<ARMOperand>
3732   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3733     auto Op = std::make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3734     Op->ISBOpt.Val = Opt;
3735     Op->StartLoc = S;
3736     Op->EndLoc = S;
3737     return Op;
3738   }
3739 
3740   static std::unique_ptr<ARMOperand>
3741   CreateTraceSyncBarrierOpt(ARM_TSB::TraceSyncBOpt Opt, SMLoc S) {
3742     auto Op = std::make_unique<ARMOperand>(k_TraceSyncBarrierOpt);
3743     Op->TSBOpt.Val = Opt;
3744     Op->StartLoc = S;
3745     Op->EndLoc = S;
3746     return Op;
3747   }
3748 
3749   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3750                                                       SMLoc S) {
3751     auto Op = std::make_unique<ARMOperand>(k_ProcIFlags);
3752     Op->IFlags.Val = IFlags;
3753     Op->StartLoc = S;
3754     Op->EndLoc = S;
3755     return Op;
3756   }
3757 
3758   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3759     auto Op = std::make_unique<ARMOperand>(k_MSRMask);
3760     Op->MMask.Val = MMask;
3761     Op->StartLoc = S;
3762     Op->EndLoc = S;
3763     return Op;
3764   }
3765 
3766   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3767     auto Op = std::make_unique<ARMOperand>(k_BankedReg);
3768     Op->BankedReg.Val = Reg;
3769     Op->StartLoc = S;
3770     Op->EndLoc = S;
3771     return Op;
3772   }
3773 };
3774 
3775 } // end anonymous namespace.
3776 
3777 void ARMOperand::print(raw_ostream &OS) const {
3778   auto RegName = [](unsigned Reg) {
3779     if (Reg)
3780       return ARMInstPrinter::getRegisterName(Reg);
3781     else
3782       return "noreg";
3783   };
3784 
3785   switch (Kind) {
3786   case k_CondCode:
3787     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3788     break;
3789   case k_VPTPred:
3790     OS << "<ARMVCC::" << ARMVPTPredToString(getVPTPred()) << ">";
3791     break;
3792   case k_CCOut:
3793     OS << "<ccout " << RegName(getReg()) << ">";
3794     break;
3795   case k_ITCondMask: {
3796     static const char *const MaskStr[] = {
3797       "(invalid)", "(tttt)", "(ttt)", "(ttte)",
3798       "(tt)",      "(ttet)", "(tte)", "(ttee)",
3799       "(t)",       "(tett)", "(tet)", "(tete)",
3800       "(te)",      "(teet)", "(tee)", "(teee)",
3801     };
3802     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3803     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3804     break;
3805   }
3806   case k_CoprocNum:
3807     OS << "<coprocessor number: " << getCoproc() << ">";
3808     break;
3809   case k_CoprocReg:
3810     OS << "<coprocessor register: " << getCoproc() << ">";
3811     break;
3812   case k_CoprocOption:
3813     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3814     break;
3815   case k_MSRMask:
3816     OS << "<mask: " << getMSRMask() << ">";
3817     break;
3818   case k_BankedReg:
3819     OS << "<banked reg: " << getBankedReg() << ">";
3820     break;
3821   case k_Immediate:
3822     OS << *getImm();
3823     break;
3824   case k_MemBarrierOpt:
3825     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3826     break;
3827   case k_InstSyncBarrierOpt:
3828     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3829     break;
3830   case k_TraceSyncBarrierOpt:
3831     OS << "<ARM_TSB::" << TraceSyncBOptToString(getTraceSyncBarrierOpt()) << ">";
3832     break;
3833   case k_Memory:
3834     OS << "<memory";
3835     if (Memory.BaseRegNum)
3836       OS << " base:" << RegName(Memory.BaseRegNum);
3837     if (Memory.OffsetImm)
3838       OS << " offset-imm:" << *Memory.OffsetImm;
3839     if (Memory.OffsetRegNum)
3840       OS << " offset-reg:" << (Memory.isNegative ? "-" : "")
3841          << RegName(Memory.OffsetRegNum);
3842     if (Memory.ShiftType != ARM_AM::no_shift) {
3843       OS << " shift-type:" << ARM_AM::getShiftOpcStr(Memory.ShiftType);
3844       OS << " shift-imm:" << Memory.ShiftImm;
3845     }
3846     if (Memory.Alignment)
3847       OS << " alignment:" << Memory.Alignment;
3848     OS << ">";
3849     break;
3850   case k_PostIndexRegister:
3851     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3852        << RegName(PostIdxReg.RegNum);
3853     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3854       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3855          << PostIdxReg.ShiftImm;
3856     OS << ">";
3857     break;
3858   case k_ProcIFlags: {
3859     OS << "<ARM_PROC::";
3860     unsigned IFlags = getProcIFlags();
3861     for (int i=2; i >= 0; --i)
3862       if (IFlags & (1 << i))
3863         OS << ARM_PROC::IFlagsToString(1 << i);
3864     OS << ">";
3865     break;
3866   }
3867   case k_Register:
3868     OS << "<register " << RegName(getReg()) << ">";
3869     break;
3870   case k_ShifterImmediate:
3871     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3872        << " #" << ShifterImm.Imm << ">";
3873     break;
3874   case k_ShiftedRegister:
3875     OS << "<so_reg_reg " << RegName(RegShiftedReg.SrcReg) << " "
3876        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy) << " "
3877        << RegName(RegShiftedReg.ShiftReg) << ">";
3878     break;
3879   case k_ShiftedImmediate:
3880     OS << "<so_reg_imm " << RegName(RegShiftedImm.SrcReg) << " "
3881        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy) << " #"
3882        << RegShiftedImm.ShiftImm << ">";
3883     break;
3884   case k_RotateImmediate:
3885     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3886     break;
3887   case k_ModifiedImmediate:
3888     OS << "<mod_imm #" << ModImm.Bits << ", #"
3889        <<  ModImm.Rot << ")>";
3890     break;
3891   case k_ConstantPoolImmediate:
3892     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3893     break;
3894   case k_BitfieldDescriptor:
3895     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3896        << ", width: " << Bitfield.Width << ">";
3897     break;
3898   case k_RegisterList:
3899   case k_RegisterListWithAPSR:
3900   case k_DPRRegisterList:
3901   case k_SPRRegisterList:
3902   case k_FPSRegisterListWithVPR:
3903   case k_FPDRegisterListWithVPR: {
3904     OS << "<register_list ";
3905 
3906     const SmallVectorImpl<unsigned> &RegList = getRegList();
3907     for (SmallVectorImpl<unsigned>::const_iterator
3908            I = RegList.begin(), E = RegList.end(); I != E; ) {
3909       OS << RegName(*I);
3910       if (++I < E) OS << ", ";
3911     }
3912 
3913     OS << ">";
3914     break;
3915   }
3916   case k_VectorList:
3917     OS << "<vector_list " << VectorList.Count << " * "
3918        << RegName(VectorList.RegNum) << ">";
3919     break;
3920   case k_VectorListAllLanes:
3921     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3922        << RegName(VectorList.RegNum) << ">";
3923     break;
3924   case k_VectorListIndexed:
3925     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3926        << VectorList.Count << " * " << RegName(VectorList.RegNum) << ">";
3927     break;
3928   case k_Token:
3929     OS << "'" << getToken() << "'";
3930     break;
3931   case k_VectorIndex:
3932     OS << "<vectorindex " << getVectorIndex() << ">";
3933     break;
3934   }
3935 }
3936 
3937 /// @name Auto-generated Match Functions
3938 /// {
3939 
3940 static unsigned MatchRegisterName(StringRef Name);
3941 
3942 /// }
3943 
3944 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3945                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3946   const AsmToken &Tok = getParser().getTok();
3947   StartLoc = Tok.getLoc();
3948   EndLoc = Tok.getEndLoc();
3949   RegNo = tryParseRegister();
3950 
3951   return (RegNo == (unsigned)-1);
3952 }
3953 
3954 OperandMatchResultTy ARMAsmParser::tryParseRegister(unsigned &RegNo,
3955                                                     SMLoc &StartLoc,
3956                                                     SMLoc &EndLoc) {
3957   if (ParseRegister(RegNo, StartLoc, EndLoc))
3958     return MatchOperand_NoMatch;
3959   return MatchOperand_Success;
3960 }
3961 
3962 /// Try to parse a register name.  The token must be an Identifier when called,
3963 /// and if it is a register name the token is eaten and the register number is
3964 /// returned.  Otherwise return -1.
3965 int ARMAsmParser::tryParseRegister() {
3966   MCAsmParser &Parser = getParser();
3967   const AsmToken &Tok = Parser.getTok();
3968   if (Tok.isNot(AsmToken::Identifier)) return -1;
3969 
3970   std::string lowerCase = Tok.getString().lower();
3971   unsigned RegNum = MatchRegisterName(lowerCase);
3972   if (!RegNum) {
3973     RegNum = StringSwitch<unsigned>(lowerCase)
3974       .Case("r13", ARM::SP)
3975       .Case("r14", ARM::LR)
3976       .Case("r15", ARM::PC)
3977       .Case("ip", ARM::R12)
3978       // Additional register name aliases for 'gas' compatibility.
3979       .Case("a1", ARM::R0)
3980       .Case("a2", ARM::R1)
3981       .Case("a3", ARM::R2)
3982       .Case("a4", ARM::R3)
3983       .Case("v1", ARM::R4)
3984       .Case("v2", ARM::R5)
3985       .Case("v3", ARM::R6)
3986       .Case("v4", ARM::R7)
3987       .Case("v5", ARM::R8)
3988       .Case("v6", ARM::R9)
3989       .Case("v7", ARM::R10)
3990       .Case("v8", ARM::R11)
3991       .Case("sb", ARM::R9)
3992       .Case("sl", ARM::R10)
3993       .Case("fp", ARM::R11)
3994       .Default(0);
3995   }
3996   if (!RegNum) {
3997     // Check for aliases registered via .req. Canonicalize to lower case.
3998     // That's more consistent since register names are case insensitive, and
3999     // it's how the original entry was passed in from MC/MCParser/AsmParser.
4000     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
4001     // If no match, return failure.
4002     if (Entry == RegisterReqs.end())
4003       return -1;
4004     Parser.Lex(); // Eat identifier token.
4005     return Entry->getValue();
4006   }
4007 
4008   // Some FPUs only have 16 D registers, so D16-D31 are invalid
4009   if (!hasD32() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
4010     return -1;
4011 
4012   Parser.Lex(); // Eat identifier token.
4013 
4014   return RegNum;
4015 }
4016 
4017 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
4018 // If a recoverable error occurs, return 1. If an irrecoverable error
4019 // occurs, return -1. An irrecoverable error is one where tokens have been
4020 // consumed in the process of trying to parse the shifter (i.e., when it is
4021 // indeed a shifter operand, but malformed).
4022 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
4023   MCAsmParser &Parser = getParser();
4024   SMLoc S = Parser.getTok().getLoc();
4025   const AsmToken &Tok = Parser.getTok();
4026   if (Tok.isNot(AsmToken::Identifier))
4027     return -1;
4028 
4029   std::string lowerCase = Tok.getString().lower();
4030   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
4031       .Case("asl", ARM_AM::lsl)
4032       .Case("lsl", ARM_AM::lsl)
4033       .Case("lsr", ARM_AM::lsr)
4034       .Case("asr", ARM_AM::asr)
4035       .Case("ror", ARM_AM::ror)
4036       .Case("rrx", ARM_AM::rrx)
4037       .Default(ARM_AM::no_shift);
4038 
4039   if (ShiftTy == ARM_AM::no_shift)
4040     return 1;
4041 
4042   Parser.Lex(); // Eat the operator.
4043 
4044   // The source register for the shift has already been added to the
4045   // operand list, so we need to pop it off and combine it into the shifted
4046   // register operand instead.
4047   std::unique_ptr<ARMOperand> PrevOp(
4048       (ARMOperand *)Operands.pop_back_val().release());
4049   if (!PrevOp->isReg())
4050     return Error(PrevOp->getStartLoc(), "shift must be of a register");
4051   int SrcReg = PrevOp->getReg();
4052 
4053   SMLoc EndLoc;
4054   int64_t Imm = 0;
4055   int ShiftReg = 0;
4056   if (ShiftTy == ARM_AM::rrx) {
4057     // RRX Doesn't have an explicit shift amount. The encoder expects
4058     // the shift register to be the same as the source register. Seems odd,
4059     // but OK.
4060     ShiftReg = SrcReg;
4061   } else {
4062     // Figure out if this is shifted by a constant or a register (for non-RRX).
4063     if (Parser.getTok().is(AsmToken::Hash) ||
4064         Parser.getTok().is(AsmToken::Dollar)) {
4065       Parser.Lex(); // Eat hash.
4066       SMLoc ImmLoc = Parser.getTok().getLoc();
4067       const MCExpr *ShiftExpr = nullptr;
4068       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
4069         Error(ImmLoc, "invalid immediate shift value");
4070         return -1;
4071       }
4072       // The expression must be evaluatable as an immediate.
4073       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
4074       if (!CE) {
4075         Error(ImmLoc, "invalid immediate shift value");
4076         return -1;
4077       }
4078       // Range check the immediate.
4079       // lsl, ror: 0 <= imm <= 31
4080       // lsr, asr: 0 <= imm <= 32
4081       Imm = CE->getValue();
4082       if (Imm < 0 ||
4083           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
4084           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
4085         Error(ImmLoc, "immediate shift value out of range");
4086         return -1;
4087       }
4088       // shift by zero is a nop. Always send it through as lsl.
4089       // ('as' compatibility)
4090       if (Imm == 0)
4091         ShiftTy = ARM_AM::lsl;
4092     } else if (Parser.getTok().is(AsmToken::Identifier)) {
4093       SMLoc L = Parser.getTok().getLoc();
4094       EndLoc = Parser.getTok().getEndLoc();
4095       ShiftReg = tryParseRegister();
4096       if (ShiftReg == -1) {
4097         Error(L, "expected immediate or register in shift operand");
4098         return -1;
4099       }
4100     } else {
4101       Error(Parser.getTok().getLoc(),
4102             "expected immediate or register in shift operand");
4103       return -1;
4104     }
4105   }
4106 
4107   if (ShiftReg && ShiftTy != ARM_AM::rrx)
4108     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
4109                                                          ShiftReg, Imm,
4110                                                          S, EndLoc));
4111   else
4112     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
4113                                                           S, EndLoc));
4114 
4115   return 0;
4116 }
4117 
4118 /// Try to parse a register name.  The token must be an Identifier when called.
4119 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
4120 /// if there is a "writeback". 'true' if it's not a register.
4121 ///
4122 /// TODO this is likely to change to allow different register types and or to
4123 /// parse for a specific register type.
4124 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
4125   MCAsmParser &Parser = getParser();
4126   SMLoc RegStartLoc = Parser.getTok().getLoc();
4127   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
4128   int RegNo = tryParseRegister();
4129   if (RegNo == -1)
4130     return true;
4131 
4132   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
4133 
4134   const AsmToken &ExclaimTok = Parser.getTok();
4135   if (ExclaimTok.is(AsmToken::Exclaim)) {
4136     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
4137                                                ExclaimTok.getLoc()));
4138     Parser.Lex(); // Eat exclaim token
4139     return false;
4140   }
4141 
4142   // Also check for an index operand. This is only legal for vector registers,
4143   // but that'll get caught OK in operand matching, so we don't need to
4144   // explicitly filter everything else out here.
4145   if (Parser.getTok().is(AsmToken::LBrac)) {
4146     SMLoc SIdx = Parser.getTok().getLoc();
4147     Parser.Lex(); // Eat left bracket token.
4148 
4149     const MCExpr *ImmVal;
4150     if (getParser().parseExpression(ImmVal))
4151       return true;
4152     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
4153     if (!MCE)
4154       return TokError("immediate value expected for vector index");
4155 
4156     if (Parser.getTok().isNot(AsmToken::RBrac))
4157       return Error(Parser.getTok().getLoc(), "']' expected");
4158 
4159     SMLoc E = Parser.getTok().getEndLoc();
4160     Parser.Lex(); // Eat right bracket token.
4161 
4162     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
4163                                                      SIdx, E,
4164                                                      getContext()));
4165   }
4166 
4167   return false;
4168 }
4169 
4170 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
4171 /// instruction with a symbolic operand name.
4172 /// We accept "crN" syntax for GAS compatibility.
4173 /// <operand-name> ::= <prefix><number>
4174 /// If CoprocOp is 'c', then:
4175 ///   <prefix> ::= c | cr
4176 /// If CoprocOp is 'p', then :
4177 ///   <prefix> ::= p
4178 /// <number> ::= integer in range [0, 15]
4179 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
4180   // Use the same layout as the tablegen'erated register name matcher. Ugly,
4181   // but efficient.
4182   if (Name.size() < 2 || Name[0] != CoprocOp)
4183     return -1;
4184   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
4185 
4186   switch (Name.size()) {
4187   default: return -1;
4188   case 1:
4189     switch (Name[0]) {
4190     default:  return -1;
4191     case '0': return 0;
4192     case '1': return 1;
4193     case '2': return 2;
4194     case '3': return 3;
4195     case '4': return 4;
4196     case '5': return 5;
4197     case '6': return 6;
4198     case '7': return 7;
4199     case '8': return 8;
4200     case '9': return 9;
4201     }
4202   case 2:
4203     if (Name[0] != '1')
4204       return -1;
4205     switch (Name[1]) {
4206     default:  return -1;
4207     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
4208     // However, old cores (v5/v6) did use them in that way.
4209     case '0': return 10;
4210     case '1': return 11;
4211     case '2': return 12;
4212     case '3': return 13;
4213     case '4': return 14;
4214     case '5': return 15;
4215     }
4216   }
4217 }
4218 
4219 /// parseITCondCode - Try to parse a condition code for an IT instruction.
4220 OperandMatchResultTy
4221 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
4222   MCAsmParser &Parser = getParser();
4223   SMLoc S = Parser.getTok().getLoc();
4224   const AsmToken &Tok = Parser.getTok();
4225   if (!Tok.is(AsmToken::Identifier))
4226     return MatchOperand_NoMatch;
4227   unsigned CC = ARMCondCodeFromString(Tok.getString());
4228   if (CC == ~0U)
4229     return MatchOperand_NoMatch;
4230   Parser.Lex(); // Eat the token.
4231 
4232   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
4233 
4234   return MatchOperand_Success;
4235 }
4236 
4237 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
4238 /// token must be an Identifier when called, and if it is a coprocessor
4239 /// number, the token is eaten and the operand is added to the operand list.
4240 OperandMatchResultTy
4241 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
4242   MCAsmParser &Parser = getParser();
4243   SMLoc S = Parser.getTok().getLoc();
4244   const AsmToken &Tok = Parser.getTok();
4245   if (Tok.isNot(AsmToken::Identifier))
4246     return MatchOperand_NoMatch;
4247 
4248   int Num = MatchCoprocessorOperandName(Tok.getString().lower(), 'p');
4249   if (Num == -1)
4250     return MatchOperand_NoMatch;
4251   if (!isValidCoprocessorNumber(Num, getSTI().getFeatureBits()))
4252     return MatchOperand_NoMatch;
4253 
4254   Parser.Lex(); // Eat identifier token.
4255   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
4256   return MatchOperand_Success;
4257 }
4258 
4259 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
4260 /// token must be an Identifier when called, and if it is a coprocessor
4261 /// number, the token is eaten and the operand is added to the operand list.
4262 OperandMatchResultTy
4263 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
4264   MCAsmParser &Parser = getParser();
4265   SMLoc S = Parser.getTok().getLoc();
4266   const AsmToken &Tok = Parser.getTok();
4267   if (Tok.isNot(AsmToken::Identifier))
4268     return MatchOperand_NoMatch;
4269 
4270   int Reg = MatchCoprocessorOperandName(Tok.getString().lower(), 'c');
4271   if (Reg == -1)
4272     return MatchOperand_NoMatch;
4273 
4274   Parser.Lex(); // Eat identifier token.
4275   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
4276   return MatchOperand_Success;
4277 }
4278 
4279 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
4280 /// coproc_option : '{' imm0_255 '}'
4281 OperandMatchResultTy
4282 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
4283   MCAsmParser &Parser = getParser();
4284   SMLoc S = Parser.getTok().getLoc();
4285 
4286   // If this isn't a '{', this isn't a coprocessor immediate operand.
4287   if (Parser.getTok().isNot(AsmToken::LCurly))
4288     return MatchOperand_NoMatch;
4289   Parser.Lex(); // Eat the '{'
4290 
4291   const MCExpr *Expr;
4292   SMLoc Loc = Parser.getTok().getLoc();
4293   if (getParser().parseExpression(Expr)) {
4294     Error(Loc, "illegal expression");
4295     return MatchOperand_ParseFail;
4296   }
4297   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4298   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
4299     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
4300     return MatchOperand_ParseFail;
4301   }
4302   int Val = CE->getValue();
4303 
4304   // Check for and consume the closing '}'
4305   if (Parser.getTok().isNot(AsmToken::RCurly))
4306     return MatchOperand_ParseFail;
4307   SMLoc E = Parser.getTok().getEndLoc();
4308   Parser.Lex(); // Eat the '}'
4309 
4310   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
4311   return MatchOperand_Success;
4312 }
4313 
4314 // For register list parsing, we need to map from raw GPR register numbering
4315 // to the enumeration values. The enumeration values aren't sorted by
4316 // register number due to our using "sp", "lr" and "pc" as canonical names.
4317 static unsigned getNextRegister(unsigned Reg) {
4318   // If this is a GPR, we need to do it manually, otherwise we can rely
4319   // on the sort ordering of the enumeration since the other reg-classes
4320   // are sane.
4321   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4322     return Reg + 1;
4323   switch(Reg) {
4324   default: llvm_unreachable("Invalid GPR number!");
4325   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
4326   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
4327   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
4328   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
4329   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
4330   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
4331   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
4332   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
4333   }
4334 }
4335 
4336 // Insert an <Encoding, Register> pair in an ordered vector. Return true on
4337 // success, or false, if duplicate encoding found.
4338 static bool
4339 insertNoDuplicates(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
4340                    unsigned Enc, unsigned Reg) {
4341   Regs.emplace_back(Enc, Reg);
4342   for (auto I = Regs.rbegin(), J = I + 1, E = Regs.rend(); J != E; ++I, ++J) {
4343     if (J->first == Enc) {
4344       Regs.erase(J.base());
4345       return false;
4346     }
4347     if (J->first < Enc)
4348       break;
4349     std::swap(*I, *J);
4350   }
4351   return true;
4352 }
4353 
4354 /// Parse a register list.
4355 bool ARMAsmParser::parseRegisterList(OperandVector &Operands,
4356                                      bool EnforceOrder) {
4357   MCAsmParser &Parser = getParser();
4358   if (Parser.getTok().isNot(AsmToken::LCurly))
4359     return TokError("Token is not a Left Curly Brace");
4360   SMLoc S = Parser.getTok().getLoc();
4361   Parser.Lex(); // Eat '{' token.
4362   SMLoc RegLoc = Parser.getTok().getLoc();
4363 
4364   // Check the first register in the list to see what register class
4365   // this is a list of.
4366   int Reg = tryParseRegister();
4367   if (Reg == -1)
4368     return Error(RegLoc, "register expected");
4369 
4370   // The reglist instructions have at most 16 registers, so reserve
4371   // space for that many.
4372   int EReg = 0;
4373   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
4374 
4375   // Allow Q regs and just interpret them as the two D sub-registers.
4376   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4377     Reg = getDRegFromQReg(Reg);
4378     EReg = MRI->getEncodingValue(Reg);
4379     Registers.emplace_back(EReg, Reg);
4380     ++Reg;
4381   }
4382   const MCRegisterClass *RC;
4383   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4384     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
4385   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
4386     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
4387   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
4388     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
4389   else if (ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4390     RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4391   else
4392     return Error(RegLoc, "invalid register in register list");
4393 
4394   // Store the register.
4395   EReg = MRI->getEncodingValue(Reg);
4396   Registers.emplace_back(EReg, Reg);
4397 
4398   // This starts immediately after the first register token in the list,
4399   // so we can see either a comma or a minus (range separator) as a legal
4400   // next token.
4401   while (Parser.getTok().is(AsmToken::Comma) ||
4402          Parser.getTok().is(AsmToken::Minus)) {
4403     if (Parser.getTok().is(AsmToken::Minus)) {
4404       Parser.Lex(); // Eat the minus.
4405       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4406       int EndReg = tryParseRegister();
4407       if (EndReg == -1)
4408         return Error(AfterMinusLoc, "register expected");
4409       // Allow Q regs and just interpret them as the two D sub-registers.
4410       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4411         EndReg = getDRegFromQReg(EndReg) + 1;
4412       // If the register is the same as the start reg, there's nothing
4413       // more to do.
4414       if (Reg == EndReg)
4415         continue;
4416       // The register must be in the same register class as the first.
4417       if (!RC->contains(EndReg))
4418         return Error(AfterMinusLoc, "invalid register in register list");
4419       // Ranges must go from low to high.
4420       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
4421         return Error(AfterMinusLoc, "bad range in register list");
4422 
4423       // Add all the registers in the range to the register list.
4424       while (Reg != EndReg) {
4425         Reg = getNextRegister(Reg);
4426         EReg = MRI->getEncodingValue(Reg);
4427         if (!insertNoDuplicates(Registers, EReg, Reg)) {
4428           Warning(AfterMinusLoc, StringRef("duplicated register (") +
4429                                      ARMInstPrinter::getRegisterName(Reg) +
4430                                      ") in register list");
4431         }
4432       }
4433       continue;
4434     }
4435     Parser.Lex(); // Eat the comma.
4436     RegLoc = Parser.getTok().getLoc();
4437     int OldReg = Reg;
4438     const AsmToken RegTok = Parser.getTok();
4439     Reg = tryParseRegister();
4440     if (Reg == -1)
4441       return Error(RegLoc, "register expected");
4442     // Allow Q regs and just interpret them as the two D sub-registers.
4443     bool isQReg = false;
4444     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4445       Reg = getDRegFromQReg(Reg);
4446       isQReg = true;
4447     }
4448     if (!RC->contains(Reg) &&
4449         RC->getID() == ARMMCRegisterClasses[ARM::GPRRegClassID].getID() &&
4450         ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg)) {
4451       // switch the register classes, as GPRwithAPSRnospRegClassID is a partial
4452       // subset of GPRRegClassId except it contains APSR as well.
4453       RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4454     }
4455     if (Reg == ARM::VPR &&
4456         (RC == &ARMMCRegisterClasses[ARM::SPRRegClassID] ||
4457          RC == &ARMMCRegisterClasses[ARM::DPRRegClassID] ||
4458          RC == &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID])) {
4459       RC = &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID];
4460       EReg = MRI->getEncodingValue(Reg);
4461       if (!insertNoDuplicates(Registers, EReg, Reg)) {
4462         Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4463                             ") in register list");
4464       }
4465       continue;
4466     }
4467     // The register must be in the same register class as the first.
4468     if (!RC->contains(Reg))
4469       return Error(RegLoc, "invalid register in register list");
4470     // In most cases, the list must be monotonically increasing. An
4471     // exception is CLRM, which is order-independent anyway, so
4472     // there's no potential for confusion if you write clrm {r2,r1}
4473     // instead of clrm {r1,r2}.
4474     if (EnforceOrder &&
4475         MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
4476       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4477         Warning(RegLoc, "register list not in ascending order");
4478       else if (!ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4479         return Error(RegLoc, "register list not in ascending order");
4480     }
4481     // VFP register lists must also be contiguous.
4482     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
4483         RC != &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID] &&
4484         Reg != OldReg + 1)
4485       return Error(RegLoc, "non-contiguous register range");
4486     EReg = MRI->getEncodingValue(Reg);
4487     if (!insertNoDuplicates(Registers, EReg, Reg)) {
4488       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4489                           ") in register list");
4490     }
4491     if (isQReg) {
4492       EReg = MRI->getEncodingValue(++Reg);
4493       Registers.emplace_back(EReg, Reg);
4494     }
4495   }
4496 
4497   if (Parser.getTok().isNot(AsmToken::RCurly))
4498     return Error(Parser.getTok().getLoc(), "'}' expected");
4499   SMLoc E = Parser.getTok().getEndLoc();
4500   Parser.Lex(); // Eat '}' token.
4501 
4502   // Push the register list operand.
4503   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
4504 
4505   // The ARM system instruction variants for LDM/STM have a '^' token here.
4506   if (Parser.getTok().is(AsmToken::Caret)) {
4507     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
4508     Parser.Lex(); // Eat '^' token.
4509   }
4510 
4511   return false;
4512 }
4513 
4514 // Helper function to parse the lane index for vector lists.
4515 OperandMatchResultTy ARMAsmParser::
4516 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
4517   MCAsmParser &Parser = getParser();
4518   Index = 0; // Always return a defined index value.
4519   if (Parser.getTok().is(AsmToken::LBrac)) {
4520     Parser.Lex(); // Eat the '['.
4521     if (Parser.getTok().is(AsmToken::RBrac)) {
4522       // "Dn[]" is the 'all lanes' syntax.
4523       LaneKind = AllLanes;
4524       EndLoc = Parser.getTok().getEndLoc();
4525       Parser.Lex(); // Eat the ']'.
4526       return MatchOperand_Success;
4527     }
4528 
4529     // There's an optional '#' token here. Normally there wouldn't be, but
4530     // inline assemble puts one in, and it's friendly to accept that.
4531     if (Parser.getTok().is(AsmToken::Hash))
4532       Parser.Lex(); // Eat '#' or '$'.
4533 
4534     const MCExpr *LaneIndex;
4535     SMLoc Loc = Parser.getTok().getLoc();
4536     if (getParser().parseExpression(LaneIndex)) {
4537       Error(Loc, "illegal expression");
4538       return MatchOperand_ParseFail;
4539     }
4540     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
4541     if (!CE) {
4542       Error(Loc, "lane index must be empty or an integer");
4543       return MatchOperand_ParseFail;
4544     }
4545     if (Parser.getTok().isNot(AsmToken::RBrac)) {
4546       Error(Parser.getTok().getLoc(), "']' expected");
4547       return MatchOperand_ParseFail;
4548     }
4549     EndLoc = Parser.getTok().getEndLoc();
4550     Parser.Lex(); // Eat the ']'.
4551     int64_t Val = CE->getValue();
4552 
4553     // FIXME: Make this range check context sensitive for .8, .16, .32.
4554     if (Val < 0 || Val > 7) {
4555       Error(Parser.getTok().getLoc(), "lane index out of range");
4556       return MatchOperand_ParseFail;
4557     }
4558     Index = Val;
4559     LaneKind = IndexedLane;
4560     return MatchOperand_Success;
4561   }
4562   LaneKind = NoLanes;
4563   return MatchOperand_Success;
4564 }
4565 
4566 // parse a vector register list
4567 OperandMatchResultTy
4568 ARMAsmParser::parseVectorList(OperandVector &Operands) {
4569   MCAsmParser &Parser = getParser();
4570   VectorLaneTy LaneKind;
4571   unsigned LaneIndex;
4572   SMLoc S = Parser.getTok().getLoc();
4573   // As an extension (to match gas), support a plain D register or Q register
4574   // (without encosing curly braces) as a single or double entry list,
4575   // respectively.
4576   if (!hasMVE() && Parser.getTok().is(AsmToken::Identifier)) {
4577     SMLoc E = Parser.getTok().getEndLoc();
4578     int Reg = tryParseRegister();
4579     if (Reg == -1)
4580       return MatchOperand_NoMatch;
4581     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
4582       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4583       if (Res != MatchOperand_Success)
4584         return Res;
4585       switch (LaneKind) {
4586       case NoLanes:
4587         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
4588         break;
4589       case AllLanes:
4590         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
4591                                                                 S, E));
4592         break;
4593       case IndexedLane:
4594         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
4595                                                                LaneIndex,
4596                                                                false, S, E));
4597         break;
4598       }
4599       return MatchOperand_Success;
4600     }
4601     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4602       Reg = getDRegFromQReg(Reg);
4603       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4604       if (Res != MatchOperand_Success)
4605         return Res;
4606       switch (LaneKind) {
4607       case NoLanes:
4608         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4609                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4610         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
4611         break;
4612       case AllLanes:
4613         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4614                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4615         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
4616                                                                 S, E));
4617         break;
4618       case IndexedLane:
4619         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
4620                                                                LaneIndex,
4621                                                                false, S, E));
4622         break;
4623       }
4624       return MatchOperand_Success;
4625     }
4626     Error(S, "vector register expected");
4627     return MatchOperand_ParseFail;
4628   }
4629 
4630   if (Parser.getTok().isNot(AsmToken::LCurly))
4631     return MatchOperand_NoMatch;
4632 
4633   Parser.Lex(); // Eat '{' token.
4634   SMLoc RegLoc = Parser.getTok().getLoc();
4635 
4636   int Reg = tryParseRegister();
4637   if (Reg == -1) {
4638     Error(RegLoc, "register expected");
4639     return MatchOperand_ParseFail;
4640   }
4641   unsigned Count = 1;
4642   int Spacing = 0;
4643   unsigned FirstReg = Reg;
4644 
4645   if (hasMVE() && !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4646       Error(Parser.getTok().getLoc(), "vector register in range Q0-Q7 expected");
4647       return MatchOperand_ParseFail;
4648   }
4649   // The list is of D registers, but we also allow Q regs and just interpret
4650   // them as the two D sub-registers.
4651   else if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4652     FirstReg = Reg = getDRegFromQReg(Reg);
4653     Spacing = 1; // double-spacing requires explicit D registers, otherwise
4654                  // it's ambiguous with four-register single spaced.
4655     ++Reg;
4656     ++Count;
4657   }
4658 
4659   SMLoc E;
4660   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
4661     return MatchOperand_ParseFail;
4662 
4663   while (Parser.getTok().is(AsmToken::Comma) ||
4664          Parser.getTok().is(AsmToken::Minus)) {
4665     if (Parser.getTok().is(AsmToken::Minus)) {
4666       if (!Spacing)
4667         Spacing = 1; // Register range implies a single spaced list.
4668       else if (Spacing == 2) {
4669         Error(Parser.getTok().getLoc(),
4670               "sequential registers in double spaced list");
4671         return MatchOperand_ParseFail;
4672       }
4673       Parser.Lex(); // Eat the minus.
4674       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4675       int EndReg = tryParseRegister();
4676       if (EndReg == -1) {
4677         Error(AfterMinusLoc, "register expected");
4678         return MatchOperand_ParseFail;
4679       }
4680       // Allow Q regs and just interpret them as the two D sub-registers.
4681       if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4682         EndReg = getDRegFromQReg(EndReg) + 1;
4683       // If the register is the same as the start reg, there's nothing
4684       // more to do.
4685       if (Reg == EndReg)
4686         continue;
4687       // The register must be in the same register class as the first.
4688       if ((hasMVE() &&
4689            !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(EndReg)) ||
4690           (!hasMVE() &&
4691            !ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg))) {
4692         Error(AfterMinusLoc, "invalid register in register list");
4693         return MatchOperand_ParseFail;
4694       }
4695       // Ranges must go from low to high.
4696       if (Reg > EndReg) {
4697         Error(AfterMinusLoc, "bad range in register list");
4698         return MatchOperand_ParseFail;
4699       }
4700       // Parse the lane specifier if present.
4701       VectorLaneTy NextLaneKind;
4702       unsigned NextLaneIndex;
4703       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4704           MatchOperand_Success)
4705         return MatchOperand_ParseFail;
4706       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4707         Error(AfterMinusLoc, "mismatched lane index in register list");
4708         return MatchOperand_ParseFail;
4709       }
4710 
4711       // Add all the registers in the range to the register list.
4712       Count += EndReg - Reg;
4713       Reg = EndReg;
4714       continue;
4715     }
4716     Parser.Lex(); // Eat the comma.
4717     RegLoc = Parser.getTok().getLoc();
4718     int OldReg = Reg;
4719     Reg = tryParseRegister();
4720     if (Reg == -1) {
4721       Error(RegLoc, "register expected");
4722       return MatchOperand_ParseFail;
4723     }
4724 
4725     if (hasMVE()) {
4726       if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4727         Error(RegLoc, "vector register in range Q0-Q7 expected");
4728         return MatchOperand_ParseFail;
4729       }
4730       Spacing = 1;
4731     }
4732     // vector register lists must be contiguous.
4733     // It's OK to use the enumeration values directly here rather, as the
4734     // VFP register classes have the enum sorted properly.
4735     //
4736     // The list is of D registers, but we also allow Q regs and just interpret
4737     // them as the two D sub-registers.
4738     else if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4739       if (!Spacing)
4740         Spacing = 1; // Register range implies a single spaced list.
4741       else if (Spacing == 2) {
4742         Error(RegLoc,
4743               "invalid register in double-spaced list (must be 'D' register')");
4744         return MatchOperand_ParseFail;
4745       }
4746       Reg = getDRegFromQReg(Reg);
4747       if (Reg != OldReg + 1) {
4748         Error(RegLoc, "non-contiguous register range");
4749         return MatchOperand_ParseFail;
4750       }
4751       ++Reg;
4752       Count += 2;
4753       // Parse the lane specifier if present.
4754       VectorLaneTy NextLaneKind;
4755       unsigned NextLaneIndex;
4756       SMLoc LaneLoc = Parser.getTok().getLoc();
4757       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4758           MatchOperand_Success)
4759         return MatchOperand_ParseFail;
4760       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4761         Error(LaneLoc, "mismatched lane index in register list");
4762         return MatchOperand_ParseFail;
4763       }
4764       continue;
4765     }
4766     // Normal D register.
4767     // Figure out the register spacing (single or double) of the list if
4768     // we don't know it already.
4769     if (!Spacing)
4770       Spacing = 1 + (Reg == OldReg + 2);
4771 
4772     // Just check that it's contiguous and keep going.
4773     if (Reg != OldReg + Spacing) {
4774       Error(RegLoc, "non-contiguous register range");
4775       return MatchOperand_ParseFail;
4776     }
4777     ++Count;
4778     // Parse the lane specifier if present.
4779     VectorLaneTy NextLaneKind;
4780     unsigned NextLaneIndex;
4781     SMLoc EndLoc = Parser.getTok().getLoc();
4782     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4783       return MatchOperand_ParseFail;
4784     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4785       Error(EndLoc, "mismatched lane index in register list");
4786       return MatchOperand_ParseFail;
4787     }
4788   }
4789 
4790   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4791     Error(Parser.getTok().getLoc(), "'}' expected");
4792     return MatchOperand_ParseFail;
4793   }
4794   E = Parser.getTok().getEndLoc();
4795   Parser.Lex(); // Eat '}' token.
4796 
4797   switch (LaneKind) {
4798   case NoLanes:
4799   case AllLanes: {
4800     // Two-register operands have been converted to the
4801     // composite register classes.
4802     if (Count == 2 && !hasMVE()) {
4803       const MCRegisterClass *RC = (Spacing == 1) ?
4804         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4805         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4806       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4807     }
4808     auto Create = (LaneKind == NoLanes ? ARMOperand::CreateVectorList :
4809                    ARMOperand::CreateVectorListAllLanes);
4810     Operands.push_back(Create(FirstReg, Count, (Spacing == 2), S, E));
4811     break;
4812   }
4813   case IndexedLane:
4814     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4815                                                            LaneIndex,
4816                                                            (Spacing == 2),
4817                                                            S, E));
4818     break;
4819   }
4820   return MatchOperand_Success;
4821 }
4822 
4823 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4824 OperandMatchResultTy
4825 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4826   MCAsmParser &Parser = getParser();
4827   SMLoc S = Parser.getTok().getLoc();
4828   const AsmToken &Tok = Parser.getTok();
4829   unsigned Opt;
4830 
4831   if (Tok.is(AsmToken::Identifier)) {
4832     StringRef OptStr = Tok.getString();
4833 
4834     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4835       .Case("sy",    ARM_MB::SY)
4836       .Case("st",    ARM_MB::ST)
4837       .Case("ld",    ARM_MB::LD)
4838       .Case("sh",    ARM_MB::ISH)
4839       .Case("ish",   ARM_MB::ISH)
4840       .Case("shst",  ARM_MB::ISHST)
4841       .Case("ishst", ARM_MB::ISHST)
4842       .Case("ishld", ARM_MB::ISHLD)
4843       .Case("nsh",   ARM_MB::NSH)
4844       .Case("un",    ARM_MB::NSH)
4845       .Case("nshst", ARM_MB::NSHST)
4846       .Case("nshld", ARM_MB::NSHLD)
4847       .Case("unst",  ARM_MB::NSHST)
4848       .Case("osh",   ARM_MB::OSH)
4849       .Case("oshst", ARM_MB::OSHST)
4850       .Case("oshld", ARM_MB::OSHLD)
4851       .Default(~0U);
4852 
4853     // ishld, oshld, nshld and ld are only available from ARMv8.
4854     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4855                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4856       Opt = ~0U;
4857 
4858     if (Opt == ~0U)
4859       return MatchOperand_NoMatch;
4860 
4861     Parser.Lex(); // Eat identifier token.
4862   } else if (Tok.is(AsmToken::Hash) ||
4863              Tok.is(AsmToken::Dollar) ||
4864              Tok.is(AsmToken::Integer)) {
4865     if (Parser.getTok().isNot(AsmToken::Integer))
4866       Parser.Lex(); // Eat '#' or '$'.
4867     SMLoc Loc = Parser.getTok().getLoc();
4868 
4869     const MCExpr *MemBarrierID;
4870     if (getParser().parseExpression(MemBarrierID)) {
4871       Error(Loc, "illegal expression");
4872       return MatchOperand_ParseFail;
4873     }
4874 
4875     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4876     if (!CE) {
4877       Error(Loc, "constant expression expected");
4878       return MatchOperand_ParseFail;
4879     }
4880 
4881     int Val = CE->getValue();
4882     if (Val & ~0xf) {
4883       Error(Loc, "immediate value out of range");
4884       return MatchOperand_ParseFail;
4885     }
4886 
4887     Opt = ARM_MB::RESERVED_0 + Val;
4888   } else
4889     return MatchOperand_ParseFail;
4890 
4891   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
4892   return MatchOperand_Success;
4893 }
4894 
4895 OperandMatchResultTy
4896 ARMAsmParser::parseTraceSyncBarrierOptOperand(OperandVector &Operands) {
4897   MCAsmParser &Parser = getParser();
4898   SMLoc S = Parser.getTok().getLoc();
4899   const AsmToken &Tok = Parser.getTok();
4900 
4901   if (Tok.isNot(AsmToken::Identifier))
4902      return MatchOperand_NoMatch;
4903 
4904   if (!Tok.getString().equals_lower("csync"))
4905     return MatchOperand_NoMatch;
4906 
4907   Parser.Lex(); // Eat identifier token.
4908 
4909   Operands.push_back(ARMOperand::CreateTraceSyncBarrierOpt(ARM_TSB::CSYNC, S));
4910   return MatchOperand_Success;
4911 }
4912 
4913 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
4914 OperandMatchResultTy
4915 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
4916   MCAsmParser &Parser = getParser();
4917   SMLoc S = Parser.getTok().getLoc();
4918   const AsmToken &Tok = Parser.getTok();
4919   unsigned Opt;
4920 
4921   if (Tok.is(AsmToken::Identifier)) {
4922     StringRef OptStr = Tok.getString();
4923 
4924     if (OptStr.equals_lower("sy"))
4925       Opt = ARM_ISB::SY;
4926     else
4927       return MatchOperand_NoMatch;
4928 
4929     Parser.Lex(); // Eat identifier token.
4930   } else if (Tok.is(AsmToken::Hash) ||
4931              Tok.is(AsmToken::Dollar) ||
4932              Tok.is(AsmToken::Integer)) {
4933     if (Parser.getTok().isNot(AsmToken::Integer))
4934       Parser.Lex(); // Eat '#' or '$'.
4935     SMLoc Loc = Parser.getTok().getLoc();
4936 
4937     const MCExpr *ISBarrierID;
4938     if (getParser().parseExpression(ISBarrierID)) {
4939       Error(Loc, "illegal expression");
4940       return MatchOperand_ParseFail;
4941     }
4942 
4943     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4944     if (!CE) {
4945       Error(Loc, "constant expression expected");
4946       return MatchOperand_ParseFail;
4947     }
4948 
4949     int Val = CE->getValue();
4950     if (Val & ~0xf) {
4951       Error(Loc, "immediate value out of range");
4952       return MatchOperand_ParseFail;
4953     }
4954 
4955     Opt = ARM_ISB::RESERVED_0 + Val;
4956   } else
4957     return MatchOperand_ParseFail;
4958 
4959   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4960           (ARM_ISB::InstSyncBOpt)Opt, S));
4961   return MatchOperand_Success;
4962 }
4963 
4964 
4965 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4966 OperandMatchResultTy
4967 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4968   MCAsmParser &Parser = getParser();
4969   SMLoc S = Parser.getTok().getLoc();
4970   const AsmToken &Tok = Parser.getTok();
4971   if (!Tok.is(AsmToken::Identifier))
4972     return MatchOperand_NoMatch;
4973   StringRef IFlagsStr = Tok.getString();
4974 
4975   // An iflags string of "none" is interpreted to mean that none of the AIF
4976   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4977   unsigned IFlags = 0;
4978   if (IFlagsStr != "none") {
4979         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4980       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
4981         .Case("a", ARM_PROC::A)
4982         .Case("i", ARM_PROC::I)
4983         .Case("f", ARM_PROC::F)
4984         .Default(~0U);
4985 
4986       // If some specific iflag is already set, it means that some letter is
4987       // present more than once, this is not acceptable.
4988       if (Flag == ~0U || (IFlags & Flag))
4989         return MatchOperand_NoMatch;
4990 
4991       IFlags |= Flag;
4992     }
4993   }
4994 
4995   Parser.Lex(); // Eat identifier token.
4996   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4997   return MatchOperand_Success;
4998 }
4999 
5000 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
5001 OperandMatchResultTy
5002 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
5003   MCAsmParser &Parser = getParser();
5004   SMLoc S = Parser.getTok().getLoc();
5005   const AsmToken &Tok = Parser.getTok();
5006 
5007   if (Tok.is(AsmToken::Integer)) {
5008     int64_t Val = Tok.getIntVal();
5009     if (Val > 255 || Val < 0) {
5010       return MatchOperand_NoMatch;
5011     }
5012     unsigned SYSmvalue = Val & 0xFF;
5013     Parser.Lex();
5014     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
5015     return MatchOperand_Success;
5016   }
5017 
5018   if (!Tok.is(AsmToken::Identifier))
5019     return MatchOperand_NoMatch;
5020   StringRef Mask = Tok.getString();
5021 
5022   if (isMClass()) {
5023     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
5024     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
5025       return MatchOperand_NoMatch;
5026 
5027     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
5028 
5029     Parser.Lex(); // Eat identifier token.
5030     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
5031     return MatchOperand_Success;
5032   }
5033 
5034   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
5035   size_t Start = 0, Next = Mask.find('_');
5036   StringRef Flags = "";
5037   std::string SpecReg = Mask.slice(Start, Next).lower();
5038   if (Next != StringRef::npos)
5039     Flags = Mask.slice(Next+1, Mask.size());
5040 
5041   // FlagsVal contains the complete mask:
5042   // 3-0: Mask
5043   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
5044   unsigned FlagsVal = 0;
5045 
5046   if (SpecReg == "apsr") {
5047     FlagsVal = StringSwitch<unsigned>(Flags)
5048     .Case("nzcvq",  0x8) // same as CPSR_f
5049     .Case("g",      0x4) // same as CPSR_s
5050     .Case("nzcvqg", 0xc) // same as CPSR_fs
5051     .Default(~0U);
5052 
5053     if (FlagsVal == ~0U) {
5054       if (!Flags.empty())
5055         return MatchOperand_NoMatch;
5056       else
5057         FlagsVal = 8; // No flag
5058     }
5059   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
5060     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
5061     if (Flags == "all" || Flags == "")
5062       Flags = "fc";
5063     for (int i = 0, e = Flags.size(); i != e; ++i) {
5064       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
5065       .Case("c", 1)
5066       .Case("x", 2)
5067       .Case("s", 4)
5068       .Case("f", 8)
5069       .Default(~0U);
5070 
5071       // If some specific flag is already set, it means that some letter is
5072       // present more than once, this is not acceptable.
5073       if (Flag == ~0U || (FlagsVal & Flag))
5074         return MatchOperand_NoMatch;
5075       FlagsVal |= Flag;
5076     }
5077   } else // No match for special register.
5078     return MatchOperand_NoMatch;
5079 
5080   // Special register without flags is NOT equivalent to "fc" flags.
5081   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
5082   // two lines would enable gas compatibility at the expense of breaking
5083   // round-tripping.
5084   //
5085   // if (!FlagsVal)
5086   //  FlagsVal = 0x9;
5087 
5088   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
5089   if (SpecReg == "spsr")
5090     FlagsVal |= 16;
5091 
5092   Parser.Lex(); // Eat identifier token.
5093   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
5094   return MatchOperand_Success;
5095 }
5096 
5097 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
5098 /// use in the MRS/MSR instructions added to support virtualization.
5099 OperandMatchResultTy
5100 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
5101   MCAsmParser &Parser = getParser();
5102   SMLoc S = Parser.getTok().getLoc();
5103   const AsmToken &Tok = Parser.getTok();
5104   if (!Tok.is(AsmToken::Identifier))
5105     return MatchOperand_NoMatch;
5106   StringRef RegName = Tok.getString();
5107 
5108   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
5109   if (!TheReg)
5110     return MatchOperand_NoMatch;
5111   unsigned Encoding = TheReg->Encoding;
5112 
5113   Parser.Lex(); // Eat identifier token.
5114   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
5115   return MatchOperand_Success;
5116 }
5117 
5118 OperandMatchResultTy
5119 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
5120                           int High) {
5121   MCAsmParser &Parser = getParser();
5122   const AsmToken &Tok = Parser.getTok();
5123   if (Tok.isNot(AsmToken::Identifier)) {
5124     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5125     return MatchOperand_ParseFail;
5126   }
5127   StringRef ShiftName = Tok.getString();
5128   std::string LowerOp = Op.lower();
5129   std::string UpperOp = Op.upper();
5130   if (ShiftName != LowerOp && ShiftName != UpperOp) {
5131     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5132     return MatchOperand_ParseFail;
5133   }
5134   Parser.Lex(); // Eat shift type token.
5135 
5136   // There must be a '#' and a shift amount.
5137   if (Parser.getTok().isNot(AsmToken::Hash) &&
5138       Parser.getTok().isNot(AsmToken::Dollar)) {
5139     Error(Parser.getTok().getLoc(), "'#' expected");
5140     return MatchOperand_ParseFail;
5141   }
5142   Parser.Lex(); // Eat hash token.
5143 
5144   const MCExpr *ShiftAmount;
5145   SMLoc Loc = Parser.getTok().getLoc();
5146   SMLoc EndLoc;
5147   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5148     Error(Loc, "illegal expression");
5149     return MatchOperand_ParseFail;
5150   }
5151   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5152   if (!CE) {
5153     Error(Loc, "constant expression expected");
5154     return MatchOperand_ParseFail;
5155   }
5156   int Val = CE->getValue();
5157   if (Val < Low || Val > High) {
5158     Error(Loc, "immediate value out of range");
5159     return MatchOperand_ParseFail;
5160   }
5161 
5162   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
5163 
5164   return MatchOperand_Success;
5165 }
5166 
5167 OperandMatchResultTy
5168 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
5169   MCAsmParser &Parser = getParser();
5170   const AsmToken &Tok = Parser.getTok();
5171   SMLoc S = Tok.getLoc();
5172   if (Tok.isNot(AsmToken::Identifier)) {
5173     Error(S, "'be' or 'le' operand expected");
5174     return MatchOperand_ParseFail;
5175   }
5176   int Val = StringSwitch<int>(Tok.getString().lower())
5177     .Case("be", 1)
5178     .Case("le", 0)
5179     .Default(-1);
5180   Parser.Lex(); // Eat the token.
5181 
5182   if (Val == -1) {
5183     Error(S, "'be' or 'le' operand expected");
5184     return MatchOperand_ParseFail;
5185   }
5186   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
5187                                                                   getContext()),
5188                                            S, Tok.getEndLoc()));
5189   return MatchOperand_Success;
5190 }
5191 
5192 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
5193 /// instructions. Legal values are:
5194 ///     lsl #n  'n' in [0,31]
5195 ///     asr #n  'n' in [1,32]
5196 ///             n == 32 encoded as n == 0.
5197 OperandMatchResultTy
5198 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
5199   MCAsmParser &Parser = getParser();
5200   const AsmToken &Tok = Parser.getTok();
5201   SMLoc S = Tok.getLoc();
5202   if (Tok.isNot(AsmToken::Identifier)) {
5203     Error(S, "shift operator 'asr' or 'lsl' expected");
5204     return MatchOperand_ParseFail;
5205   }
5206   StringRef ShiftName = Tok.getString();
5207   bool isASR;
5208   if (ShiftName == "lsl" || ShiftName == "LSL")
5209     isASR = false;
5210   else if (ShiftName == "asr" || ShiftName == "ASR")
5211     isASR = true;
5212   else {
5213     Error(S, "shift operator 'asr' or 'lsl' expected");
5214     return MatchOperand_ParseFail;
5215   }
5216   Parser.Lex(); // Eat the operator.
5217 
5218   // A '#' and a shift amount.
5219   if (Parser.getTok().isNot(AsmToken::Hash) &&
5220       Parser.getTok().isNot(AsmToken::Dollar)) {
5221     Error(Parser.getTok().getLoc(), "'#' expected");
5222     return MatchOperand_ParseFail;
5223   }
5224   Parser.Lex(); // Eat hash token.
5225   SMLoc ExLoc = Parser.getTok().getLoc();
5226 
5227   const MCExpr *ShiftAmount;
5228   SMLoc EndLoc;
5229   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5230     Error(ExLoc, "malformed shift expression");
5231     return MatchOperand_ParseFail;
5232   }
5233   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5234   if (!CE) {
5235     Error(ExLoc, "shift amount must be an immediate");
5236     return MatchOperand_ParseFail;
5237   }
5238 
5239   int64_t Val = CE->getValue();
5240   if (isASR) {
5241     // Shift amount must be in [1,32]
5242     if (Val < 1 || Val > 32) {
5243       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
5244       return MatchOperand_ParseFail;
5245     }
5246     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
5247     if (isThumb() && Val == 32) {
5248       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
5249       return MatchOperand_ParseFail;
5250     }
5251     if (Val == 32) Val = 0;
5252   } else {
5253     // Shift amount must be in [1,32]
5254     if (Val < 0 || Val > 31) {
5255       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
5256       return MatchOperand_ParseFail;
5257     }
5258   }
5259 
5260   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
5261 
5262   return MatchOperand_Success;
5263 }
5264 
5265 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
5266 /// of instructions. Legal values are:
5267 ///     ror #n  'n' in {0, 8, 16, 24}
5268 OperandMatchResultTy
5269 ARMAsmParser::parseRotImm(OperandVector &Operands) {
5270   MCAsmParser &Parser = getParser();
5271   const AsmToken &Tok = Parser.getTok();
5272   SMLoc S = Tok.getLoc();
5273   if (Tok.isNot(AsmToken::Identifier))
5274     return MatchOperand_NoMatch;
5275   StringRef ShiftName = Tok.getString();
5276   if (ShiftName != "ror" && ShiftName != "ROR")
5277     return MatchOperand_NoMatch;
5278   Parser.Lex(); // Eat the operator.
5279 
5280   // A '#' and a rotate amount.
5281   if (Parser.getTok().isNot(AsmToken::Hash) &&
5282       Parser.getTok().isNot(AsmToken::Dollar)) {
5283     Error(Parser.getTok().getLoc(), "'#' expected");
5284     return MatchOperand_ParseFail;
5285   }
5286   Parser.Lex(); // Eat hash token.
5287   SMLoc ExLoc = Parser.getTok().getLoc();
5288 
5289   const MCExpr *ShiftAmount;
5290   SMLoc EndLoc;
5291   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5292     Error(ExLoc, "malformed rotate expression");
5293     return MatchOperand_ParseFail;
5294   }
5295   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5296   if (!CE) {
5297     Error(ExLoc, "rotate amount must be an immediate");
5298     return MatchOperand_ParseFail;
5299   }
5300 
5301   int64_t Val = CE->getValue();
5302   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
5303   // normally, zero is represented in asm by omitting the rotate operand
5304   // entirely.
5305   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
5306     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
5307     return MatchOperand_ParseFail;
5308   }
5309 
5310   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
5311 
5312   return MatchOperand_Success;
5313 }
5314 
5315 OperandMatchResultTy
5316 ARMAsmParser::parseModImm(OperandVector &Operands) {
5317   MCAsmParser &Parser = getParser();
5318   MCAsmLexer &Lexer = getLexer();
5319   int64_t Imm1, Imm2;
5320 
5321   SMLoc S = Parser.getTok().getLoc();
5322 
5323   // 1) A mod_imm operand can appear in the place of a register name:
5324   //   add r0, #mod_imm
5325   //   add r0, r0, #mod_imm
5326   // to correctly handle the latter, we bail out as soon as we see an
5327   // identifier.
5328   //
5329   // 2) Similarly, we do not want to parse into complex operands:
5330   //   mov r0, #mod_imm
5331   //   mov r0, :lower16:(_foo)
5332   if (Parser.getTok().is(AsmToken::Identifier) ||
5333       Parser.getTok().is(AsmToken::Colon))
5334     return MatchOperand_NoMatch;
5335 
5336   // Hash (dollar) is optional as per the ARMARM
5337   if (Parser.getTok().is(AsmToken::Hash) ||
5338       Parser.getTok().is(AsmToken::Dollar)) {
5339     // Avoid parsing into complex operands (#:)
5340     if (Lexer.peekTok().is(AsmToken::Colon))
5341       return MatchOperand_NoMatch;
5342 
5343     // Eat the hash (dollar)
5344     Parser.Lex();
5345   }
5346 
5347   SMLoc Sx1, Ex1;
5348   Sx1 = Parser.getTok().getLoc();
5349   const MCExpr *Imm1Exp;
5350   if (getParser().parseExpression(Imm1Exp, Ex1)) {
5351     Error(Sx1, "malformed expression");
5352     return MatchOperand_ParseFail;
5353   }
5354 
5355   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
5356 
5357   if (CE) {
5358     // Immediate must fit within 32-bits
5359     Imm1 = CE->getValue();
5360     int Enc = ARM_AM::getSOImmVal(Imm1);
5361     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
5362       // We have a match!
5363       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
5364                                                   (Enc & 0xF00) >> 7,
5365                                                   Sx1, Ex1));
5366       return MatchOperand_Success;
5367     }
5368 
5369     // We have parsed an immediate which is not for us, fallback to a plain
5370     // immediate. This can happen for instruction aliases. For an example,
5371     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
5372     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
5373     // instruction with a mod_imm operand. The alias is defined such that the
5374     // parser method is shared, that's why we have to do this here.
5375     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
5376       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5377       return MatchOperand_Success;
5378     }
5379   } else {
5380     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
5381     // MCFixup). Fallback to a plain immediate.
5382     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5383     return MatchOperand_Success;
5384   }
5385 
5386   // From this point onward, we expect the input to be a (#bits, #rot) pair
5387   if (Parser.getTok().isNot(AsmToken::Comma)) {
5388     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
5389     return MatchOperand_ParseFail;
5390   }
5391 
5392   if (Imm1 & ~0xFF) {
5393     Error(Sx1, "immediate operand must a number in the range [0, 255]");
5394     return MatchOperand_ParseFail;
5395   }
5396 
5397   // Eat the comma
5398   Parser.Lex();
5399 
5400   // Repeat for #rot
5401   SMLoc Sx2, Ex2;
5402   Sx2 = Parser.getTok().getLoc();
5403 
5404   // Eat the optional hash (dollar)
5405   if (Parser.getTok().is(AsmToken::Hash) ||
5406       Parser.getTok().is(AsmToken::Dollar))
5407     Parser.Lex();
5408 
5409   const MCExpr *Imm2Exp;
5410   if (getParser().parseExpression(Imm2Exp, Ex2)) {
5411     Error(Sx2, "malformed expression");
5412     return MatchOperand_ParseFail;
5413   }
5414 
5415   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
5416 
5417   if (CE) {
5418     Imm2 = CE->getValue();
5419     if (!(Imm2 & ~0x1E)) {
5420       // We have a match!
5421       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
5422       return MatchOperand_Success;
5423     }
5424     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
5425     return MatchOperand_ParseFail;
5426   } else {
5427     Error(Sx2, "constant expression expected");
5428     return MatchOperand_ParseFail;
5429   }
5430 }
5431 
5432 OperandMatchResultTy
5433 ARMAsmParser::parseBitfield(OperandVector &Operands) {
5434   MCAsmParser &Parser = getParser();
5435   SMLoc S = Parser.getTok().getLoc();
5436   // The bitfield descriptor is really two operands, the LSB and the width.
5437   if (Parser.getTok().isNot(AsmToken::Hash) &&
5438       Parser.getTok().isNot(AsmToken::Dollar)) {
5439     Error(Parser.getTok().getLoc(), "'#' expected");
5440     return MatchOperand_ParseFail;
5441   }
5442   Parser.Lex(); // Eat hash token.
5443 
5444   const MCExpr *LSBExpr;
5445   SMLoc E = Parser.getTok().getLoc();
5446   if (getParser().parseExpression(LSBExpr)) {
5447     Error(E, "malformed immediate expression");
5448     return MatchOperand_ParseFail;
5449   }
5450   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
5451   if (!CE) {
5452     Error(E, "'lsb' operand must be an immediate");
5453     return MatchOperand_ParseFail;
5454   }
5455 
5456   int64_t LSB = CE->getValue();
5457   // The LSB must be in the range [0,31]
5458   if (LSB < 0 || LSB > 31) {
5459     Error(E, "'lsb' operand must be in the range [0,31]");
5460     return MatchOperand_ParseFail;
5461   }
5462   E = Parser.getTok().getLoc();
5463 
5464   // Expect another immediate operand.
5465   if (Parser.getTok().isNot(AsmToken::Comma)) {
5466     Error(Parser.getTok().getLoc(), "too few operands");
5467     return MatchOperand_ParseFail;
5468   }
5469   Parser.Lex(); // Eat hash token.
5470   if (Parser.getTok().isNot(AsmToken::Hash) &&
5471       Parser.getTok().isNot(AsmToken::Dollar)) {
5472     Error(Parser.getTok().getLoc(), "'#' expected");
5473     return MatchOperand_ParseFail;
5474   }
5475   Parser.Lex(); // Eat hash token.
5476 
5477   const MCExpr *WidthExpr;
5478   SMLoc EndLoc;
5479   if (getParser().parseExpression(WidthExpr, EndLoc)) {
5480     Error(E, "malformed immediate expression");
5481     return MatchOperand_ParseFail;
5482   }
5483   CE = dyn_cast<MCConstantExpr>(WidthExpr);
5484   if (!CE) {
5485     Error(E, "'width' operand must be an immediate");
5486     return MatchOperand_ParseFail;
5487   }
5488 
5489   int64_t Width = CE->getValue();
5490   // The LSB must be in the range [1,32-lsb]
5491   if (Width < 1 || Width > 32 - LSB) {
5492     Error(E, "'width' operand must be in the range [1,32-lsb]");
5493     return MatchOperand_ParseFail;
5494   }
5495 
5496   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
5497 
5498   return MatchOperand_Success;
5499 }
5500 
5501 OperandMatchResultTy
5502 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
5503   // Check for a post-index addressing register operand. Specifically:
5504   // postidx_reg := '+' register {, shift}
5505   //              | '-' register {, shift}
5506   //              | register {, shift}
5507 
5508   // This method must return MatchOperand_NoMatch without consuming any tokens
5509   // in the case where there is no match, as other alternatives take other
5510   // parse methods.
5511   MCAsmParser &Parser = getParser();
5512   AsmToken Tok = Parser.getTok();
5513   SMLoc S = Tok.getLoc();
5514   bool haveEaten = false;
5515   bool isAdd = true;
5516   if (Tok.is(AsmToken::Plus)) {
5517     Parser.Lex(); // Eat the '+' token.
5518     haveEaten = true;
5519   } else if (Tok.is(AsmToken::Minus)) {
5520     Parser.Lex(); // Eat the '-' token.
5521     isAdd = false;
5522     haveEaten = true;
5523   }
5524 
5525   SMLoc E = Parser.getTok().getEndLoc();
5526   int Reg = tryParseRegister();
5527   if (Reg == -1) {
5528     if (!haveEaten)
5529       return MatchOperand_NoMatch;
5530     Error(Parser.getTok().getLoc(), "register expected");
5531     return MatchOperand_ParseFail;
5532   }
5533 
5534   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
5535   unsigned ShiftImm = 0;
5536   if (Parser.getTok().is(AsmToken::Comma)) {
5537     Parser.Lex(); // Eat the ','.
5538     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
5539       return MatchOperand_ParseFail;
5540 
5541     // FIXME: Only approximates end...may include intervening whitespace.
5542     E = Parser.getTok().getLoc();
5543   }
5544 
5545   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
5546                                                   ShiftImm, S, E));
5547 
5548   return MatchOperand_Success;
5549 }
5550 
5551 OperandMatchResultTy
5552 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
5553   // Check for a post-index addressing register operand. Specifically:
5554   // am3offset := '+' register
5555   //              | '-' register
5556   //              | register
5557   //              | # imm
5558   //              | # + imm
5559   //              | # - imm
5560 
5561   // This method must return MatchOperand_NoMatch without consuming any tokens
5562   // in the case where there is no match, as other alternatives take other
5563   // parse methods.
5564   MCAsmParser &Parser = getParser();
5565   AsmToken Tok = Parser.getTok();
5566   SMLoc S = Tok.getLoc();
5567 
5568   // Do immediates first, as we always parse those if we have a '#'.
5569   if (Parser.getTok().is(AsmToken::Hash) ||
5570       Parser.getTok().is(AsmToken::Dollar)) {
5571     Parser.Lex(); // Eat '#' or '$'.
5572     // Explicitly look for a '-', as we need to encode negative zero
5573     // differently.
5574     bool isNegative = Parser.getTok().is(AsmToken::Minus);
5575     const MCExpr *Offset;
5576     SMLoc E;
5577     if (getParser().parseExpression(Offset, E))
5578       return MatchOperand_ParseFail;
5579     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5580     if (!CE) {
5581       Error(S, "constant expression expected");
5582       return MatchOperand_ParseFail;
5583     }
5584     // Negative zero is encoded as the flag value
5585     // std::numeric_limits<int32_t>::min().
5586     int32_t Val = CE->getValue();
5587     if (isNegative && Val == 0)
5588       Val = std::numeric_limits<int32_t>::min();
5589 
5590     Operands.push_back(
5591       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
5592 
5593     return MatchOperand_Success;
5594   }
5595 
5596   bool haveEaten = false;
5597   bool isAdd = true;
5598   if (Tok.is(AsmToken::Plus)) {
5599     Parser.Lex(); // Eat the '+' token.
5600     haveEaten = true;
5601   } else if (Tok.is(AsmToken::Minus)) {
5602     Parser.Lex(); // Eat the '-' token.
5603     isAdd = false;
5604     haveEaten = true;
5605   }
5606 
5607   Tok = Parser.getTok();
5608   int Reg = tryParseRegister();
5609   if (Reg == -1) {
5610     if (!haveEaten)
5611       return MatchOperand_NoMatch;
5612     Error(Tok.getLoc(), "register expected");
5613     return MatchOperand_ParseFail;
5614   }
5615 
5616   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
5617                                                   0, S, Tok.getEndLoc()));
5618 
5619   return MatchOperand_Success;
5620 }
5621 
5622 /// Convert parsed operands to MCInst.  Needed here because this instruction
5623 /// only has two register operands, but multiplication is commutative so
5624 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
5625 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
5626                                     const OperandVector &Operands) {
5627   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
5628   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
5629   // If we have a three-operand form, make sure to set Rn to be the operand
5630   // that isn't the same as Rd.
5631   unsigned RegOp = 4;
5632   if (Operands.size() == 6 &&
5633       ((ARMOperand &)*Operands[4]).getReg() ==
5634           ((ARMOperand &)*Operands[3]).getReg())
5635     RegOp = 5;
5636   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
5637   Inst.addOperand(Inst.getOperand(0));
5638   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
5639 }
5640 
5641 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
5642                                     const OperandVector &Operands) {
5643   int CondOp = -1, ImmOp = -1;
5644   switch(Inst.getOpcode()) {
5645     case ARM::tB:
5646     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
5647 
5648     case ARM::t2B:
5649     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
5650 
5651     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
5652   }
5653   // first decide whether or not the branch should be conditional
5654   // by looking at it's location relative to an IT block
5655   if(inITBlock()) {
5656     // inside an IT block we cannot have any conditional branches. any
5657     // such instructions needs to be converted to unconditional form
5658     switch(Inst.getOpcode()) {
5659       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
5660       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
5661     }
5662   } else {
5663     // outside IT blocks we can only have unconditional branches with AL
5664     // condition code or conditional branches with non-AL condition code
5665     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
5666     switch(Inst.getOpcode()) {
5667       case ARM::tB:
5668       case ARM::tBcc:
5669         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
5670         break;
5671       case ARM::t2B:
5672       case ARM::t2Bcc:
5673         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
5674         break;
5675     }
5676   }
5677 
5678   // now decide on encoding size based on branch target range
5679   switch(Inst.getOpcode()) {
5680     // classify tB as either t2B or t1B based on range of immediate operand
5681     case ARM::tB: {
5682       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5683       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
5684         Inst.setOpcode(ARM::t2B);
5685       break;
5686     }
5687     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
5688     case ARM::tBcc: {
5689       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5690       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
5691         Inst.setOpcode(ARM::t2Bcc);
5692       break;
5693     }
5694   }
5695   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
5696   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
5697 }
5698 
5699 void ARMAsmParser::cvtMVEVMOVQtoDReg(
5700   MCInst &Inst, const OperandVector &Operands) {
5701 
5702   // mnemonic, condition code, Rt, Rt2, Qd, idx, Qd again, idx2
5703   assert(Operands.size() == 8);
5704 
5705   ((ARMOperand &)*Operands[2]).addRegOperands(Inst, 1); // Rt
5706   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1); // Rt2
5707   ((ARMOperand &)*Operands[4]).addRegOperands(Inst, 1); // Qd
5708   ((ARMOperand &)*Operands[5]).addMVEPairVectorIndexOperands(Inst, 1); // idx
5709   // skip second copy of Qd in Operands[6]
5710   ((ARMOperand &)*Operands[7]).addMVEPairVectorIndexOperands(Inst, 1); // idx2
5711   ((ARMOperand &)*Operands[1]).addCondCodeOperands(Inst, 2); // condition code
5712 }
5713 
5714 /// Parse an ARM memory expression, return false if successful else return true
5715 /// or an error.  The first token must be a '[' when called.
5716 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
5717   MCAsmParser &Parser = getParser();
5718   SMLoc S, E;
5719   if (Parser.getTok().isNot(AsmToken::LBrac))
5720     return TokError("Token is not a Left Bracket");
5721   S = Parser.getTok().getLoc();
5722   Parser.Lex(); // Eat left bracket token.
5723 
5724   const AsmToken &BaseRegTok = Parser.getTok();
5725   int BaseRegNum = tryParseRegister();
5726   if (BaseRegNum == -1)
5727     return Error(BaseRegTok.getLoc(), "register expected");
5728 
5729   // The next token must either be a comma, a colon or a closing bracket.
5730   const AsmToken &Tok = Parser.getTok();
5731   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
5732       !Tok.is(AsmToken::RBrac))
5733     return Error(Tok.getLoc(), "malformed memory operand");
5734 
5735   if (Tok.is(AsmToken::RBrac)) {
5736     E = Tok.getEndLoc();
5737     Parser.Lex(); // Eat right bracket token.
5738 
5739     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5740                                              ARM_AM::no_shift, 0, 0, false,
5741                                              S, E));
5742 
5743     // If there's a pre-indexing writeback marker, '!', just add it as a token
5744     // operand. It's rather odd, but syntactically valid.
5745     if (Parser.getTok().is(AsmToken::Exclaim)) {
5746       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5747       Parser.Lex(); // Eat the '!'.
5748     }
5749 
5750     return false;
5751   }
5752 
5753   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
5754          "Lost colon or comma in memory operand?!");
5755   if (Tok.is(AsmToken::Comma)) {
5756     Parser.Lex(); // Eat the comma.
5757   }
5758 
5759   // If we have a ':', it's an alignment specifier.
5760   if (Parser.getTok().is(AsmToken::Colon)) {
5761     Parser.Lex(); // Eat the ':'.
5762     E = Parser.getTok().getLoc();
5763     SMLoc AlignmentLoc = Tok.getLoc();
5764 
5765     const MCExpr *Expr;
5766     if (getParser().parseExpression(Expr))
5767      return true;
5768 
5769     // The expression has to be a constant. Memory references with relocations
5770     // don't come through here, as they use the <label> forms of the relevant
5771     // instructions.
5772     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5773     if (!CE)
5774       return Error (E, "constant expression expected");
5775 
5776     unsigned Align = 0;
5777     switch (CE->getValue()) {
5778     default:
5779       return Error(E,
5780                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
5781     case 16:  Align = 2; break;
5782     case 32:  Align = 4; break;
5783     case 64:  Align = 8; break;
5784     case 128: Align = 16; break;
5785     case 256: Align = 32; break;
5786     }
5787 
5788     // Now we should have the closing ']'
5789     if (Parser.getTok().isNot(AsmToken::RBrac))
5790       return Error(Parser.getTok().getLoc(), "']' expected");
5791     E = Parser.getTok().getEndLoc();
5792     Parser.Lex(); // Eat right bracket token.
5793 
5794     // Don't worry about range checking the value here. That's handled by
5795     // the is*() predicates.
5796     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5797                                              ARM_AM::no_shift, 0, Align,
5798                                              false, S, E, AlignmentLoc));
5799 
5800     // If there's a pre-indexing writeback marker, '!', just add it as a token
5801     // operand.
5802     if (Parser.getTok().is(AsmToken::Exclaim)) {
5803       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5804       Parser.Lex(); // Eat the '!'.
5805     }
5806 
5807     return false;
5808   }
5809 
5810   // If we have a '#' or '$', it's an immediate offset, else assume it's a
5811   // register offset. Be friendly and also accept a plain integer or expression
5812   // (without a leading hash) for gas compatibility.
5813   if (Parser.getTok().is(AsmToken::Hash) ||
5814       Parser.getTok().is(AsmToken::Dollar) ||
5815       Parser.getTok().is(AsmToken::LParen) ||
5816       Parser.getTok().is(AsmToken::Integer)) {
5817     if (Parser.getTok().is(AsmToken::Hash) ||
5818         Parser.getTok().is(AsmToken::Dollar))
5819       Parser.Lex(); // Eat '#' or '$'
5820     E = Parser.getTok().getLoc();
5821 
5822     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5823     const MCExpr *Offset;
5824     if (getParser().parseExpression(Offset))
5825      return true;
5826 
5827     // The expression has to be a constant. Memory references with relocations
5828     // don't come through here, as they use the <label> forms of the relevant
5829     // instructions.
5830     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5831     if (!CE)
5832       return Error (E, "constant expression expected");
5833 
5834     // If the constant was #-0, represent it as
5835     // std::numeric_limits<int32_t>::min().
5836     int32_t Val = CE->getValue();
5837     if (isNegative && Val == 0)
5838       CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5839                                   getContext());
5840 
5841     // Now we should have the closing ']'
5842     if (Parser.getTok().isNot(AsmToken::RBrac))
5843       return Error(Parser.getTok().getLoc(), "']' expected");
5844     E = Parser.getTok().getEndLoc();
5845     Parser.Lex(); // Eat right bracket token.
5846 
5847     // Don't worry about range checking the value here. That's handled by
5848     // the is*() predicates.
5849     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5850                                              ARM_AM::no_shift, 0, 0,
5851                                              false, S, E));
5852 
5853     // If there's a pre-indexing writeback marker, '!', just add it as a token
5854     // operand.
5855     if (Parser.getTok().is(AsmToken::Exclaim)) {
5856       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5857       Parser.Lex(); // Eat the '!'.
5858     }
5859 
5860     return false;
5861   }
5862 
5863   // The register offset is optionally preceded by a '+' or '-'
5864   bool isNegative = false;
5865   if (Parser.getTok().is(AsmToken::Minus)) {
5866     isNegative = true;
5867     Parser.Lex(); // Eat the '-'.
5868   } else if (Parser.getTok().is(AsmToken::Plus)) {
5869     // Nothing to do.
5870     Parser.Lex(); // Eat the '+'.
5871   }
5872 
5873   E = Parser.getTok().getLoc();
5874   int OffsetRegNum = tryParseRegister();
5875   if (OffsetRegNum == -1)
5876     return Error(E, "register expected");
5877 
5878   // If there's a shift operator, handle it.
5879   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5880   unsigned ShiftImm = 0;
5881   if (Parser.getTok().is(AsmToken::Comma)) {
5882     Parser.Lex(); // Eat the ','.
5883     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5884       return true;
5885   }
5886 
5887   // Now we should have the closing ']'
5888   if (Parser.getTok().isNot(AsmToken::RBrac))
5889     return Error(Parser.getTok().getLoc(), "']' expected");
5890   E = Parser.getTok().getEndLoc();
5891   Parser.Lex(); // Eat right bracket token.
5892 
5893   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5894                                            ShiftType, ShiftImm, 0, isNegative,
5895                                            S, E));
5896 
5897   // If there's a pre-indexing writeback marker, '!', just add it as a token
5898   // operand.
5899   if (Parser.getTok().is(AsmToken::Exclaim)) {
5900     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5901     Parser.Lex(); // Eat the '!'.
5902   }
5903 
5904   return false;
5905 }
5906 
5907 /// parseMemRegOffsetShift - one of these two:
5908 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5909 ///   rrx
5910 /// return true if it parses a shift otherwise it returns false.
5911 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5912                                           unsigned &Amount) {
5913   MCAsmParser &Parser = getParser();
5914   SMLoc Loc = Parser.getTok().getLoc();
5915   const AsmToken &Tok = Parser.getTok();
5916   if (Tok.isNot(AsmToken::Identifier))
5917     return Error(Loc, "illegal shift operator");
5918   StringRef ShiftName = Tok.getString();
5919   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5920       ShiftName == "asl" || ShiftName == "ASL")
5921     St = ARM_AM::lsl;
5922   else if (ShiftName == "lsr" || ShiftName == "LSR")
5923     St = ARM_AM::lsr;
5924   else if (ShiftName == "asr" || ShiftName == "ASR")
5925     St = ARM_AM::asr;
5926   else if (ShiftName == "ror" || ShiftName == "ROR")
5927     St = ARM_AM::ror;
5928   else if (ShiftName == "rrx" || ShiftName == "RRX")
5929     St = ARM_AM::rrx;
5930   else if (ShiftName == "uxtw" || ShiftName == "UXTW")
5931     St = ARM_AM::uxtw;
5932   else
5933     return Error(Loc, "illegal shift operator");
5934   Parser.Lex(); // Eat shift type token.
5935 
5936   // rrx stands alone.
5937   Amount = 0;
5938   if (St != ARM_AM::rrx) {
5939     Loc = Parser.getTok().getLoc();
5940     // A '#' and a shift amount.
5941     const AsmToken &HashTok = Parser.getTok();
5942     if (HashTok.isNot(AsmToken::Hash) &&
5943         HashTok.isNot(AsmToken::Dollar))
5944       return Error(HashTok.getLoc(), "'#' expected");
5945     Parser.Lex(); // Eat hash token.
5946 
5947     const MCExpr *Expr;
5948     if (getParser().parseExpression(Expr))
5949       return true;
5950     // Range check the immediate.
5951     // lsl, ror: 0 <= imm <= 31
5952     // lsr, asr: 0 <= imm <= 32
5953     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5954     if (!CE)
5955       return Error(Loc, "shift amount must be an immediate");
5956     int64_t Imm = CE->getValue();
5957     if (Imm < 0 ||
5958         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5959         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5960       return Error(Loc, "immediate shift value out of range");
5961     // If <ShiftTy> #0, turn it into a no_shift.
5962     if (Imm == 0)
5963       St = ARM_AM::lsl;
5964     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5965     if (Imm == 32)
5966       Imm = 0;
5967     Amount = Imm;
5968   }
5969 
5970   return false;
5971 }
5972 
5973 /// parseFPImm - A floating point immediate expression operand.
5974 OperandMatchResultTy
5975 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5976   MCAsmParser &Parser = getParser();
5977   // Anything that can accept a floating point constant as an operand
5978   // needs to go through here, as the regular parseExpression is
5979   // integer only.
5980   //
5981   // This routine still creates a generic Immediate operand, containing
5982   // a bitcast of the 64-bit floating point value. The various operands
5983   // that accept floats can check whether the value is valid for them
5984   // via the standard is*() predicates.
5985 
5986   SMLoc S = Parser.getTok().getLoc();
5987 
5988   if (Parser.getTok().isNot(AsmToken::Hash) &&
5989       Parser.getTok().isNot(AsmToken::Dollar))
5990     return MatchOperand_NoMatch;
5991 
5992   // Disambiguate the VMOV forms that can accept an FP immediate.
5993   // vmov.f32 <sreg>, #imm
5994   // vmov.f64 <dreg>, #imm
5995   // vmov.f32 <dreg>, #imm  @ vector f32x2
5996   // vmov.f32 <qreg>, #imm  @ vector f32x4
5997   //
5998   // There are also the NEON VMOV instructions which expect an
5999   // integer constant. Make sure we don't try to parse an FPImm
6000   // for these:
6001   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
6002   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
6003   bool isVmovf = TyOp.isToken() &&
6004                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
6005                   TyOp.getToken() == ".f16");
6006   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
6007   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
6008                                          Mnemonic.getToken() == "fconsts");
6009   if (!(isVmovf || isFconst))
6010     return MatchOperand_NoMatch;
6011 
6012   Parser.Lex(); // Eat '#' or '$'.
6013 
6014   // Handle negation, as that still comes through as a separate token.
6015   bool isNegative = false;
6016   if (Parser.getTok().is(AsmToken::Minus)) {
6017     isNegative = true;
6018     Parser.Lex();
6019   }
6020   const AsmToken &Tok = Parser.getTok();
6021   SMLoc Loc = Tok.getLoc();
6022   if (Tok.is(AsmToken::Real) && isVmovf) {
6023     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
6024     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
6025     // If we had a '-' in front, toggle the sign bit.
6026     IntVal ^= (uint64_t)isNegative << 31;
6027     Parser.Lex(); // Eat the token.
6028     Operands.push_back(ARMOperand::CreateImm(
6029           MCConstantExpr::create(IntVal, getContext()),
6030           S, Parser.getTok().getLoc()));
6031     return MatchOperand_Success;
6032   }
6033   // Also handle plain integers. Instructions which allow floating point
6034   // immediates also allow a raw encoded 8-bit value.
6035   if (Tok.is(AsmToken::Integer) && isFconst) {
6036     int64_t Val = Tok.getIntVal();
6037     Parser.Lex(); // Eat the token.
6038     if (Val > 255 || Val < 0) {
6039       Error(Loc, "encoded floating point value out of range");
6040       return MatchOperand_ParseFail;
6041     }
6042     float RealVal = ARM_AM::getFPImmFloat(Val);
6043     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
6044 
6045     Operands.push_back(ARMOperand::CreateImm(
6046         MCConstantExpr::create(Val, getContext()), S,
6047         Parser.getTok().getLoc()));
6048     return MatchOperand_Success;
6049   }
6050 
6051   Error(Loc, "invalid floating point immediate");
6052   return MatchOperand_ParseFail;
6053 }
6054 
6055 /// Parse a arm instruction operand.  For now this parses the operand regardless
6056 /// of the mnemonic.
6057 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
6058   MCAsmParser &Parser = getParser();
6059   SMLoc S, E;
6060 
6061   // Check if the current operand has a custom associated parser, if so, try to
6062   // custom parse the operand, or fallback to the general approach.
6063   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
6064   if (ResTy == MatchOperand_Success)
6065     return false;
6066   // If there wasn't a custom match, try the generic matcher below. Otherwise,
6067   // there was a match, but an error occurred, in which case, just return that
6068   // the operand parsing failed.
6069   if (ResTy == MatchOperand_ParseFail)
6070     return true;
6071 
6072   switch (getLexer().getKind()) {
6073   default:
6074     Error(Parser.getTok().getLoc(), "unexpected token in operand");
6075     return true;
6076   case AsmToken::Identifier: {
6077     // If we've seen a branch mnemonic, the next operand must be a label.  This
6078     // is true even if the label is a register name.  So "br r1" means branch to
6079     // label "r1".
6080     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
6081     if (!ExpectLabel) {
6082       if (!tryParseRegisterWithWriteBack(Operands))
6083         return false;
6084       int Res = tryParseShiftRegister(Operands);
6085       if (Res == 0) // success
6086         return false;
6087       else if (Res == -1) // irrecoverable error
6088         return true;
6089       // If this is VMRS, check for the apsr_nzcv operand.
6090       if (Mnemonic == "vmrs" &&
6091           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
6092         S = Parser.getTok().getLoc();
6093         Parser.Lex();
6094         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
6095         return false;
6096       }
6097     }
6098 
6099     // Fall though for the Identifier case that is not a register or a
6100     // special name.
6101     LLVM_FALLTHROUGH;
6102   }
6103   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
6104   case AsmToken::Integer: // things like 1f and 2b as a branch targets
6105   case AsmToken::String:  // quoted label names.
6106   case AsmToken::Dot: {   // . as a branch target
6107     // This was not a register so parse other operands that start with an
6108     // identifier (like labels) as expressions and create them as immediates.
6109     const MCExpr *IdVal;
6110     S = Parser.getTok().getLoc();
6111     if (getParser().parseExpression(IdVal))
6112       return true;
6113     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6114     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
6115     return false;
6116   }
6117   case AsmToken::LBrac:
6118     return parseMemory(Operands);
6119   case AsmToken::LCurly:
6120     return parseRegisterList(Operands, !Mnemonic.startswith("clr"));
6121   case AsmToken::Dollar:
6122   case AsmToken::Hash:
6123     // #42 -> immediate.
6124     S = Parser.getTok().getLoc();
6125     Parser.Lex();
6126 
6127     if (Parser.getTok().isNot(AsmToken::Colon)) {
6128       bool isNegative = Parser.getTok().is(AsmToken::Minus);
6129       const MCExpr *ImmVal;
6130       if (getParser().parseExpression(ImmVal))
6131         return true;
6132       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
6133       if (CE) {
6134         int32_t Val = CE->getValue();
6135         if (isNegative && Val == 0)
6136           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
6137                                           getContext());
6138       }
6139       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6140       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
6141 
6142       // There can be a trailing '!' on operands that we want as a separate
6143       // '!' Token operand. Handle that here. For example, the compatibility
6144       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
6145       if (Parser.getTok().is(AsmToken::Exclaim)) {
6146         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
6147                                                    Parser.getTok().getLoc()));
6148         Parser.Lex(); // Eat exclaim token
6149       }
6150       return false;
6151     }
6152     // w/ a ':' after the '#', it's just like a plain ':'.
6153     LLVM_FALLTHROUGH;
6154 
6155   case AsmToken::Colon: {
6156     S = Parser.getTok().getLoc();
6157     // ":lower16:" and ":upper16:" expression prefixes
6158     // FIXME: Check it's an expression prefix,
6159     // e.g. (FOO - :lower16:BAR) isn't legal.
6160     ARMMCExpr::VariantKind RefKind;
6161     if (parsePrefix(RefKind))
6162       return true;
6163 
6164     const MCExpr *SubExprVal;
6165     if (getParser().parseExpression(SubExprVal))
6166       return true;
6167 
6168     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
6169                                               getContext());
6170     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6171     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
6172     return false;
6173   }
6174   case AsmToken::Equal: {
6175     S = Parser.getTok().getLoc();
6176     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
6177       return Error(S, "unexpected token in operand");
6178     Parser.Lex(); // Eat '='
6179     const MCExpr *SubExprVal;
6180     if (getParser().parseExpression(SubExprVal))
6181       return true;
6182     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6183 
6184     // execute-only: we assume that assembly programmers know what they are
6185     // doing and allow literal pool creation here
6186     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
6187     return false;
6188   }
6189   }
6190 }
6191 
6192 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
6193 //  :lower16: and :upper16:.
6194 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
6195   MCAsmParser &Parser = getParser();
6196   RefKind = ARMMCExpr::VK_ARM_None;
6197 
6198   // consume an optional '#' (GNU compatibility)
6199   if (getLexer().is(AsmToken::Hash))
6200     Parser.Lex();
6201 
6202   // :lower16: and :upper16: modifiers
6203   assert(getLexer().is(AsmToken::Colon) && "expected a :");
6204   Parser.Lex(); // Eat ':'
6205 
6206   if (getLexer().isNot(AsmToken::Identifier)) {
6207     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
6208     return true;
6209   }
6210 
6211   enum {
6212     COFF = (1 << MCObjectFileInfo::IsCOFF),
6213     ELF = (1 << MCObjectFileInfo::IsELF),
6214     MACHO = (1 << MCObjectFileInfo::IsMachO),
6215     WASM = (1 << MCObjectFileInfo::IsWasm),
6216   };
6217   static const struct PrefixEntry {
6218     const char *Spelling;
6219     ARMMCExpr::VariantKind VariantKind;
6220     uint8_t SupportedFormats;
6221   } PrefixEntries[] = {
6222     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
6223     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
6224   };
6225 
6226   StringRef IDVal = Parser.getTok().getIdentifier();
6227 
6228   const auto &Prefix =
6229       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
6230                    [&IDVal](const PrefixEntry &PE) {
6231                       return PE.Spelling == IDVal;
6232                    });
6233   if (Prefix == std::end(PrefixEntries)) {
6234     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
6235     return true;
6236   }
6237 
6238   uint8_t CurrentFormat;
6239   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
6240   case MCObjectFileInfo::IsMachO:
6241     CurrentFormat = MACHO;
6242     break;
6243   case MCObjectFileInfo::IsELF:
6244     CurrentFormat = ELF;
6245     break;
6246   case MCObjectFileInfo::IsCOFF:
6247     CurrentFormat = COFF;
6248     break;
6249   case MCObjectFileInfo::IsWasm:
6250     CurrentFormat = WASM;
6251     break;
6252   case MCObjectFileInfo::IsXCOFF:
6253     llvm_unreachable("unexpected object format");
6254     break;
6255   }
6256 
6257   if (~Prefix->SupportedFormats & CurrentFormat) {
6258     Error(Parser.getTok().getLoc(),
6259           "cannot represent relocation in the current file format");
6260     return true;
6261   }
6262 
6263   RefKind = Prefix->VariantKind;
6264   Parser.Lex();
6265 
6266   if (getLexer().isNot(AsmToken::Colon)) {
6267     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
6268     return true;
6269   }
6270   Parser.Lex(); // Eat the last ':'
6271 
6272   return false;
6273 }
6274 
6275 /// Given a mnemonic, split out possible predication code and carry
6276 /// setting letters to form a canonical mnemonic and flags.
6277 //
6278 // FIXME: Would be nice to autogen this.
6279 // FIXME: This is a bit of a maze of special cases.
6280 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
6281                                       StringRef ExtraToken,
6282                                       unsigned &PredicationCode,
6283                                       unsigned &VPTPredicationCode,
6284                                       bool &CarrySetting,
6285                                       unsigned &ProcessorIMod,
6286                                       StringRef &ITMask) {
6287   PredicationCode = ARMCC::AL;
6288   VPTPredicationCode = ARMVCC::None;
6289   CarrySetting = false;
6290   ProcessorIMod = 0;
6291 
6292   // Ignore some mnemonics we know aren't predicated forms.
6293   //
6294   // FIXME: Would be nice to autogen this.
6295   if ((Mnemonic == "movs" && isThumb()) ||
6296       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
6297       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
6298       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
6299       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
6300       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
6301       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
6302       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
6303       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
6304       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
6305       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
6306       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
6307       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
6308       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
6309       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
6310       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6311       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6312       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6313       Mnemonic == "wls" || Mnemonic == "le" || Mnemonic == "dls" ||
6314       Mnemonic == "csel" || Mnemonic == "csinc" ||
6315       Mnemonic == "csinv" || Mnemonic == "csneg" || Mnemonic == "cinc" ||
6316       Mnemonic == "cinv" || Mnemonic == "cneg" || Mnemonic == "cset" ||
6317       Mnemonic == "csetm")
6318     return Mnemonic;
6319 
6320   // First, split out any predication code. Ignore mnemonics we know aren't
6321   // predicated but do have a carry-set and so weren't caught above.
6322   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
6323       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
6324       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
6325       Mnemonic != "sbcs" && Mnemonic != "rscs" &&
6326       !(hasMVE() &&
6327         (Mnemonic == "vmine" ||
6328          Mnemonic == "vshle" || Mnemonic == "vshlt" || Mnemonic == "vshllt" ||
6329          Mnemonic == "vrshle" || Mnemonic == "vrshlt" ||
6330          Mnemonic == "vmvne" || Mnemonic == "vorne" ||
6331          Mnemonic == "vnege" || Mnemonic == "vnegt" ||
6332          Mnemonic == "vmule" || Mnemonic == "vmult" ||
6333          Mnemonic == "vrintne" ||
6334          Mnemonic == "vcmult" || Mnemonic == "vcmule" ||
6335          Mnemonic == "vpsele" || Mnemonic == "vpselt" ||
6336          Mnemonic.startswith("vq")))) {
6337     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
6338     if (CC != ~0U) {
6339       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
6340       PredicationCode = CC;
6341     }
6342   }
6343 
6344   // Next, determine if we have a carry setting bit. We explicitly ignore all
6345   // the instructions we know end in 's'.
6346   if (Mnemonic.endswith("s") &&
6347       !(Mnemonic == "cps" || Mnemonic == "mls" ||
6348         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
6349         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
6350         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
6351         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
6352         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
6353         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
6354         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
6355         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
6356         Mnemonic == "bxns" || Mnemonic == "blxns" || Mnemonic == "vfmas" ||
6357         Mnemonic == "vmlas" ||
6358         (Mnemonic == "movs" && isThumb()))) {
6359     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
6360     CarrySetting = true;
6361   }
6362 
6363   // The "cps" instruction can have a interrupt mode operand which is glued into
6364   // the mnemonic. Check if this is the case, split it and parse the imod op
6365   if (Mnemonic.startswith("cps")) {
6366     // Split out any imod code.
6367     unsigned IMod =
6368       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
6369       .Case("ie", ARM_PROC::IE)
6370       .Case("id", ARM_PROC::ID)
6371       .Default(~0U);
6372     if (IMod != ~0U) {
6373       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
6374       ProcessorIMod = IMod;
6375     }
6376   }
6377 
6378   if (isMnemonicVPTPredicable(Mnemonic, ExtraToken) && Mnemonic != "vmovlt" &&
6379       Mnemonic != "vshllt" && Mnemonic != "vrshrnt" && Mnemonic != "vshrnt" &&
6380       Mnemonic != "vqrshrunt" && Mnemonic != "vqshrunt" &&
6381       Mnemonic != "vqrshrnt" && Mnemonic != "vqshrnt" && Mnemonic != "vmullt" &&
6382       Mnemonic != "vqmovnt" && Mnemonic != "vqmovunt" &&
6383       Mnemonic != "vqmovnt" && Mnemonic != "vmovnt" && Mnemonic != "vqdmullt" &&
6384       Mnemonic != "vpnot" && Mnemonic != "vcvtt" && Mnemonic != "vcvt") {
6385     unsigned CC = ARMVectorCondCodeFromString(Mnemonic.substr(Mnemonic.size()-1));
6386     if (CC != ~0U) {
6387       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-1);
6388       VPTPredicationCode = CC;
6389     }
6390     return Mnemonic;
6391   }
6392 
6393   // The "it" instruction has the condition mask on the end of the mnemonic.
6394   if (Mnemonic.startswith("it")) {
6395     ITMask = Mnemonic.slice(2, Mnemonic.size());
6396     Mnemonic = Mnemonic.slice(0, 2);
6397   }
6398 
6399   if (Mnemonic.startswith("vpst")) {
6400     ITMask = Mnemonic.slice(4, Mnemonic.size());
6401     Mnemonic = Mnemonic.slice(0, 4);
6402   }
6403   else if (Mnemonic.startswith("vpt")) {
6404     ITMask = Mnemonic.slice(3, Mnemonic.size());
6405     Mnemonic = Mnemonic.slice(0, 3);
6406   }
6407 
6408   return Mnemonic;
6409 }
6410 
6411 /// Given a canonical mnemonic, determine if the instruction ever allows
6412 /// inclusion of carry set or predication code operands.
6413 //
6414 // FIXME: It would be nice to autogen this.
6415 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic,
6416                                          StringRef ExtraToken,
6417                                          StringRef FullInst,
6418                                          bool &CanAcceptCarrySet,
6419                                          bool &CanAcceptPredicationCode,
6420                                          bool &CanAcceptVPTPredicationCode) {
6421   CanAcceptVPTPredicationCode = isMnemonicVPTPredicable(Mnemonic, ExtraToken);
6422 
6423   CanAcceptCarrySet =
6424       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6425       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
6426       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
6427       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
6428       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
6429       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
6430       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
6431       (!isThumb() &&
6432        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
6433         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
6434 
6435   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
6436       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
6437       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
6438       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
6439       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
6440       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
6441       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
6442       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
6443       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
6444       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
6445       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
6446       Mnemonic == "vmovx" || Mnemonic == "vins" ||
6447       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6448       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6449       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6450       Mnemonic == "sb"    || Mnemonic == "ssbb"  ||
6451       Mnemonic == "pssbb" ||
6452       Mnemonic == "bfcsel" || Mnemonic == "wls" ||
6453       Mnemonic == "dls" || Mnemonic == "le" || Mnemonic == "csel" ||
6454       Mnemonic == "csinc" || Mnemonic == "csinv" || Mnemonic == "csneg" ||
6455       Mnemonic == "cinc" || Mnemonic == "cinv" || Mnemonic == "cneg" ||
6456       Mnemonic == "cset" || Mnemonic == "csetm" ||
6457       Mnemonic.startswith("vpt") || Mnemonic.startswith("vpst") ||
6458       (hasCDE() && MS.isCDEInstr(Mnemonic) &&
6459        !MS.isITPredicableCDEInstr(Mnemonic)) ||
6460       (hasMVE() &&
6461        (Mnemonic.startswith("vst2") || Mnemonic.startswith("vld2") ||
6462         Mnemonic.startswith("vst4") || Mnemonic.startswith("vld4") ||
6463         Mnemonic.startswith("wlstp") || Mnemonic.startswith("dlstp") ||
6464         Mnemonic.startswith("letp")))) {
6465     // These mnemonics are never predicable
6466     CanAcceptPredicationCode = false;
6467   } else if (!isThumb()) {
6468     // Some instructions are only predicable in Thumb mode
6469     CanAcceptPredicationCode =
6470         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
6471         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
6472         Mnemonic != "dmb" && Mnemonic != "dfb" && Mnemonic != "dsb" &&
6473         Mnemonic != "isb" && Mnemonic != "pld" && Mnemonic != "pli" &&
6474         Mnemonic != "pldw" && Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
6475         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
6476         Mnemonic != "tsb" &&
6477         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
6478   } else if (isThumbOne()) {
6479     if (hasV6MOps())
6480       CanAcceptPredicationCode = Mnemonic != "movs";
6481     else
6482       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
6483   } else
6484     CanAcceptPredicationCode = true;
6485 }
6486 
6487 // Some Thumb instructions have two operand forms that are not
6488 // available as three operand, convert to two operand form if possible.
6489 //
6490 // FIXME: We would really like to be able to tablegen'erate this.
6491 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
6492                                                  bool CarrySetting,
6493                                                  OperandVector &Operands) {
6494   if (Operands.size() != 6)
6495     return;
6496 
6497   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6498         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
6499   if (!Op3.isReg() || !Op4.isReg())
6500     return;
6501 
6502   auto Op3Reg = Op3.getReg();
6503   auto Op4Reg = Op4.getReg();
6504 
6505   // For most Thumb2 cases we just generate the 3 operand form and reduce
6506   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
6507   // won't accept SP or PC so we do the transformation here taking care
6508   // with immediate range in the 'add sp, sp #imm' case.
6509   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
6510   if (isThumbTwo()) {
6511     if (Mnemonic != "add")
6512       return;
6513     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
6514                         (Op5.isReg() && Op5.getReg() == ARM::PC);
6515     if (!TryTransform) {
6516       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
6517                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
6518                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
6519                        Op5.isImm() && !Op5.isImm0_508s4());
6520     }
6521     if (!TryTransform)
6522       return;
6523   } else if (!isThumbOne())
6524     return;
6525 
6526   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
6527         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6528         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
6529         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
6530     return;
6531 
6532   // If first 2 operands of a 3 operand instruction are the same
6533   // then transform to 2 operand version of the same instruction
6534   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
6535   bool Transform = Op3Reg == Op4Reg;
6536 
6537   // For communtative operations, we might be able to transform if we swap
6538   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
6539   // as tADDrsp.
6540   const ARMOperand *LastOp = &Op5;
6541   bool Swap = false;
6542   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
6543       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
6544        Mnemonic == "and" || Mnemonic == "eor" ||
6545        Mnemonic == "adc" || Mnemonic == "orr")) {
6546     Swap = true;
6547     LastOp = &Op4;
6548     Transform = true;
6549   }
6550 
6551   // If both registers are the same then remove one of them from
6552   // the operand list, with certain exceptions.
6553   if (Transform) {
6554     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
6555     // 2 operand forms don't exist.
6556     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
6557         LastOp->isReg())
6558       Transform = false;
6559 
6560     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
6561     // 3-bits because the ARMARM says not to.
6562     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
6563       Transform = false;
6564   }
6565 
6566   if (Transform) {
6567     if (Swap)
6568       std::swap(Op4, Op5);
6569     Operands.erase(Operands.begin() + 3);
6570   }
6571 }
6572 
6573 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
6574                                           OperandVector &Operands) {
6575   // FIXME: This is all horribly hacky. We really need a better way to deal
6576   // with optional operands like this in the matcher table.
6577 
6578   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
6579   // another does not. Specifically, the MOVW instruction does not. So we
6580   // special case it here and remove the defaulted (non-setting) cc_out
6581   // operand if that's the instruction we're trying to match.
6582   //
6583   // We do this as post-processing of the explicit operands rather than just
6584   // conditionally adding the cc_out in the first place because we need
6585   // to check the type of the parsed immediate operand.
6586   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
6587       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
6588       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
6589       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6590     return true;
6591 
6592   // Register-register 'add' for thumb does not have a cc_out operand
6593   // when there are only two register operands.
6594   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
6595       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6596       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6597       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6598     return true;
6599   // Register-register 'add' for thumb does not have a cc_out operand
6600   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
6601   // have to check the immediate range here since Thumb2 has a variant
6602   // that can handle a different range and has a cc_out operand.
6603   if (((isThumb() && Mnemonic == "add") ||
6604        (isThumbTwo() && Mnemonic == "sub")) &&
6605       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6606       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6607       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
6608       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6609       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
6610        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
6611     return true;
6612   // For Thumb2, add/sub immediate does not have a cc_out operand for the
6613   // imm0_4095 variant. That's the least-preferred variant when
6614   // selecting via the generic "add" mnemonic, so to know that we
6615   // should remove the cc_out operand, we have to explicitly check that
6616   // it's not one of the other variants. Ugh.
6617   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6618       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6619       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6620       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6621     // Nest conditions rather than one big 'if' statement for readability.
6622     //
6623     // If both registers are low, we're in an IT block, and the immediate is
6624     // in range, we should use encoding T1 instead, which has a cc_out.
6625     if (inITBlock() &&
6626         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
6627         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
6628         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
6629       return false;
6630     // Check against T3. If the second register is the PC, this is an
6631     // alternate form of ADR, which uses encoding T4, so check for that too.
6632     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
6633         (static_cast<ARMOperand &>(*Operands[5]).isT2SOImm() ||
6634          static_cast<ARMOperand &>(*Operands[5]).isT2SOImmNeg()))
6635       return false;
6636 
6637     // Otherwise, we use encoding T4, which does not have a cc_out
6638     // operand.
6639     return true;
6640   }
6641 
6642   // The thumb2 multiply instruction doesn't have a CCOut register, so
6643   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
6644   // use the 16-bit encoding or not.
6645   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
6646       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6647       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6648       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6649       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
6650       // If the registers aren't low regs, the destination reg isn't the
6651       // same as one of the source regs, or the cc_out operand is zero
6652       // outside of an IT block, we have to use the 32-bit encoding, so
6653       // remove the cc_out operand.
6654       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6655        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6656        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
6657        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6658                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
6659                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6660                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
6661     return true;
6662 
6663   // Also check the 'mul' syntax variant that doesn't specify an explicit
6664   // destination register.
6665   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
6666       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6667       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6668       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6669       // If the registers aren't low regs  or the cc_out operand is zero
6670       // outside of an IT block, we have to use the 32-bit encoding, so
6671       // remove the cc_out operand.
6672       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6673        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6674        !inITBlock()))
6675     return true;
6676 
6677   // Register-register 'add/sub' for thumb does not have a cc_out operand
6678   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
6679   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
6680   // right, this will result in better diagnostics (which operand is off)
6681   // anyway.
6682   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
6683       (Operands.size() == 5 || Operands.size() == 6) &&
6684       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6685       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
6686       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6687       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
6688        (Operands.size() == 6 &&
6689         static_cast<ARMOperand &>(*Operands[5]).isImm()))) {
6690     // Thumb2 (add|sub){s}{p}.w GPRnopc, sp, #{T2SOImm} has cc_out
6691     return (!(isThumbTwo() &&
6692               (static_cast<ARMOperand &>(*Operands[4]).isT2SOImm() ||
6693                static_cast<ARMOperand &>(*Operands[4]).isT2SOImmNeg())));
6694   }
6695   // Fixme: Should join all the thumb+thumb2 (add|sub) in a single if case
6696   // Thumb2 ADD r0, #4095 -> ADDW r0, r0, #4095 (T4)
6697   // Thumb2 SUB r0, #4095 -> SUBW r0, r0, #4095
6698   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6699       (Operands.size() == 5) &&
6700       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6701       static_cast<ARMOperand &>(*Operands[3]).getReg() != ARM::SP &&
6702       static_cast<ARMOperand &>(*Operands[3]).getReg() != ARM::PC &&
6703       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6704       static_cast<ARMOperand &>(*Operands[4]).isImm()) {
6705     const ARMOperand &IMM = static_cast<ARMOperand &>(*Operands[4]);
6706     if (IMM.isT2SOImm() || IMM.isT2SOImmNeg())
6707       return false; // add.w / sub.w
6708     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IMM.getImm())) {
6709       const int64_t Value = CE->getValue();
6710       // Thumb1 imm8 sub / add
6711       if ((Value < ((1 << 7) - 1) << 2) && inITBlock() && (!(Value & 3)) &&
6712           isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()))
6713         return false;
6714       return true; // Thumb2 T4 addw / subw
6715     }
6716   }
6717   return false;
6718 }
6719 
6720 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
6721                                               OperandVector &Operands) {
6722   // VRINT{Z, X} have a predicate operand in VFP, but not in NEON
6723   unsigned RegIdx = 3;
6724   if ((((Mnemonic == "vrintz" || Mnemonic == "vrintx") && !hasMVE()) ||
6725       Mnemonic == "vrintr") &&
6726       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
6727        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
6728     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6729         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
6730          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
6731       RegIdx = 4;
6732 
6733     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
6734         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6735              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
6736          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6737              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
6738       return true;
6739   }
6740   return false;
6741 }
6742 
6743 bool ARMAsmParser::shouldOmitVectorPredicateOperand(StringRef Mnemonic,
6744                                                     OperandVector &Operands) {
6745   if (!hasMVE() || Operands.size() < 3)
6746     return true;
6747 
6748   if (Mnemonic.startswith("vld2") || Mnemonic.startswith("vld4") ||
6749       Mnemonic.startswith("vst2") || Mnemonic.startswith("vst4"))
6750     return true;
6751 
6752   if (Mnemonic.startswith("vctp") || Mnemonic.startswith("vpnot"))
6753     return false;
6754 
6755   if (Mnemonic.startswith("vmov") &&
6756       !(Mnemonic.startswith("vmovl") || Mnemonic.startswith("vmovn") ||
6757         Mnemonic.startswith("vmovx"))) {
6758     for (auto &Operand : Operands) {
6759       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6760           ((*Operand).isReg() &&
6761            (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
6762              (*Operand).getReg()) ||
6763             ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6764               (*Operand).getReg())))) {
6765         return true;
6766       }
6767     }
6768     return false;
6769   } else {
6770     for (auto &Operand : Operands) {
6771       // We check the larger class QPR instead of just the legal class
6772       // MQPR, to more accurately report errors when using Q registers
6773       // outside of the allowed range.
6774       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6775           (Operand->isReg() &&
6776            (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6777              Operand->getReg()))))
6778         return false;
6779     }
6780     return true;
6781   }
6782 }
6783 
6784 static bool isDataTypeToken(StringRef Tok) {
6785   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
6786     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
6787     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
6788     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
6789     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
6790     Tok == ".f" || Tok == ".d";
6791 }
6792 
6793 // FIXME: This bit should probably be handled via an explicit match class
6794 // in the .td files that matches the suffix instead of having it be
6795 // a literal string token the way it is now.
6796 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
6797   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
6798 }
6799 
6800 static void applyMnemonicAliases(StringRef &Mnemonic,
6801                                  const FeatureBitset &Features,
6802                                  unsigned VariantID);
6803 
6804 // The GNU assembler has aliases of ldrd and strd with the second register
6805 // omitted. We don't have a way to do that in tablegen, so fix it up here.
6806 //
6807 // We have to be careful to not emit an invalid Rt2 here, because the rest of
6808 // the assembly parser could then generate confusing diagnostics refering to
6809 // it. If we do find anything that prevents us from doing the transformation we
6810 // bail out, and let the assembly parser report an error on the instruction as
6811 // it is written.
6812 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
6813                                      OperandVector &Operands) {
6814   if (Mnemonic != "ldrd" && Mnemonic != "strd")
6815     return;
6816   if (Operands.size() < 4)
6817     return;
6818 
6819   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6820   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6821 
6822   if (!Op2.isReg())
6823     return;
6824   if (!Op3.isGPRMem())
6825     return;
6826 
6827   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
6828   if (!GPR.contains(Op2.getReg()))
6829     return;
6830 
6831   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
6832   if (!isThumb() && (RtEncoding & 1)) {
6833     // In ARM mode, the registers must be from an aligned pair, this
6834     // restriction does not apply in Thumb mode.
6835     return;
6836   }
6837   if (Op2.getReg() == ARM::PC)
6838     return;
6839   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
6840   if (!PairedReg || PairedReg == ARM::PC ||
6841       (PairedReg == ARM::SP && !hasV8Ops()))
6842     return;
6843 
6844   Operands.insert(
6845       Operands.begin() + 3,
6846       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6847 }
6848 
6849 // Dual-register instruction have the following syntax:
6850 // <mnemonic> <predicate>? <coproc>, <Rdest>, <Rdest+1>, <Rsrc>, ..., #imm
6851 // This function tries to remove <Rdest+1> and replace <Rdest> with a pair
6852 // operand. If the conversion fails an error is diagnosed, and the function
6853 // returns true.
6854 bool ARMAsmParser::CDEConvertDualRegOperand(StringRef Mnemonic,
6855                                             OperandVector &Operands) {
6856   assert(MS.isCDEDualRegInstr(Mnemonic));
6857   bool isPredicable =
6858       Mnemonic == "cx1da" || Mnemonic == "cx2da" || Mnemonic == "cx3da";
6859   size_t NumPredOps = isPredicable ? 1 : 0;
6860 
6861   if (Operands.size() <= 3 + NumPredOps)
6862     return false;
6863 
6864   StringRef Op2Diag(
6865       "operand must be an even-numbered register in the range [r0, r10]");
6866 
6867   const MCParsedAsmOperand &Op2 = *Operands[2 + NumPredOps];
6868   if (!Op2.isReg())
6869     return Error(Op2.getStartLoc(), Op2Diag);
6870 
6871   unsigned RNext;
6872   unsigned RPair;
6873   switch (Op2.getReg()) {
6874   default:
6875     return Error(Op2.getStartLoc(), Op2Diag);
6876   case ARM::R0:
6877     RNext = ARM::R1;
6878     RPair = ARM::R0_R1;
6879     break;
6880   case ARM::R2:
6881     RNext = ARM::R3;
6882     RPair = ARM::R2_R3;
6883     break;
6884   case ARM::R4:
6885     RNext = ARM::R5;
6886     RPair = ARM::R4_R5;
6887     break;
6888   case ARM::R6:
6889     RNext = ARM::R7;
6890     RPair = ARM::R6_R7;
6891     break;
6892   case ARM::R8:
6893     RNext = ARM::R9;
6894     RPair = ARM::R8_R9;
6895     break;
6896   case ARM::R10:
6897     RNext = ARM::R11;
6898     RPair = ARM::R10_R11;
6899     break;
6900   }
6901 
6902   const MCParsedAsmOperand &Op3 = *Operands[3 + NumPredOps];
6903   if (!Op3.isReg() || Op3.getReg() != RNext)
6904     return Error(Op3.getStartLoc(), "operand must be a consecutive register");
6905 
6906   Operands.erase(Operands.begin() + 3 + NumPredOps);
6907   Operands[2 + NumPredOps] =
6908       ARMOperand::CreateReg(RPair, Op2.getStartLoc(), Op2.getEndLoc());
6909   return false;
6910 }
6911 
6912 /// Parse an arm instruction mnemonic followed by its operands.
6913 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
6914                                     SMLoc NameLoc, OperandVector &Operands) {
6915   MCAsmParser &Parser = getParser();
6916 
6917   // Apply mnemonic aliases before doing anything else, as the destination
6918   // mnemonic may include suffices and we want to handle them normally.
6919   // The generic tblgen'erated code does this later, at the start of
6920   // MatchInstructionImpl(), but that's too late for aliases that include
6921   // any sort of suffix.
6922   const FeatureBitset &AvailableFeatures = getAvailableFeatures();
6923   unsigned AssemblerDialect = getParser().getAssemblerDialect();
6924   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
6925 
6926   // First check for the ARM-specific .req directive.
6927   if (Parser.getTok().is(AsmToken::Identifier) &&
6928       Parser.getTok().getIdentifier().lower() == ".req") {
6929     parseDirectiveReq(Name, NameLoc);
6930     // We always return 'error' for this, as we're done with this
6931     // statement and don't need to match the 'instruction."
6932     return true;
6933   }
6934 
6935   // Create the leading tokens for the mnemonic, split by '.' characters.
6936   size_t Start = 0, Next = Name.find('.');
6937   StringRef Mnemonic = Name.slice(Start, Next);
6938   StringRef ExtraToken = Name.slice(Next, Name.find(' ', Next + 1));
6939 
6940   // Split out the predication code and carry setting flag from the mnemonic.
6941   unsigned PredicationCode;
6942   unsigned VPTPredicationCode;
6943   unsigned ProcessorIMod;
6944   bool CarrySetting;
6945   StringRef ITMask;
6946   Mnemonic = splitMnemonic(Mnemonic, ExtraToken, PredicationCode, VPTPredicationCode,
6947                            CarrySetting, ProcessorIMod, ITMask);
6948 
6949   // In Thumb1, only the branch (B) instruction can be predicated.
6950   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
6951     return Error(NameLoc, "conditional execution not supported in Thumb1");
6952   }
6953 
6954   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
6955 
6956   // Handle the mask for IT and VPT instructions. In ARMOperand and
6957   // MCOperand, this is stored in a format independent of the
6958   // condition code: the lowest set bit indicates the end of the
6959   // encoding, and above that, a 1 bit indicates 'else', and an 0
6960   // indicates 'then'. E.g.
6961   //    IT    -> 1000
6962   //    ITx   -> x100    (ITT -> 0100, ITE -> 1100)
6963   //    ITxy  -> xy10    (e.g. ITET -> 1010)
6964   //    ITxyz -> xyz1    (e.g. ITEET -> 1101)
6965   if (Mnemonic == "it" || Mnemonic.startswith("vpt") ||
6966       Mnemonic.startswith("vpst")) {
6967     SMLoc Loc = Mnemonic == "it"  ? SMLoc::getFromPointer(NameLoc.getPointer() + 2) :
6968                 Mnemonic == "vpt" ? SMLoc::getFromPointer(NameLoc.getPointer() + 3) :
6969                                     SMLoc::getFromPointer(NameLoc.getPointer() + 4);
6970     if (ITMask.size() > 3) {
6971       if (Mnemonic == "it")
6972         return Error(Loc, "too many conditions on IT instruction");
6973       return Error(Loc, "too many conditions on VPT instruction");
6974     }
6975     unsigned Mask = 8;
6976     for (unsigned i = ITMask.size(); i != 0; --i) {
6977       char pos = ITMask[i - 1];
6978       if (pos != 't' && pos != 'e') {
6979         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
6980       }
6981       Mask >>= 1;
6982       if (ITMask[i - 1] == 'e')
6983         Mask |= 8;
6984     }
6985     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
6986   }
6987 
6988   // FIXME: This is all a pretty gross hack. We should automatically handle
6989   // optional operands like this via tblgen.
6990 
6991   // Next, add the CCOut and ConditionCode operands, if needed.
6992   //
6993   // For mnemonics which can ever incorporate a carry setting bit or predication
6994   // code, our matching model involves us always generating CCOut and
6995   // ConditionCode operands to match the mnemonic "as written" and then we let
6996   // the matcher deal with finding the right instruction or generating an
6997   // appropriate error.
6998   bool CanAcceptCarrySet, CanAcceptPredicationCode, CanAcceptVPTPredicationCode;
6999   getMnemonicAcceptInfo(Mnemonic, ExtraToken, Name, CanAcceptCarrySet,
7000                         CanAcceptPredicationCode, CanAcceptVPTPredicationCode);
7001 
7002   // If we had a carry-set on an instruction that can't do that, issue an
7003   // error.
7004   if (!CanAcceptCarrySet && CarrySetting) {
7005     return Error(NameLoc, "instruction '" + Mnemonic +
7006                  "' can not set flags, but 's' suffix specified");
7007   }
7008   // If we had a predication code on an instruction that can't do that, issue an
7009   // error.
7010   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
7011     return Error(NameLoc, "instruction '" + Mnemonic +
7012                  "' is not predicable, but condition code specified");
7013   }
7014 
7015   // If we had a VPT predication code on an instruction that can't do that, issue an
7016   // error.
7017   if (!CanAcceptVPTPredicationCode && VPTPredicationCode != ARMVCC::None) {
7018     return Error(NameLoc, "instruction '" + Mnemonic +
7019                  "' is not VPT predicable, but VPT code T/E is specified");
7020   }
7021 
7022   // Add the carry setting operand, if necessary.
7023   if (CanAcceptCarrySet) {
7024     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
7025     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
7026                                                Loc));
7027   }
7028 
7029   // Add the predication code operand, if necessary.
7030   if (CanAcceptPredicationCode) {
7031     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
7032                                       CarrySetting);
7033     Operands.push_back(ARMOperand::CreateCondCode(
7034                        ARMCC::CondCodes(PredicationCode), Loc));
7035   }
7036 
7037   // Add the VPT predication code operand, if necessary.
7038   // FIXME: We don't add them for the instructions filtered below as these can
7039   // have custom operands which need special parsing.  This parsing requires
7040   // the operand to be in the same place in the OperandVector as their
7041   // definition in tblgen.  Since these instructions may also have the
7042   // scalar predication operand we do not add the vector one and leave until
7043   // now to fix it up.
7044   if (CanAcceptVPTPredicationCode && Mnemonic != "vmov" &&
7045       !Mnemonic.startswith("vcmp") &&
7046       !(Mnemonic.startswith("vcvt") && Mnemonic != "vcvta" &&
7047         Mnemonic != "vcvtn" && Mnemonic != "vcvtp" && Mnemonic != "vcvtm")) {
7048     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
7049                                       CarrySetting);
7050     Operands.push_back(ARMOperand::CreateVPTPred(
7051                          ARMVCC::VPTCodes(VPTPredicationCode), Loc));
7052   }
7053 
7054   // Add the processor imod operand, if necessary.
7055   if (ProcessorIMod) {
7056     Operands.push_back(ARMOperand::CreateImm(
7057           MCConstantExpr::create(ProcessorIMod, getContext()),
7058                                  NameLoc, NameLoc));
7059   } else if (Mnemonic == "cps" && isMClass()) {
7060     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
7061   }
7062 
7063   // Add the remaining tokens in the mnemonic.
7064   while (Next != StringRef::npos) {
7065     Start = Next;
7066     Next = Name.find('.', Start + 1);
7067     ExtraToken = Name.slice(Start, Next);
7068 
7069     // Some NEON instructions have an optional datatype suffix that is
7070     // completely ignored. Check for that.
7071     if (isDataTypeToken(ExtraToken) &&
7072         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
7073       continue;
7074 
7075     // For for ARM mode generate an error if the .n qualifier is used.
7076     if (ExtraToken == ".n" && !isThumb()) {
7077       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
7078       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
7079                    "arm mode");
7080     }
7081 
7082     // The .n qualifier is always discarded as that is what the tables
7083     // and matcher expect.  In ARM mode the .w qualifier has no effect,
7084     // so discard it to avoid errors that can be caused by the matcher.
7085     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
7086       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
7087       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
7088     }
7089   }
7090 
7091   // Read the remaining operands.
7092   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7093     // Read the first operand.
7094     if (parseOperand(Operands, Mnemonic)) {
7095       return true;
7096     }
7097 
7098     while (parseOptionalToken(AsmToken::Comma)) {
7099       // Parse and remember the operand.
7100       if (parseOperand(Operands, Mnemonic)) {
7101         return true;
7102       }
7103     }
7104   }
7105 
7106   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
7107     return true;
7108 
7109   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
7110 
7111   if (hasCDE() && MS.isCDEInstr(Mnemonic)) {
7112     // Dual-register instructions use even-odd register pairs as their
7113     // destination operand, in assembly such pair is spelled as two
7114     // consecutive registers, without any special syntax. ConvertDualRegOperand
7115     // tries to convert such operand into register pair, e.g. r2, r3 -> r2_r3.
7116     // It returns true, if an error message has been emitted. If the function
7117     // returns false, the function either succeeded or an error (e.g. missing
7118     // operand) will be diagnosed elsewhere.
7119     if (MS.isCDEDualRegInstr(Mnemonic)) {
7120       bool GotError = CDEConvertDualRegOperand(Mnemonic, Operands);
7121       if (GotError)
7122         return GotError;
7123     }
7124   }
7125 
7126   // Some instructions, mostly Thumb, have forms for the same mnemonic that
7127   // do and don't have a cc_out optional-def operand. With some spot-checks
7128   // of the operand list, we can figure out which variant we're trying to
7129   // parse and adjust accordingly before actually matching. We shouldn't ever
7130   // try to remove a cc_out operand that was explicitly set on the
7131   // mnemonic, of course (CarrySetting == true). Reason number #317 the
7132   // table driven matcher doesn't fit well with the ARM instruction set.
7133   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
7134     Operands.erase(Operands.begin() + 1);
7135 
7136   // Some instructions have the same mnemonic, but don't always
7137   // have a predicate. Distinguish them here and delete the
7138   // appropriate predicate if needed.  This could be either the scalar
7139   // predication code or the vector predication code.
7140   if (PredicationCode == ARMCC::AL &&
7141       shouldOmitPredicateOperand(Mnemonic, Operands))
7142     Operands.erase(Operands.begin() + 1);
7143 
7144 
7145   if (hasMVE()) {
7146     if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands) &&
7147         Mnemonic == "vmov" && PredicationCode == ARMCC::LT) {
7148       // Very nasty hack to deal with the vector predicated variant of vmovlt
7149       // the scalar predicated vmov with condition 'lt'.  We can not tell them
7150       // apart until we have parsed their operands.
7151       Operands.erase(Operands.begin() + 1);
7152       Operands.erase(Operands.begin());
7153       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7154       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7155                                          Mnemonic.size() - 1 + CarrySetting);
7156       Operands.insert(Operands.begin(),
7157                       ARMOperand::CreateVPTPred(ARMVCC::None, PLoc));
7158       Operands.insert(Operands.begin(),
7159                       ARMOperand::CreateToken(StringRef("vmovlt"), MLoc));
7160     } else if (Mnemonic == "vcvt" && PredicationCode == ARMCC::NE &&
7161                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7162       // Another nasty hack to deal with the ambiguity between vcvt with scalar
7163       // predication 'ne' and vcvtn with vector predication 'e'.  As above we
7164       // can only distinguish between the two after we have parsed their
7165       // operands.
7166       Operands.erase(Operands.begin() + 1);
7167       Operands.erase(Operands.begin());
7168       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7169       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7170                                          Mnemonic.size() - 1 + CarrySetting);
7171       Operands.insert(Operands.begin(),
7172                       ARMOperand::CreateVPTPred(ARMVCC::Else, PLoc));
7173       Operands.insert(Operands.begin(),
7174                       ARMOperand::CreateToken(StringRef("vcvtn"), MLoc));
7175     } else if (Mnemonic == "vmul" && PredicationCode == ARMCC::LT &&
7176                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7177       // Another hack, this time to distinguish between scalar predicated vmul
7178       // with 'lt' predication code and the vector instruction vmullt with
7179       // vector predication code "none"
7180       Operands.erase(Operands.begin() + 1);
7181       Operands.erase(Operands.begin());
7182       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7183       Operands.insert(Operands.begin(),
7184                       ARMOperand::CreateToken(StringRef("vmullt"), MLoc));
7185     }
7186     // For vmov and vcmp, as mentioned earlier, we did not add the vector
7187     // predication code, since these may contain operands that require
7188     // special parsing.  So now we have to see if they require vector
7189     // predication and replace the scalar one with the vector predication
7190     // operand if that is the case.
7191     else if (Mnemonic == "vmov" || Mnemonic.startswith("vcmp") ||
7192              (Mnemonic.startswith("vcvt") && !Mnemonic.startswith("vcvta") &&
7193               !Mnemonic.startswith("vcvtn") && !Mnemonic.startswith("vcvtp") &&
7194               !Mnemonic.startswith("vcvtm"))) {
7195       if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7196         // We could not split the vector predicate off vcvt because it might
7197         // have been the scalar vcvtt instruction.  Now we know its a vector
7198         // instruction, we still need to check whether its the vector
7199         // predicated vcvt with 'Then' predication or the vector vcvtt.  We can
7200         // distinguish the two based on the suffixes, if it is any of
7201         // ".f16.f32", ".f32.f16", ".f16.f64" or ".f64.f16" then it is the vcvtt.
7202         if (Mnemonic.startswith("vcvtt") && Operands.size() >= 4) {
7203           auto Sz1 = static_cast<ARMOperand &>(*Operands[2]);
7204           auto Sz2 = static_cast<ARMOperand &>(*Operands[3]);
7205           if (!(Sz1.isToken() && Sz1.getToken().startswith(".f") &&
7206               Sz2.isToken() && Sz2.getToken().startswith(".f"))) {
7207             Operands.erase(Operands.begin());
7208             SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7209             VPTPredicationCode = ARMVCC::Then;
7210 
7211             Mnemonic = Mnemonic.substr(0, 4);
7212             Operands.insert(Operands.begin(),
7213                             ARMOperand::CreateToken(Mnemonic, MLoc));
7214           }
7215         }
7216         Operands.erase(Operands.begin() + 1);
7217         SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7218                                           Mnemonic.size() + CarrySetting);
7219         Operands.insert(Operands.begin() + 1,
7220                         ARMOperand::CreateVPTPred(
7221                             ARMVCC::VPTCodes(VPTPredicationCode), PLoc));
7222       }
7223     } else if (CanAcceptVPTPredicationCode) {
7224       // For all other instructions, make sure only one of the two
7225       // predication operands is left behind, depending on whether we should
7226       // use the vector predication.
7227       if (shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7228         if (CanAcceptPredicationCode)
7229           Operands.erase(Operands.begin() + 2);
7230         else
7231           Operands.erase(Operands.begin() + 1);
7232       } else if (CanAcceptPredicationCode && PredicationCode == ARMCC::AL) {
7233         Operands.erase(Operands.begin() + 1);
7234       }
7235     }
7236   }
7237 
7238   if (VPTPredicationCode != ARMVCC::None) {
7239     bool usedVPTPredicationCode = false;
7240     for (unsigned I = 1; I < Operands.size(); ++I)
7241       if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7242         usedVPTPredicationCode = true;
7243     if (!usedVPTPredicationCode) {
7244       // If we have a VPT predication code and we haven't just turned it
7245       // into an operand, then it was a mistake for splitMnemonic to
7246       // separate it from the rest of the mnemonic in the first place,
7247       // and this may lead to wrong disassembly (e.g. scalar floating
7248       // point VCMPE is actually a different instruction from VCMP, so
7249       // we mustn't treat them the same). In that situation, glue it
7250       // back on.
7251       Mnemonic = Name.slice(0, Mnemonic.size() + 1);
7252       Operands.erase(Operands.begin());
7253       Operands.insert(Operands.begin(),
7254                       ARMOperand::CreateToken(Mnemonic, NameLoc));
7255     }
7256   }
7257 
7258     // ARM mode 'blx' need special handling, as the register operand version
7259     // is predicable, but the label operand version is not. So, we can't rely
7260     // on the Mnemonic based checking to correctly figure out when to put
7261     // a k_CondCode operand in the list. If we're trying to match the label
7262     // version, remove the k_CondCode operand here.
7263     if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
7264         static_cast<ARMOperand &>(*Operands[2]).isImm())
7265       Operands.erase(Operands.begin() + 1);
7266 
7267     // Adjust operands of ldrexd/strexd to MCK_GPRPair.
7268     // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
7269     // a single GPRPair reg operand is used in the .td file to replace the two
7270     // GPRs. However, when parsing from asm, the two GRPs cannot be
7271     // automatically
7272     // expressed as a GPRPair, so we have to manually merge them.
7273     // FIXME: We would really like to be able to tablegen'erate this.
7274     if (!isThumb() && Operands.size() > 4 &&
7275         (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
7276          Mnemonic == "stlexd")) {
7277       bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
7278       unsigned Idx = isLoad ? 2 : 3;
7279       ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
7280       ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
7281 
7282       const MCRegisterClass &MRC = MRI->getRegClass(ARM::GPRRegClassID);
7283       // Adjust only if Op1 and Op2 are GPRs.
7284       if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
7285           MRC.contains(Op2.getReg())) {
7286         unsigned Reg1 = Op1.getReg();
7287         unsigned Reg2 = Op2.getReg();
7288         unsigned Rt = MRI->getEncodingValue(Reg1);
7289         unsigned Rt2 = MRI->getEncodingValue(Reg2);
7290 
7291         // Rt2 must be Rt + 1 and Rt must be even.
7292         if (Rt + 1 != Rt2 || (Rt & 1)) {
7293           return Error(Op2.getStartLoc(),
7294                        isLoad ? "destination operands must be sequential"
7295                               : "source operands must be sequential");
7296         }
7297         unsigned NewReg = MRI->getMatchingSuperReg(
7298             Reg1, ARM::gsub_0, &(MRI->getRegClass(ARM::GPRPairRegClassID)));
7299         Operands[Idx] =
7300             ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
7301         Operands.erase(Operands.begin() + Idx + 1);
7302       }
7303   }
7304 
7305   // GNU Assembler extension (compatibility).
7306   fixupGNULDRDAlias(Mnemonic, Operands);
7307 
7308   // FIXME: As said above, this is all a pretty gross hack.  This instruction
7309   // does not fit with other "subs" and tblgen.
7310   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
7311   // so the Mnemonic is the original name "subs" and delete the predicate
7312   // operand so it will match the table entry.
7313   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
7314       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
7315       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
7316       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
7317       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
7318       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
7319     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
7320     Operands.erase(Operands.begin() + 1);
7321   }
7322   return false;
7323 }
7324 
7325 // Validate context-sensitive operand constraints.
7326 
7327 // return 'true' if register list contains non-low GPR registers,
7328 // 'false' otherwise. If Reg is in the register list or is HiReg, set
7329 // 'containsReg' to true.
7330 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
7331                                  unsigned Reg, unsigned HiReg,
7332                                  bool &containsReg) {
7333   containsReg = false;
7334   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
7335     unsigned OpReg = Inst.getOperand(i).getReg();
7336     if (OpReg == Reg)
7337       containsReg = true;
7338     // Anything other than a low register isn't legal here.
7339     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
7340       return true;
7341   }
7342   return false;
7343 }
7344 
7345 // Check if the specified regisgter is in the register list of the inst,
7346 // starting at the indicated operand number.
7347 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
7348   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
7349     unsigned OpReg = Inst.getOperand(i).getReg();
7350     if (OpReg == Reg)
7351       return true;
7352   }
7353   return false;
7354 }
7355 
7356 // Return true if instruction has the interesting property of being
7357 // allowed in IT blocks, but not being predicable.
7358 static bool instIsBreakpoint(const MCInst &Inst) {
7359     return Inst.getOpcode() == ARM::tBKPT ||
7360            Inst.getOpcode() == ARM::BKPT ||
7361            Inst.getOpcode() == ARM::tHLT ||
7362            Inst.getOpcode() == ARM::HLT;
7363 }
7364 
7365 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
7366                                        const OperandVector &Operands,
7367                                        unsigned ListNo, bool IsARPop) {
7368   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7369   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7370 
7371   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7372   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
7373   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7374 
7375   if (!IsARPop && ListContainsSP)
7376     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7377                  "SP may not be in the register list");
7378   else if (ListContainsPC && ListContainsLR)
7379     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7380                  "PC and LR may not be in the register list simultaneously");
7381   return false;
7382 }
7383 
7384 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
7385                                        const OperandVector &Operands,
7386                                        unsigned ListNo) {
7387   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7388   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7389 
7390   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7391   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7392 
7393   if (ListContainsSP && ListContainsPC)
7394     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7395                  "SP and PC may not be in the register list");
7396   else if (ListContainsSP)
7397     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7398                  "SP may not be in the register list");
7399   else if (ListContainsPC)
7400     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7401                  "PC may not be in the register list");
7402   return false;
7403 }
7404 
7405 bool ARMAsmParser::validateLDRDSTRD(MCInst &Inst,
7406                                     const OperandVector &Operands,
7407                                     bool Load, bool ARMMode, bool Writeback) {
7408   unsigned RtIndex = Load || !Writeback ? 0 : 1;
7409   unsigned Rt = MRI->getEncodingValue(Inst.getOperand(RtIndex).getReg());
7410   unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(RtIndex + 1).getReg());
7411 
7412   if (ARMMode) {
7413     // Rt can't be R14.
7414     if (Rt == 14)
7415       return Error(Operands[3]->getStartLoc(),
7416                   "Rt can't be R14");
7417 
7418     // Rt must be even-numbered.
7419     if ((Rt & 1) == 1)
7420       return Error(Operands[3]->getStartLoc(),
7421                    "Rt must be even-numbered");
7422 
7423     // Rt2 must be Rt + 1.
7424     if (Rt2 != Rt + 1) {
7425       if (Load)
7426         return Error(Operands[3]->getStartLoc(),
7427                      "destination operands must be sequential");
7428       else
7429         return Error(Operands[3]->getStartLoc(),
7430                      "source operands must be sequential");
7431     }
7432 
7433     // FIXME: Diagnose m == 15
7434     // FIXME: Diagnose ldrd with m == t || m == t2.
7435   }
7436 
7437   if (!ARMMode && Load) {
7438     if (Rt2 == Rt)
7439       return Error(Operands[3]->getStartLoc(),
7440                    "destination operands can't be identical");
7441   }
7442 
7443   if (Writeback) {
7444     unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
7445 
7446     if (Rn == Rt || Rn == Rt2) {
7447       if (Load)
7448         return Error(Operands[3]->getStartLoc(),
7449                      "base register needs to be different from destination "
7450                      "registers");
7451       else
7452         return Error(Operands[3]->getStartLoc(),
7453                      "source register and base register can't be identical");
7454     }
7455 
7456     // FIXME: Diagnose ldrd/strd with writeback and n == 15.
7457     // (Except the immediate form of ldrd?)
7458   }
7459 
7460   return false;
7461 }
7462 
7463 static int findFirstVectorPredOperandIdx(const MCInstrDesc &MCID) {
7464   for (unsigned i = 0; i < MCID.NumOperands; ++i) {
7465     if (ARM::isVpred(MCID.OpInfo[i].OperandType))
7466       return i;
7467   }
7468   return -1;
7469 }
7470 
7471 static bool isVectorPredicable(const MCInstrDesc &MCID) {
7472   return findFirstVectorPredOperandIdx(MCID) != -1;
7473 }
7474 
7475 // FIXME: We would really like to be able to tablegen'erate this.
7476 bool ARMAsmParser::validateInstruction(MCInst &Inst,
7477                                        const OperandVector &Operands) {
7478   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
7479   SMLoc Loc = Operands[0]->getStartLoc();
7480 
7481   // Check the IT block state first.
7482   // NOTE: BKPT and HLT instructions have the interesting property of being
7483   // allowed in IT blocks, but not being predicable. They just always execute.
7484   if (inITBlock() && !instIsBreakpoint(Inst)) {
7485     // The instruction must be predicable.
7486     if (!MCID.isPredicable())
7487       return Error(Loc, "instructions in IT block must be predicable");
7488     ARMCC::CondCodes Cond = ARMCC::CondCodes(
7489         Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm());
7490     if (Cond != currentITCond()) {
7491       // Find the condition code Operand to get its SMLoc information.
7492       SMLoc CondLoc;
7493       for (unsigned I = 1; I < Operands.size(); ++I)
7494         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
7495           CondLoc = Operands[I]->getStartLoc();
7496       return Error(CondLoc, "incorrect condition in IT block; got '" +
7497                                 StringRef(ARMCondCodeToString(Cond)) +
7498                                 "', but expected '" +
7499                                 ARMCondCodeToString(currentITCond()) + "'");
7500     }
7501   // Check for non-'al' condition codes outside of the IT block.
7502   } else if (isThumbTwo() && MCID.isPredicable() &&
7503              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7504              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
7505              Inst.getOpcode() != ARM::t2Bcc &&
7506              Inst.getOpcode() != ARM::t2BFic) {
7507     return Error(Loc, "predicated instructions must be in IT block");
7508   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
7509              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7510                  ARMCC::AL) {
7511     return Warning(Loc, "predicated instructions should be in IT block");
7512   } else if (!MCID.isPredicable()) {
7513     // Check the instruction doesn't have a predicate operand anyway
7514     // that it's not allowed to use. Sometimes this happens in order
7515     // to keep instructions the same shape even though one cannot
7516     // legally be predicated, e.g. vmul.f16 vs vmul.f32.
7517     for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
7518       if (MCID.OpInfo[i].isPredicate()) {
7519         if (Inst.getOperand(i).getImm() != ARMCC::AL)
7520           return Error(Loc, "instruction is not predicable");
7521         break;
7522       }
7523     }
7524   }
7525 
7526   // PC-setting instructions in an IT block, but not the last instruction of
7527   // the block, are UNPREDICTABLE.
7528   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
7529     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
7530   }
7531 
7532   if (inVPTBlock() && !instIsBreakpoint(Inst)) {
7533     unsigned Bit = extractITMaskBit(VPTState.Mask, VPTState.CurPosition);
7534     if (!isVectorPredicable(MCID))
7535       return Error(Loc, "instruction in VPT block must be predicable");
7536     unsigned Pred = Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm();
7537     unsigned VPTPred = Bit ? ARMVCC::Else : ARMVCC::Then;
7538     if (Pred != VPTPred) {
7539       SMLoc PredLoc;
7540       for (unsigned I = 1; I < Operands.size(); ++I)
7541         if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7542           PredLoc = Operands[I]->getStartLoc();
7543       return Error(PredLoc, "incorrect predication in VPT block; got '" +
7544                    StringRef(ARMVPTPredToString(ARMVCC::VPTCodes(Pred))) +
7545                    "', but expected '" +
7546                    ARMVPTPredToString(ARMVCC::VPTCodes(VPTPred)) + "'");
7547     }
7548   }
7549   else if (isVectorPredicable(MCID) &&
7550            Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm() !=
7551            ARMVCC::None)
7552     return Error(Loc, "VPT predicated instructions must be in VPT block");
7553 
7554   const unsigned Opcode = Inst.getOpcode();
7555   switch (Opcode) {
7556   case ARM::t2IT: {
7557     // Encoding is unpredictable if it ever results in a notional 'NV'
7558     // predicate. Since we don't parse 'NV' directly this means an 'AL'
7559     // predicate with an "else" mask bit.
7560     unsigned Cond = Inst.getOperand(0).getImm();
7561     unsigned Mask = Inst.getOperand(1).getImm();
7562 
7563     // Conditions only allowing a 't' are those with no set bit except
7564     // the lowest-order one that indicates the end of the sequence. In
7565     // other words, powers of 2.
7566     if (Cond == ARMCC::AL && countPopulation(Mask) != 1)
7567       return Error(Loc, "unpredictable IT predicate sequence");
7568     break;
7569   }
7570   case ARM::LDRD:
7571     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7572                          /*Writeback*/false))
7573       return true;
7574     break;
7575   case ARM::LDRD_PRE:
7576   case ARM::LDRD_POST:
7577     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7578                          /*Writeback*/true))
7579       return true;
7580     break;
7581   case ARM::t2LDRDi8:
7582     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7583                          /*Writeback*/false))
7584       return true;
7585     break;
7586   case ARM::t2LDRD_PRE:
7587   case ARM::t2LDRD_POST:
7588     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7589                          /*Writeback*/true))
7590       return true;
7591     break;
7592   case ARM::t2BXJ: {
7593     const unsigned RmReg = Inst.getOperand(0).getReg();
7594     // Rm = SP is no longer unpredictable in v8-A
7595     if (RmReg == ARM::SP && !hasV8Ops())
7596       return Error(Operands[2]->getStartLoc(),
7597                    "r13 (SP) is an unpredictable operand to BXJ");
7598     return false;
7599   }
7600   case ARM::STRD:
7601     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7602                          /*Writeback*/false))
7603       return true;
7604     break;
7605   case ARM::STRD_PRE:
7606   case ARM::STRD_POST:
7607     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7608                          /*Writeback*/true))
7609       return true;
7610     break;
7611   case ARM::t2STRD_PRE:
7612   case ARM::t2STRD_POST:
7613     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/false,
7614                          /*Writeback*/true))
7615       return true;
7616     break;
7617   case ARM::STR_PRE_IMM:
7618   case ARM::STR_PRE_REG:
7619   case ARM::t2STR_PRE:
7620   case ARM::STR_POST_IMM:
7621   case ARM::STR_POST_REG:
7622   case ARM::t2STR_POST:
7623   case ARM::STRH_PRE:
7624   case ARM::t2STRH_PRE:
7625   case ARM::STRH_POST:
7626   case ARM::t2STRH_POST:
7627   case ARM::STRB_PRE_IMM:
7628   case ARM::STRB_PRE_REG:
7629   case ARM::t2STRB_PRE:
7630   case ARM::STRB_POST_IMM:
7631   case ARM::STRB_POST_REG:
7632   case ARM::t2STRB_POST: {
7633     // Rt must be different from Rn.
7634     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7635     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7636 
7637     if (Rt == Rn)
7638       return Error(Operands[3]->getStartLoc(),
7639                    "source register and base register can't be identical");
7640     return false;
7641   }
7642   case ARM::LDR_PRE_IMM:
7643   case ARM::LDR_PRE_REG:
7644   case ARM::t2LDR_PRE:
7645   case ARM::LDR_POST_IMM:
7646   case ARM::LDR_POST_REG:
7647   case ARM::t2LDR_POST:
7648   case ARM::LDRH_PRE:
7649   case ARM::t2LDRH_PRE:
7650   case ARM::LDRH_POST:
7651   case ARM::t2LDRH_POST:
7652   case ARM::LDRSH_PRE:
7653   case ARM::t2LDRSH_PRE:
7654   case ARM::LDRSH_POST:
7655   case ARM::t2LDRSH_POST:
7656   case ARM::LDRB_PRE_IMM:
7657   case ARM::LDRB_PRE_REG:
7658   case ARM::t2LDRB_PRE:
7659   case ARM::LDRB_POST_IMM:
7660   case ARM::LDRB_POST_REG:
7661   case ARM::t2LDRB_POST:
7662   case ARM::LDRSB_PRE:
7663   case ARM::t2LDRSB_PRE:
7664   case ARM::LDRSB_POST:
7665   case ARM::t2LDRSB_POST: {
7666     // Rt must be different from Rn.
7667     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7668     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7669 
7670     if (Rt == Rn)
7671       return Error(Operands[3]->getStartLoc(),
7672                    "destination register and base register can't be identical");
7673     return false;
7674   }
7675 
7676   case ARM::MVE_VLDRBU8_rq:
7677   case ARM::MVE_VLDRBU16_rq:
7678   case ARM::MVE_VLDRBS16_rq:
7679   case ARM::MVE_VLDRBU32_rq:
7680   case ARM::MVE_VLDRBS32_rq:
7681   case ARM::MVE_VLDRHU16_rq:
7682   case ARM::MVE_VLDRHU16_rq_u:
7683   case ARM::MVE_VLDRHU32_rq:
7684   case ARM::MVE_VLDRHU32_rq_u:
7685   case ARM::MVE_VLDRHS32_rq:
7686   case ARM::MVE_VLDRHS32_rq_u:
7687   case ARM::MVE_VLDRWU32_rq:
7688   case ARM::MVE_VLDRWU32_rq_u:
7689   case ARM::MVE_VLDRDU64_rq:
7690   case ARM::MVE_VLDRDU64_rq_u:
7691   case ARM::MVE_VLDRWU32_qi:
7692   case ARM::MVE_VLDRWU32_qi_pre:
7693   case ARM::MVE_VLDRDU64_qi:
7694   case ARM::MVE_VLDRDU64_qi_pre: {
7695     // Qd must be different from Qm.
7696     unsigned QdIdx = 0, QmIdx = 2;
7697     bool QmIsPointer = false;
7698     switch (Opcode) {
7699     case ARM::MVE_VLDRWU32_qi:
7700     case ARM::MVE_VLDRDU64_qi:
7701       QmIdx = 1;
7702       QmIsPointer = true;
7703       break;
7704     case ARM::MVE_VLDRWU32_qi_pre:
7705     case ARM::MVE_VLDRDU64_qi_pre:
7706       QdIdx = 1;
7707       QmIsPointer = true;
7708       break;
7709     }
7710 
7711     const unsigned Qd = MRI->getEncodingValue(Inst.getOperand(QdIdx).getReg());
7712     const unsigned Qm = MRI->getEncodingValue(Inst.getOperand(QmIdx).getReg());
7713 
7714     if (Qd == Qm) {
7715       return Error(Operands[3]->getStartLoc(),
7716                    Twine("destination vector register and vector ") +
7717                    (QmIsPointer ? "pointer" : "offset") +
7718                    " register can't be identical");
7719     }
7720     return false;
7721   }
7722 
7723   case ARM::SBFX:
7724   case ARM::t2SBFX:
7725   case ARM::UBFX:
7726   case ARM::t2UBFX: {
7727     // Width must be in range [1, 32-lsb].
7728     unsigned LSB = Inst.getOperand(2).getImm();
7729     unsigned Widthm1 = Inst.getOperand(3).getImm();
7730     if (Widthm1 >= 32 - LSB)
7731       return Error(Operands[5]->getStartLoc(),
7732                    "bitfield width must be in range [1,32-lsb]");
7733     return false;
7734   }
7735   // Notionally handles ARM::tLDMIA_UPD too.
7736   case ARM::tLDMIA: {
7737     // If we're parsing Thumb2, the .w variant is available and handles
7738     // most cases that are normally illegal for a Thumb1 LDM instruction.
7739     // We'll make the transformation in processInstruction() if necessary.
7740     //
7741     // Thumb LDM instructions are writeback iff the base register is not
7742     // in the register list.
7743     unsigned Rn = Inst.getOperand(0).getReg();
7744     bool HasWritebackToken =
7745         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7746          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
7747     bool ListContainsBase;
7748     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
7749       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
7750                    "registers must be in range r0-r7");
7751     // If we should have writeback, then there should be a '!' token.
7752     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
7753       return Error(Operands[2]->getStartLoc(),
7754                    "writeback operator '!' expected");
7755     // If we should not have writeback, there must not be a '!'. This is
7756     // true even for the 32-bit wide encodings.
7757     if (ListContainsBase && HasWritebackToken)
7758       return Error(Operands[3]->getStartLoc(),
7759                    "writeback operator '!' not allowed when base register "
7760                    "in register list");
7761 
7762     if (validatetLDMRegList(Inst, Operands, 3))
7763       return true;
7764     break;
7765   }
7766   case ARM::LDMIA_UPD:
7767   case ARM::LDMDB_UPD:
7768   case ARM::LDMIB_UPD:
7769   case ARM::LDMDA_UPD:
7770     // ARM variants loading and updating the same register are only officially
7771     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
7772     if (!hasV7Ops())
7773       break;
7774     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7775       return Error(Operands.back()->getStartLoc(),
7776                    "writeback register not allowed in register list");
7777     break;
7778   case ARM::t2LDMIA:
7779   case ARM::t2LDMDB:
7780     if (validatetLDMRegList(Inst, Operands, 3))
7781       return true;
7782     break;
7783   case ARM::t2STMIA:
7784   case ARM::t2STMDB:
7785     if (validatetSTMRegList(Inst, Operands, 3))
7786       return true;
7787     break;
7788   case ARM::t2LDMIA_UPD:
7789   case ARM::t2LDMDB_UPD:
7790   case ARM::t2STMIA_UPD:
7791   case ARM::t2STMDB_UPD:
7792     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7793       return Error(Operands.back()->getStartLoc(),
7794                    "writeback register not allowed in register list");
7795 
7796     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
7797       if (validatetLDMRegList(Inst, Operands, 3))
7798         return true;
7799     } else {
7800       if (validatetSTMRegList(Inst, Operands, 3))
7801         return true;
7802     }
7803     break;
7804 
7805   case ARM::sysLDMIA_UPD:
7806   case ARM::sysLDMDA_UPD:
7807   case ARM::sysLDMDB_UPD:
7808   case ARM::sysLDMIB_UPD:
7809     if (!listContainsReg(Inst, 3, ARM::PC))
7810       return Error(Operands[4]->getStartLoc(),
7811                    "writeback register only allowed on system LDM "
7812                    "if PC in register-list");
7813     break;
7814   case ARM::sysSTMIA_UPD:
7815   case ARM::sysSTMDA_UPD:
7816   case ARM::sysSTMDB_UPD:
7817   case ARM::sysSTMIB_UPD:
7818     return Error(Operands[2]->getStartLoc(),
7819                  "system STM cannot have writeback register");
7820   case ARM::tMUL:
7821     // The second source operand must be the same register as the destination
7822     // operand.
7823     //
7824     // In this case, we must directly check the parsed operands because the
7825     // cvtThumbMultiply() function is written in such a way that it guarantees
7826     // this first statement is always true for the new Inst.  Essentially, the
7827     // destination is unconditionally copied into the second source operand
7828     // without checking to see if it matches what we actually parsed.
7829     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
7830                                  ((ARMOperand &)*Operands[5]).getReg()) &&
7831         (((ARMOperand &)*Operands[3]).getReg() !=
7832          ((ARMOperand &)*Operands[4]).getReg())) {
7833       return Error(Operands[3]->getStartLoc(),
7834                    "destination register must match source register");
7835     }
7836     break;
7837 
7838   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
7839   // so only issue a diagnostic for thumb1. The instructions will be
7840   // switched to the t2 encodings in processInstruction() if necessary.
7841   case ARM::tPOP: {
7842     bool ListContainsBase;
7843     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
7844         !isThumbTwo())
7845       return Error(Operands[2]->getStartLoc(),
7846                    "registers must be in range r0-r7 or pc");
7847     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
7848       return true;
7849     break;
7850   }
7851   case ARM::tPUSH: {
7852     bool ListContainsBase;
7853     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
7854         !isThumbTwo())
7855       return Error(Operands[2]->getStartLoc(),
7856                    "registers must be in range r0-r7 or lr");
7857     if (validatetSTMRegList(Inst, Operands, 2))
7858       return true;
7859     break;
7860   }
7861   case ARM::tSTMIA_UPD: {
7862     bool ListContainsBase, InvalidLowList;
7863     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
7864                                           0, ListContainsBase);
7865     if (InvalidLowList && !isThumbTwo())
7866       return Error(Operands[4]->getStartLoc(),
7867                    "registers must be in range r0-r7");
7868 
7869     // This would be converted to a 32-bit stm, but that's not valid if the
7870     // writeback register is in the list.
7871     if (InvalidLowList && ListContainsBase)
7872       return Error(Operands[4]->getStartLoc(),
7873                    "writeback operator '!' not allowed when base register "
7874                    "in register list");
7875 
7876     if (validatetSTMRegList(Inst, Operands, 4))
7877       return true;
7878     break;
7879   }
7880   case ARM::tADDrSP:
7881     // If the non-SP source operand and the destination operand are not the
7882     // same, we need thumb2 (for the wide encoding), or we have an error.
7883     if (!isThumbTwo() &&
7884         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
7885       return Error(Operands[4]->getStartLoc(),
7886                    "source register must be the same as destination");
7887     }
7888     break;
7889 
7890   case ARM::t2ADDrr:
7891   case ARM::t2ADDrs:
7892   case ARM::t2SUBrr:
7893   case ARM::t2SUBrs:
7894     if (Inst.getOperand(0).getReg() == ARM::SP &&
7895         Inst.getOperand(1).getReg() != ARM::SP)
7896       return Error(Operands[4]->getStartLoc(),
7897                    "source register must be sp if destination is sp");
7898     break;
7899 
7900   // Final range checking for Thumb unconditional branch instructions.
7901   case ARM::tB:
7902     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
7903       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7904     break;
7905   case ARM::t2B: {
7906     int op = (Operands[2]->isImm()) ? 2 : 3;
7907     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
7908       return Error(Operands[op]->getStartLoc(), "branch target out of range");
7909     break;
7910   }
7911   // Final range checking for Thumb conditional branch instructions.
7912   case ARM::tBcc:
7913     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
7914       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7915     break;
7916   case ARM::t2Bcc: {
7917     int Op = (Operands[2]->isImm()) ? 2 : 3;
7918     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
7919       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
7920     break;
7921   }
7922   case ARM::tCBZ:
7923   case ARM::tCBNZ: {
7924     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
7925       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7926     break;
7927   }
7928   case ARM::MOVi16:
7929   case ARM::MOVTi16:
7930   case ARM::t2MOVi16:
7931   case ARM::t2MOVTi16:
7932     {
7933     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
7934     // especially when we turn it into a movw and the expression <symbol> does
7935     // not have a :lower16: or :upper16 as part of the expression.  We don't
7936     // want the behavior of silently truncating, which can be unexpected and
7937     // lead to bugs that are difficult to find since this is an easy mistake
7938     // to make.
7939     int i = (Operands[3]->isImm()) ? 3 : 4;
7940     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
7941     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
7942     if (CE) break;
7943     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
7944     if (!E) break;
7945     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
7946     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
7947                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
7948       return Error(
7949           Op.getStartLoc(),
7950           "immediate expression for mov requires :lower16: or :upper16");
7951     break;
7952   }
7953   case ARM::HINT:
7954   case ARM::t2HINT: {
7955     unsigned Imm8 = Inst.getOperand(0).getImm();
7956     unsigned Pred = Inst.getOperand(1).getImm();
7957     // ESB is not predicable (pred must be AL). Without the RAS extension, this
7958     // behaves as any other unallocated hint.
7959     if (Imm8 == 0x10 && Pred != ARMCC::AL && hasRAS())
7960       return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
7961                                                "predicable, but condition "
7962                                                "code specified");
7963     if (Imm8 == 0x14 && Pred != ARMCC::AL)
7964       return Error(Operands[1]->getStartLoc(), "instruction 'csdb' is not "
7965                                                "predicable, but condition "
7966                                                "code specified");
7967     break;
7968   }
7969   case ARM::t2BFi:
7970   case ARM::t2BFr:
7971   case ARM::t2BFLi:
7972   case ARM::t2BFLr: {
7973     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<4, 1>() ||
7974         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
7975       return Error(Operands[2]->getStartLoc(),
7976                    "branch location out of range or not a multiple of 2");
7977 
7978     if (Opcode == ARM::t2BFi) {
7979       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<16, 1>())
7980         return Error(Operands[3]->getStartLoc(),
7981                      "branch target out of range or not a multiple of 2");
7982     } else if (Opcode == ARM::t2BFLi) {
7983       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<18, 1>())
7984         return Error(Operands[3]->getStartLoc(),
7985                      "branch target out of range or not a multiple of 2");
7986     }
7987     break;
7988   }
7989   case ARM::t2BFic: {
7990     if (!static_cast<ARMOperand &>(*Operands[1]).isUnsignedOffset<4, 1>() ||
7991         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
7992       return Error(Operands[1]->getStartLoc(),
7993                    "branch location out of range or not a multiple of 2");
7994 
7995     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<16, 1>())
7996       return Error(Operands[2]->getStartLoc(),
7997                    "branch target out of range or not a multiple of 2");
7998 
7999     assert(Inst.getOperand(0).isImm() == Inst.getOperand(2).isImm() &&
8000            "branch location and else branch target should either both be "
8001            "immediates or both labels");
8002 
8003     if (Inst.getOperand(0).isImm() && Inst.getOperand(2).isImm()) {
8004       int Diff = Inst.getOperand(2).getImm() - Inst.getOperand(0).getImm();
8005       if (Diff != 4 && Diff != 2)
8006         return Error(
8007             Operands[3]->getStartLoc(),
8008             "else branch target must be 2 or 4 greater than the branch location");
8009     }
8010     break;
8011   }
8012   case ARM::t2CLRM: {
8013     for (unsigned i = 2; i < Inst.getNumOperands(); i++) {
8014       if (Inst.getOperand(i).isReg() &&
8015           !ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(
8016               Inst.getOperand(i).getReg())) {
8017         return Error(Operands[2]->getStartLoc(),
8018                      "invalid register in register list. Valid registers are "
8019                      "r0-r12, lr/r14 and APSR.");
8020       }
8021     }
8022     break;
8023   }
8024   case ARM::DSB:
8025   case ARM::t2DSB: {
8026 
8027     if (Inst.getNumOperands() < 2)
8028       break;
8029 
8030     unsigned Option = Inst.getOperand(0).getImm();
8031     unsigned Pred = Inst.getOperand(1).getImm();
8032 
8033     // SSBB and PSSBB (DSB #0|#4) are not predicable (pred must be AL).
8034     if (Option == 0 && Pred != ARMCC::AL)
8035       return Error(Operands[1]->getStartLoc(),
8036                    "instruction 'ssbb' is not predicable, but condition code "
8037                    "specified");
8038     if (Option == 4 && Pred != ARMCC::AL)
8039       return Error(Operands[1]->getStartLoc(),
8040                    "instruction 'pssbb' is not predicable, but condition code "
8041                    "specified");
8042     break;
8043   }
8044   case ARM::VMOVRRS: {
8045     // Source registers must be sequential.
8046     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(2).getReg());
8047     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(3).getReg());
8048     if (Sm1 != Sm + 1)
8049       return Error(Operands[5]->getStartLoc(),
8050                    "source operands must be sequential");
8051     break;
8052   }
8053   case ARM::VMOVSRR: {
8054     // Destination registers must be sequential.
8055     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(0).getReg());
8056     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
8057     if (Sm1 != Sm + 1)
8058       return Error(Operands[3]->getStartLoc(),
8059                    "destination operands must be sequential");
8060     break;
8061   }
8062   case ARM::VLDMDIA:
8063   case ARM::VSTMDIA: {
8064     ARMOperand &Op = static_cast<ARMOperand&>(*Operands[3]);
8065     auto &RegList = Op.getRegList();
8066     if (RegList.size() < 1 || RegList.size() > 16)
8067       return Error(Operands[3]->getStartLoc(),
8068                    "list of registers must be at least 1 and at most 16");
8069     break;
8070   }
8071   case ARM::MVE_VQDMULLs32bh:
8072   case ARM::MVE_VQDMULLs32th:
8073   case ARM::MVE_VCMULf32:
8074   case ARM::MVE_VMULLBs32:
8075   case ARM::MVE_VMULLTs32:
8076   case ARM::MVE_VMULLBu32:
8077   case ARM::MVE_VMULLTu32: {
8078     if (Operands[3]->getReg() == Operands[4]->getReg()) {
8079       return Error (Operands[3]->getStartLoc(),
8080                     "Qd register and Qn register can't be identical");
8081     }
8082     if (Operands[3]->getReg() == Operands[5]->getReg()) {
8083       return Error (Operands[3]->getStartLoc(),
8084                     "Qd register and Qm register can't be identical");
8085     }
8086     break;
8087   }
8088   case ARM::MVE_VMOV_rr_q: {
8089     if (Operands[4]->getReg() != Operands[6]->getReg())
8090       return Error (Operands[4]->getStartLoc(), "Q-registers must be the same");
8091     if (static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() !=
8092         static_cast<ARMOperand &>(*Operands[7]).getVectorIndex() + 2)
8093       return Error (Operands[5]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
8094     break;
8095   }
8096   case ARM::MVE_VMOV_q_rr: {
8097     if (Operands[2]->getReg() != Operands[4]->getReg())
8098       return Error (Operands[2]->getStartLoc(), "Q-registers must be the same");
8099     if (static_cast<ARMOperand &>(*Operands[3]).getVectorIndex() !=
8100         static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() + 2)
8101       return Error (Operands[3]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
8102     break;
8103   }
8104   case ARM::UMAAL:
8105   case ARM::UMLAL:
8106   case ARM::UMULL:
8107   case ARM::t2UMAAL:
8108   case ARM::t2UMLAL:
8109   case ARM::t2UMULL:
8110   case ARM::SMLAL:
8111   case ARM::SMLALBB:
8112   case ARM::SMLALBT:
8113   case ARM::SMLALD:
8114   case ARM::SMLALDX:
8115   case ARM::SMLALTB:
8116   case ARM::SMLALTT:
8117   case ARM::SMLSLD:
8118   case ARM::SMLSLDX:
8119   case ARM::SMULL:
8120   case ARM::t2SMLAL:
8121   case ARM::t2SMLALBB:
8122   case ARM::t2SMLALBT:
8123   case ARM::t2SMLALD:
8124   case ARM::t2SMLALDX:
8125   case ARM::t2SMLALTB:
8126   case ARM::t2SMLALTT:
8127   case ARM::t2SMLSLD:
8128   case ARM::t2SMLSLDX:
8129   case ARM::t2SMULL: {
8130     unsigned RdHi = Inst.getOperand(0).getReg();
8131     unsigned RdLo = Inst.getOperand(1).getReg();
8132     if(RdHi == RdLo) {
8133       return Error(Loc,
8134                    "unpredictable instruction, RdHi and RdLo must be different");
8135     }
8136     break;
8137   }
8138 
8139   case ARM::CDE_CX1:
8140   case ARM::CDE_CX1A:
8141   case ARM::CDE_CX1D:
8142   case ARM::CDE_CX1DA:
8143   case ARM::CDE_CX2:
8144   case ARM::CDE_CX2A:
8145   case ARM::CDE_CX2D:
8146   case ARM::CDE_CX2DA:
8147   case ARM::CDE_CX3:
8148   case ARM::CDE_CX3A:
8149   case ARM::CDE_CX3D:
8150   case ARM::CDE_CX3DA:
8151   case ARM::CDE_VCX1_vec:
8152   case ARM::CDE_VCX1_fpsp:
8153   case ARM::CDE_VCX1_fpdp:
8154   case ARM::CDE_VCX1A_vec:
8155   case ARM::CDE_VCX1A_fpsp:
8156   case ARM::CDE_VCX1A_fpdp:
8157   case ARM::CDE_VCX2_vec:
8158   case ARM::CDE_VCX2_fpsp:
8159   case ARM::CDE_VCX2_fpdp:
8160   case ARM::CDE_VCX2A_vec:
8161   case ARM::CDE_VCX2A_fpsp:
8162   case ARM::CDE_VCX2A_fpdp:
8163   case ARM::CDE_VCX3_vec:
8164   case ARM::CDE_VCX3_fpsp:
8165   case ARM::CDE_VCX3_fpdp:
8166   case ARM::CDE_VCX3A_vec:
8167   case ARM::CDE_VCX3A_fpsp:
8168   case ARM::CDE_VCX3A_fpdp: {
8169     assert(Inst.getOperand(1).isImm() &&
8170            "CDE operand 1 must be a coprocessor ID");
8171     int64_t Coproc = Inst.getOperand(1).getImm();
8172     if (Coproc < 8 && !ARM::isCDECoproc(Coproc, *STI))
8173       return Error(Operands[1]->getStartLoc(),
8174                    "coprocessor must be configured as CDE");
8175     else if (Coproc >= 8)
8176       return Error(Operands[1]->getStartLoc(),
8177                    "coprocessor must be in the range [p0, p7]");
8178     break;
8179   }
8180 
8181   case ARM::t2CDP:
8182   case ARM::t2CDP2:
8183   case ARM::t2LDC2L_OFFSET:
8184   case ARM::t2LDC2L_OPTION:
8185   case ARM::t2LDC2L_POST:
8186   case ARM::t2LDC2L_PRE:
8187   case ARM::t2LDC2_OFFSET:
8188   case ARM::t2LDC2_OPTION:
8189   case ARM::t2LDC2_POST:
8190   case ARM::t2LDC2_PRE:
8191   case ARM::t2LDCL_OFFSET:
8192   case ARM::t2LDCL_OPTION:
8193   case ARM::t2LDCL_POST:
8194   case ARM::t2LDCL_PRE:
8195   case ARM::t2LDC_OFFSET:
8196   case ARM::t2LDC_OPTION:
8197   case ARM::t2LDC_POST:
8198   case ARM::t2LDC_PRE:
8199   case ARM::t2MCR:
8200   case ARM::t2MCR2:
8201   case ARM::t2MCRR:
8202   case ARM::t2MCRR2:
8203   case ARM::t2MRC:
8204   case ARM::t2MRC2:
8205   case ARM::t2MRRC:
8206   case ARM::t2MRRC2:
8207   case ARM::t2STC2L_OFFSET:
8208   case ARM::t2STC2L_OPTION:
8209   case ARM::t2STC2L_POST:
8210   case ARM::t2STC2L_PRE:
8211   case ARM::t2STC2_OFFSET:
8212   case ARM::t2STC2_OPTION:
8213   case ARM::t2STC2_POST:
8214   case ARM::t2STC2_PRE:
8215   case ARM::t2STCL_OFFSET:
8216   case ARM::t2STCL_OPTION:
8217   case ARM::t2STCL_POST:
8218   case ARM::t2STCL_PRE:
8219   case ARM::t2STC_OFFSET:
8220   case ARM::t2STC_OPTION:
8221   case ARM::t2STC_POST:
8222   case ARM::t2STC_PRE: {
8223     unsigned Opcode = Inst.getOpcode();
8224     // Inst.getOperand indexes operands in the (oops ...) and (iops ...) dags,
8225     // CopInd is the index of the coprocessor operand.
8226     size_t CopInd = 0;
8227     if (Opcode == ARM::t2MRRC || Opcode == ARM::t2MRRC2)
8228       CopInd = 2;
8229     else if (Opcode == ARM::t2MRC || Opcode == ARM::t2MRC2)
8230       CopInd = 1;
8231     assert(Inst.getOperand(CopInd).isImm() &&
8232            "Operand must be a coprocessor ID");
8233     int64_t Coproc = Inst.getOperand(CopInd).getImm();
8234     // Operands[2] is the coprocessor operand at syntactic level
8235     if (ARM::isCDECoproc(Coproc, *STI))
8236       return Error(Operands[2]->getStartLoc(),
8237                    "coprocessor must be configured as GCP");
8238     break;
8239   }
8240   }
8241 
8242   return false;
8243 }
8244 
8245 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
8246   switch(Opc) {
8247   default: llvm_unreachable("unexpected opcode!");
8248   // VST1LN
8249   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
8250   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
8251   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
8252   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
8253   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
8254   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
8255   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
8256   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
8257   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
8258 
8259   // VST2LN
8260   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
8261   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
8262   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
8263   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
8264   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
8265 
8266   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
8267   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
8268   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
8269   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
8270   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
8271 
8272   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
8273   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
8274   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
8275   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
8276   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
8277 
8278   // VST3LN
8279   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
8280   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
8281   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
8282   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
8283   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
8284   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
8285   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
8286   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
8287   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
8288   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
8289   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
8290   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
8291   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
8292   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
8293   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
8294 
8295   // VST3
8296   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
8297   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
8298   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
8299   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
8300   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
8301   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
8302   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
8303   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
8304   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
8305   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
8306   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
8307   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
8308   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
8309   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
8310   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
8311   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
8312   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
8313   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
8314 
8315   // VST4LN
8316   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
8317   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
8318   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
8319   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
8320   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
8321   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
8322   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
8323   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
8324   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
8325   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
8326   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
8327   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
8328   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
8329   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
8330   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
8331 
8332   // VST4
8333   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8334   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8335   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8336   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8337   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8338   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8339   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8340   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8341   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8342   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8343   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8344   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8345   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
8346   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
8347   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
8348   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
8349   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
8350   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
8351   }
8352 }
8353 
8354 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
8355   switch(Opc) {
8356   default: llvm_unreachable("unexpected opcode!");
8357   // VLD1LN
8358   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8359   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8360   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8361   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8362   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8363   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8364   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
8365   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
8366   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
8367 
8368   // VLD2LN
8369   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8370   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8371   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8372   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
8373   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8374   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8375   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8376   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8377   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
8378   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8379   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
8380   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
8381   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
8382   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
8383   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
8384 
8385   // VLD3DUP
8386   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8387   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8388   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8389   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
8390   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8391   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8392   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8393   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8394   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8395   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
8396   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8397   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8398   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
8399   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
8400   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
8401   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
8402   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
8403   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
8404 
8405   // VLD3LN
8406   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8407   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8408   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8409   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
8410   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8411   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8412   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8413   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8414   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
8415   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8416   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
8417   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
8418   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
8419   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
8420   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
8421 
8422   // VLD3
8423   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8424   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8425   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8426   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8427   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8428   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8429   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8430   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8431   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8432   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8433   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8434   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8435   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
8436   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
8437   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
8438   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
8439   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
8440   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
8441 
8442   // VLD4LN
8443   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8444   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8445   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8446   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8447   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8448   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8449   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8450   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8451   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8452   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8453   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
8454   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
8455   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
8456   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
8457   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
8458 
8459   // VLD4DUP
8460   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8461   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8462   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8463   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
8464   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
8465   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8466   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8467   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8468   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8469   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
8470   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
8471   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8472   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
8473   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
8474   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
8475   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
8476   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
8477   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
8478 
8479   // VLD4
8480   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8481   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8482   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8483   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8484   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8485   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8486   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8487   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8488   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8489   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8490   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8491   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8492   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
8493   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
8494   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
8495   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
8496   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
8497   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
8498   }
8499 }
8500 
8501 bool ARMAsmParser::processInstruction(MCInst &Inst,
8502                                       const OperandVector &Operands,
8503                                       MCStreamer &Out) {
8504   // Check if we have the wide qualifier, because if it's present we
8505   // must avoid selecting a 16-bit thumb instruction.
8506   bool HasWideQualifier = false;
8507   for (auto &Op : Operands) {
8508     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
8509     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
8510       HasWideQualifier = true;
8511       break;
8512     }
8513   }
8514 
8515   switch (Inst.getOpcode()) {
8516   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
8517   case ARM::LDRT_POST:
8518   case ARM::LDRBT_POST: {
8519     const unsigned Opcode =
8520       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
8521                                            : ARM::LDRBT_POST_IMM;
8522     MCInst TmpInst;
8523     TmpInst.setOpcode(Opcode);
8524     TmpInst.addOperand(Inst.getOperand(0));
8525     TmpInst.addOperand(Inst.getOperand(1));
8526     TmpInst.addOperand(Inst.getOperand(1));
8527     TmpInst.addOperand(MCOperand::createReg(0));
8528     TmpInst.addOperand(MCOperand::createImm(0));
8529     TmpInst.addOperand(Inst.getOperand(2));
8530     TmpInst.addOperand(Inst.getOperand(3));
8531     Inst = TmpInst;
8532     return true;
8533   }
8534   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
8535   case ARM::STRT_POST:
8536   case ARM::STRBT_POST: {
8537     const unsigned Opcode =
8538       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
8539                                            : ARM::STRBT_POST_IMM;
8540     MCInst TmpInst;
8541     TmpInst.setOpcode(Opcode);
8542     TmpInst.addOperand(Inst.getOperand(1));
8543     TmpInst.addOperand(Inst.getOperand(0));
8544     TmpInst.addOperand(Inst.getOperand(1));
8545     TmpInst.addOperand(MCOperand::createReg(0));
8546     TmpInst.addOperand(MCOperand::createImm(0));
8547     TmpInst.addOperand(Inst.getOperand(2));
8548     TmpInst.addOperand(Inst.getOperand(3));
8549     Inst = TmpInst;
8550     return true;
8551   }
8552   // Alias for alternate form of 'ADR Rd, #imm' instruction.
8553   case ARM::ADDri: {
8554     if (Inst.getOperand(1).getReg() != ARM::PC ||
8555         Inst.getOperand(5).getReg() != 0 ||
8556         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
8557       return false;
8558     MCInst TmpInst;
8559     TmpInst.setOpcode(ARM::ADR);
8560     TmpInst.addOperand(Inst.getOperand(0));
8561     if (Inst.getOperand(2).isImm()) {
8562       // Immediate (mod_imm) will be in its encoded form, we must unencode it
8563       // before passing it to the ADR instruction.
8564       unsigned Enc = Inst.getOperand(2).getImm();
8565       TmpInst.addOperand(MCOperand::createImm(
8566         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
8567     } else {
8568       // Turn PC-relative expression into absolute expression.
8569       // Reading PC provides the start of the current instruction + 8 and
8570       // the transform to adr is biased by that.
8571       MCSymbol *Dot = getContext().createTempSymbol();
8572       Out.emitLabel(Dot);
8573       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
8574       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
8575                                                      MCSymbolRefExpr::VK_None,
8576                                                      getContext());
8577       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
8578       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
8579                                                      getContext());
8580       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
8581                                                         getContext());
8582       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
8583     }
8584     TmpInst.addOperand(Inst.getOperand(3));
8585     TmpInst.addOperand(Inst.getOperand(4));
8586     Inst = TmpInst;
8587     return true;
8588   }
8589   // Aliases for alternate PC+imm syntax of LDR instructions.
8590   case ARM::t2LDRpcrel:
8591     // Select the narrow version if the immediate will fit.
8592     if (Inst.getOperand(1).getImm() > 0 &&
8593         Inst.getOperand(1).getImm() <= 0xff &&
8594         !HasWideQualifier)
8595       Inst.setOpcode(ARM::tLDRpci);
8596     else
8597       Inst.setOpcode(ARM::t2LDRpci);
8598     return true;
8599   case ARM::t2LDRBpcrel:
8600     Inst.setOpcode(ARM::t2LDRBpci);
8601     return true;
8602   case ARM::t2LDRHpcrel:
8603     Inst.setOpcode(ARM::t2LDRHpci);
8604     return true;
8605   case ARM::t2LDRSBpcrel:
8606     Inst.setOpcode(ARM::t2LDRSBpci);
8607     return true;
8608   case ARM::t2LDRSHpcrel:
8609     Inst.setOpcode(ARM::t2LDRSHpci);
8610     return true;
8611   case ARM::LDRConstPool:
8612   case ARM::tLDRConstPool:
8613   case ARM::t2LDRConstPool: {
8614     // Pseudo instruction ldr rt, =immediate is converted to a
8615     // MOV rt, immediate if immediate is known and representable
8616     // otherwise we create a constant pool entry that we load from.
8617     MCInst TmpInst;
8618     if (Inst.getOpcode() == ARM::LDRConstPool)
8619       TmpInst.setOpcode(ARM::LDRi12);
8620     else if (Inst.getOpcode() == ARM::tLDRConstPool)
8621       TmpInst.setOpcode(ARM::tLDRpci);
8622     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
8623       TmpInst.setOpcode(ARM::t2LDRpci);
8624     const ARMOperand &PoolOperand =
8625       (HasWideQualifier ?
8626        static_cast<ARMOperand &>(*Operands[4]) :
8627        static_cast<ARMOperand &>(*Operands[3]));
8628     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
8629     // If SubExprVal is a constant we may be able to use a MOV
8630     if (isa<MCConstantExpr>(SubExprVal) &&
8631         Inst.getOperand(0).getReg() != ARM::PC &&
8632         Inst.getOperand(0).getReg() != ARM::SP) {
8633       int64_t Value =
8634         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
8635       bool UseMov  = true;
8636       bool MovHasS = true;
8637       if (Inst.getOpcode() == ARM::LDRConstPool) {
8638         // ARM Constant
8639         if (ARM_AM::getSOImmVal(Value) != -1) {
8640           Value = ARM_AM::getSOImmVal(Value);
8641           TmpInst.setOpcode(ARM::MOVi);
8642         }
8643         else if (ARM_AM::getSOImmVal(~Value) != -1) {
8644           Value = ARM_AM::getSOImmVal(~Value);
8645           TmpInst.setOpcode(ARM::MVNi);
8646         }
8647         else if (hasV6T2Ops() &&
8648                  Value >=0 && Value < 65536) {
8649           TmpInst.setOpcode(ARM::MOVi16);
8650           MovHasS = false;
8651         }
8652         else
8653           UseMov = false;
8654       }
8655       else {
8656         // Thumb/Thumb2 Constant
8657         if (hasThumb2() &&
8658             ARM_AM::getT2SOImmVal(Value) != -1)
8659           TmpInst.setOpcode(ARM::t2MOVi);
8660         else if (hasThumb2() &&
8661                  ARM_AM::getT2SOImmVal(~Value) != -1) {
8662           TmpInst.setOpcode(ARM::t2MVNi);
8663           Value = ~Value;
8664         }
8665         else if (hasV8MBaseline() &&
8666                  Value >=0 && Value < 65536) {
8667           TmpInst.setOpcode(ARM::t2MOVi16);
8668           MovHasS = false;
8669         }
8670         else
8671           UseMov = false;
8672       }
8673       if (UseMov) {
8674         TmpInst.addOperand(Inst.getOperand(0));           // Rt
8675         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
8676         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8677         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8678         if (MovHasS)
8679           TmpInst.addOperand(MCOperand::createReg(0));    // S
8680         Inst = TmpInst;
8681         return true;
8682       }
8683     }
8684     // No opportunity to use MOV/MVN create constant pool
8685     const MCExpr *CPLoc =
8686       getTargetStreamer().addConstantPoolEntry(SubExprVal,
8687                                                PoolOperand.getStartLoc());
8688     TmpInst.addOperand(Inst.getOperand(0));           // Rt
8689     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
8690     if (TmpInst.getOpcode() == ARM::LDRi12)
8691       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
8692     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8693     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8694     Inst = TmpInst;
8695     return true;
8696   }
8697   // Handle NEON VST complex aliases.
8698   case ARM::VST1LNdWB_register_Asm_8:
8699   case ARM::VST1LNdWB_register_Asm_16:
8700   case ARM::VST1LNdWB_register_Asm_32: {
8701     MCInst TmpInst;
8702     // Shuffle the operands around so the lane index operand is in the
8703     // right place.
8704     unsigned Spacing;
8705     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8706     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8707     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8708     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8709     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8710     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8711     TmpInst.addOperand(Inst.getOperand(1)); // lane
8712     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8713     TmpInst.addOperand(Inst.getOperand(6));
8714     Inst = TmpInst;
8715     return true;
8716   }
8717 
8718   case ARM::VST2LNdWB_register_Asm_8:
8719   case ARM::VST2LNdWB_register_Asm_16:
8720   case ARM::VST2LNdWB_register_Asm_32:
8721   case ARM::VST2LNqWB_register_Asm_16:
8722   case ARM::VST2LNqWB_register_Asm_32: {
8723     MCInst TmpInst;
8724     // Shuffle the operands around so the lane index operand is in the
8725     // right place.
8726     unsigned Spacing;
8727     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8728     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8729     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8730     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8731     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8732     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8733     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8734                                             Spacing));
8735     TmpInst.addOperand(Inst.getOperand(1)); // lane
8736     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8737     TmpInst.addOperand(Inst.getOperand(6));
8738     Inst = TmpInst;
8739     return true;
8740   }
8741 
8742   case ARM::VST3LNdWB_register_Asm_8:
8743   case ARM::VST3LNdWB_register_Asm_16:
8744   case ARM::VST3LNdWB_register_Asm_32:
8745   case ARM::VST3LNqWB_register_Asm_16:
8746   case ARM::VST3LNqWB_register_Asm_32: {
8747     MCInst TmpInst;
8748     // Shuffle the operands around so the lane index operand is in the
8749     // right place.
8750     unsigned Spacing;
8751     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8752     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8753     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8754     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8755     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8756     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8757     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8758                                             Spacing));
8759     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8760                                             Spacing * 2));
8761     TmpInst.addOperand(Inst.getOperand(1)); // lane
8762     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8763     TmpInst.addOperand(Inst.getOperand(6));
8764     Inst = TmpInst;
8765     return true;
8766   }
8767 
8768   case ARM::VST4LNdWB_register_Asm_8:
8769   case ARM::VST4LNdWB_register_Asm_16:
8770   case ARM::VST4LNdWB_register_Asm_32:
8771   case ARM::VST4LNqWB_register_Asm_16:
8772   case ARM::VST4LNqWB_register_Asm_32: {
8773     MCInst TmpInst;
8774     // Shuffle the operands around so the lane index operand is in the
8775     // right place.
8776     unsigned Spacing;
8777     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8778     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8779     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8780     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8781     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8782     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8783     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8784                                             Spacing));
8785     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8786                                             Spacing * 2));
8787     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8788                                             Spacing * 3));
8789     TmpInst.addOperand(Inst.getOperand(1)); // lane
8790     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8791     TmpInst.addOperand(Inst.getOperand(6));
8792     Inst = TmpInst;
8793     return true;
8794   }
8795 
8796   case ARM::VST1LNdWB_fixed_Asm_8:
8797   case ARM::VST1LNdWB_fixed_Asm_16:
8798   case ARM::VST1LNdWB_fixed_Asm_32: {
8799     MCInst TmpInst;
8800     // Shuffle the operands around so the lane index operand is in the
8801     // right place.
8802     unsigned Spacing;
8803     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8804     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8805     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8806     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8807     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8808     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8809     TmpInst.addOperand(Inst.getOperand(1)); // lane
8810     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8811     TmpInst.addOperand(Inst.getOperand(5));
8812     Inst = TmpInst;
8813     return true;
8814   }
8815 
8816   case ARM::VST2LNdWB_fixed_Asm_8:
8817   case ARM::VST2LNdWB_fixed_Asm_16:
8818   case ARM::VST2LNdWB_fixed_Asm_32:
8819   case ARM::VST2LNqWB_fixed_Asm_16:
8820   case ARM::VST2LNqWB_fixed_Asm_32: {
8821     MCInst TmpInst;
8822     // Shuffle the operands around so the lane index operand is in the
8823     // right place.
8824     unsigned Spacing;
8825     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8826     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8827     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8828     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8829     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8830     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8831     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8832                                             Spacing));
8833     TmpInst.addOperand(Inst.getOperand(1)); // lane
8834     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8835     TmpInst.addOperand(Inst.getOperand(5));
8836     Inst = TmpInst;
8837     return true;
8838   }
8839 
8840   case ARM::VST3LNdWB_fixed_Asm_8:
8841   case ARM::VST3LNdWB_fixed_Asm_16:
8842   case ARM::VST3LNdWB_fixed_Asm_32:
8843   case ARM::VST3LNqWB_fixed_Asm_16:
8844   case ARM::VST3LNqWB_fixed_Asm_32: {
8845     MCInst TmpInst;
8846     // Shuffle the operands around so the lane index operand is in the
8847     // right place.
8848     unsigned Spacing;
8849     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8850     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8851     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8852     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8853     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8854     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8855     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8856                                             Spacing));
8857     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8858                                             Spacing * 2));
8859     TmpInst.addOperand(Inst.getOperand(1)); // lane
8860     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8861     TmpInst.addOperand(Inst.getOperand(5));
8862     Inst = TmpInst;
8863     return true;
8864   }
8865 
8866   case ARM::VST4LNdWB_fixed_Asm_8:
8867   case ARM::VST4LNdWB_fixed_Asm_16:
8868   case ARM::VST4LNdWB_fixed_Asm_32:
8869   case ARM::VST4LNqWB_fixed_Asm_16:
8870   case ARM::VST4LNqWB_fixed_Asm_32: {
8871     MCInst TmpInst;
8872     // Shuffle the operands around so the lane index operand is in the
8873     // right place.
8874     unsigned Spacing;
8875     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8876     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8877     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8878     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8879     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8880     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8881     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8882                                             Spacing));
8883     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8884                                             Spacing * 2));
8885     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8886                                             Spacing * 3));
8887     TmpInst.addOperand(Inst.getOperand(1)); // lane
8888     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8889     TmpInst.addOperand(Inst.getOperand(5));
8890     Inst = TmpInst;
8891     return true;
8892   }
8893 
8894   case ARM::VST1LNdAsm_8:
8895   case ARM::VST1LNdAsm_16:
8896   case ARM::VST1LNdAsm_32: {
8897     MCInst TmpInst;
8898     // Shuffle the operands around so the lane index operand is in the
8899     // right place.
8900     unsigned Spacing;
8901     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8902     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8903     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8904     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8905     TmpInst.addOperand(Inst.getOperand(1)); // lane
8906     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8907     TmpInst.addOperand(Inst.getOperand(5));
8908     Inst = TmpInst;
8909     return true;
8910   }
8911 
8912   case ARM::VST2LNdAsm_8:
8913   case ARM::VST2LNdAsm_16:
8914   case ARM::VST2LNdAsm_32:
8915   case ARM::VST2LNqAsm_16:
8916   case ARM::VST2LNqAsm_32: {
8917     MCInst TmpInst;
8918     // Shuffle the operands around so the lane index operand is in the
8919     // right place.
8920     unsigned Spacing;
8921     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8922     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8923     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8924     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8925     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8926                                             Spacing));
8927     TmpInst.addOperand(Inst.getOperand(1)); // lane
8928     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8929     TmpInst.addOperand(Inst.getOperand(5));
8930     Inst = TmpInst;
8931     return true;
8932   }
8933 
8934   case ARM::VST3LNdAsm_8:
8935   case ARM::VST3LNdAsm_16:
8936   case ARM::VST3LNdAsm_32:
8937   case ARM::VST3LNqAsm_16:
8938   case ARM::VST3LNqAsm_32: {
8939     MCInst TmpInst;
8940     // Shuffle the operands around so the lane index operand is in the
8941     // right place.
8942     unsigned Spacing;
8943     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8944     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8945     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8946     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8947     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8948                                             Spacing));
8949     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8950                                             Spacing * 2));
8951     TmpInst.addOperand(Inst.getOperand(1)); // lane
8952     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8953     TmpInst.addOperand(Inst.getOperand(5));
8954     Inst = TmpInst;
8955     return true;
8956   }
8957 
8958   case ARM::VST4LNdAsm_8:
8959   case ARM::VST4LNdAsm_16:
8960   case ARM::VST4LNdAsm_32:
8961   case ARM::VST4LNqAsm_16:
8962   case ARM::VST4LNqAsm_32: {
8963     MCInst TmpInst;
8964     // Shuffle the operands around so the lane index operand is in the
8965     // right place.
8966     unsigned Spacing;
8967     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8968     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8969     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8970     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8971     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8972                                             Spacing));
8973     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8974                                             Spacing * 2));
8975     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8976                                             Spacing * 3));
8977     TmpInst.addOperand(Inst.getOperand(1)); // lane
8978     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8979     TmpInst.addOperand(Inst.getOperand(5));
8980     Inst = TmpInst;
8981     return true;
8982   }
8983 
8984   // Handle NEON VLD complex aliases.
8985   case ARM::VLD1LNdWB_register_Asm_8:
8986   case ARM::VLD1LNdWB_register_Asm_16:
8987   case ARM::VLD1LNdWB_register_Asm_32: {
8988     MCInst TmpInst;
8989     // Shuffle the operands around so the lane index operand is in the
8990     // right place.
8991     unsigned Spacing;
8992     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8993     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8994     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8995     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8996     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8997     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8998     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8999     TmpInst.addOperand(Inst.getOperand(1)); // lane
9000     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9001     TmpInst.addOperand(Inst.getOperand(6));
9002     Inst = TmpInst;
9003     return true;
9004   }
9005 
9006   case ARM::VLD2LNdWB_register_Asm_8:
9007   case ARM::VLD2LNdWB_register_Asm_16:
9008   case ARM::VLD2LNdWB_register_Asm_32:
9009   case ARM::VLD2LNqWB_register_Asm_16:
9010   case ARM::VLD2LNqWB_register_Asm_32: {
9011     MCInst TmpInst;
9012     // Shuffle the operands around so the lane index operand is in the
9013     // right place.
9014     unsigned Spacing;
9015     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9016     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9017     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9018                                             Spacing));
9019     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9020     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9021     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9022     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9023     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9024     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9025                                             Spacing));
9026     TmpInst.addOperand(Inst.getOperand(1)); // lane
9027     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9028     TmpInst.addOperand(Inst.getOperand(6));
9029     Inst = TmpInst;
9030     return true;
9031   }
9032 
9033   case ARM::VLD3LNdWB_register_Asm_8:
9034   case ARM::VLD3LNdWB_register_Asm_16:
9035   case ARM::VLD3LNdWB_register_Asm_32:
9036   case ARM::VLD3LNqWB_register_Asm_16:
9037   case ARM::VLD3LNqWB_register_Asm_32: {
9038     MCInst TmpInst;
9039     // Shuffle the operands around so the lane index operand is in the
9040     // right place.
9041     unsigned Spacing;
9042     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9043     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9044     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9045                                             Spacing));
9046     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9047                                             Spacing * 2));
9048     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9049     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9050     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9051     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9052     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9053     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9054                                             Spacing));
9055     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9056                                             Spacing * 2));
9057     TmpInst.addOperand(Inst.getOperand(1)); // lane
9058     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9059     TmpInst.addOperand(Inst.getOperand(6));
9060     Inst = TmpInst;
9061     return true;
9062   }
9063 
9064   case ARM::VLD4LNdWB_register_Asm_8:
9065   case ARM::VLD4LNdWB_register_Asm_16:
9066   case ARM::VLD4LNdWB_register_Asm_32:
9067   case ARM::VLD4LNqWB_register_Asm_16:
9068   case ARM::VLD4LNqWB_register_Asm_32: {
9069     MCInst TmpInst;
9070     // Shuffle the operands around so the lane index operand is in the
9071     // right place.
9072     unsigned Spacing;
9073     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9074     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9075     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9076                                             Spacing));
9077     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9078                                             Spacing * 2));
9079     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9080                                             Spacing * 3));
9081     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9082     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9083     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9084     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9085     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9086     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9087                                             Spacing));
9088     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9089                                             Spacing * 2));
9090     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9091                                             Spacing * 3));
9092     TmpInst.addOperand(Inst.getOperand(1)); // lane
9093     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9094     TmpInst.addOperand(Inst.getOperand(6));
9095     Inst = TmpInst;
9096     return true;
9097   }
9098 
9099   case ARM::VLD1LNdWB_fixed_Asm_8:
9100   case ARM::VLD1LNdWB_fixed_Asm_16:
9101   case ARM::VLD1LNdWB_fixed_Asm_32: {
9102     MCInst TmpInst;
9103     // Shuffle the operands around so the lane index operand is in the
9104     // right place.
9105     unsigned Spacing;
9106     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9107     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9108     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9109     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9110     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9111     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9112     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9113     TmpInst.addOperand(Inst.getOperand(1)); // lane
9114     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9115     TmpInst.addOperand(Inst.getOperand(5));
9116     Inst = TmpInst;
9117     return true;
9118   }
9119 
9120   case ARM::VLD2LNdWB_fixed_Asm_8:
9121   case ARM::VLD2LNdWB_fixed_Asm_16:
9122   case ARM::VLD2LNdWB_fixed_Asm_32:
9123   case ARM::VLD2LNqWB_fixed_Asm_16:
9124   case ARM::VLD2LNqWB_fixed_Asm_32: {
9125     MCInst TmpInst;
9126     // Shuffle the operands around so the lane index operand is in the
9127     // right place.
9128     unsigned Spacing;
9129     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9130     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9131     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9132                                             Spacing));
9133     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9134     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9135     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9136     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9137     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9138     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9139                                             Spacing));
9140     TmpInst.addOperand(Inst.getOperand(1)); // lane
9141     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9142     TmpInst.addOperand(Inst.getOperand(5));
9143     Inst = TmpInst;
9144     return true;
9145   }
9146 
9147   case ARM::VLD3LNdWB_fixed_Asm_8:
9148   case ARM::VLD3LNdWB_fixed_Asm_16:
9149   case ARM::VLD3LNdWB_fixed_Asm_32:
9150   case ARM::VLD3LNqWB_fixed_Asm_16:
9151   case ARM::VLD3LNqWB_fixed_Asm_32: {
9152     MCInst TmpInst;
9153     // Shuffle the operands around so the lane index operand is in the
9154     // right place.
9155     unsigned Spacing;
9156     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9157     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9158     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9159                                             Spacing));
9160     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9161                                             Spacing * 2));
9162     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9163     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9164     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9165     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9166     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9167     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9168                                             Spacing));
9169     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9170                                             Spacing * 2));
9171     TmpInst.addOperand(Inst.getOperand(1)); // lane
9172     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9173     TmpInst.addOperand(Inst.getOperand(5));
9174     Inst = TmpInst;
9175     return true;
9176   }
9177 
9178   case ARM::VLD4LNdWB_fixed_Asm_8:
9179   case ARM::VLD4LNdWB_fixed_Asm_16:
9180   case ARM::VLD4LNdWB_fixed_Asm_32:
9181   case ARM::VLD4LNqWB_fixed_Asm_16:
9182   case ARM::VLD4LNqWB_fixed_Asm_32: {
9183     MCInst TmpInst;
9184     // Shuffle the operands around so the lane index operand is in the
9185     // right place.
9186     unsigned Spacing;
9187     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9188     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9189     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9190                                             Spacing));
9191     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9192                                             Spacing * 2));
9193     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9194                                             Spacing * 3));
9195     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9196     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9197     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9198     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9199     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9200     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9201                                             Spacing));
9202     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9203                                             Spacing * 2));
9204     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9205                                             Spacing * 3));
9206     TmpInst.addOperand(Inst.getOperand(1)); // lane
9207     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9208     TmpInst.addOperand(Inst.getOperand(5));
9209     Inst = TmpInst;
9210     return true;
9211   }
9212 
9213   case ARM::VLD1LNdAsm_8:
9214   case ARM::VLD1LNdAsm_16:
9215   case ARM::VLD1LNdAsm_32: {
9216     MCInst TmpInst;
9217     // Shuffle the operands around so the lane index operand is in the
9218     // right place.
9219     unsigned Spacing;
9220     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9221     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9222     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9223     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9224     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9225     TmpInst.addOperand(Inst.getOperand(1)); // lane
9226     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9227     TmpInst.addOperand(Inst.getOperand(5));
9228     Inst = TmpInst;
9229     return true;
9230   }
9231 
9232   case ARM::VLD2LNdAsm_8:
9233   case ARM::VLD2LNdAsm_16:
9234   case ARM::VLD2LNdAsm_32:
9235   case ARM::VLD2LNqAsm_16:
9236   case ARM::VLD2LNqAsm_32: {
9237     MCInst TmpInst;
9238     // Shuffle the operands around so the lane index operand is in the
9239     // right place.
9240     unsigned Spacing;
9241     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9242     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9243     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9244                                             Spacing));
9245     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9246     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9247     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9248     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9249                                             Spacing));
9250     TmpInst.addOperand(Inst.getOperand(1)); // lane
9251     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9252     TmpInst.addOperand(Inst.getOperand(5));
9253     Inst = TmpInst;
9254     return true;
9255   }
9256 
9257   case ARM::VLD3LNdAsm_8:
9258   case ARM::VLD3LNdAsm_16:
9259   case ARM::VLD3LNdAsm_32:
9260   case ARM::VLD3LNqAsm_16:
9261   case ARM::VLD3LNqAsm_32: {
9262     MCInst TmpInst;
9263     // Shuffle the operands around so the lane index operand is in the
9264     // right place.
9265     unsigned Spacing;
9266     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9267     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9268     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9269                                             Spacing));
9270     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9271                                             Spacing * 2));
9272     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9273     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9274     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9275     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9276                                             Spacing));
9277     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9278                                             Spacing * 2));
9279     TmpInst.addOperand(Inst.getOperand(1)); // lane
9280     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9281     TmpInst.addOperand(Inst.getOperand(5));
9282     Inst = TmpInst;
9283     return true;
9284   }
9285 
9286   case ARM::VLD4LNdAsm_8:
9287   case ARM::VLD4LNdAsm_16:
9288   case ARM::VLD4LNdAsm_32:
9289   case ARM::VLD4LNqAsm_16:
9290   case ARM::VLD4LNqAsm_32: {
9291     MCInst TmpInst;
9292     // Shuffle the operands around so the lane index operand is in the
9293     // right place.
9294     unsigned Spacing;
9295     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9296     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9297     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9298                                             Spacing));
9299     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9300                                             Spacing * 2));
9301     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9302                                             Spacing * 3));
9303     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9304     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9305     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9306     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9307                                             Spacing));
9308     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9309                                             Spacing * 2));
9310     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9311                                             Spacing * 3));
9312     TmpInst.addOperand(Inst.getOperand(1)); // lane
9313     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9314     TmpInst.addOperand(Inst.getOperand(5));
9315     Inst = TmpInst;
9316     return true;
9317   }
9318 
9319   // VLD3DUP single 3-element structure to all lanes instructions.
9320   case ARM::VLD3DUPdAsm_8:
9321   case ARM::VLD3DUPdAsm_16:
9322   case ARM::VLD3DUPdAsm_32:
9323   case ARM::VLD3DUPqAsm_8:
9324   case ARM::VLD3DUPqAsm_16:
9325   case ARM::VLD3DUPqAsm_32: {
9326     MCInst TmpInst;
9327     unsigned Spacing;
9328     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9329     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9330     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9331                                             Spacing));
9332     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9333                                             Spacing * 2));
9334     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9335     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9336     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9337     TmpInst.addOperand(Inst.getOperand(4));
9338     Inst = TmpInst;
9339     return true;
9340   }
9341 
9342   case ARM::VLD3DUPdWB_fixed_Asm_8:
9343   case ARM::VLD3DUPdWB_fixed_Asm_16:
9344   case ARM::VLD3DUPdWB_fixed_Asm_32:
9345   case ARM::VLD3DUPqWB_fixed_Asm_8:
9346   case ARM::VLD3DUPqWB_fixed_Asm_16:
9347   case ARM::VLD3DUPqWB_fixed_Asm_32: {
9348     MCInst TmpInst;
9349     unsigned Spacing;
9350     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9351     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9352     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9353                                             Spacing));
9354     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9355                                             Spacing * 2));
9356     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9357     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9358     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9359     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9360     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9361     TmpInst.addOperand(Inst.getOperand(4));
9362     Inst = TmpInst;
9363     return true;
9364   }
9365 
9366   case ARM::VLD3DUPdWB_register_Asm_8:
9367   case ARM::VLD3DUPdWB_register_Asm_16:
9368   case ARM::VLD3DUPdWB_register_Asm_32:
9369   case ARM::VLD3DUPqWB_register_Asm_8:
9370   case ARM::VLD3DUPqWB_register_Asm_16:
9371   case ARM::VLD3DUPqWB_register_Asm_32: {
9372     MCInst TmpInst;
9373     unsigned Spacing;
9374     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9375     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9376     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9377                                             Spacing));
9378     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9379                                             Spacing * 2));
9380     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9381     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9382     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9383     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9384     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9385     TmpInst.addOperand(Inst.getOperand(5));
9386     Inst = TmpInst;
9387     return true;
9388   }
9389 
9390   // VLD3 multiple 3-element structure instructions.
9391   case ARM::VLD3dAsm_8:
9392   case ARM::VLD3dAsm_16:
9393   case ARM::VLD3dAsm_32:
9394   case ARM::VLD3qAsm_8:
9395   case ARM::VLD3qAsm_16:
9396   case ARM::VLD3qAsm_32: {
9397     MCInst TmpInst;
9398     unsigned Spacing;
9399     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9400     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9401     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9402                                             Spacing));
9403     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9404                                             Spacing * 2));
9405     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9406     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9407     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9408     TmpInst.addOperand(Inst.getOperand(4));
9409     Inst = TmpInst;
9410     return true;
9411   }
9412 
9413   case ARM::VLD3dWB_fixed_Asm_8:
9414   case ARM::VLD3dWB_fixed_Asm_16:
9415   case ARM::VLD3dWB_fixed_Asm_32:
9416   case ARM::VLD3qWB_fixed_Asm_8:
9417   case ARM::VLD3qWB_fixed_Asm_16:
9418   case ARM::VLD3qWB_fixed_Asm_32: {
9419     MCInst TmpInst;
9420     unsigned Spacing;
9421     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9422     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9423     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9424                                             Spacing));
9425     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9426                                             Spacing * 2));
9427     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9428     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9429     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9430     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9431     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9432     TmpInst.addOperand(Inst.getOperand(4));
9433     Inst = TmpInst;
9434     return true;
9435   }
9436 
9437   case ARM::VLD3dWB_register_Asm_8:
9438   case ARM::VLD3dWB_register_Asm_16:
9439   case ARM::VLD3dWB_register_Asm_32:
9440   case ARM::VLD3qWB_register_Asm_8:
9441   case ARM::VLD3qWB_register_Asm_16:
9442   case ARM::VLD3qWB_register_Asm_32: {
9443     MCInst TmpInst;
9444     unsigned Spacing;
9445     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9446     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9447     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9448                                             Spacing));
9449     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9450                                             Spacing * 2));
9451     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9452     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9453     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9454     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9455     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9456     TmpInst.addOperand(Inst.getOperand(5));
9457     Inst = TmpInst;
9458     return true;
9459   }
9460 
9461   // VLD4DUP single 3-element structure to all lanes instructions.
9462   case ARM::VLD4DUPdAsm_8:
9463   case ARM::VLD4DUPdAsm_16:
9464   case ARM::VLD4DUPdAsm_32:
9465   case ARM::VLD4DUPqAsm_8:
9466   case ARM::VLD4DUPqAsm_16:
9467   case ARM::VLD4DUPqAsm_32: {
9468     MCInst TmpInst;
9469     unsigned Spacing;
9470     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9471     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9472     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9473                                             Spacing));
9474     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9475                                             Spacing * 2));
9476     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9477                                             Spacing * 3));
9478     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9479     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9480     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9481     TmpInst.addOperand(Inst.getOperand(4));
9482     Inst = TmpInst;
9483     return true;
9484   }
9485 
9486   case ARM::VLD4DUPdWB_fixed_Asm_8:
9487   case ARM::VLD4DUPdWB_fixed_Asm_16:
9488   case ARM::VLD4DUPdWB_fixed_Asm_32:
9489   case ARM::VLD4DUPqWB_fixed_Asm_8:
9490   case ARM::VLD4DUPqWB_fixed_Asm_16:
9491   case ARM::VLD4DUPqWB_fixed_Asm_32: {
9492     MCInst TmpInst;
9493     unsigned Spacing;
9494     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9495     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9496     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9497                                             Spacing));
9498     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9499                                             Spacing * 2));
9500     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9501                                             Spacing * 3));
9502     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9503     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9504     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9505     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9506     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9507     TmpInst.addOperand(Inst.getOperand(4));
9508     Inst = TmpInst;
9509     return true;
9510   }
9511 
9512   case ARM::VLD4DUPdWB_register_Asm_8:
9513   case ARM::VLD4DUPdWB_register_Asm_16:
9514   case ARM::VLD4DUPdWB_register_Asm_32:
9515   case ARM::VLD4DUPqWB_register_Asm_8:
9516   case ARM::VLD4DUPqWB_register_Asm_16:
9517   case ARM::VLD4DUPqWB_register_Asm_32: {
9518     MCInst TmpInst;
9519     unsigned Spacing;
9520     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9521     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9522     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9523                                             Spacing));
9524     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9525                                             Spacing * 2));
9526     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9527                                             Spacing * 3));
9528     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9529     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9530     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9531     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9532     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9533     TmpInst.addOperand(Inst.getOperand(5));
9534     Inst = TmpInst;
9535     return true;
9536   }
9537 
9538   // VLD4 multiple 4-element structure instructions.
9539   case ARM::VLD4dAsm_8:
9540   case ARM::VLD4dAsm_16:
9541   case ARM::VLD4dAsm_32:
9542   case ARM::VLD4qAsm_8:
9543   case ARM::VLD4qAsm_16:
9544   case ARM::VLD4qAsm_32: {
9545     MCInst TmpInst;
9546     unsigned Spacing;
9547     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9548     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9549     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9550                                             Spacing));
9551     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9552                                             Spacing * 2));
9553     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9554                                             Spacing * 3));
9555     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9556     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9557     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9558     TmpInst.addOperand(Inst.getOperand(4));
9559     Inst = TmpInst;
9560     return true;
9561   }
9562 
9563   case ARM::VLD4dWB_fixed_Asm_8:
9564   case ARM::VLD4dWB_fixed_Asm_16:
9565   case ARM::VLD4dWB_fixed_Asm_32:
9566   case ARM::VLD4qWB_fixed_Asm_8:
9567   case ARM::VLD4qWB_fixed_Asm_16:
9568   case ARM::VLD4qWB_fixed_Asm_32: {
9569     MCInst TmpInst;
9570     unsigned Spacing;
9571     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9572     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9573     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9574                                             Spacing));
9575     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9576                                             Spacing * 2));
9577     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9578                                             Spacing * 3));
9579     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9580     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9581     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9582     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9583     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9584     TmpInst.addOperand(Inst.getOperand(4));
9585     Inst = TmpInst;
9586     return true;
9587   }
9588 
9589   case ARM::VLD4dWB_register_Asm_8:
9590   case ARM::VLD4dWB_register_Asm_16:
9591   case ARM::VLD4dWB_register_Asm_32:
9592   case ARM::VLD4qWB_register_Asm_8:
9593   case ARM::VLD4qWB_register_Asm_16:
9594   case ARM::VLD4qWB_register_Asm_32: {
9595     MCInst TmpInst;
9596     unsigned Spacing;
9597     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9598     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9599     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9600                                             Spacing));
9601     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9602                                             Spacing * 2));
9603     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9604                                             Spacing * 3));
9605     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9606     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9607     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9608     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9609     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9610     TmpInst.addOperand(Inst.getOperand(5));
9611     Inst = TmpInst;
9612     return true;
9613   }
9614 
9615   // VST3 multiple 3-element structure instructions.
9616   case ARM::VST3dAsm_8:
9617   case ARM::VST3dAsm_16:
9618   case ARM::VST3dAsm_32:
9619   case ARM::VST3qAsm_8:
9620   case ARM::VST3qAsm_16:
9621   case ARM::VST3qAsm_32: {
9622     MCInst TmpInst;
9623     unsigned Spacing;
9624     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9625     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9626     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9627     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9628     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9629                                             Spacing));
9630     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9631                                             Spacing * 2));
9632     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9633     TmpInst.addOperand(Inst.getOperand(4));
9634     Inst = TmpInst;
9635     return true;
9636   }
9637 
9638   case ARM::VST3dWB_fixed_Asm_8:
9639   case ARM::VST3dWB_fixed_Asm_16:
9640   case ARM::VST3dWB_fixed_Asm_32:
9641   case ARM::VST3qWB_fixed_Asm_8:
9642   case ARM::VST3qWB_fixed_Asm_16:
9643   case ARM::VST3qWB_fixed_Asm_32: {
9644     MCInst TmpInst;
9645     unsigned Spacing;
9646     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9647     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9648     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9649     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9650     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9651     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9652     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9653                                             Spacing));
9654     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9655                                             Spacing * 2));
9656     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9657     TmpInst.addOperand(Inst.getOperand(4));
9658     Inst = TmpInst;
9659     return true;
9660   }
9661 
9662   case ARM::VST3dWB_register_Asm_8:
9663   case ARM::VST3dWB_register_Asm_16:
9664   case ARM::VST3dWB_register_Asm_32:
9665   case ARM::VST3qWB_register_Asm_8:
9666   case ARM::VST3qWB_register_Asm_16:
9667   case ARM::VST3qWB_register_Asm_32: {
9668     MCInst TmpInst;
9669     unsigned Spacing;
9670     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9671     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9672     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9673     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9674     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9675     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9676     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9677                                             Spacing));
9678     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9679                                             Spacing * 2));
9680     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9681     TmpInst.addOperand(Inst.getOperand(5));
9682     Inst = TmpInst;
9683     return true;
9684   }
9685 
9686   // VST4 multiple 3-element structure instructions.
9687   case ARM::VST4dAsm_8:
9688   case ARM::VST4dAsm_16:
9689   case ARM::VST4dAsm_32:
9690   case ARM::VST4qAsm_8:
9691   case ARM::VST4qAsm_16:
9692   case ARM::VST4qAsm_32: {
9693     MCInst TmpInst;
9694     unsigned Spacing;
9695     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9696     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9697     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9698     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9699     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9700                                             Spacing));
9701     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9702                                             Spacing * 2));
9703     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9704                                             Spacing * 3));
9705     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9706     TmpInst.addOperand(Inst.getOperand(4));
9707     Inst = TmpInst;
9708     return true;
9709   }
9710 
9711   case ARM::VST4dWB_fixed_Asm_8:
9712   case ARM::VST4dWB_fixed_Asm_16:
9713   case ARM::VST4dWB_fixed_Asm_32:
9714   case ARM::VST4qWB_fixed_Asm_8:
9715   case ARM::VST4qWB_fixed_Asm_16:
9716   case ARM::VST4qWB_fixed_Asm_32: {
9717     MCInst TmpInst;
9718     unsigned Spacing;
9719     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9720     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9721     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9722     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9723     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9724     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9725     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9726                                             Spacing));
9727     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9728                                             Spacing * 2));
9729     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9730                                             Spacing * 3));
9731     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9732     TmpInst.addOperand(Inst.getOperand(4));
9733     Inst = TmpInst;
9734     return true;
9735   }
9736 
9737   case ARM::VST4dWB_register_Asm_8:
9738   case ARM::VST4dWB_register_Asm_16:
9739   case ARM::VST4dWB_register_Asm_32:
9740   case ARM::VST4qWB_register_Asm_8:
9741   case ARM::VST4qWB_register_Asm_16:
9742   case ARM::VST4qWB_register_Asm_32: {
9743     MCInst TmpInst;
9744     unsigned Spacing;
9745     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9746     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9747     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9748     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9749     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9750     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9751     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9752                                             Spacing));
9753     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9754                                             Spacing * 2));
9755     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9756                                             Spacing * 3));
9757     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9758     TmpInst.addOperand(Inst.getOperand(5));
9759     Inst = TmpInst;
9760     return true;
9761   }
9762 
9763   // Handle encoding choice for the shift-immediate instructions.
9764   case ARM::t2LSLri:
9765   case ARM::t2LSRri:
9766   case ARM::t2ASRri:
9767     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9768         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9769         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9770         !HasWideQualifier) {
9771       unsigned NewOpc;
9772       switch (Inst.getOpcode()) {
9773       default: llvm_unreachable("unexpected opcode");
9774       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
9775       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
9776       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
9777       }
9778       // The Thumb1 operands aren't in the same order. Awesome, eh?
9779       MCInst TmpInst;
9780       TmpInst.setOpcode(NewOpc);
9781       TmpInst.addOperand(Inst.getOperand(0));
9782       TmpInst.addOperand(Inst.getOperand(5));
9783       TmpInst.addOperand(Inst.getOperand(1));
9784       TmpInst.addOperand(Inst.getOperand(2));
9785       TmpInst.addOperand(Inst.getOperand(3));
9786       TmpInst.addOperand(Inst.getOperand(4));
9787       Inst = TmpInst;
9788       return true;
9789     }
9790     return false;
9791 
9792   // Handle the Thumb2 mode MOV complex aliases.
9793   case ARM::t2MOVsr:
9794   case ARM::t2MOVSsr: {
9795     // Which instruction to expand to depends on the CCOut operand and
9796     // whether we're in an IT block if the register operands are low
9797     // registers.
9798     bool isNarrow = false;
9799     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9800         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9801         isARMLowRegister(Inst.getOperand(2).getReg()) &&
9802         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
9803         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
9804         !HasWideQualifier)
9805       isNarrow = true;
9806     MCInst TmpInst;
9807     unsigned newOpc;
9808     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
9809     default: llvm_unreachable("unexpected opcode!");
9810     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
9811     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
9812     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
9813     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
9814     }
9815     TmpInst.setOpcode(newOpc);
9816     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9817     if (isNarrow)
9818       TmpInst.addOperand(MCOperand::createReg(
9819           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
9820     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9821     TmpInst.addOperand(Inst.getOperand(2)); // Rm
9822     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9823     TmpInst.addOperand(Inst.getOperand(5));
9824     if (!isNarrow)
9825       TmpInst.addOperand(MCOperand::createReg(
9826           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
9827     Inst = TmpInst;
9828     return true;
9829   }
9830   case ARM::t2MOVsi:
9831   case ARM::t2MOVSsi: {
9832     // Which instruction to expand to depends on the CCOut operand and
9833     // whether we're in an IT block if the register operands are low
9834     // registers.
9835     bool isNarrow = false;
9836     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9837         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9838         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
9839         !HasWideQualifier)
9840       isNarrow = true;
9841     MCInst TmpInst;
9842     unsigned newOpc;
9843     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
9844     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
9845     bool isMov = false;
9846     // MOV rd, rm, LSL #0 is actually a MOV instruction
9847     if (Shift == ARM_AM::lsl && Amount == 0) {
9848       isMov = true;
9849       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
9850       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
9851       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
9852       // instead.
9853       if (inITBlock()) {
9854         isNarrow = false;
9855       }
9856       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
9857     } else {
9858       switch(Shift) {
9859       default: llvm_unreachable("unexpected opcode!");
9860       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
9861       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
9862       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
9863       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
9864       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
9865       }
9866     }
9867     if (Amount == 32) Amount = 0;
9868     TmpInst.setOpcode(newOpc);
9869     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9870     if (isNarrow && !isMov)
9871       TmpInst.addOperand(MCOperand::createReg(
9872           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
9873     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9874     if (newOpc != ARM::t2RRX && !isMov)
9875       TmpInst.addOperand(MCOperand::createImm(Amount));
9876     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9877     TmpInst.addOperand(Inst.getOperand(4));
9878     if (!isNarrow)
9879       TmpInst.addOperand(MCOperand::createReg(
9880           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
9881     Inst = TmpInst;
9882     return true;
9883   }
9884   // Handle the ARM mode MOV complex aliases.
9885   case ARM::ASRr:
9886   case ARM::LSRr:
9887   case ARM::LSLr:
9888   case ARM::RORr: {
9889     ARM_AM::ShiftOpc ShiftTy;
9890     switch(Inst.getOpcode()) {
9891     default: llvm_unreachable("unexpected opcode!");
9892     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
9893     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
9894     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
9895     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
9896     }
9897     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
9898     MCInst TmpInst;
9899     TmpInst.setOpcode(ARM::MOVsr);
9900     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9901     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9902     TmpInst.addOperand(Inst.getOperand(2)); // Rm
9903     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9904     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9905     TmpInst.addOperand(Inst.getOperand(4));
9906     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
9907     Inst = TmpInst;
9908     return true;
9909   }
9910   case ARM::ASRi:
9911   case ARM::LSRi:
9912   case ARM::LSLi:
9913   case ARM::RORi: {
9914     ARM_AM::ShiftOpc ShiftTy;
9915     switch(Inst.getOpcode()) {
9916     default: llvm_unreachable("unexpected opcode!");
9917     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
9918     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
9919     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
9920     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
9921     }
9922     // A shift by zero is a plain MOVr, not a MOVsi.
9923     unsigned Amt = Inst.getOperand(2).getImm();
9924     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
9925     // A shift by 32 should be encoded as 0 when permitted
9926     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
9927       Amt = 0;
9928     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
9929     MCInst TmpInst;
9930     TmpInst.setOpcode(Opc);
9931     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9932     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9933     if (Opc == ARM::MOVsi)
9934       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9935     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9936     TmpInst.addOperand(Inst.getOperand(4));
9937     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
9938     Inst = TmpInst;
9939     return true;
9940   }
9941   case ARM::RRXi: {
9942     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
9943     MCInst TmpInst;
9944     TmpInst.setOpcode(ARM::MOVsi);
9945     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9946     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9947     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9948     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9949     TmpInst.addOperand(Inst.getOperand(3));
9950     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
9951     Inst = TmpInst;
9952     return true;
9953   }
9954   case ARM::t2LDMIA_UPD: {
9955     // If this is a load of a single register, then we should use
9956     // a post-indexed LDR instruction instead, per the ARM ARM.
9957     if (Inst.getNumOperands() != 5)
9958       return false;
9959     MCInst TmpInst;
9960     TmpInst.setOpcode(ARM::t2LDR_POST);
9961     TmpInst.addOperand(Inst.getOperand(4)); // Rt
9962     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9963     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9964     TmpInst.addOperand(MCOperand::createImm(4));
9965     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9966     TmpInst.addOperand(Inst.getOperand(3));
9967     Inst = TmpInst;
9968     return true;
9969   }
9970   case ARM::t2STMDB_UPD: {
9971     // If this is a store of a single register, then we should use
9972     // a pre-indexed STR instruction instead, per the ARM ARM.
9973     if (Inst.getNumOperands() != 5)
9974       return false;
9975     MCInst TmpInst;
9976     TmpInst.setOpcode(ARM::t2STR_PRE);
9977     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9978     TmpInst.addOperand(Inst.getOperand(4)); // Rt
9979     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9980     TmpInst.addOperand(MCOperand::createImm(-4));
9981     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9982     TmpInst.addOperand(Inst.getOperand(3));
9983     Inst = TmpInst;
9984     return true;
9985   }
9986   case ARM::LDMIA_UPD:
9987     // If this is a load of a single register via a 'pop', then we should use
9988     // a post-indexed LDR instruction instead, per the ARM ARM.
9989     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
9990         Inst.getNumOperands() == 5) {
9991       MCInst TmpInst;
9992       TmpInst.setOpcode(ARM::LDR_POST_IMM);
9993       TmpInst.addOperand(Inst.getOperand(4)); // Rt
9994       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9995       TmpInst.addOperand(Inst.getOperand(1)); // Rn
9996       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
9997       TmpInst.addOperand(MCOperand::createImm(4));
9998       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9999       TmpInst.addOperand(Inst.getOperand(3));
10000       Inst = TmpInst;
10001       return true;
10002     }
10003     break;
10004   case ARM::STMDB_UPD:
10005     // If this is a store of a single register via a 'push', then we should use
10006     // a pre-indexed STR instruction instead, per the ARM ARM.
10007     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
10008         Inst.getNumOperands() == 5) {
10009       MCInst TmpInst;
10010       TmpInst.setOpcode(ARM::STR_PRE_IMM);
10011       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10012       TmpInst.addOperand(Inst.getOperand(4)); // Rt
10013       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
10014       TmpInst.addOperand(MCOperand::createImm(-4));
10015       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10016       TmpInst.addOperand(Inst.getOperand(3));
10017       Inst = TmpInst;
10018     }
10019     break;
10020   case ARM::t2ADDri12:
10021   case ARM::t2SUBri12:
10022   case ARM::t2ADDspImm12:
10023   case ARM::t2SUBspImm12: {
10024     // If the immediate fits for encoding T3 and the generic
10025     // mnemonic was used, encoding T3 is preferred.
10026     const StringRef Token = static_cast<ARMOperand &>(*Operands[0]).getToken();
10027     if ((Token != "add" && Token != "sub") ||
10028         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
10029       break;
10030     switch (Inst.getOpcode()) {
10031     case ARM::t2ADDri12:
10032       Inst.setOpcode(ARM::t2ADDri);
10033       break;
10034     case ARM::t2SUBri12:
10035       Inst.setOpcode(ARM::t2SUBri);
10036       break;
10037     case ARM::t2ADDspImm12:
10038       Inst.setOpcode(ARM::t2ADDspImm);
10039       break;
10040     case ARM::t2SUBspImm12:
10041       Inst.setOpcode(ARM::t2SUBspImm);
10042       break;
10043     }
10044 
10045     Inst.addOperand(MCOperand::createReg(0)); // cc_out
10046     return true;
10047   }
10048   case ARM::tADDi8:
10049     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
10050     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
10051     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
10052     // to encoding T1 if <Rd> is omitted."
10053     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
10054       Inst.setOpcode(ARM::tADDi3);
10055       return true;
10056     }
10057     break;
10058   case ARM::tSUBi8:
10059     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
10060     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
10061     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
10062     // to encoding T1 if <Rd> is omitted."
10063     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
10064       Inst.setOpcode(ARM::tSUBi3);
10065       return true;
10066     }
10067     break;
10068   case ARM::t2ADDri:
10069   case ARM::t2SUBri: {
10070     // If the destination and first source operand are the same, and
10071     // the flags are compatible with the current IT status, use encoding T2
10072     // instead of T3. For compatibility with the system 'as'. Make sure the
10073     // wide encoding wasn't explicit.
10074     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
10075         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
10076         (Inst.getOperand(2).isImm() &&
10077          (unsigned)Inst.getOperand(2).getImm() > 255) ||
10078         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
10079         HasWideQualifier)
10080       break;
10081     MCInst TmpInst;
10082     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
10083                       ARM::tADDi8 : ARM::tSUBi8);
10084     TmpInst.addOperand(Inst.getOperand(0));
10085     TmpInst.addOperand(Inst.getOperand(5));
10086     TmpInst.addOperand(Inst.getOperand(0));
10087     TmpInst.addOperand(Inst.getOperand(2));
10088     TmpInst.addOperand(Inst.getOperand(3));
10089     TmpInst.addOperand(Inst.getOperand(4));
10090     Inst = TmpInst;
10091     return true;
10092   }
10093   case ARM::t2ADDspImm:
10094   case ARM::t2SUBspImm: {
10095     // Prefer T1 encoding if possible
10096     if (Inst.getOperand(5).getReg() != 0 || HasWideQualifier)
10097       break;
10098     unsigned V = Inst.getOperand(2).getImm();
10099     if (V & 3 || V > ((1 << 7) - 1) << 2)
10100       break;
10101     MCInst TmpInst;
10102     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDspImm ? ARM::tADDspi
10103                                                           : ARM::tSUBspi);
10104     TmpInst.addOperand(MCOperand::createReg(ARM::SP)); // destination reg
10105     TmpInst.addOperand(MCOperand::createReg(ARM::SP)); // source reg
10106     TmpInst.addOperand(MCOperand::createImm(V / 4));   // immediate
10107     TmpInst.addOperand(Inst.getOperand(3));            // pred
10108     TmpInst.addOperand(Inst.getOperand(4));
10109     Inst = TmpInst;
10110     return true;
10111   }
10112   case ARM::t2ADDrr: {
10113     // If the destination and first source operand are the same, and
10114     // there's no setting of the flags, use encoding T2 instead of T3.
10115     // Note that this is only for ADD, not SUB. This mirrors the system
10116     // 'as' behaviour.  Also take advantage of ADD being commutative.
10117     // Make sure the wide encoding wasn't explicit.
10118     bool Swap = false;
10119     auto DestReg = Inst.getOperand(0).getReg();
10120     bool Transform = DestReg == Inst.getOperand(1).getReg();
10121     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
10122       Transform = true;
10123       Swap = true;
10124     }
10125     if (!Transform ||
10126         Inst.getOperand(5).getReg() != 0 ||
10127         HasWideQualifier)
10128       break;
10129     MCInst TmpInst;
10130     TmpInst.setOpcode(ARM::tADDhirr);
10131     TmpInst.addOperand(Inst.getOperand(0));
10132     TmpInst.addOperand(Inst.getOperand(0));
10133     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
10134     TmpInst.addOperand(Inst.getOperand(3));
10135     TmpInst.addOperand(Inst.getOperand(4));
10136     Inst = TmpInst;
10137     return true;
10138   }
10139   case ARM::tADDrSP:
10140     // If the non-SP source operand and the destination operand are not the
10141     // same, we need to use the 32-bit encoding if it's available.
10142     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
10143       Inst.setOpcode(ARM::t2ADDrr);
10144       Inst.addOperand(MCOperand::createReg(0)); // cc_out
10145       return true;
10146     }
10147     break;
10148   case ARM::tB:
10149     // A Thumb conditional branch outside of an IT block is a tBcc.
10150     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
10151       Inst.setOpcode(ARM::tBcc);
10152       return true;
10153     }
10154     break;
10155   case ARM::t2B:
10156     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
10157     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
10158       Inst.setOpcode(ARM::t2Bcc);
10159       return true;
10160     }
10161     break;
10162   case ARM::t2Bcc:
10163     // If the conditional is AL or we're in an IT block, we really want t2B.
10164     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
10165       Inst.setOpcode(ARM::t2B);
10166       return true;
10167     }
10168     break;
10169   case ARM::tBcc:
10170     // If the conditional is AL, we really want tB.
10171     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
10172       Inst.setOpcode(ARM::tB);
10173       return true;
10174     }
10175     break;
10176   case ARM::tLDMIA: {
10177     // If the register list contains any high registers, or if the writeback
10178     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
10179     // instead if we're in Thumb2. Otherwise, this should have generated
10180     // an error in validateInstruction().
10181     unsigned Rn = Inst.getOperand(0).getReg();
10182     bool hasWritebackToken =
10183         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
10184          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
10185     bool listContainsBase;
10186     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
10187         (!listContainsBase && !hasWritebackToken) ||
10188         (listContainsBase && hasWritebackToken)) {
10189       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
10190       assert(isThumbTwo());
10191       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
10192       // If we're switching to the updating version, we need to insert
10193       // the writeback tied operand.
10194       if (hasWritebackToken)
10195         Inst.insert(Inst.begin(),
10196                     MCOperand::createReg(Inst.getOperand(0).getReg()));
10197       return true;
10198     }
10199     break;
10200   }
10201   case ARM::tSTMIA_UPD: {
10202     // If the register list contains any high registers, we need to use
10203     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
10204     // should have generated an error in validateInstruction().
10205     unsigned Rn = Inst.getOperand(0).getReg();
10206     bool listContainsBase;
10207     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
10208       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
10209       assert(isThumbTwo());
10210       Inst.setOpcode(ARM::t2STMIA_UPD);
10211       return true;
10212     }
10213     break;
10214   }
10215   case ARM::tPOP: {
10216     bool listContainsBase;
10217     // If the register list contains any high registers, we need to use
10218     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
10219     // should have generated an error in validateInstruction().
10220     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
10221       return false;
10222     assert(isThumbTwo());
10223     Inst.setOpcode(ARM::t2LDMIA_UPD);
10224     // Add the base register and writeback operands.
10225     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10226     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10227     return true;
10228   }
10229   case ARM::tPUSH: {
10230     bool listContainsBase;
10231     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
10232       return false;
10233     assert(isThumbTwo());
10234     Inst.setOpcode(ARM::t2STMDB_UPD);
10235     // Add the base register and writeback operands.
10236     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10237     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10238     return true;
10239   }
10240   case ARM::t2MOVi:
10241     // If we can use the 16-bit encoding and the user didn't explicitly
10242     // request the 32-bit variant, transform it here.
10243     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10244         (Inst.getOperand(1).isImm() &&
10245          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
10246         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10247         !HasWideQualifier) {
10248       // The operands aren't in the same order for tMOVi8...
10249       MCInst TmpInst;
10250       TmpInst.setOpcode(ARM::tMOVi8);
10251       TmpInst.addOperand(Inst.getOperand(0));
10252       TmpInst.addOperand(Inst.getOperand(4));
10253       TmpInst.addOperand(Inst.getOperand(1));
10254       TmpInst.addOperand(Inst.getOperand(2));
10255       TmpInst.addOperand(Inst.getOperand(3));
10256       Inst = TmpInst;
10257       return true;
10258     }
10259     break;
10260 
10261   case ARM::t2MOVr:
10262     // If we can use the 16-bit encoding and the user didn't explicitly
10263     // request the 32-bit variant, transform it here.
10264     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10265         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10266         Inst.getOperand(2).getImm() == ARMCC::AL &&
10267         Inst.getOperand(4).getReg() == ARM::CPSR &&
10268         !HasWideQualifier) {
10269       // The operands aren't the same for tMOV[S]r... (no cc_out)
10270       MCInst TmpInst;
10271       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
10272       TmpInst.addOperand(Inst.getOperand(0));
10273       TmpInst.addOperand(Inst.getOperand(1));
10274       TmpInst.addOperand(Inst.getOperand(2));
10275       TmpInst.addOperand(Inst.getOperand(3));
10276       Inst = TmpInst;
10277       return true;
10278     }
10279     break;
10280 
10281   case ARM::t2SXTH:
10282   case ARM::t2SXTB:
10283   case ARM::t2UXTH:
10284   case ARM::t2UXTB:
10285     // If we can use the 16-bit encoding and the user didn't explicitly
10286     // request the 32-bit variant, transform it here.
10287     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10288         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10289         Inst.getOperand(2).getImm() == 0 &&
10290         !HasWideQualifier) {
10291       unsigned NewOpc;
10292       switch (Inst.getOpcode()) {
10293       default: llvm_unreachable("Illegal opcode!");
10294       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
10295       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
10296       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
10297       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
10298       }
10299       // The operands aren't the same for thumb1 (no rotate operand).
10300       MCInst TmpInst;
10301       TmpInst.setOpcode(NewOpc);
10302       TmpInst.addOperand(Inst.getOperand(0));
10303       TmpInst.addOperand(Inst.getOperand(1));
10304       TmpInst.addOperand(Inst.getOperand(3));
10305       TmpInst.addOperand(Inst.getOperand(4));
10306       Inst = TmpInst;
10307       return true;
10308     }
10309     break;
10310 
10311   case ARM::MOVsi: {
10312     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
10313     // rrx shifts and asr/lsr of #32 is encoded as 0
10314     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
10315       return false;
10316     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
10317       // Shifting by zero is accepted as a vanilla 'MOVr'
10318       MCInst TmpInst;
10319       TmpInst.setOpcode(ARM::MOVr);
10320       TmpInst.addOperand(Inst.getOperand(0));
10321       TmpInst.addOperand(Inst.getOperand(1));
10322       TmpInst.addOperand(Inst.getOperand(3));
10323       TmpInst.addOperand(Inst.getOperand(4));
10324       TmpInst.addOperand(Inst.getOperand(5));
10325       Inst = TmpInst;
10326       return true;
10327     }
10328     return false;
10329   }
10330   case ARM::ANDrsi:
10331   case ARM::ORRrsi:
10332   case ARM::EORrsi:
10333   case ARM::BICrsi:
10334   case ARM::SUBrsi:
10335   case ARM::ADDrsi: {
10336     unsigned newOpc;
10337     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
10338     if (SOpc == ARM_AM::rrx) return false;
10339     switch (Inst.getOpcode()) {
10340     default: llvm_unreachable("unexpected opcode!");
10341     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
10342     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
10343     case ARM::EORrsi: newOpc = ARM::EORrr; break;
10344     case ARM::BICrsi: newOpc = ARM::BICrr; break;
10345     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
10346     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
10347     }
10348     // If the shift is by zero, use the non-shifted instruction definition.
10349     // The exception is for right shifts, where 0 == 32
10350     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
10351         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
10352       MCInst TmpInst;
10353       TmpInst.setOpcode(newOpc);
10354       TmpInst.addOperand(Inst.getOperand(0));
10355       TmpInst.addOperand(Inst.getOperand(1));
10356       TmpInst.addOperand(Inst.getOperand(2));
10357       TmpInst.addOperand(Inst.getOperand(4));
10358       TmpInst.addOperand(Inst.getOperand(5));
10359       TmpInst.addOperand(Inst.getOperand(6));
10360       Inst = TmpInst;
10361       return true;
10362     }
10363     return false;
10364   }
10365   case ARM::ITasm:
10366   case ARM::t2IT: {
10367     // Set up the IT block state according to the IT instruction we just
10368     // matched.
10369     assert(!inITBlock() && "nested IT blocks?!");
10370     startExplicitITBlock(ARMCC::CondCodes(Inst.getOperand(0).getImm()),
10371                          Inst.getOperand(1).getImm());
10372     break;
10373   }
10374   case ARM::t2LSLrr:
10375   case ARM::t2LSRrr:
10376   case ARM::t2ASRrr:
10377   case ARM::t2SBCrr:
10378   case ARM::t2RORrr:
10379   case ARM::t2BICrr:
10380     // Assemblers should use the narrow encodings of these instructions when permissible.
10381     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10382          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10383         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
10384         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10385         !HasWideQualifier) {
10386       unsigned NewOpc;
10387       switch (Inst.getOpcode()) {
10388         default: llvm_unreachable("unexpected opcode");
10389         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
10390         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
10391         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
10392         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
10393         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
10394         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
10395       }
10396       MCInst TmpInst;
10397       TmpInst.setOpcode(NewOpc);
10398       TmpInst.addOperand(Inst.getOperand(0));
10399       TmpInst.addOperand(Inst.getOperand(5));
10400       TmpInst.addOperand(Inst.getOperand(1));
10401       TmpInst.addOperand(Inst.getOperand(2));
10402       TmpInst.addOperand(Inst.getOperand(3));
10403       TmpInst.addOperand(Inst.getOperand(4));
10404       Inst = TmpInst;
10405       return true;
10406     }
10407     return false;
10408 
10409   case ARM::t2ANDrr:
10410   case ARM::t2EORrr:
10411   case ARM::t2ADCrr:
10412   case ARM::t2ORRrr:
10413     // Assemblers should use the narrow encodings of these instructions when permissible.
10414     // These instructions are special in that they are commutable, so shorter encodings
10415     // are available more often.
10416     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10417          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10418         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
10419          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
10420         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10421         !HasWideQualifier) {
10422       unsigned NewOpc;
10423       switch (Inst.getOpcode()) {
10424         default: llvm_unreachable("unexpected opcode");
10425         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
10426         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
10427         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
10428         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
10429       }
10430       MCInst TmpInst;
10431       TmpInst.setOpcode(NewOpc);
10432       TmpInst.addOperand(Inst.getOperand(0));
10433       TmpInst.addOperand(Inst.getOperand(5));
10434       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
10435         TmpInst.addOperand(Inst.getOperand(1));
10436         TmpInst.addOperand(Inst.getOperand(2));
10437       } else {
10438         TmpInst.addOperand(Inst.getOperand(2));
10439         TmpInst.addOperand(Inst.getOperand(1));
10440       }
10441       TmpInst.addOperand(Inst.getOperand(3));
10442       TmpInst.addOperand(Inst.getOperand(4));
10443       Inst = TmpInst;
10444       return true;
10445     }
10446     return false;
10447   case ARM::MVE_VPST:
10448   case ARM::MVE_VPTv16i8:
10449   case ARM::MVE_VPTv8i16:
10450   case ARM::MVE_VPTv4i32:
10451   case ARM::MVE_VPTv16u8:
10452   case ARM::MVE_VPTv8u16:
10453   case ARM::MVE_VPTv4u32:
10454   case ARM::MVE_VPTv16s8:
10455   case ARM::MVE_VPTv8s16:
10456   case ARM::MVE_VPTv4s32:
10457   case ARM::MVE_VPTv4f32:
10458   case ARM::MVE_VPTv8f16:
10459   case ARM::MVE_VPTv16i8r:
10460   case ARM::MVE_VPTv8i16r:
10461   case ARM::MVE_VPTv4i32r:
10462   case ARM::MVE_VPTv16u8r:
10463   case ARM::MVE_VPTv8u16r:
10464   case ARM::MVE_VPTv4u32r:
10465   case ARM::MVE_VPTv16s8r:
10466   case ARM::MVE_VPTv8s16r:
10467   case ARM::MVE_VPTv4s32r:
10468   case ARM::MVE_VPTv4f32r:
10469   case ARM::MVE_VPTv8f16r: {
10470     assert(!inVPTBlock() && "Nested VPT blocks are not allowed");
10471     MCOperand &MO = Inst.getOperand(0);
10472     VPTState.Mask = MO.getImm();
10473     VPTState.CurPosition = 0;
10474     break;
10475   }
10476   }
10477   return false;
10478 }
10479 
10480 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
10481   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
10482   // suffix depending on whether they're in an IT block or not.
10483   unsigned Opc = Inst.getOpcode();
10484   const MCInstrDesc &MCID = MII.get(Opc);
10485   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
10486     assert(MCID.hasOptionalDef() &&
10487            "optionally flag setting instruction missing optional def operand");
10488     assert(MCID.NumOperands == Inst.getNumOperands() &&
10489            "operand count mismatch!");
10490     // Find the optional-def operand (cc_out).
10491     unsigned OpNo;
10492     for (OpNo = 0;
10493          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
10494          ++OpNo)
10495       ;
10496     // If we're parsing Thumb1, reject it completely.
10497     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
10498       return Match_RequiresFlagSetting;
10499     // If we're parsing Thumb2, which form is legal depends on whether we're
10500     // in an IT block.
10501     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
10502         !inITBlock())
10503       return Match_RequiresITBlock;
10504     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
10505         inITBlock())
10506       return Match_RequiresNotITBlock;
10507     // LSL with zero immediate is not allowed in an IT block
10508     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
10509       return Match_RequiresNotITBlock;
10510   } else if (isThumbOne()) {
10511     // Some high-register supporting Thumb1 encodings only allow both registers
10512     // to be from r0-r7 when in Thumb2.
10513     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
10514         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10515         isARMLowRegister(Inst.getOperand(2).getReg()))
10516       return Match_RequiresThumb2;
10517     // Others only require ARMv6 or later.
10518     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
10519              isARMLowRegister(Inst.getOperand(0).getReg()) &&
10520              isARMLowRegister(Inst.getOperand(1).getReg()))
10521       return Match_RequiresV6;
10522   }
10523 
10524   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
10525   // than the loop below can handle, so it uses the GPRnopc register class and
10526   // we do SP handling here.
10527   if (Opc == ARM::t2MOVr && !hasV8Ops())
10528   {
10529     // SP as both source and destination is not allowed
10530     if (Inst.getOperand(0).getReg() == ARM::SP &&
10531         Inst.getOperand(1).getReg() == ARM::SP)
10532       return Match_RequiresV8;
10533     // When flags-setting SP as either source or destination is not allowed
10534     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
10535         (Inst.getOperand(0).getReg() == ARM::SP ||
10536          Inst.getOperand(1).getReg() == ARM::SP))
10537       return Match_RequiresV8;
10538   }
10539 
10540   switch (Inst.getOpcode()) {
10541   case ARM::VMRS:
10542   case ARM::VMSR:
10543   case ARM::VMRS_FPCXTS:
10544   case ARM::VMRS_FPCXTNS:
10545   case ARM::VMSR_FPCXTS:
10546   case ARM::VMSR_FPCXTNS:
10547   case ARM::VMRS_FPSCR_NZCVQC:
10548   case ARM::VMSR_FPSCR_NZCVQC:
10549   case ARM::FMSTAT:
10550   case ARM::VMRS_VPR:
10551   case ARM::VMRS_P0:
10552   case ARM::VMSR_VPR:
10553   case ARM::VMSR_P0:
10554     // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
10555     // ARMv8-A.
10556     if (Inst.getOperand(0).isReg() && Inst.getOperand(0).getReg() == ARM::SP &&
10557         (isThumb() && !hasV8Ops()))
10558       return Match_InvalidOperand;
10559     break;
10560   default:
10561     break;
10562   }
10563 
10564   for (unsigned I = 0; I < MCID.NumOperands; ++I)
10565     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
10566       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
10567       const auto &Op = Inst.getOperand(I);
10568       if (!Op.isReg()) {
10569         // This can happen in awkward cases with tied operands, e.g. a
10570         // writeback load/store with a complex addressing mode in
10571         // which there's an output operand corresponding to the
10572         // updated written-back base register: the Tablegen-generated
10573         // AsmMatcher will have written a placeholder operand to that
10574         // slot in the form of an immediate 0, because it can't
10575         // generate the register part of the complex addressing-mode
10576         // operand ahead of time.
10577         continue;
10578       }
10579 
10580       unsigned Reg = Op.getReg();
10581       if ((Reg == ARM::SP) && !hasV8Ops())
10582         return Match_RequiresV8;
10583       else if (Reg == ARM::PC)
10584         return Match_InvalidOperand;
10585     }
10586 
10587   return Match_Success;
10588 }
10589 
10590 namespace llvm {
10591 
10592 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
10593   return true; // In an assembly source, no need to second-guess
10594 }
10595 
10596 } // end namespace llvm
10597 
10598 // Returns true if Inst is unpredictable if it is in and IT block, but is not
10599 // the last instruction in the block.
10600 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
10601   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10602 
10603   // All branch & call instructions terminate IT blocks with the exception of
10604   // SVC.
10605   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
10606       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
10607     return true;
10608 
10609   // Any arithmetic instruction which writes to the PC also terminates the IT
10610   // block.
10611   if (MCID.hasDefOfPhysReg(Inst, ARM::PC, *MRI))
10612     return true;
10613 
10614   return false;
10615 }
10616 
10617 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
10618                                           SmallVectorImpl<NearMissInfo> &NearMisses,
10619                                           bool MatchingInlineAsm,
10620                                           bool &EmitInITBlock,
10621                                           MCStreamer &Out) {
10622   // If we can't use an implicit IT block here, just match as normal.
10623   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
10624     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10625 
10626   // Try to match the instruction in an extension of the current IT block (if
10627   // there is one).
10628   if (inImplicitITBlock()) {
10629     extendImplicitITBlock(ITState.Cond);
10630     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10631             Match_Success) {
10632       // The match succeded, but we still have to check that the instruction is
10633       // valid in this implicit IT block.
10634       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10635       if (MCID.isPredicable()) {
10636         ARMCC::CondCodes InstCond =
10637             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10638                 .getImm();
10639         ARMCC::CondCodes ITCond = currentITCond();
10640         if (InstCond == ITCond) {
10641           EmitInITBlock = true;
10642           return Match_Success;
10643         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
10644           invertCurrentITCondition();
10645           EmitInITBlock = true;
10646           return Match_Success;
10647         }
10648       }
10649     }
10650     rewindImplicitITPosition();
10651   }
10652 
10653   // Finish the current IT block, and try to match outside any IT block.
10654   flushPendingInstructions(Out);
10655   unsigned PlainMatchResult =
10656       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10657   if (PlainMatchResult == Match_Success) {
10658     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10659     if (MCID.isPredicable()) {
10660       ARMCC::CondCodes InstCond =
10661           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10662               .getImm();
10663       // Some forms of the branch instruction have their own condition code
10664       // fields, so can be conditionally executed without an IT block.
10665       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
10666         EmitInITBlock = false;
10667         return Match_Success;
10668       }
10669       if (InstCond == ARMCC::AL) {
10670         EmitInITBlock = false;
10671         return Match_Success;
10672       }
10673     } else {
10674       EmitInITBlock = false;
10675       return Match_Success;
10676     }
10677   }
10678 
10679   // Try to match in a new IT block. The matcher doesn't check the actual
10680   // condition, so we create an IT block with a dummy condition, and fix it up
10681   // once we know the actual condition.
10682   startImplicitITBlock();
10683   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10684       Match_Success) {
10685     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10686     if (MCID.isPredicable()) {
10687       ITState.Cond =
10688           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10689               .getImm();
10690       EmitInITBlock = true;
10691       return Match_Success;
10692     }
10693   }
10694   discardImplicitITBlock();
10695 
10696   // If none of these succeed, return the error we got when trying to match
10697   // outside any IT blocks.
10698   EmitInITBlock = false;
10699   return PlainMatchResult;
10700 }
10701 
10702 static std::string ARMMnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,
10703                                          unsigned VariantID = 0);
10704 
10705 static const char *getSubtargetFeatureName(uint64_t Val);
10706 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
10707                                            OperandVector &Operands,
10708                                            MCStreamer &Out, uint64_t &ErrorInfo,
10709                                            bool MatchingInlineAsm) {
10710   MCInst Inst;
10711   unsigned MatchResult;
10712   bool PendConditionalInstruction = false;
10713 
10714   SmallVector<NearMissInfo, 4> NearMisses;
10715   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
10716                                  PendConditionalInstruction, Out);
10717 
10718   switch (MatchResult) {
10719   case Match_Success:
10720     LLVM_DEBUG(dbgs() << "Parsed as: ";
10721                Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10722                dbgs() << "\n");
10723 
10724     // Context sensitive operand constraints aren't handled by the matcher,
10725     // so check them here.
10726     if (validateInstruction(Inst, Operands)) {
10727       // Still progress the IT block, otherwise one wrong condition causes
10728       // nasty cascading errors.
10729       forwardITPosition();
10730       forwardVPTPosition();
10731       return true;
10732     }
10733 
10734     { // processInstruction() updates inITBlock state, we need to save it away
10735       bool wasInITBlock = inITBlock();
10736 
10737       // Some instructions need post-processing to, for example, tweak which
10738       // encoding is selected. Loop on it while changes happen so the
10739       // individual transformations can chain off each other. E.g.,
10740       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
10741       while (processInstruction(Inst, Operands, Out))
10742         LLVM_DEBUG(dbgs() << "Changed to: ";
10743                    Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10744                    dbgs() << "\n");
10745 
10746       // Only after the instruction is fully processed, we can validate it
10747       if (wasInITBlock && hasV8Ops() && isThumb() &&
10748           !isV8EligibleForIT(&Inst)) {
10749         Warning(IDLoc, "deprecated instruction in IT block");
10750       }
10751     }
10752 
10753     // Only move forward at the very end so that everything in validate
10754     // and process gets a consistent answer about whether we're in an IT
10755     // block.
10756     forwardITPosition();
10757     forwardVPTPosition();
10758 
10759     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
10760     // doesn't actually encode.
10761     if (Inst.getOpcode() == ARM::ITasm)
10762       return false;
10763 
10764     Inst.setLoc(IDLoc);
10765     if (PendConditionalInstruction) {
10766       PendingConditionalInsts.push_back(Inst);
10767       if (isITBlockFull() || isITBlockTerminator(Inst))
10768         flushPendingInstructions(Out);
10769     } else {
10770       Out.emitInstruction(Inst, getSTI());
10771     }
10772     return false;
10773   case Match_NearMisses:
10774     ReportNearMisses(NearMisses, IDLoc, Operands);
10775     return true;
10776   case Match_MnemonicFail: {
10777     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
10778     std::string Suggestion = ARMMnemonicSpellCheck(
10779       ((ARMOperand &)*Operands[0]).getToken(), FBS);
10780     return Error(IDLoc, "invalid instruction" + Suggestion,
10781                  ((ARMOperand &)*Operands[0]).getLocRange());
10782   }
10783   }
10784 
10785   llvm_unreachable("Implement any new match types added!");
10786 }
10787 
10788 /// parseDirective parses the arm specific directives
10789 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
10790   const MCObjectFileInfo::Environment Format =
10791     getContext().getObjectFileInfo()->getObjectFileType();
10792   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
10793   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
10794 
10795   std::string IDVal = DirectiveID.getIdentifier().lower();
10796   if (IDVal == ".word")
10797     parseLiteralValues(4, DirectiveID.getLoc());
10798   else if (IDVal == ".short" || IDVal == ".hword")
10799     parseLiteralValues(2, DirectiveID.getLoc());
10800   else if (IDVal == ".thumb")
10801     parseDirectiveThumb(DirectiveID.getLoc());
10802   else if (IDVal == ".arm")
10803     parseDirectiveARM(DirectiveID.getLoc());
10804   else if (IDVal == ".thumb_func")
10805     parseDirectiveThumbFunc(DirectiveID.getLoc());
10806   else if (IDVal == ".code")
10807     parseDirectiveCode(DirectiveID.getLoc());
10808   else if (IDVal == ".syntax")
10809     parseDirectiveSyntax(DirectiveID.getLoc());
10810   else if (IDVal == ".unreq")
10811     parseDirectiveUnreq(DirectiveID.getLoc());
10812   else if (IDVal == ".fnend")
10813     parseDirectiveFnEnd(DirectiveID.getLoc());
10814   else if (IDVal == ".cantunwind")
10815     parseDirectiveCantUnwind(DirectiveID.getLoc());
10816   else if (IDVal == ".personality")
10817     parseDirectivePersonality(DirectiveID.getLoc());
10818   else if (IDVal == ".handlerdata")
10819     parseDirectiveHandlerData(DirectiveID.getLoc());
10820   else if (IDVal == ".setfp")
10821     parseDirectiveSetFP(DirectiveID.getLoc());
10822   else if (IDVal == ".pad")
10823     parseDirectivePad(DirectiveID.getLoc());
10824   else if (IDVal == ".save")
10825     parseDirectiveRegSave(DirectiveID.getLoc(), false);
10826   else if (IDVal == ".vsave")
10827     parseDirectiveRegSave(DirectiveID.getLoc(), true);
10828   else if (IDVal == ".ltorg" || IDVal == ".pool")
10829     parseDirectiveLtorg(DirectiveID.getLoc());
10830   else if (IDVal == ".even")
10831     parseDirectiveEven(DirectiveID.getLoc());
10832   else if (IDVal == ".personalityindex")
10833     parseDirectivePersonalityIndex(DirectiveID.getLoc());
10834   else if (IDVal == ".unwind_raw")
10835     parseDirectiveUnwindRaw(DirectiveID.getLoc());
10836   else if (IDVal == ".movsp")
10837     parseDirectiveMovSP(DirectiveID.getLoc());
10838   else if (IDVal == ".arch_extension")
10839     parseDirectiveArchExtension(DirectiveID.getLoc());
10840   else if (IDVal == ".align")
10841     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
10842   else if (IDVal == ".thumb_set")
10843     parseDirectiveThumbSet(DirectiveID.getLoc());
10844   else if (IDVal == ".inst")
10845     parseDirectiveInst(DirectiveID.getLoc());
10846   else if (IDVal == ".inst.n")
10847     parseDirectiveInst(DirectiveID.getLoc(), 'n');
10848   else if (IDVal == ".inst.w")
10849     parseDirectiveInst(DirectiveID.getLoc(), 'w');
10850   else if (!IsMachO && !IsCOFF) {
10851     if (IDVal == ".arch")
10852       parseDirectiveArch(DirectiveID.getLoc());
10853     else if (IDVal == ".cpu")
10854       parseDirectiveCPU(DirectiveID.getLoc());
10855     else if (IDVal == ".eabi_attribute")
10856       parseDirectiveEabiAttr(DirectiveID.getLoc());
10857     else if (IDVal == ".fpu")
10858       parseDirectiveFPU(DirectiveID.getLoc());
10859     else if (IDVal == ".fnstart")
10860       parseDirectiveFnStart(DirectiveID.getLoc());
10861     else if (IDVal == ".object_arch")
10862       parseDirectiveObjectArch(DirectiveID.getLoc());
10863     else if (IDVal == ".tlsdescseq")
10864       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
10865     else
10866       return true;
10867   } else
10868     return true;
10869   return false;
10870 }
10871 
10872 /// parseLiteralValues
10873 ///  ::= .hword expression [, expression]*
10874 ///  ::= .short expression [, expression]*
10875 ///  ::= .word expression [, expression]*
10876 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
10877   auto parseOne = [&]() -> bool {
10878     const MCExpr *Value;
10879     if (getParser().parseExpression(Value))
10880       return true;
10881     getParser().getStreamer().emitValue(Value, Size, L);
10882     return false;
10883   };
10884   return (parseMany(parseOne));
10885 }
10886 
10887 /// parseDirectiveThumb
10888 ///  ::= .thumb
10889 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
10890   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
10891       check(!hasThumb(), L, "target does not support Thumb mode"))
10892     return true;
10893 
10894   if (!isThumb())
10895     SwitchMode();
10896 
10897   getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
10898   return false;
10899 }
10900 
10901 /// parseDirectiveARM
10902 ///  ::= .arm
10903 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
10904   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
10905       check(!hasARM(), L, "target does not support ARM mode"))
10906     return true;
10907 
10908   if (isThumb())
10909     SwitchMode();
10910   getParser().getStreamer().emitAssemblerFlag(MCAF_Code32);
10911   return false;
10912 }
10913 
10914 void ARMAsmParser::doBeforeLabelEmit(MCSymbol *Symbol) {
10915   // We need to flush the current implicit IT block on a label, because it is
10916   // not legal to branch into an IT block.
10917   flushPendingInstructions(getStreamer());
10918 }
10919 
10920 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
10921   if (NextSymbolIsThumb) {
10922     getParser().getStreamer().emitThumbFunc(Symbol);
10923     NextSymbolIsThumb = false;
10924   }
10925 }
10926 
10927 /// parseDirectiveThumbFunc
10928 ///  ::= .thumbfunc symbol_name
10929 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
10930   MCAsmParser &Parser = getParser();
10931   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
10932   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
10933 
10934   // Darwin asm has (optionally) function name after .thumb_func direction
10935   // ELF doesn't
10936 
10937   if (IsMachO) {
10938     if (Parser.getTok().is(AsmToken::Identifier) ||
10939         Parser.getTok().is(AsmToken::String)) {
10940       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
10941           Parser.getTok().getIdentifier());
10942       getParser().getStreamer().emitThumbFunc(Func);
10943       Parser.Lex();
10944       if (parseToken(AsmToken::EndOfStatement,
10945                      "unexpected token in '.thumb_func' directive"))
10946         return true;
10947       return false;
10948     }
10949   }
10950 
10951   if (parseToken(AsmToken::EndOfStatement,
10952                  "unexpected token in '.thumb_func' directive"))
10953     return true;
10954 
10955   NextSymbolIsThumb = true;
10956   return false;
10957 }
10958 
10959 /// parseDirectiveSyntax
10960 ///  ::= .syntax unified | divided
10961 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
10962   MCAsmParser &Parser = getParser();
10963   const AsmToken &Tok = Parser.getTok();
10964   if (Tok.isNot(AsmToken::Identifier)) {
10965     Error(L, "unexpected token in .syntax directive");
10966     return false;
10967   }
10968 
10969   StringRef Mode = Tok.getString();
10970   Parser.Lex();
10971   if (check(Mode == "divided" || Mode == "DIVIDED", L,
10972             "'.syntax divided' arm assembly not supported") ||
10973       check(Mode != "unified" && Mode != "UNIFIED", L,
10974             "unrecognized syntax mode in .syntax directive") ||
10975       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10976     return true;
10977 
10978   // TODO tell the MC streamer the mode
10979   // getParser().getStreamer().Emit???();
10980   return false;
10981 }
10982 
10983 /// parseDirectiveCode
10984 ///  ::= .code 16 | 32
10985 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
10986   MCAsmParser &Parser = getParser();
10987   const AsmToken &Tok = Parser.getTok();
10988   if (Tok.isNot(AsmToken::Integer))
10989     return Error(L, "unexpected token in .code directive");
10990   int64_t Val = Parser.getTok().getIntVal();
10991   if (Val != 16 && Val != 32) {
10992     Error(L, "invalid operand to .code directive");
10993     return false;
10994   }
10995   Parser.Lex();
10996 
10997   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10998     return true;
10999 
11000   if (Val == 16) {
11001     if (!hasThumb())
11002       return Error(L, "target does not support Thumb mode");
11003 
11004     if (!isThumb())
11005       SwitchMode();
11006     getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
11007   } else {
11008     if (!hasARM())
11009       return Error(L, "target does not support ARM mode");
11010 
11011     if (isThumb())
11012       SwitchMode();
11013     getParser().getStreamer().emitAssemblerFlag(MCAF_Code32);
11014   }
11015 
11016   return false;
11017 }
11018 
11019 /// parseDirectiveReq
11020 ///  ::= name .req registername
11021 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
11022   MCAsmParser &Parser = getParser();
11023   Parser.Lex(); // Eat the '.req' token.
11024   unsigned Reg;
11025   SMLoc SRegLoc, ERegLoc;
11026   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
11027             "register name expected") ||
11028       parseToken(AsmToken::EndOfStatement,
11029                  "unexpected input in .req directive."))
11030     return true;
11031 
11032   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
11033     return Error(SRegLoc,
11034                  "redefinition of '" + Name + "' does not match original.");
11035 
11036   return false;
11037 }
11038 
11039 /// parseDirectiveUneq
11040 ///  ::= .unreq registername
11041 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
11042   MCAsmParser &Parser = getParser();
11043   if (Parser.getTok().isNot(AsmToken::Identifier))
11044     return Error(L, "unexpected input in .unreq directive.");
11045   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
11046   Parser.Lex(); // Eat the identifier.
11047   if (parseToken(AsmToken::EndOfStatement,
11048                  "unexpected input in '.unreq' directive"))
11049     return true;
11050   return false;
11051 }
11052 
11053 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
11054 // before, if supported by the new target, or emit mapping symbols for the mode
11055 // switch.
11056 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
11057   if (WasThumb != isThumb()) {
11058     if (WasThumb && hasThumb()) {
11059       // Stay in Thumb mode
11060       SwitchMode();
11061     } else if (!WasThumb && hasARM()) {
11062       // Stay in ARM mode
11063       SwitchMode();
11064     } else {
11065       // Mode switch forced, because the new arch doesn't support the old mode.
11066       getParser().getStreamer().emitAssemblerFlag(isThumb() ? MCAF_Code16
11067                                                             : MCAF_Code32);
11068       // Warn about the implcit mode switch. GAS does not switch modes here,
11069       // but instead stays in the old mode, reporting an error on any following
11070       // instructions as the mode does not exist on the target.
11071       Warning(Loc, Twine("new target does not support ") +
11072                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
11073                        (!WasThumb ? "thumb" : "arm") + " mode");
11074     }
11075   }
11076 }
11077 
11078 /// parseDirectiveArch
11079 ///  ::= .arch token
11080 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
11081   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
11082   ARM::ArchKind ID = ARM::parseArch(Arch);
11083 
11084   if (ID == ARM::ArchKind::INVALID)
11085     return Error(L, "Unknown arch name");
11086 
11087   bool WasThumb = isThumb();
11088   Triple T;
11089   MCSubtargetInfo &STI = copySTI();
11090   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
11091   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11092   FixModeAfterArchChange(WasThumb, L);
11093 
11094   getTargetStreamer().emitArch(ID);
11095   return false;
11096 }
11097 
11098 /// parseDirectiveEabiAttr
11099 ///  ::= .eabi_attribute int, int [, "str"]
11100 ///  ::= .eabi_attribute Tag_name, int [, "str"]
11101 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
11102   MCAsmParser &Parser = getParser();
11103   int64_t Tag;
11104   SMLoc TagLoc;
11105   TagLoc = Parser.getTok().getLoc();
11106   if (Parser.getTok().is(AsmToken::Identifier)) {
11107     StringRef Name = Parser.getTok().getIdentifier();
11108     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
11109     if (Tag == -1) {
11110       Error(TagLoc, "attribute name not recognised: " + Name);
11111       return false;
11112     }
11113     Parser.Lex();
11114   } else {
11115     const MCExpr *AttrExpr;
11116 
11117     TagLoc = Parser.getTok().getLoc();
11118     if (Parser.parseExpression(AttrExpr))
11119       return true;
11120 
11121     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
11122     if (check(!CE, TagLoc, "expected numeric constant"))
11123       return true;
11124 
11125     Tag = CE->getValue();
11126   }
11127 
11128   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
11129     return true;
11130 
11131   StringRef StringValue = "";
11132   bool IsStringValue = false;
11133 
11134   int64_t IntegerValue = 0;
11135   bool IsIntegerValue = false;
11136 
11137   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
11138     IsStringValue = true;
11139   else if (Tag == ARMBuildAttrs::compatibility) {
11140     IsStringValue = true;
11141     IsIntegerValue = true;
11142   } else if (Tag < 32 || Tag % 2 == 0)
11143     IsIntegerValue = true;
11144   else if (Tag % 2 == 1)
11145     IsStringValue = true;
11146   else
11147     llvm_unreachable("invalid tag type");
11148 
11149   if (IsIntegerValue) {
11150     const MCExpr *ValueExpr;
11151     SMLoc ValueExprLoc = Parser.getTok().getLoc();
11152     if (Parser.parseExpression(ValueExpr))
11153       return true;
11154 
11155     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
11156     if (!CE)
11157       return Error(ValueExprLoc, "expected numeric constant");
11158     IntegerValue = CE->getValue();
11159   }
11160 
11161   if (Tag == ARMBuildAttrs::compatibility) {
11162     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
11163       return true;
11164   }
11165 
11166   if (IsStringValue) {
11167     if (Parser.getTok().isNot(AsmToken::String))
11168       return Error(Parser.getTok().getLoc(), "bad string constant");
11169 
11170     StringValue = Parser.getTok().getStringContents();
11171     Parser.Lex();
11172   }
11173 
11174   if (Parser.parseToken(AsmToken::EndOfStatement,
11175                         "unexpected token in '.eabi_attribute' directive"))
11176     return true;
11177 
11178   if (IsIntegerValue && IsStringValue) {
11179     assert(Tag == ARMBuildAttrs::compatibility);
11180     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
11181   } else if (IsIntegerValue)
11182     getTargetStreamer().emitAttribute(Tag, IntegerValue);
11183   else if (IsStringValue)
11184     getTargetStreamer().emitTextAttribute(Tag, StringValue);
11185   return false;
11186 }
11187 
11188 /// parseDirectiveCPU
11189 ///  ::= .cpu str
11190 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
11191   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
11192   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
11193 
11194   // FIXME: This is using table-gen data, but should be moved to
11195   // ARMTargetParser once that is table-gen'd.
11196   if (!getSTI().isCPUStringValid(CPU))
11197     return Error(L, "Unknown CPU name");
11198 
11199   bool WasThumb = isThumb();
11200   MCSubtargetInfo &STI = copySTI();
11201   STI.setDefaultFeatures(CPU, "");
11202   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11203   FixModeAfterArchChange(WasThumb, L);
11204 
11205   return false;
11206 }
11207 
11208 /// parseDirectiveFPU
11209 ///  ::= .fpu str
11210 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
11211   SMLoc FPUNameLoc = getTok().getLoc();
11212   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
11213 
11214   unsigned ID = ARM::parseFPU(FPU);
11215   std::vector<StringRef> Features;
11216   if (!ARM::getFPUFeatures(ID, Features))
11217     return Error(FPUNameLoc, "Unknown FPU name");
11218 
11219   MCSubtargetInfo &STI = copySTI();
11220   for (auto Feature : Features)
11221     STI.ApplyFeatureFlag(Feature);
11222   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11223 
11224   getTargetStreamer().emitFPU(ID);
11225   return false;
11226 }
11227 
11228 /// parseDirectiveFnStart
11229 ///  ::= .fnstart
11230 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
11231   if (parseToken(AsmToken::EndOfStatement,
11232                  "unexpected token in '.fnstart' directive"))
11233     return true;
11234 
11235   if (UC.hasFnStart()) {
11236     Error(L, ".fnstart starts before the end of previous one");
11237     UC.emitFnStartLocNotes();
11238     return true;
11239   }
11240 
11241   // Reset the unwind directives parser state
11242   UC.reset();
11243 
11244   getTargetStreamer().emitFnStart();
11245 
11246   UC.recordFnStart(L);
11247   return false;
11248 }
11249 
11250 /// parseDirectiveFnEnd
11251 ///  ::= .fnend
11252 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
11253   if (parseToken(AsmToken::EndOfStatement,
11254                  "unexpected token in '.fnend' directive"))
11255     return true;
11256   // Check the ordering of unwind directives
11257   if (!UC.hasFnStart())
11258     return Error(L, ".fnstart must precede .fnend directive");
11259 
11260   // Reset the unwind directives parser state
11261   getTargetStreamer().emitFnEnd();
11262 
11263   UC.reset();
11264   return false;
11265 }
11266 
11267 /// parseDirectiveCantUnwind
11268 ///  ::= .cantunwind
11269 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
11270   if (parseToken(AsmToken::EndOfStatement,
11271                  "unexpected token in '.cantunwind' directive"))
11272     return true;
11273 
11274   UC.recordCantUnwind(L);
11275   // Check the ordering of unwind directives
11276   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
11277     return true;
11278 
11279   if (UC.hasHandlerData()) {
11280     Error(L, ".cantunwind can't be used with .handlerdata directive");
11281     UC.emitHandlerDataLocNotes();
11282     return true;
11283   }
11284   if (UC.hasPersonality()) {
11285     Error(L, ".cantunwind can't be used with .personality directive");
11286     UC.emitPersonalityLocNotes();
11287     return true;
11288   }
11289 
11290   getTargetStreamer().emitCantUnwind();
11291   return false;
11292 }
11293 
11294 /// parseDirectivePersonality
11295 ///  ::= .personality name
11296 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
11297   MCAsmParser &Parser = getParser();
11298   bool HasExistingPersonality = UC.hasPersonality();
11299 
11300   // Parse the name of the personality routine
11301   if (Parser.getTok().isNot(AsmToken::Identifier))
11302     return Error(L, "unexpected input in .personality directive.");
11303   StringRef Name(Parser.getTok().getIdentifier());
11304   Parser.Lex();
11305 
11306   if (parseToken(AsmToken::EndOfStatement,
11307                  "unexpected token in '.personality' directive"))
11308     return true;
11309 
11310   UC.recordPersonality(L);
11311 
11312   // Check the ordering of unwind directives
11313   if (!UC.hasFnStart())
11314     return Error(L, ".fnstart must precede .personality directive");
11315   if (UC.cantUnwind()) {
11316     Error(L, ".personality can't be used with .cantunwind directive");
11317     UC.emitCantUnwindLocNotes();
11318     return true;
11319   }
11320   if (UC.hasHandlerData()) {
11321     Error(L, ".personality must precede .handlerdata directive");
11322     UC.emitHandlerDataLocNotes();
11323     return true;
11324   }
11325   if (HasExistingPersonality) {
11326     Error(L, "multiple personality directives");
11327     UC.emitPersonalityLocNotes();
11328     return true;
11329   }
11330 
11331   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
11332   getTargetStreamer().emitPersonality(PR);
11333   return false;
11334 }
11335 
11336 /// parseDirectiveHandlerData
11337 ///  ::= .handlerdata
11338 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
11339   if (parseToken(AsmToken::EndOfStatement,
11340                  "unexpected token in '.handlerdata' directive"))
11341     return true;
11342 
11343   UC.recordHandlerData(L);
11344   // Check the ordering of unwind directives
11345   if (!UC.hasFnStart())
11346     return Error(L, ".fnstart must precede .personality directive");
11347   if (UC.cantUnwind()) {
11348     Error(L, ".handlerdata can't be used with .cantunwind directive");
11349     UC.emitCantUnwindLocNotes();
11350     return true;
11351   }
11352 
11353   getTargetStreamer().emitHandlerData();
11354   return false;
11355 }
11356 
11357 /// parseDirectiveSetFP
11358 ///  ::= .setfp fpreg, spreg [, offset]
11359 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
11360   MCAsmParser &Parser = getParser();
11361   // Check the ordering of unwind directives
11362   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
11363       check(UC.hasHandlerData(), L,
11364             ".setfp must precede .handlerdata directive"))
11365     return true;
11366 
11367   // Parse fpreg
11368   SMLoc FPRegLoc = Parser.getTok().getLoc();
11369   int FPReg = tryParseRegister();
11370 
11371   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
11372       Parser.parseToken(AsmToken::Comma, "comma expected"))
11373     return true;
11374 
11375   // Parse spreg
11376   SMLoc SPRegLoc = Parser.getTok().getLoc();
11377   int SPReg = tryParseRegister();
11378   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
11379       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
11380             "register should be either $sp or the latest fp register"))
11381     return true;
11382 
11383   // Update the frame pointer register
11384   UC.saveFPReg(FPReg);
11385 
11386   // Parse offset
11387   int64_t Offset = 0;
11388   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11389     if (Parser.getTok().isNot(AsmToken::Hash) &&
11390         Parser.getTok().isNot(AsmToken::Dollar))
11391       return Error(Parser.getTok().getLoc(), "'#' expected");
11392     Parser.Lex(); // skip hash token.
11393 
11394     const MCExpr *OffsetExpr;
11395     SMLoc ExLoc = Parser.getTok().getLoc();
11396     SMLoc EndLoc;
11397     if (getParser().parseExpression(OffsetExpr, EndLoc))
11398       return Error(ExLoc, "malformed setfp offset");
11399     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11400     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
11401       return true;
11402     Offset = CE->getValue();
11403   }
11404 
11405   if (Parser.parseToken(AsmToken::EndOfStatement))
11406     return true;
11407 
11408   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
11409                                 static_cast<unsigned>(SPReg), Offset);
11410   return false;
11411 }
11412 
11413 /// parseDirective
11414 ///  ::= .pad offset
11415 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
11416   MCAsmParser &Parser = getParser();
11417   // Check the ordering of unwind directives
11418   if (!UC.hasFnStart())
11419     return Error(L, ".fnstart must precede .pad directive");
11420   if (UC.hasHandlerData())
11421     return Error(L, ".pad must precede .handlerdata directive");
11422 
11423   // Parse the offset
11424   if (Parser.getTok().isNot(AsmToken::Hash) &&
11425       Parser.getTok().isNot(AsmToken::Dollar))
11426     return Error(Parser.getTok().getLoc(), "'#' expected");
11427   Parser.Lex(); // skip hash token.
11428 
11429   const MCExpr *OffsetExpr;
11430   SMLoc ExLoc = Parser.getTok().getLoc();
11431   SMLoc EndLoc;
11432   if (getParser().parseExpression(OffsetExpr, EndLoc))
11433     return Error(ExLoc, "malformed pad offset");
11434   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11435   if (!CE)
11436     return Error(ExLoc, "pad offset must be an immediate");
11437 
11438   if (parseToken(AsmToken::EndOfStatement,
11439                  "unexpected token in '.pad' directive"))
11440     return true;
11441 
11442   getTargetStreamer().emitPad(CE->getValue());
11443   return false;
11444 }
11445 
11446 /// parseDirectiveRegSave
11447 ///  ::= .save  { registers }
11448 ///  ::= .vsave { registers }
11449 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
11450   // Check the ordering of unwind directives
11451   if (!UC.hasFnStart())
11452     return Error(L, ".fnstart must precede .save or .vsave directives");
11453   if (UC.hasHandlerData())
11454     return Error(L, ".save or .vsave must precede .handlerdata directive");
11455 
11456   // RAII object to make sure parsed operands are deleted.
11457   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
11458 
11459   // Parse the register list
11460   if (parseRegisterList(Operands) ||
11461       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11462     return true;
11463   ARMOperand &Op = (ARMOperand &)*Operands[0];
11464   if (!IsVector && !Op.isRegList())
11465     return Error(L, ".save expects GPR registers");
11466   if (IsVector && !Op.isDPRRegList())
11467     return Error(L, ".vsave expects DPR registers");
11468 
11469   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
11470   return false;
11471 }
11472 
11473 /// parseDirectiveInst
11474 ///  ::= .inst opcode [, ...]
11475 ///  ::= .inst.n opcode [, ...]
11476 ///  ::= .inst.w opcode [, ...]
11477 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
11478   int Width = 4;
11479 
11480   if (isThumb()) {
11481     switch (Suffix) {
11482     case 'n':
11483       Width = 2;
11484       break;
11485     case 'w':
11486       break;
11487     default:
11488       Width = 0;
11489       break;
11490     }
11491   } else {
11492     if (Suffix)
11493       return Error(Loc, "width suffixes are invalid in ARM mode");
11494   }
11495 
11496   auto parseOne = [&]() -> bool {
11497     const MCExpr *Expr;
11498     if (getParser().parseExpression(Expr))
11499       return true;
11500     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
11501     if (!Value) {
11502       return Error(Loc, "expected constant expression");
11503     }
11504 
11505     char CurSuffix = Suffix;
11506     switch (Width) {
11507     case 2:
11508       if (Value->getValue() > 0xffff)
11509         return Error(Loc, "inst.n operand is too big, use inst.w instead");
11510       break;
11511     case 4:
11512       if (Value->getValue() > 0xffffffff)
11513         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
11514                               " operand is too big");
11515       break;
11516     case 0:
11517       // Thumb mode, no width indicated. Guess from the opcode, if possible.
11518       if (Value->getValue() < 0xe800)
11519         CurSuffix = 'n';
11520       else if (Value->getValue() >= 0xe8000000)
11521         CurSuffix = 'w';
11522       else
11523         return Error(Loc, "cannot determine Thumb instruction size, "
11524                           "use inst.n/inst.w instead");
11525       break;
11526     default:
11527       llvm_unreachable("only supported widths are 2 and 4");
11528     }
11529 
11530     getTargetStreamer().emitInst(Value->getValue(), CurSuffix);
11531     return false;
11532   };
11533 
11534   if (parseOptionalToken(AsmToken::EndOfStatement))
11535     return Error(Loc, "expected expression following directive");
11536   if (parseMany(parseOne))
11537     return true;
11538   return false;
11539 }
11540 
11541 /// parseDirectiveLtorg
11542 ///  ::= .ltorg | .pool
11543 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
11544   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11545     return true;
11546   getTargetStreamer().emitCurrentConstantPool();
11547   return false;
11548 }
11549 
11550 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
11551   const MCSection *Section = getStreamer().getCurrentSectionOnly();
11552 
11553   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11554     return true;
11555 
11556   if (!Section) {
11557     getStreamer().InitSections(false);
11558     Section = getStreamer().getCurrentSectionOnly();
11559   }
11560 
11561   assert(Section && "must have section to emit alignment");
11562   if (Section->UseCodeAlign())
11563     getStreamer().emitCodeAlignment(2);
11564   else
11565     getStreamer().emitValueToAlignment(2);
11566 
11567   return false;
11568 }
11569 
11570 /// parseDirectivePersonalityIndex
11571 ///   ::= .personalityindex index
11572 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
11573   MCAsmParser &Parser = getParser();
11574   bool HasExistingPersonality = UC.hasPersonality();
11575 
11576   const MCExpr *IndexExpression;
11577   SMLoc IndexLoc = Parser.getTok().getLoc();
11578   if (Parser.parseExpression(IndexExpression) ||
11579       parseToken(AsmToken::EndOfStatement,
11580                  "unexpected token in '.personalityindex' directive")) {
11581     return true;
11582   }
11583 
11584   UC.recordPersonalityIndex(L);
11585 
11586   if (!UC.hasFnStart()) {
11587     return Error(L, ".fnstart must precede .personalityindex directive");
11588   }
11589   if (UC.cantUnwind()) {
11590     Error(L, ".personalityindex cannot be used with .cantunwind");
11591     UC.emitCantUnwindLocNotes();
11592     return true;
11593   }
11594   if (UC.hasHandlerData()) {
11595     Error(L, ".personalityindex must precede .handlerdata directive");
11596     UC.emitHandlerDataLocNotes();
11597     return true;
11598   }
11599   if (HasExistingPersonality) {
11600     Error(L, "multiple personality directives");
11601     UC.emitPersonalityLocNotes();
11602     return true;
11603   }
11604 
11605   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
11606   if (!CE)
11607     return Error(IndexLoc, "index must be a constant number");
11608   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
11609     return Error(IndexLoc,
11610                  "personality routine index should be in range [0-3]");
11611 
11612   getTargetStreamer().emitPersonalityIndex(CE->getValue());
11613   return false;
11614 }
11615 
11616 /// parseDirectiveUnwindRaw
11617 ///   ::= .unwind_raw offset, opcode [, opcode...]
11618 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
11619   MCAsmParser &Parser = getParser();
11620   int64_t StackOffset;
11621   const MCExpr *OffsetExpr;
11622   SMLoc OffsetLoc = getLexer().getLoc();
11623 
11624   if (!UC.hasFnStart())
11625     return Error(L, ".fnstart must precede .unwind_raw directives");
11626   if (getParser().parseExpression(OffsetExpr))
11627     return Error(OffsetLoc, "expected expression");
11628 
11629   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11630   if (!CE)
11631     return Error(OffsetLoc, "offset must be a constant");
11632 
11633   StackOffset = CE->getValue();
11634 
11635   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
11636     return true;
11637 
11638   SmallVector<uint8_t, 16> Opcodes;
11639 
11640   auto parseOne = [&]() -> bool {
11641     const MCExpr *OE = nullptr;
11642     SMLoc OpcodeLoc = getLexer().getLoc();
11643     if (check(getLexer().is(AsmToken::EndOfStatement) ||
11644                   Parser.parseExpression(OE),
11645               OpcodeLoc, "expected opcode expression"))
11646       return true;
11647     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
11648     if (!OC)
11649       return Error(OpcodeLoc, "opcode value must be a constant");
11650     const int64_t Opcode = OC->getValue();
11651     if (Opcode & ~0xff)
11652       return Error(OpcodeLoc, "invalid opcode");
11653     Opcodes.push_back(uint8_t(Opcode));
11654     return false;
11655   };
11656 
11657   // Must have at least 1 element
11658   SMLoc OpcodeLoc = getLexer().getLoc();
11659   if (parseOptionalToken(AsmToken::EndOfStatement))
11660     return Error(OpcodeLoc, "expected opcode expression");
11661   if (parseMany(parseOne))
11662     return true;
11663 
11664   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
11665   return false;
11666 }
11667 
11668 /// parseDirectiveTLSDescSeq
11669 ///   ::= .tlsdescseq tls-variable
11670 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
11671   MCAsmParser &Parser = getParser();
11672 
11673   if (getLexer().isNot(AsmToken::Identifier))
11674     return TokError("expected variable after '.tlsdescseq' directive");
11675 
11676   const MCSymbolRefExpr *SRE =
11677     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
11678                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
11679   Lex();
11680 
11681   if (parseToken(AsmToken::EndOfStatement,
11682                  "unexpected token in '.tlsdescseq' directive"))
11683     return true;
11684 
11685   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
11686   return false;
11687 }
11688 
11689 /// parseDirectiveMovSP
11690 ///  ::= .movsp reg [, #offset]
11691 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
11692   MCAsmParser &Parser = getParser();
11693   if (!UC.hasFnStart())
11694     return Error(L, ".fnstart must precede .movsp directives");
11695   if (UC.getFPReg() != ARM::SP)
11696     return Error(L, "unexpected .movsp directive");
11697 
11698   SMLoc SPRegLoc = Parser.getTok().getLoc();
11699   int SPReg = tryParseRegister();
11700   if (SPReg == -1)
11701     return Error(SPRegLoc, "register expected");
11702   if (SPReg == ARM::SP || SPReg == ARM::PC)
11703     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
11704 
11705   int64_t Offset = 0;
11706   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11707     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
11708       return true;
11709 
11710     const MCExpr *OffsetExpr;
11711     SMLoc OffsetLoc = Parser.getTok().getLoc();
11712 
11713     if (Parser.parseExpression(OffsetExpr))
11714       return Error(OffsetLoc, "malformed offset expression");
11715 
11716     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11717     if (!CE)
11718       return Error(OffsetLoc, "offset must be an immediate constant");
11719 
11720     Offset = CE->getValue();
11721   }
11722 
11723   if (parseToken(AsmToken::EndOfStatement,
11724                  "unexpected token in '.movsp' directive"))
11725     return true;
11726 
11727   getTargetStreamer().emitMovSP(SPReg, Offset);
11728   UC.saveFPReg(SPReg);
11729 
11730   return false;
11731 }
11732 
11733 /// parseDirectiveObjectArch
11734 ///   ::= .object_arch name
11735 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
11736   MCAsmParser &Parser = getParser();
11737   if (getLexer().isNot(AsmToken::Identifier))
11738     return Error(getLexer().getLoc(), "unexpected token");
11739 
11740   StringRef Arch = Parser.getTok().getString();
11741   SMLoc ArchLoc = Parser.getTok().getLoc();
11742   Lex();
11743 
11744   ARM::ArchKind ID = ARM::parseArch(Arch);
11745 
11746   if (ID == ARM::ArchKind::INVALID)
11747     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
11748   if (parseToken(AsmToken::EndOfStatement))
11749     return true;
11750 
11751   getTargetStreamer().emitObjectArch(ID);
11752   return false;
11753 }
11754 
11755 /// parseDirectiveAlign
11756 ///   ::= .align
11757 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
11758   // NOTE: if this is not the end of the statement, fall back to the target
11759   // agnostic handling for this directive which will correctly handle this.
11760   if (parseOptionalToken(AsmToken::EndOfStatement)) {
11761     // '.align' is target specifically handled to mean 2**2 byte alignment.
11762     const MCSection *Section = getStreamer().getCurrentSectionOnly();
11763     assert(Section && "must have section to emit alignment");
11764     if (Section->UseCodeAlign())
11765       getStreamer().emitCodeAlignment(4, 0);
11766     else
11767       getStreamer().emitValueToAlignment(4, 0, 1, 0);
11768     return false;
11769   }
11770   return true;
11771 }
11772 
11773 /// parseDirectiveThumbSet
11774 ///  ::= .thumb_set name, value
11775 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
11776   MCAsmParser &Parser = getParser();
11777 
11778   StringRef Name;
11779   if (check(Parser.parseIdentifier(Name),
11780             "expected identifier after '.thumb_set'") ||
11781       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
11782     return true;
11783 
11784   MCSymbol *Sym;
11785   const MCExpr *Value;
11786   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
11787                                                Parser, Sym, Value))
11788     return true;
11789 
11790   getTargetStreamer().emitThumbSet(Sym, Value);
11791   return false;
11792 }
11793 
11794 /// Force static initialization.
11795 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeARMAsmParser() {
11796   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
11797   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
11798   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
11799   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
11800 }
11801 
11802 #define GET_REGISTER_MATCHER
11803 #define GET_SUBTARGET_FEATURE_NAME
11804 #define GET_MATCHER_IMPLEMENTATION
11805 #define GET_MNEMONIC_SPELL_CHECKER
11806 #include "ARMGenAsmMatcher.inc"
11807 
11808 // Some diagnostics need to vary with subtarget features, so they are handled
11809 // here. For example, the DPR class has either 16 or 32 registers, depending
11810 // on the FPU available.
11811 const char *
11812 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
11813   switch (MatchError) {
11814   // rGPR contains sp starting with ARMv8.
11815   case Match_rGPR:
11816     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
11817                       : "operand must be a register in range [r0, r12] or r14";
11818   // DPR contains 16 registers for some FPUs, and 32 for others.
11819   case Match_DPR:
11820     return hasD32() ? "operand must be a register in range [d0, d31]"
11821                     : "operand must be a register in range [d0, d15]";
11822   case Match_DPR_RegList:
11823     return hasD32() ? "operand must be a list of registers in range [d0, d31]"
11824                     : "operand must be a list of registers in range [d0, d15]";
11825 
11826   // For all other diags, use the static string from tablegen.
11827   default:
11828     return getMatchKindDiag(MatchError);
11829   }
11830 }
11831 
11832 // Process the list of near-misses, throwing away ones we don't want to report
11833 // to the user, and converting the rest to a source location and string that
11834 // should be reported.
11835 void
11836 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
11837                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
11838                                SMLoc IDLoc, OperandVector &Operands) {
11839   // TODO: If operand didn't match, sub in a dummy one and run target
11840   // predicate, so that we can avoid reporting near-misses that are invalid?
11841   // TODO: Many operand types dont have SuperClasses set, so we report
11842   // redundant ones.
11843   // TODO: Some operands are superclasses of registers (e.g.
11844   // MCK_RegShiftedImm), we don't have any way to represent that currently.
11845   // TODO: This is not all ARM-specific, can some of it be factored out?
11846 
11847   // Record some information about near-misses that we have already seen, so
11848   // that we can avoid reporting redundant ones. For example, if there are
11849   // variants of an instruction that take 8- and 16-bit immediates, we want
11850   // to only report the widest one.
11851   std::multimap<unsigned, unsigned> OperandMissesSeen;
11852   SmallSet<FeatureBitset, 4> FeatureMissesSeen;
11853   bool ReportedTooFewOperands = false;
11854 
11855   // Process the near-misses in reverse order, so that we see more general ones
11856   // first, and so can avoid emitting more specific ones.
11857   for (NearMissInfo &I : reverse(NearMissesIn)) {
11858     switch (I.getKind()) {
11859     case NearMissInfo::NearMissOperand: {
11860       SMLoc OperandLoc =
11861           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
11862       const char *OperandDiag =
11863           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
11864 
11865       // If we have already emitted a message for a superclass, don't also report
11866       // the sub-class. We consider all operand classes that we don't have a
11867       // specialised diagnostic for to be equal for the propose of this check,
11868       // so that we don't report the generic error multiple times on the same
11869       // operand.
11870       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
11871       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
11872       if (std::any_of(PrevReports.first, PrevReports.second,
11873                       [DupCheckMatchClass](
11874                           const std::pair<unsigned, unsigned> Pair) {
11875             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
11876               return Pair.second == DupCheckMatchClass;
11877             else
11878               return isSubclass((MatchClassKind)DupCheckMatchClass,
11879                                 (MatchClassKind)Pair.second);
11880           }))
11881         break;
11882       OperandMissesSeen.insert(
11883           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
11884 
11885       NearMissMessage Message;
11886       Message.Loc = OperandLoc;
11887       if (OperandDiag) {
11888         Message.Message = OperandDiag;
11889       } else if (I.getOperandClass() == InvalidMatchClass) {
11890         Message.Message = "too many operands for instruction";
11891       } else {
11892         Message.Message = "invalid operand for instruction";
11893         LLVM_DEBUG(
11894             dbgs() << "Missing diagnostic string for operand class "
11895                    << getMatchClassName((MatchClassKind)I.getOperandClass())
11896                    << I.getOperandClass() << ", error " << I.getOperandError()
11897                    << ", opcode " << MII.getName(I.getOpcode()) << "\n");
11898       }
11899       NearMissesOut.emplace_back(Message);
11900       break;
11901     }
11902     case NearMissInfo::NearMissFeature: {
11903       const FeatureBitset &MissingFeatures = I.getFeatures();
11904       // Don't report the same set of features twice.
11905       if (FeatureMissesSeen.count(MissingFeatures))
11906         break;
11907       FeatureMissesSeen.insert(MissingFeatures);
11908 
11909       // Special case: don't report a feature set which includes arm-mode for
11910       // targets that don't have ARM mode.
11911       if (MissingFeatures.test(Feature_IsARMBit) && !hasARM())
11912         break;
11913       // Don't report any near-misses that both require switching instruction
11914       // set, and adding other subtarget features.
11915       if (isThumb() && MissingFeatures.test(Feature_IsARMBit) &&
11916           MissingFeatures.count() > 1)
11917         break;
11918       if (!isThumb() && MissingFeatures.test(Feature_IsThumbBit) &&
11919           MissingFeatures.count() > 1)
11920         break;
11921       if (!isThumb() && MissingFeatures.test(Feature_IsThumb2Bit) &&
11922           (MissingFeatures & ~FeatureBitset({Feature_IsThumb2Bit,
11923                                              Feature_IsThumbBit})).any())
11924         break;
11925       if (isMClass() && MissingFeatures.test(Feature_HasNEONBit))
11926         break;
11927 
11928       NearMissMessage Message;
11929       Message.Loc = IDLoc;
11930       raw_svector_ostream OS(Message.Message);
11931 
11932       OS << "instruction requires:";
11933       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
11934         if (MissingFeatures.test(i))
11935           OS << ' ' << getSubtargetFeatureName(i);
11936 
11937       NearMissesOut.emplace_back(Message);
11938 
11939       break;
11940     }
11941     case NearMissInfo::NearMissPredicate: {
11942       NearMissMessage Message;
11943       Message.Loc = IDLoc;
11944       switch (I.getPredicateError()) {
11945       case Match_RequiresNotITBlock:
11946         Message.Message = "flag setting instruction only valid outside IT block";
11947         break;
11948       case Match_RequiresITBlock:
11949         Message.Message = "instruction only valid inside IT block";
11950         break;
11951       case Match_RequiresV6:
11952         Message.Message = "instruction variant requires ARMv6 or later";
11953         break;
11954       case Match_RequiresThumb2:
11955         Message.Message = "instruction variant requires Thumb2";
11956         break;
11957       case Match_RequiresV8:
11958         Message.Message = "instruction variant requires ARMv8 or later";
11959         break;
11960       case Match_RequiresFlagSetting:
11961         Message.Message = "no flag-preserving variant of this instruction available";
11962         break;
11963       case Match_InvalidOperand:
11964         Message.Message = "invalid operand for instruction";
11965         break;
11966       default:
11967         llvm_unreachable("Unhandled target predicate error");
11968         break;
11969       }
11970       NearMissesOut.emplace_back(Message);
11971       break;
11972     }
11973     case NearMissInfo::NearMissTooFewOperands: {
11974       if (!ReportedTooFewOperands) {
11975         SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
11976         NearMissesOut.emplace_back(NearMissMessage{
11977             EndLoc, StringRef("too few operands for instruction")});
11978         ReportedTooFewOperands = true;
11979       }
11980       break;
11981     }
11982     case NearMissInfo::NoNearMiss:
11983       // This should never leave the matcher.
11984       llvm_unreachable("not a near-miss");
11985       break;
11986     }
11987   }
11988 }
11989 
11990 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
11991                                     SMLoc IDLoc, OperandVector &Operands) {
11992   SmallVector<NearMissMessage, 4> Messages;
11993   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
11994 
11995   if (Messages.size() == 0) {
11996     // No near-misses were found, so the best we can do is "invalid
11997     // instruction".
11998     Error(IDLoc, "invalid instruction");
11999   } else if (Messages.size() == 1) {
12000     // One near miss was found, report it as the sole error.
12001     Error(Messages[0].Loc, Messages[0].Message);
12002   } else {
12003     // More than one near miss, so report a generic "invalid instruction"
12004     // error, followed by notes for each of the near-misses.
12005     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
12006     for (auto &M : Messages) {
12007       Note(M.Loc, M.Message);
12008     }
12009   }
12010 }
12011 
12012 /// parseDirectiveArchExtension
12013 ///   ::= .arch_extension [no]feature
12014 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
12015   // FIXME: This structure should be moved inside ARMTargetParser
12016   // when we start to table-generate them, and we can use the ARM
12017   // flags below, that were generated by table-gen.
12018   static const struct {
12019     const uint64_t Kind;
12020     const FeatureBitset ArchCheck;
12021     const FeatureBitset Features;
12022   } Extensions[] = {
12023     { ARM::AEK_CRC, {Feature_HasV8Bit}, {ARM::FeatureCRC} },
12024     { ARM::AEK_CRYPTO,  {Feature_HasV8Bit},
12025       {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
12026     { ARM::AEK_FP, {Feature_HasV8Bit},
12027       {ARM::FeatureVFP2_SP, ARM::FeatureFPARMv8} },
12028     { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM),
12029       {Feature_HasV7Bit, Feature_IsNotMClassBit},
12030       {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
12031     { ARM::AEK_MP, {Feature_HasV7Bit, Feature_IsNotMClassBit},
12032       {ARM::FeatureMP} },
12033     { ARM::AEK_SIMD, {Feature_HasV8Bit},
12034       {ARM::FeatureNEON, ARM::FeatureVFP2_SP, ARM::FeatureFPARMv8} },
12035     { ARM::AEK_SEC, {Feature_HasV6KBit}, {ARM::FeatureTrustZone} },
12036     // FIXME: Only available in A-class, isel not predicated
12037     { ARM::AEK_VIRT, {Feature_HasV7Bit}, {ARM::FeatureVirtualization} },
12038     { ARM::AEK_FP16, {Feature_HasV8_2aBit},
12039       {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
12040     { ARM::AEK_RAS, {Feature_HasV8Bit}, {ARM::FeatureRAS} },
12041     { ARM::AEK_LOB, {Feature_HasV8_1MMainlineBit}, {ARM::FeatureLOB} },
12042     // FIXME: Unsupported extensions.
12043     { ARM::AEK_OS, {}, {} },
12044     { ARM::AEK_IWMMXT, {}, {} },
12045     { ARM::AEK_IWMMXT2, {}, {} },
12046     { ARM::AEK_MAVERICK, {}, {} },
12047     { ARM::AEK_XSCALE, {}, {} },
12048   };
12049 
12050   MCAsmParser &Parser = getParser();
12051 
12052   if (getLexer().isNot(AsmToken::Identifier))
12053     return Error(getLexer().getLoc(), "expected architecture extension name");
12054 
12055   StringRef Name = Parser.getTok().getString();
12056   SMLoc ExtLoc = Parser.getTok().getLoc();
12057   Lex();
12058 
12059   if (parseToken(AsmToken::EndOfStatement,
12060                  "unexpected token in '.arch_extension' directive"))
12061     return true;
12062 
12063   bool EnableFeature = true;
12064   if (Name.startswith_lower("no")) {
12065     EnableFeature = false;
12066     Name = Name.substr(2);
12067   }
12068   uint64_t FeatureKind = ARM::parseArchExt(Name);
12069   if (FeatureKind == ARM::AEK_INVALID)
12070     return Error(ExtLoc, "unknown architectural extension: " + Name);
12071 
12072   for (const auto &Extension : Extensions) {
12073     if (Extension.Kind != FeatureKind)
12074       continue;
12075 
12076     if (Extension.Features.none())
12077       return Error(ExtLoc, "unsupported architectural extension: " + Name);
12078 
12079     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
12080       return Error(ExtLoc, "architectural extension '" + Name +
12081                                "' is not "
12082                                "allowed for the current base architecture");
12083 
12084     MCSubtargetInfo &STI = copySTI();
12085     if (EnableFeature) {
12086       STI.SetFeatureBitsTransitively(Extension.Features);
12087     } else {
12088       STI.ClearFeatureBitsTransitively(Extension.Features);
12089     }
12090     FeatureBitset Features = ComputeAvailableFeatures(STI.getFeatureBits());
12091     setAvailableFeatures(Features);
12092     return false;
12093   }
12094 
12095   return Error(ExtLoc, "unknown architectural extension: " + Name);
12096 }
12097 
12098 // Define this matcher function after the auto-generated include so we
12099 // have the match class enum definitions.
12100 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
12101                                                   unsigned Kind) {
12102   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
12103   // If the kind is a token for a literal immediate, check if our asm
12104   // operand matches. This is for InstAliases which have a fixed-value
12105   // immediate in the syntax.
12106   switch (Kind) {
12107   default: break;
12108   case MCK__HASH_0:
12109     if (Op.isImm())
12110       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12111         if (CE->getValue() == 0)
12112           return Match_Success;
12113     break;
12114   case MCK__HASH_8:
12115     if (Op.isImm())
12116       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12117         if (CE->getValue() == 8)
12118           return Match_Success;
12119     break;
12120   case MCK__HASH_16:
12121     if (Op.isImm())
12122       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12123         if (CE->getValue() == 16)
12124           return Match_Success;
12125     break;
12126   case MCK_ModImm:
12127     if (Op.isImm()) {
12128       const MCExpr *SOExpr = Op.getImm();
12129       int64_t Value;
12130       if (!SOExpr->evaluateAsAbsolute(Value))
12131         return Match_Success;
12132       assert((Value >= std::numeric_limits<int32_t>::min() &&
12133               Value <= std::numeric_limits<uint32_t>::max()) &&
12134              "expression value must be representable in 32 bits");
12135     }
12136     break;
12137   case MCK_rGPR:
12138     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
12139       return Match_Success;
12140     return Match_rGPR;
12141   case MCK_GPRPair:
12142     if (Op.isReg() &&
12143         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
12144       return Match_Success;
12145     break;
12146   }
12147   return Match_InvalidOperand;
12148 }
12149 
12150 bool ARMAsmParser::isMnemonicVPTPredicable(StringRef Mnemonic,
12151                                            StringRef ExtraToken) {
12152   if (!hasMVE())
12153     return false;
12154 
12155   return Mnemonic.startswith("vabav") || Mnemonic.startswith("vaddv") ||
12156          Mnemonic.startswith("vaddlv") || Mnemonic.startswith("vminnmv") ||
12157          Mnemonic.startswith("vminnmav") || Mnemonic.startswith("vminv") ||
12158          Mnemonic.startswith("vminav") || Mnemonic.startswith("vmaxnmv") ||
12159          Mnemonic.startswith("vmaxnmav") || Mnemonic.startswith("vmaxv") ||
12160          Mnemonic.startswith("vmaxav") || Mnemonic.startswith("vmladav") ||
12161          Mnemonic.startswith("vrmlaldavh") || Mnemonic.startswith("vrmlalvh") ||
12162          Mnemonic.startswith("vmlsdav") || Mnemonic.startswith("vmlav") ||
12163          Mnemonic.startswith("vmlaldav") || Mnemonic.startswith("vmlalv") ||
12164          Mnemonic.startswith("vmaxnm") || Mnemonic.startswith("vminnm") ||
12165          Mnemonic.startswith("vmax") || Mnemonic.startswith("vmin") ||
12166          Mnemonic.startswith("vshlc") || Mnemonic.startswith("vmovlt") ||
12167          Mnemonic.startswith("vmovlb") || Mnemonic.startswith("vshll") ||
12168          Mnemonic.startswith("vrshrn") || Mnemonic.startswith("vshrn") ||
12169          Mnemonic.startswith("vqrshrun") || Mnemonic.startswith("vqshrun") ||
12170          Mnemonic.startswith("vqrshrn") || Mnemonic.startswith("vqshrn") ||
12171          Mnemonic.startswith("vbic") || Mnemonic.startswith("vrev64") ||
12172          Mnemonic.startswith("vrev32") || Mnemonic.startswith("vrev16") ||
12173          Mnemonic.startswith("vmvn") || Mnemonic.startswith("veor") ||
12174          Mnemonic.startswith("vorn") || Mnemonic.startswith("vorr") ||
12175          Mnemonic.startswith("vand") || Mnemonic.startswith("vmul") ||
12176          Mnemonic.startswith("vqrdmulh") || Mnemonic.startswith("vqdmulh") ||
12177          Mnemonic.startswith("vsub") || Mnemonic.startswith("vadd") ||
12178          Mnemonic.startswith("vqsub") || Mnemonic.startswith("vqadd") ||
12179          Mnemonic.startswith("vabd") || Mnemonic.startswith("vrhadd") ||
12180          Mnemonic.startswith("vhsub") || Mnemonic.startswith("vhadd") ||
12181          Mnemonic.startswith("vdup") || Mnemonic.startswith("vcls") ||
12182          Mnemonic.startswith("vclz") || Mnemonic.startswith("vneg") ||
12183          Mnemonic.startswith("vabs") || Mnemonic.startswith("vqneg") ||
12184          Mnemonic.startswith("vqabs") ||
12185          (Mnemonic.startswith("vrint") && Mnemonic != "vrintr") ||
12186          Mnemonic.startswith("vcmla") || Mnemonic.startswith("vfma") ||
12187          Mnemonic.startswith("vfms") || Mnemonic.startswith("vcadd") ||
12188          Mnemonic.startswith("vadd") || Mnemonic.startswith("vsub") ||
12189          Mnemonic.startswith("vshl") || Mnemonic.startswith("vqshl") ||
12190          Mnemonic.startswith("vqrshl") || Mnemonic.startswith("vrshl") ||
12191          Mnemonic.startswith("vsri") || Mnemonic.startswith("vsli") ||
12192          Mnemonic.startswith("vrshr") || Mnemonic.startswith("vshr") ||
12193          Mnemonic.startswith("vpsel") || Mnemonic.startswith("vcmp") ||
12194          Mnemonic.startswith("vqdmladh") || Mnemonic.startswith("vqrdmladh") ||
12195          Mnemonic.startswith("vqdmlsdh") || Mnemonic.startswith("vqrdmlsdh") ||
12196          Mnemonic.startswith("vcmul") || Mnemonic.startswith("vrmulh") ||
12197          Mnemonic.startswith("vqmovn") || Mnemonic.startswith("vqmovun") ||
12198          Mnemonic.startswith("vmovnt") || Mnemonic.startswith("vmovnb") ||
12199          Mnemonic.startswith("vmaxa") || Mnemonic.startswith("vmaxnma") ||
12200          Mnemonic.startswith("vhcadd") || Mnemonic.startswith("vadc") ||
12201          Mnemonic.startswith("vsbc") || Mnemonic.startswith("vrshr") ||
12202          Mnemonic.startswith("vshr") || Mnemonic.startswith("vstrb") ||
12203          Mnemonic.startswith("vldrb") ||
12204          (Mnemonic.startswith("vstrh") && Mnemonic != "vstrhi") ||
12205          (Mnemonic.startswith("vldrh") && Mnemonic != "vldrhi") ||
12206          Mnemonic.startswith("vstrw") || Mnemonic.startswith("vldrw") ||
12207          Mnemonic.startswith("vldrd") || Mnemonic.startswith("vstrd") ||
12208          Mnemonic.startswith("vqdmull") || Mnemonic.startswith("vbrsr") ||
12209          Mnemonic.startswith("vfmas") || Mnemonic.startswith("vmlas") ||
12210          Mnemonic.startswith("vmla") || Mnemonic.startswith("vqdmlash") ||
12211          Mnemonic.startswith("vqdmlah") || Mnemonic.startswith("vqrdmlash") ||
12212          Mnemonic.startswith("vqrdmlah") || Mnemonic.startswith("viwdup") ||
12213          Mnemonic.startswith("vdwdup") || Mnemonic.startswith("vidup") ||
12214          Mnemonic.startswith("vddup") || Mnemonic.startswith("vctp") ||
12215          Mnemonic.startswith("vpnot") || Mnemonic.startswith("vbic") ||
12216          Mnemonic.startswith("vrmlsldavh") || Mnemonic.startswith("vmlsldav") ||
12217          Mnemonic.startswith("vcvt") ||
12218          MS.isVPTPredicableCDEInstr(Mnemonic) ||
12219          (Mnemonic.startswith("vmov") &&
12220           !(ExtraToken == ".f16" || ExtraToken == ".32" ||
12221             ExtraToken == ".16" || ExtraToken == ".8"));
12222 }
12223